From 8c32467bd40f4913b7c9facd002ad2cbb647b9dc Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 26 Apr 2023 10:25:43 -0400 Subject: [PATCH 001/137] chore: Copy JS templates to C and create language.config.json --- languages/c/Types.mjs | 78 +++++++++++++++++++ languages/c/language.config.json | 14 ++++ languages/c/src/index.mjs | 19 +++++ languages/c/src/types/CommonCppTypes.mjs | 60 ++++++++++++++ languages/c/src/types/CommonHeaderTypes.mjs | 55 +++++++++++++ languages/c/src/types/CppTypes.mjs | 55 +++++++++++++ languages/c/src/types/HeaderTypes.mjs | 55 +++++++++++++ languages/c/src/types/JSONTypes.mjs | 56 +++++++++++++ languages/c/templates/codeblocks/export.mjs | 1 + .../c/templates/codeblocks/mock-import.mjs | 1 + .../c/templates/codeblocks/mock-parameter.mjs | 1 + languages/c/templates/codeblocks/module.mjs | 11 +++ languages/c/templates/declarations/clear.js | 0 languages/c/templates/declarations/default.js | 4 + languages/c/templates/declarations/listen.js | 0 languages/c/templates/declarations/once.js | 0 .../declarations/polymorphic-reducer.js | 6 ++ languages/c/templates/declarations/provide.js | 0 .../c/templates/declarations/rpc-only.js | 0 languages/c/templates/defaults/default.mjs | 1 + languages/c/templates/defaults/property.mjs | 1 + languages/c/templates/examples/default.md | 6 ++ languages/c/templates/examples/event.md | 5 ++ .../examples/polymorphic-pull-event.md | 9 +++ .../c/templates/examples/polymorphic-pull.md | 6 ++ languages/c/templates/examples/provider.md | 10 +++ languages/c/templates/examples/setter.md | 6 ++ languages/c/templates/examples/subscriber.md | 7 ++ languages/c/templates/examples/synchronous.md | 4 + .../c/templates/examples/temporal-set.md | 13 ++++ .../c/templates/imports/context-event.mjs | 1 + languages/c/templates/imports/event.mjs | 2 + languages/c/templates/imports/property.mjs | 1 + languages/c/templates/imports/provider.mjs | 2 + languages/c/templates/imports/rpc.mjs | 1 + .../c/templates/imports/temporal-set.mjs | 1 + languages/c/templates/imports/x-method.mjs | 1 + .../templates/initializations/deprecated.mjs | 1 + .../c/templates/initializations/event.mjs | 1 + .../c/templates/initializations/provider.mjs | 1 + languages/c/templates/methods/clear.js | 0 languages/c/templates/methods/default.js | 7 ++ languages/c/templates/methods/listen.js | 0 languages/c/templates/methods/once.js | 0 .../templates/methods/polymorphic-reducer.js | 11 +++ languages/c/templates/methods/provide.js | 3 + languages/c/templates/methods/rpc-only.js | 0 .../templates/modules/include/Common/Module.h | 23 ++++++ .../c/templates/modules/include/Module.h | 25 ++++++ .../c/templates/modules/src/JsonData_Module.h | 23 ++++++ languages/c/templates/modules/src/Module.cpp | 29 +++++++ .../c/templates/modules/src/Module_Common.cpp | 26 +++++++ languages/c/templates/parameters/default.js | 1 + languages/c/templates/schemas/default.js | 5 ++ .../templates/schemas/include/Common/Module.h | 25 ++++++ .../c/templates/schemas/include/Module.h | 23 ++++++ .../c/templates/schemas/src/JsonData_Module.h | 23 ++++++ languages/c/templates/schemas/src/Module.cpp | 29 +++++++ .../c/templates/schemas/src/Module_Common.cpp | 26 +++++++ languages/c/templates/sdk/main.cpp | 30 +++++++ .../c/templates/sections/declarations.js | 1 + languages/c/templates/sections/events.js | 1 + languages/c/templates/sections/methods.js | 3 + .../templates/sections/provider-interfaces.js | 11 +++ languages/c/templates/sections/schemas.js | 3 + languages/c/templates/types/enum.mjs | 3 + 66 files changed, 827 insertions(+) create mode 100644 languages/c/Types.mjs create mode 100644 languages/c/language.config.json create mode 100644 languages/c/src/index.mjs create mode 100644 languages/c/src/types/CommonCppTypes.mjs create mode 100644 languages/c/src/types/CommonHeaderTypes.mjs create mode 100644 languages/c/src/types/CppTypes.mjs create mode 100644 languages/c/src/types/HeaderTypes.mjs create mode 100644 languages/c/src/types/JSONTypes.mjs create mode 100644 languages/c/templates/codeblocks/export.mjs create mode 100644 languages/c/templates/codeblocks/mock-import.mjs create mode 100644 languages/c/templates/codeblocks/mock-parameter.mjs create mode 100644 languages/c/templates/codeblocks/module.mjs create mode 100644 languages/c/templates/declarations/clear.js create mode 100644 languages/c/templates/declarations/default.js create mode 100644 languages/c/templates/declarations/listen.js create mode 100644 languages/c/templates/declarations/once.js create mode 100644 languages/c/templates/declarations/polymorphic-reducer.js create mode 100644 languages/c/templates/declarations/provide.js create mode 100644 languages/c/templates/declarations/rpc-only.js create mode 100644 languages/c/templates/defaults/default.mjs create mode 100644 languages/c/templates/defaults/property.mjs create mode 100644 languages/c/templates/examples/default.md create mode 100644 languages/c/templates/examples/event.md create mode 100644 languages/c/templates/examples/polymorphic-pull-event.md create mode 100644 languages/c/templates/examples/polymorphic-pull.md create mode 100644 languages/c/templates/examples/provider.md create mode 100644 languages/c/templates/examples/setter.md create mode 100644 languages/c/templates/examples/subscriber.md create mode 100644 languages/c/templates/examples/synchronous.md create mode 100644 languages/c/templates/examples/temporal-set.md create mode 100644 languages/c/templates/imports/context-event.mjs create mode 100644 languages/c/templates/imports/event.mjs create mode 100644 languages/c/templates/imports/property.mjs create mode 100644 languages/c/templates/imports/provider.mjs create mode 100644 languages/c/templates/imports/rpc.mjs create mode 100644 languages/c/templates/imports/temporal-set.mjs create mode 100644 languages/c/templates/imports/x-method.mjs create mode 100644 languages/c/templates/initializations/deprecated.mjs create mode 100644 languages/c/templates/initializations/event.mjs create mode 100644 languages/c/templates/initializations/provider.mjs create mode 100644 languages/c/templates/methods/clear.js create mode 100644 languages/c/templates/methods/default.js create mode 100644 languages/c/templates/methods/listen.js create mode 100644 languages/c/templates/methods/once.js create mode 100644 languages/c/templates/methods/polymorphic-reducer.js create mode 100644 languages/c/templates/methods/provide.js create mode 100644 languages/c/templates/methods/rpc-only.js create mode 100644 languages/c/templates/modules/include/Common/Module.h create mode 100644 languages/c/templates/modules/include/Module.h create mode 100644 languages/c/templates/modules/src/JsonData_Module.h create mode 100644 languages/c/templates/modules/src/Module.cpp create mode 100644 languages/c/templates/modules/src/Module_Common.cpp create mode 100644 languages/c/templates/parameters/default.js create mode 100644 languages/c/templates/schemas/default.js create mode 100644 languages/c/templates/schemas/include/Common/Module.h create mode 100644 languages/c/templates/schemas/include/Module.h create mode 100644 languages/c/templates/schemas/src/JsonData_Module.h create mode 100644 languages/c/templates/schemas/src/Module.cpp create mode 100644 languages/c/templates/schemas/src/Module_Common.cpp create mode 100644 languages/c/templates/sdk/main.cpp create mode 100644 languages/c/templates/sections/declarations.js create mode 100644 languages/c/templates/sections/events.js create mode 100644 languages/c/templates/sections/methods.js create mode 100644 languages/c/templates/sections/provider-interfaces.js create mode 100644 languages/c/templates/sections/schemas.js create mode 100644 languages/c/templates/types/enum.mjs diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs new file mode 100644 index 00000000..31f48dd1 --- /dev/null +++ b/languages/c/Types.mjs @@ -0,0 +1,78 @@ +/* + * Copyright 2021 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 + */ + +import jsonTypes from './src/types/JSONTypes.mjs' +import commonTypes from './src/types/CommonCppTypes.mjs' +import headerCommonTypes from './src/types/CommonHeaderTypes.mjs' +import headerTypes from './src/types/HeaderTypes.mjs' +import cppTypes from './src/types/CppTypes.mjs' + +import path from "path" + +const isSynchronous = m => !m.tags ? false : m.tags.map(t => t.name).find(s => s === 'synchronous') + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return routeToDestination('getMethodSignature', arguments) +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return routeToDestination('getMethodSignatureParams', arguments) +} + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + return routeToDestination('getSchemaShape', arguments) +} + +function getSchemaType(schema, module, { destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + const value = routeToDestination('getSchemaType', arguments) + return value +} + +function routeToDestination(method, args) { + const destination = args[args.length-1].destination || '' + + if ( path.basename(destination) === 'JsonData_Module.h') { + return jsonTypes[method](...args) + } + else if (path.basename(destination) === 'Module.cpp') { + return cppTypes[method](...args) + } + else if (path.basename(destination) === 'Module_Common.cpp') { + return commonTypes[method](...args) + } + else if (path.basename(destination) === 'Module.h' && path.dirname(destination).endsWith(path.sep + 'Common')) { + return headerCommonTypes[method](...args) + } + else if (path.basename(destination) === 'Module.h') { + return headerTypes[method](...args) + } + + return '' +} + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/language.config.json b/languages/c/language.config.json new file mode 100644 index 00000000..185b0370 --- /dev/null +++ b/languages/c/language.config.json @@ -0,0 +1,14 @@ +{ + "name": "C", + "langcode": "c", + "createModuleDirectories": false, + "templatesPerModule": [ + "/include/Module.h", + "/src/Module.cpp" + ], + "templatesPerSchema": [ + "/include/Common/Module.h", + "/src/Module_Common.cpp", + "/src/JsonData_Module.h" + ] +} \ No newline at end of file diff --git a/languages/c/src/index.mjs b/languages/c/src/index.mjs new file mode 100644 index 00000000..51c547a1 --- /dev/null +++ b/languages/c/src/index.mjs @@ -0,0 +1,19 @@ +/* + * Copyright 2021 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 + */ + +export { default as Transport } from './shared/Transport/index.mjs' \ No newline at end of file diff --git a/languages/c/src/types/CommonCppTypes.mjs b/languages/c/src/types/CommonCppTypes.mjs new file mode 100644 index 00000000..863cd77b --- /dev/null +++ b/languages/c/src/types/CommonCppTypes.mjs @@ -0,0 +1,60 @@ +/* + * Copyright 2021 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 + */ + +// import deepmerge from 'deepmerge' +// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' +// import { getLinkFromRef } from '../../src/shared/markdown.mjs' +// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' + + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return `// Common CPP Signatures for ${module}_${method}` +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return `// Common CPP Signature Params for ${module}_${method}` +} + +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + + return { + dependencies: [], + code: `// Common CPP Schema Shape` + } + return `// Common CPP Schema Shape` +} + +function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + return `// Common CPP Schema Type` +} + + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/src/types/CommonHeaderTypes.mjs b/languages/c/src/types/CommonHeaderTypes.mjs new file mode 100644 index 00000000..9c40c084 --- /dev/null +++ b/languages/c/src/types/CommonHeaderTypes.mjs @@ -0,0 +1,55 @@ +/* + * Copyright 2021 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 + */ + +// import deepmerge from 'deepmerge' +// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' +// import { getLinkFromRef } from '../../src/shared/markdown.mjs' +// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' + + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return `// common .h Signatures for ${module}_${method}` +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return `// common .h Signature Params for ${module}_${method}` +} + +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + return `// common .h Schema Shape` +} + +function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + return `// common .h Schema Type` +} + + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/src/types/CppTypes.mjs b/languages/c/src/types/CppTypes.mjs new file mode 100644 index 00000000..4b6fa6a8 --- /dev/null +++ b/languages/c/src/types/CppTypes.mjs @@ -0,0 +1,55 @@ +/* + * Copyright 2021 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 + */ + +// import deepmerge from 'deepmerge' +// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' +// import { getLinkFromRef } from '../../src/shared/markdown.mjs' +// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' + + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return `// CPP Signatures for ${module}_${method}` +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return `// CPP Signature Params for ${module}_${method}` +} + +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + return `// CPP Schema Shape` +} + +function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + return `// CPP Schema Type` +} + + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/src/types/HeaderTypes.mjs b/languages/c/src/types/HeaderTypes.mjs new file mode 100644 index 00000000..9ce0155e --- /dev/null +++ b/languages/c/src/types/HeaderTypes.mjs @@ -0,0 +1,55 @@ +/* + * Copyright 2021 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 + */ + +// import deepmerge from 'deepmerge' +// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' +// import { getLinkFromRef } from '../../src/shared/markdown.mjs' +// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' + + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return `// .h Signatures for ${module.info.title}_${method.name}` +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return `// .h Signature Params for ${module.info.title}_${method.name}` +} + +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + return `// .h Schema Shape` +} + +function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + return `// .h Schema Type` +} + + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/src/types/JSONTypes.mjs b/languages/c/src/types/JSONTypes.mjs new file mode 100644 index 00000000..d2961794 --- /dev/null +++ b/languages/c/src/types/JSONTypes.mjs @@ -0,0 +1,56 @@ + +/* + * Copyright 2021 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 + */ + +// import deepmerge from 'deepmerge' +// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' +// import { getLinkFromRef } from '../../src/shared/markdown.mjs' +// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' + + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return `// JSON Signatures for ${module}_${method}` +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return `// JSON Signature Params for ${module}_${method}` +} + +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + return `// JSON Schema Shape` +} + +function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + return `// JSON Schema Type` +} + + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/templates/codeblocks/export.mjs b/languages/c/templates/codeblocks/export.mjs new file mode 100644 index 00000000..c98498e4 --- /dev/null +++ b/languages/c/templates/codeblocks/export.mjs @@ -0,0 +1 @@ +export { default as ${info.title} } from './${info.title}/index.mjs' \ No newline at end of file diff --git a/languages/c/templates/codeblocks/mock-import.mjs b/languages/c/templates/codeblocks/mock-import.mjs new file mode 100644 index 00000000..5d22512a --- /dev/null +++ b/languages/c/templates/codeblocks/mock-import.mjs @@ -0,0 +1 @@ +import { default as _${info.title} } from './${info.title}/defaults.mjs' \ No newline at end of file diff --git a/languages/c/templates/codeblocks/mock-parameter.mjs b/languages/c/templates/codeblocks/mock-parameter.mjs new file mode 100644 index 00000000..63e63902 --- /dev/null +++ b/languages/c/templates/codeblocks/mock-parameter.mjs @@ -0,0 +1 @@ + ${info.title}: _${info.title}, \ No newline at end of file diff --git a/languages/c/templates/codeblocks/module.mjs b/languages/c/templates/codeblocks/module.mjs new file mode 100644 index 00000000..48f6d6bc --- /dev/null +++ b/languages/c/templates/codeblocks/module.mjs @@ -0,0 +1,11 @@ +// JEREMY + +export module ${info.title} { + + /* ${SCHEMAS} */ + + /* ${DECLARATIONS} */ + + /* ${PROVIDERS} */ + +} \ No newline at end of file diff --git a/languages/c/templates/declarations/clear.js b/languages/c/templates/declarations/clear.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/declarations/default.js b/languages/c/templates/declarations/default.js new file mode 100644 index 00000000..bd8b6fcf --- /dev/null +++ b/languages/c/templates/declarations/default.js @@ -0,0 +1,4 @@ + /** + * ${method.summary} + ${method.params} */ + ${method.signature} diff --git a/languages/c/templates/declarations/listen.js b/languages/c/templates/declarations/listen.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/declarations/once.js b/languages/c/templates/declarations/once.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/declarations/polymorphic-reducer.js b/languages/c/templates/declarations/polymorphic-reducer.js new file mode 100644 index 00000000..979832b2 --- /dev/null +++ b/languages/c/templates/declarations/polymorphic-reducer.js @@ -0,0 +1,6 @@ + /** + * ${method.summary} + ${method.params} */ + ${method.signature} + +// TODO: generate reducer signature \ No newline at end of file diff --git a/languages/c/templates/declarations/provide.js b/languages/c/templates/declarations/provide.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/declarations/rpc-only.js b/languages/c/templates/declarations/rpc-only.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/defaults/default.mjs b/languages/c/templates/defaults/default.mjs new file mode 100644 index 00000000..e29085d1 --- /dev/null +++ b/languages/c/templates/defaults/default.mjs @@ -0,0 +1 @@ + ${method.name}: ${method.example.value} \ No newline at end of file diff --git a/languages/c/templates/defaults/property.mjs b/languages/c/templates/defaults/property.mjs new file mode 100644 index 00000000..95ef20cf --- /dev/null +++ b/languages/c/templates/defaults/property.mjs @@ -0,0 +1 @@ + ${method.name}: function () { return MockProps.mock('${info.title}', '${method.name}', arguments, ${method.example.value}) } \ No newline at end of file diff --git a/languages/c/templates/examples/default.md b/languages/c/templates/examples/default.md new file mode 100644 index 00000000..ecc979ba --- /dev/null +++ b/languages/c/templates/examples/default.md @@ -0,0 +1,6 @@ +import { ${module} } from '${package.name}' + +${module}.${method.name}(${example.params}) + .then(${method.result.name} => { + console.log(${method.result.name}) + }) \ No newline at end of file diff --git a/languages/c/templates/examples/event.md b/languages/c/templates/examples/event.md new file mode 100644 index 00000000..7b78fe76 --- /dev/null +++ b/languages/c/templates/examples/event.md @@ -0,0 +1,5 @@ +import { ${module} } from '${package.name}' + +${module}.listen('${event.name}', ${method.result.name} => { + console.log(${method.result.name}) +}) \ No newline at end of file diff --git a/languages/c/templates/examples/polymorphic-pull-event.md b/languages/c/templates/examples/polymorphic-pull-event.md new file mode 100644 index 00000000..7bc2baa7 --- /dev/null +++ b/languages/c/templates/examples/polymorphic-pull-event.md @@ -0,0 +1,9 @@ +import { ${module} } from '${package.name}' + +${module}.${method.pulls.for}(function(parameters) { + console.log(parameters.entityId) + console.log(parameters.assetId) + return Promise.resolve(${originator.params[1].example.value}) +}).then(success => { + console.log(success) +}) \ No newline at end of file diff --git a/languages/c/templates/examples/polymorphic-pull.md b/languages/c/templates/examples/polymorphic-pull.md new file mode 100644 index 00000000..7c53080c --- /dev/null +++ b/languages/c/templates/examples/polymorphic-pull.md @@ -0,0 +1,6 @@ +import { ${module} } from '${package.name}' + +${module}.${method.name}(${method.params[1].example.value}) + .then(success => { + console.log(success) + }) \ No newline at end of file diff --git a/languages/c/templates/examples/provider.md b/languages/c/templates/examples/provider.md new file mode 100644 index 00000000..d2d16366 --- /dev/null +++ b/languages/c/templates/examples/provider.md @@ -0,0 +1,10 @@ +import { ${module} } from '${package.name}' + +class MyProvider { + async ${example.providerMethod}(${method.result.name}, responder) { + console.log(JSON.stringify(${method.result.name}, null, 2)) + responder(${example.providerResponse}) + } +} + +${module}.provide(new MyProvider()) \ No newline at end of file diff --git a/languages/c/templates/examples/setter.md b/languages/c/templates/examples/setter.md new file mode 100644 index 00000000..c258314a --- /dev/null +++ b/languages/c/templates/examples/setter.md @@ -0,0 +1,6 @@ +import { ${module} } from '${package.name}' + +${module}.${method.setter.for}(${example.params}) + .then(${method.result.name} => { + console.log(${method.result.name}) + }) \ No newline at end of file diff --git a/languages/c/templates/examples/subscriber.md b/languages/c/templates/examples/subscriber.md new file mode 100644 index 00000000..99c0516f --- /dev/null +++ b/languages/c/templates/examples/subscriber.md @@ -0,0 +1,7 @@ +import { ${module} } from '${package.name}' + +${method.alternative}(value => { + console.log(value) +}).then(listenerId => { + console.log(listenerId) +}) \ No newline at end of file diff --git a/languages/c/templates/examples/synchronous.md b/languages/c/templates/examples/synchronous.md new file mode 100644 index 00000000..6e8e1e82 --- /dev/null +++ b/languages/c/templates/examples/synchronous.md @@ -0,0 +1,4 @@ +import { ${module} } from '${package.name}' + +const ${method.result.name} = ${module}.${method.name}(${example.params}) +console.log(${method.result.name}) \ No newline at end of file diff --git a/languages/c/templates/examples/temporal-set.md b/languages/c/templates/examples/temporal-set.md new file mode 100644 index 00000000..4a8e94ea --- /dev/null +++ b/languages/c/templates/examples/temporal-set.md @@ -0,0 +1,13 @@ +import { ${module} } from '${package.name}' + +const process = ${module}.${method.name}(function(${example.params}${if.params},${end.if.params} + ${method.item} => { + console.log('Added to temporal set:') + console.dir(${method.item}) + }, + ${method.item} => { + console.log('Removed from temporal set:') + console.dir(${method.item}) + }) + +setTimeout( () => process.stop(), 10000) \ No newline at end of file diff --git a/languages/c/templates/imports/context-event.mjs b/languages/c/templates/imports/context-event.mjs new file mode 100644 index 00000000..fcd3186b --- /dev/null +++ b/languages/c/templates/imports/context-event.mjs @@ -0,0 +1 @@ +import { registerEventContext } from '../Events/index.mjs' diff --git a/languages/c/templates/imports/event.mjs b/languages/c/templates/imports/event.mjs new file mode 100644 index 00000000..bc019bca --- /dev/null +++ b/languages/c/templates/imports/event.mjs @@ -0,0 +1,2 @@ +import Events from '../Events/index.mjs' +import { registerEvents } from '../Events/index.mjs' diff --git a/languages/c/templates/imports/property.mjs b/languages/c/templates/imports/property.mjs new file mode 100644 index 00000000..7107a163 --- /dev/null +++ b/languages/c/templates/imports/property.mjs @@ -0,0 +1 @@ +import Prop from '../Prop/index.mjs' diff --git a/languages/c/templates/imports/provider.mjs b/languages/c/templates/imports/provider.mjs new file mode 100644 index 00000000..b3ea7b4f --- /dev/null +++ b/languages/c/templates/imports/provider.mjs @@ -0,0 +1,2 @@ +import ProvideManager from '../ProvideManager/index.mjs' +import { registerProviderInterface } from '../ProvideManager/index.mjs' diff --git a/languages/c/templates/imports/rpc.mjs b/languages/c/templates/imports/rpc.mjs new file mode 100644 index 00000000..af459a1e --- /dev/null +++ b/languages/c/templates/imports/rpc.mjs @@ -0,0 +1 @@ +import Transport from '../Transport/index.mjs' diff --git a/languages/c/templates/imports/temporal-set.mjs b/languages/c/templates/imports/temporal-set.mjs new file mode 100644 index 00000000..089d35b1 --- /dev/null +++ b/languages/c/templates/imports/temporal-set.mjs @@ -0,0 +1 @@ +import TemporalSet from '../TemporalSet/index.mjs' \ No newline at end of file diff --git a/languages/c/templates/imports/x-method.mjs b/languages/c/templates/imports/x-method.mjs new file mode 100644 index 00000000..42453ecb --- /dev/null +++ b/languages/c/templates/imports/x-method.mjs @@ -0,0 +1 @@ +import Results from '../Results/index.mjs' \ No newline at end of file diff --git a/languages/c/templates/initializations/deprecated.mjs b/languages/c/templates/initializations/deprecated.mjs new file mode 100644 index 00000000..737d1c25 --- /dev/null +++ b/languages/c/templates/initializations/deprecated.mjs @@ -0,0 +1 @@ +Transport.registerDeprecatedMethod('${info.title}', '${method.name}', 'Use ${method.alternative} instead.') diff --git a/languages/c/templates/initializations/event.mjs b/languages/c/templates/initializations/event.mjs new file mode 100644 index 00000000..c151f674 --- /dev/null +++ b/languages/c/templates/initializations/event.mjs @@ -0,0 +1 @@ +registerEvents('${info.title}', ${events.array}) diff --git a/languages/c/templates/initializations/provider.mjs b/languages/c/templates/initializations/provider.mjs new file mode 100644 index 00000000..b113d236 --- /dev/null +++ b/languages/c/templates/initializations/provider.mjs @@ -0,0 +1 @@ +registerProviderInterface('${capability}', '${info.title}', ${interface}) diff --git a/languages/c/templates/methods/clear.js b/languages/c/templates/methods/clear.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/methods/default.js b/languages/c/templates/methods/default.js new file mode 100644 index 00000000..0c7f799b --- /dev/null +++ b/languages/c/templates/methods/default.js @@ -0,0 +1,7 @@ + +function ${method.name}(${method.params.list}) { + + const transforms = ${method.transforms} + + return Transport.send('${info.title}', '${method.name}', { ${method.params.list} }, transforms) +} \ No newline at end of file diff --git a/languages/c/templates/methods/listen.js b/languages/c/templates/methods/listen.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/methods/once.js b/languages/c/templates/methods/once.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/methods/polymorphic-reducer.js b/languages/c/templates/methods/polymorphic-reducer.js new file mode 100644 index 00000000..db07747f --- /dev/null +++ b/languages/c/templates/methods/polymorphic-reducer.js @@ -0,0 +1,11 @@ + +function ${method.name}(${method.params.list}) { + const transforms = ${method.transforms} + + if (arguments.length === 1 && Array.isArray(arguments[0])) { + return Transport.send('${info.title}', '${method.name}', arguments[0], transforms) + } + else { + return Transport.send('${info.title}', '${method.name}', { ${method.params.list} }, transforms) + } +} \ No newline at end of file diff --git a/languages/c/templates/methods/provide.js b/languages/c/templates/methods/provide.js new file mode 100644 index 00000000..8cb48885 --- /dev/null +++ b/languages/c/templates/methods/provide.js @@ -0,0 +1,3 @@ +function provide(capability, provider) { + return ProvideManager.provide(capability, provider) +} diff --git a/languages/c/templates/methods/rpc-only.js b/languages/c/templates/methods/rpc-only.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/modules/include/Common/Module.h b/languages/c/templates/modules/include/Common/Module.h new file mode 100644 index 00000000..4cee1781 --- /dev/null +++ b/languages/c/templates/modules/include/Common/Module.h @@ -0,0 +1,23 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${DECLARATIONS} */ + +} diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h new file mode 100644 index 00000000..60a75f5f --- /dev/null +++ b/languages/c/templates/modules/include/Module.h @@ -0,0 +1,25 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${SCHEMAS} */ + + /* ${DECLARATIONS} */ + +} diff --git a/languages/c/templates/modules/src/JsonData_Module.h b/languages/c/templates/modules/src/JsonData_Module.h new file mode 100644 index 00000000..4cee1781 --- /dev/null +++ b/languages/c/templates/modules/src/JsonData_Module.h @@ -0,0 +1,23 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${DECLARATIONS} */ + +} diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp new file mode 100644 index 00000000..26a26050 --- /dev/null +++ b/languages/c/templates/modules/src/Module.cpp @@ -0,0 +1,29 @@ +/* + * 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 + */ + +/* ${IMPORTS} */ + + +namespace FireboltSDK { + + namespace ${info.title} { + + /* ${METHODS} */ + + } +} diff --git a/languages/c/templates/modules/src/Module_Common.cpp b/languages/c/templates/modules/src/Module_Common.cpp new file mode 100644 index 00000000..8460c52a --- /dev/null +++ b/languages/c/templates/modules/src/Module_Common.cpp @@ -0,0 +1,26 @@ +/* + * 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 + */ + +/* ${IMPORTS} */ + + +namespace FireboltSDK { + + /* ${METHODS} */ + +} diff --git a/languages/c/templates/parameters/default.js b/languages/c/templates/parameters/default.js new file mode 100644 index 00000000..916a8adf --- /dev/null +++ b/languages/c/templates/parameters/default.js @@ -0,0 +1 @@ +${method.params.list} \ No newline at end of file diff --git a/languages/c/templates/schemas/default.js b/languages/c/templates/schemas/default.js new file mode 100644 index 00000000..bc9ab873 --- /dev/null +++ b/languages/c/templates/schemas/default.js @@ -0,0 +1,5 @@ + /** + * ${schema.description} + */ + +${schema.shape} diff --git a/languages/c/templates/schemas/include/Common/Module.h b/languages/c/templates/schemas/include/Common/Module.h new file mode 100644 index 00000000..5582d8ea --- /dev/null +++ b/languages/c/templates/schemas/include/Common/Module.h @@ -0,0 +1,25 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${DECLARATIONS} */ + + /* ${SCHEMAS} */ + +} diff --git a/languages/c/templates/schemas/include/Module.h b/languages/c/templates/schemas/include/Module.h new file mode 100644 index 00000000..4cee1781 --- /dev/null +++ b/languages/c/templates/schemas/include/Module.h @@ -0,0 +1,23 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${DECLARATIONS} */ + +} diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/JsonData_Module.h new file mode 100644 index 00000000..4cee1781 --- /dev/null +++ b/languages/c/templates/schemas/src/JsonData_Module.h @@ -0,0 +1,23 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${DECLARATIONS} */ + +} diff --git a/languages/c/templates/schemas/src/Module.cpp b/languages/c/templates/schemas/src/Module.cpp new file mode 100644 index 00000000..26a26050 --- /dev/null +++ b/languages/c/templates/schemas/src/Module.cpp @@ -0,0 +1,29 @@ +/* + * 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 + */ + +/* ${IMPORTS} */ + + +namespace FireboltSDK { + + namespace ${info.title} { + + /* ${METHODS} */ + + } +} diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/Module_Common.cpp new file mode 100644 index 00000000..8460c52a --- /dev/null +++ b/languages/c/templates/schemas/src/Module_Common.cpp @@ -0,0 +1,26 @@ +/* + * 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 + */ + +/* ${IMPORTS} */ + + +namespace FireboltSDK { + + /* ${METHODS} */ + +} diff --git a/languages/c/templates/sdk/main.cpp b/languages/c/templates/sdk/main.cpp new file mode 100644 index 00000000..a9f2f5ca --- /dev/null +++ b/languages/c/templates/sdk/main.cpp @@ -0,0 +1,30 @@ +/* + * Copyright 2021 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 + */ + +import { setMockResponses } from './Transport/MockTransport.mjs' + +/* ${MOCK_IMPORTS} */ + +setMockResponses({ + /* ${MOCK_OBJECTS} */ +}) + +/* ${EXPORTS} */ +export { default as Log } from './Log/index.mjs' +export { default as Events } from './Events/index.mjs' +export { default as Settings } from './Settings/index.mjs' diff --git a/languages/c/templates/sections/declarations.js b/languages/c/templates/sections/declarations.js new file mode 100644 index 00000000..b3ef974d --- /dev/null +++ b/languages/c/templates/sections/declarations.js @@ -0,0 +1 @@ +${declaration.list} diff --git a/languages/c/templates/sections/events.js b/languages/c/templates/sections/events.js new file mode 100644 index 00000000..5be10409 --- /dev/null +++ b/languages/c/templates/sections/events.js @@ -0,0 +1 @@ +${event.list} diff --git a/languages/c/templates/sections/methods.js b/languages/c/templates/sections/methods.js new file mode 100644 index 00000000..3f382a63 --- /dev/null +++ b/languages/c/templates/sections/methods.js @@ -0,0 +1,3 @@ + + // Methods +${method.list} diff --git a/languages/c/templates/sections/provider-interfaces.js b/languages/c/templates/sections/provider-interfaces.js new file mode 100644 index 00000000..418d7abf --- /dev/null +++ b/languages/c/templates/sections/provider-interfaces.js @@ -0,0 +1,11 @@ + // Provider Interfaces + + interface ProviderSession { + correlationId(): string // Returns the correlation id of the current provider session + } + + interface FocusableProviderSession extends ProviderSession { + focus(): Promise // Requests that the provider app be moved into focus to prevent a user experience + } + + ${providers.list} \ No newline at end of file diff --git a/languages/c/templates/sections/schemas.js b/languages/c/templates/sections/schemas.js new file mode 100644 index 00000000..a2d20dbb --- /dev/null +++ b/languages/c/templates/sections/schemas.js @@ -0,0 +1,3 @@ +// Types + +${schema.list} diff --git a/languages/c/templates/types/enum.mjs b/languages/c/templates/types/enum.mjs new file mode 100644 index 00000000..907fb37d --- /dev/null +++ b/languages/c/templates/types/enum.mjs @@ -0,0 +1,3 @@ +${name}: { + ${key}: '${value}', +}, From 86921634e02eff11b0f4195831d7151d9a7fb8a0 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 26 Apr 2023 14:42:31 -0400 Subject: [PATCH 002/137] feat(languages): Add support for a distinct JSON-type for each schema Also started tweaking C templates and adding a few useful macros. --- languages/c/Types.mjs | 73 ++- languages/c/src/types/NativeHelpers.mjs | 494 ++++++++++++++++++ languages/c/templates/methods/default.c | 24 + languages/c/templates/methods/default.js | 7 - languages/c/templates/methods/property.c | 12 + .../templates/modules/include/Common/Module.h | 15 +- .../c/templates/modules/include/Module.h | 14 +- .../c/templates/modules/src/JsonData_Module.h | 8 +- languages/c/templates/modules/src/Module.cpp | 17 +- .../c/templates/modules/src/Module_Common.cpp | 15 +- languages/c/templates/parameters/default.c | 1 + languages/c/templates/parameters/default.js | 1 - languages/c/templates/parameters/json.c | 3 + .../javascript/templates/methods/property.js | 2 +- src/macrofier/engine.mjs | 33 +- src/macrofier/index.mjs | 3 + src/shared/typescript.mjs | 11 +- 17 files changed, 687 insertions(+), 46 deletions(-) create mode 100644 languages/c/src/types/NativeHelpers.mjs create mode 100644 languages/c/templates/methods/default.c delete mode 100644 languages/c/templates/methods/default.js create mode 100644 languages/c/templates/methods/property.c create mode 100644 languages/c/templates/parameters/default.c delete mode 100644 languages/c/templates/parameters/default.js create mode 100644 languages/c/templates/parameters/json.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 31f48dd1..aa209ad4 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -21,6 +21,8 @@ import commonTypes from './src/types/CommonCppTypes.mjs' import headerCommonTypes from './src/types/CommonHeaderTypes.mjs' import headerTypes from './src/types/HeaderTypes.mjs' import cppTypes from './src/types/CppTypes.mjs' +import typeScriptTypes from '../../src/shared/typescript.mjs' +import { getNativeType } from './src/types/NativeHelpers.mjs' import path from "path" @@ -31,8 +33,13 @@ const isSynchronous = m => !m.tags ? false : m.tags.map(t => t.name).find(s => s // getSchemaType(schema, module, options = { destination: 'file.txt' }) // getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -function getMethodSignature(method, module, { destination = '' } = {}) { - return routeToDestination('getMethodSignature', arguments) +function getMethodSignature(method, module, { destination = '' } = {}) { + const returnType = getNativeType(method.result.schema) + const useHandle = !returnType + const extraParam = useHandle ? '${info.title}_${method.result.type}Handle* ${method.result.name}' : '' + + + return (returnType || 'uint32_t') + ' ${info.title}_Get${method.Name}(' + extraParam + ')' } function getMethodSignatureParams(method, module, { destination = '' } = {}) { @@ -44,8 +51,53 @@ function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', } function getSchemaType(schema, module, { destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - const value = routeToDestination('getSchemaType', arguments) - return value + let type = getNativeType(schema) + + if (!type) { + type = typeScriptTypes.getSchemaType(...arguments) + + const array = type.endsWith('[]') + + if (array) { + type = type.substring(0, type.length-2) + type = `${type}ObjectArrayHandle` + } + + type = `${module.info.title}_${type}` + } + return type +} + +function getJsonType(schema, module, { destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + let type = getSchemaType(...arguments) + + // FireboltSDK::JSON::String&, etc. + // FireboltSDK::::& + // WPEFramework::Core::JSON::Boolean + + const array = type.endsWith('[]') + + if (array) { + type = type.substring(0, type.length-2) + } + + let jsonType + + if (type === 'string') { + jsonType = 'FireboltSDK::JSON::String' + } + else if (type === 'boolean') { + jsonType = 'WPEFramework::Core::JSON::Boolean' + } + else { + jsonType = `FireboltSDK::${module.info.title}::${getSchemaType(...arguments)}` + } + + if (array) { + jsonType = `WPEFramework::Core::JSON::ArrayType<${jsonType}>` + } + + return `${jsonType}&` } function routeToDestination(method, args) { @@ -70,9 +122,22 @@ function routeToDestination(method, args) { return '' } +function getPrimativeType(schema) { + if (schema.type === "boolean") { + return "bool" + } + else if (schema.type === "integer") { + return "uint32_t" + } + else if (schema.type === "number") { + return + } +} + export default { getMethodSignature, getMethodSignatureParams, getSchemaShape, getSchemaType, + getJsonType } \ No newline at end of file diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs new file mode 100644 index 00000000..e51c47d7 --- /dev/null +++ b/languages/c/src/types/NativeHelpers.mjs @@ -0,0 +1,494 @@ +/* + * Copyright 2021 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 + */ + +import helpers from 'crocks/helpers/index.js' +const { compose, getPathOr } = helpers +import safe from 'crocks/Maybe/safe.js' +import pointfree from 'crocks/pointfree/index.js' +const { chain, filter, reduce, option, map } = pointfree +import predicates from 'crocks/predicates/index.js' +import { getPath, getExternalSchemaPaths } from '../../../../src/shared/json-schema.mjs' +import deepmerge from 'deepmerge' + +const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = predicates + +const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' + +const getHeaderText = () => { + + return `/* +* Copyright 2022 Comcast +* +* Auto Generated using firebolt-openrpc tools. DO NOT EDIT. +* +*/ + +` +} + +const getIncludeGuardOpen = (json, prefix=null) => { + prefix = prefix ? `${prefix.toUpperCase()}_` : '' + return ` +#ifndef _${prefix}${getModuleName(json).toUpperCase()}_H +#define _${prefix}${getModuleName(json).toUpperCase()}_H + +` +} + +const getStyleGuardOpen = () => { + return ` +#ifdef __cplusplus +extern "C" { +#endif + +` +} + +const getStyleGuardClose = () => { + return ` + +#ifdef __cplusplus +} +#endif + +` +} + +const getIncludeGuardClose = () => { + return ` +#endif // Header Include Guard +` +} + +const capitalize = str => str[0].toUpperCase() + str.substr(1) +const description = (title, str='') => '/* ' + title + (str.length > 0 ? ' - ' + str : '') + ' */' +const isOptional = (prop, json) => (!json.required || !json.required.includes(prop)) + +const SdkTypesPrefix = 'Firebolt' + +const Indent = ' ' + +const getNativeType = json => { + let type + + if (json.const) { + if (typeof json.const === 'string') { + type = 'char*' + } + else if (typeof json.const === 'number') { + type = 'uint32_t' + if (json.const < 0) + type = 'int32_t' + } else if (typeof json.const === 'boolean'){ + type = 'bool' + } + } + else if (json.type === 'string') { + type = 'char*' + } + else if (json.type === 'number' || json.type === 'integer') { //Lets keep it simple for now + type = 'uint32_t' + if ((json.minimum && json.minimum < 0) + || (json.exclusiveMinimum && json.exclusiveMinimum < 0)) { + type = 'int32_t' + } + } + else if (json.type === 'boolean') { + type = 'bool' + } + return type +} + +const getObjectHandleManagement = varName => { + + let result = `typedef void* ${varName}Handle; +${varName}Handle ${varName}Handle_Create(void); +void ${varName}Handle_Addref(${varName}Handle handle); +void ${varName}Handle_Release(${varName}Handle handle); +bool ${varName}Handle_IsValid(${varName}Handle handle); +` + return result +} + +const getPropertyAccessors = (objName, propertyName, propertyType, options = {level:0, readonly:false, optional:false}) => { + + let result = `${Indent.repeat(options.level)}${propertyType} ${objName}_Get_${propertyName}(${objName}Handle handle);` + '\n' + + if (!options.readonly) { + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${propertyType} ${propertyName.toLowerCase()});` + '\n' + } + + if (options.optional === true) { + result += `${Indent.repeat(options.level)}bool ${objName}_has_${propertyName}(${objName}Handle handle);` + '\n' + result += `${Indent.repeat(options.level)}void ${objName}_clear_${propertyName}(${objName}Handle handle);` + '\n' + } + + return result +} + +const getMapAccessors = (typeName, nativeType, level=0) => { + + let res + + res = `${Indent.repeat(level)}uint32_t ${typeName}_KeysCount(${typeName}Handle handle);` + '\n' + res += `${Indent.repeat(level)}void ${typeName}_AddKey(${typeName}Handle handle, char* key, ${nativeType} value);` + '\n' + res += `${Indent.repeat(level)}void ${typeName}_RemoveKey(${typeName}Handle handle, char* key);` + '\n' + res += `${Indent.repeat(level)}${nativeType} ${typeName}_FindKey(${typeName}Handle handle, char* key);` + '\n' + + return res +} + +const getTypeName = (moduleName, varName, upperCase = false) => { + let mName = upperCase ? moduleName.toUpperCase() : capitalize(moduleName) + let vName = upperCase ? varName.toUpperCase() : capitalize(varName) + + return `${mName}_${vName}` +} + +const getArrayAccessors = (arrayName, valueType) => { + + let res = `uint32_t ${arrayName}_Size(${arrayName}Handle handle);` + '\n' + res += `${valueType} ${arrayName}_Get(${arrayName}Handle handle, uint32_t index);` + '\n' + res += `void ${arrayName}_Add(${arrayName}Handle handle, ${valueType} value);` + '\n' + res += `void ${arrayName}_Clear(${arrayName}Handle handle);` + '\n' + + return res +} + +const enumValue = (val,prefix) => { + const keyName = val.replace(/[\.\-:]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + return ` ${prefix.toUpperCase()}_${keyName.toUpperCase()}` +} + +const generateEnum = (schema, prefix)=> { + if (!schema.enum) { + return '' + } + else { + let str = `typedef enum {\n` + str += schema.enum.map(e => enumValue(e, prefix)).join(',\n') + str += `\n} ${prefix};\n` + return str + } +} + +const getIncludeDefinitions = (json = {}, jsonData = false) => { + return getExternalSchemaPaths(json) + .map(ref => { + const mod = ref.split('#')[0].split('/').pop() + let i = `#include "Common/${capitalize(mod)}.h"` + if(jsonData === true) { + i += '\n' + `#include "JsonData_${capitalize(mod)}.h"` + } + return i + }) + .filter((item, index, arr) => arr.indexOf(item) === index) + .concat([`#include "Firebolt/Types.h"`]) +} + +function getSchemaType(module = {}, json = {}, name = '', schemas = {}, options = {level: 0, descriptions: true, title: false}) { + if (json.schema) { + json = json.schema + } + + let structure = {} + structure["deps"] = new Set() //To avoid duplication of local ref definitions + structure["type"] = [] + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(json['$ref'], module, schemas) + let tName = definition.title || json['$ref'].split('/').pop() + const res = getSchemaType(module, definition, tName, schemas, {descriptions: options.descriptions, level: options.level}) + res.deps.forEach(dep => structure.deps.add(dep)) + structure.type = res.type + return structure + } + else { + // External dependency. + // e.g, "https://meta.comcast.com/firebolt/entertainment#/definitions/ProgramType" + + //Get the module of this definition + const schema = getPath(json['$ref'].split('#')[0], schemas) || module + + //Get the schema of the definition + const definition = getPath(json['$ref'], module, schemas) + let tName = definition.title || json['$ref'].split('/').pop() + const res = getSchemaType(schema, definition, tName, schemas, {descriptions: options.descriptions, level: options.level}) + //We are only interested in the type definition for external modules + structure.type = res.type + return structure + } + } + else if (json.const) { + structure.type = getNativeType(json) + return structure + } + else if (json['x-method']) { + console.log(`WARNING UNHANDLED: x-method in ${name}`) + return structure + //throw "x-methods not supported yet" + } + else if (json.type === 'string' && json.enum) { + //Enum + let typeName = getTypeName(getModuleName(module), name || json.title) + let res = description(capitalize(name || json.title), json.description) + '\n' + generateEnum(json, typeName) + structure.deps.add(res) + structure.type.push(typeName) + return structure + } + else if (Array.isArray(json.type)) { + let type = json.type.find(t => t !== 'null') + console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) + } + else if (json.type === 'array' && json.items) { + let res + if (Array.isArray(json.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(json.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getSchemaType(module, json.items[0],'',schemas) + } + else { + // grab the type for the non-array schema + res = getSchemaType(module, json.items, '', schemas) + } + + res.deps.forEach(dep => structure.deps.add(dep)) + let n = getTypeName(getModuleName(module), name || json.title) + let def = description(name || json.title, json.description) + '\n' + if (options.level === 0) { + def += getObjectHandleManagement(n + 'Array') + '\n' + } + def += getArrayAccessors(n + 'Array', res.type) + structure.deps.add(def) + structure.type.push(n + 'ArrayHandle') + return structure + } + else if (json.allOf) { + let union = deepmerge.all([...json.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)]) + if (json.title) { + union['title'] = json.title + } + else { + union['title'] = name + } + delete union['$ref'] + return getSchemaType(module, union, '',schemas, options) + } + else if (json.oneOf || json.anyOf) { + return structure + //TODO + } + else if (json.type === 'object') { + let res = getSchemaShape(module, json, schemas, json.title || name, {descriptions: options.descriptions, level: 0}) + res.deps.forEach(dep => structure.deps.add(dep)) + res.type.forEach(t => structure.deps.add(t)) + structure.type.push(getTypeName(getModuleName(module), json.title || name) + 'Handle') + return structure + //TODO + } + else if (json.type) { + structure.type = getNativeType(json) + return structure + } + return structure +} + +function getSchemaShape(moduleJson = {}, json = {}, schemas = {}, name = '', options = {level: 0, descriptions: true}) { + json = JSON.parse(JSON.stringify(json)) + let level = options.level + let descriptions = options.descriptions + + let structure = {} + structure["deps"] = new Set() //To avoid duplication of local ref definitions + structure["type"] = [] + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + + const schema = getPath(json['$ref'], module, schemas) + const tname = schema.title || json['$ref'].split('/').pop() + res = getSchemaShape(module, schema, schemas, tname, {descriptions: descriptions, level: level}) + res.deps.forEach(dep => structure.deps.add(dep)) + structure.type = res.type + } + else { + // External dependency. Return only type + // e.g, "https://meta.comcast.com/firebolt/entertainment#/definitions/ProgramType" + + //Get the module of this definition + const schema = getPath(json['$ref'].split('#')[0], schemas) || module + + //Get the schema of the definition + const definition = getPath(json['$ref'], schema, schemas) + const pname = (json.title || name) + (definition.title || json['$ref'].split('/').pop()) + + res = getSchemaShape(schema, definition, schemas, pname,{descriptions: descriptions, level: level}) + //We are only interested in the type definition for external modules + structure.type = res.type + } + } + //If the schema is a const, + else if (json.hasOwnProperty('const')) { + if (level > 0) { + + let t = description(name, json.description) + typeName = getTypeName(getModuleName(moduleJson), name) + t += getPropertyAccessors(typeName, capitalize(name), typeof json.const, {level: level, readonly:true, optional:false}) + structure.type.push(t) + } + } + else if (json.type === 'object') { + + if (json.properties) { + let tName = getTypeName(getModuleName(moduleJson), name) + let t = description(name, json.description) + t += '\n' + getObjectHandleManagement(tName) + Object.entries(json.properties).forEach(([pname, prop]) => { + t += '\n' + description(pname, prop.description) + let res + if (prop.type === 'array') { + if (Array.isArray(prop.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(prop.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getSchemaType(moduleJson, prop.items[0],pname, schemas, {level : options.level, descriptions: options.descriptions, title: true}) + } + else { + // grab the type for the non-array schema + res = getSchemaType(moduleJson, prop.items, pname, schemas, {level : options.level, descriptions: options.descriptions, title: true}) + } + if (res.type && res.type.length > 0) { + let n = tName + '_' + capitalize(pname || prop.title) + let def = getArrayAccessors(n + 'Array', res.type) + t += '\n' + def + } + else { + console.log(`WARNING: Type undetermined for ${name}:${pname}`) + } + } else { + res = getSchemaType(moduleJson, prop, pname,schemas, {descriptions: descriptions, level: level + 1, title: true}) + if (res.type && res.type.length > 0) { + t += '\n' + getPropertyAccessors(tName, capitalize(pname), res.type, {level: level, readonly:false, optional:isOptional(pname, json)}) + } + else { + console.log(`WARNING: Type undetermined for ${name}:${pname}`) + } + } + res.deps.forEach(dep => structure.deps.add(dep)) + }) + structure.type.push(t) + } + else if (json.propertyNames && json.propertyNames.enum) { + //propertyNames in object not handled yet + } + else if (json.additionalProperties && (typeof json.additionalProperties === 'object')) { + //This is a map of string to type in schema + //Get the Type + let type = getSchemaType(moduleJson, json.additionalProperties, name,schemas) + if (type.type && type.type.length > 0) { + let tName = getTypeName(getModuleName(moduleJson), name) + type.deps.forEach(dep => structure.deps.add(dep)) + let t = description(name, json.description) + t += '\n' + getObjectHandleManagement(tName) + '\n' + t += getMapAccessors(getTypeName(getModuleName(moduleJson), name), type.type,{descriptions: descriptions, level: level}) + structure.type.push(t) + } + else { + console.log(`WARNING: Type undetermined for ${name}`) + } + } + else if (json.patternProperties) { + throw "patternProperties are not supported by Firebolt" + } + } + else if (json.anyOf) { + + } + else if (json.oneOf) { + + } + else if (json.allOf) { + let union = deepmerge.all([...json.allOf.map(x => x['$ref'] ? getPath(x['$ref'], moduleJson, schemas) || x : x)], options) + if (json.title) { + union['title'] = json.title + } + else { + union['title'] = name + } + delete union['$ref'] + return getSchemaShape(moduleJson, union, schemas, name, options) + + } + else if (json.type === 'array') { + let res = getSchemaType(moduleJson, json, name, schemas, {level: 0, descriptions: descriptions}) + res.deps.forEach(dep => structure.deps.add(dep)) + } + else { + let res = getSchemaType(moduleJson, json, name, schemas, {level: level, descriptions: descriptions}) + res.deps.forEach(dep => structure.deps.add(dep)) + } + return structure + } + + function getPropertyGetterSignature(method, module, paramType) { + let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` + return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` + } + + function getPropertySetterSignature(method, module, paramType) { + let m = `${capitalize(getModuleName(module))}_Set${capitalize(method.name)}` + return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType} ${method.result.name || method.name} )` + } + + function getPropertyEventCallbackSignature(method, module, paramType) { + return `typedef void (*On${capitalize(method.name)}Changed)(${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType})` + } + + function getPropertyEventSignature(method, module) { + return `${description(method.name, 'Listen to updates')}\n` + `uint32_t ${capitalize(getModuleName(module))}_Listen${capitalize(method.name)}Update(On${capitalize(method.name)}Changed notification, uint16_t* listenerId)` + } + + export { + getHeaderText, + getIncludeGuardOpen, + getStyleGuardOpen, + getStyleGuardClose, + getIncludeGuardClose, + getNativeType, + getSchemaType, + getSchemaShape, + getModuleName, + getIncludeDefinitions, + getPropertyGetterSignature, + getPropertySetterSignature, + getPropertyEventCallbackSignature, + getPropertyEventSignature, + capitalize, + description, + getTypeName + } diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c new file mode 100644 index 00000000..7d10ba97 --- /dev/null +++ b/languages/c/templates/methods/default.c @@ -0,0 +1,24 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.title}_${method.Name}(${method.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { + uint32_t status = FireboltSDKErrorUnavailable; + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + + JsonObject jsonParameters; + + ${if.params} +${method.params.json} + ${end.if.params} + + WPEFramework::Core::JSON::Boolean jsonResult; + status = transport->Invoke("${info.title}.${method.name}", jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + *success = jsonResult.Value(); + } + + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; +} \ No newline at end of file diff --git a/languages/c/templates/methods/default.js b/languages/c/templates/methods/default.js deleted file mode 100644 index 0c7f799b..00000000 --- a/languages/c/templates/methods/default.js +++ /dev/null @@ -1,7 +0,0 @@ - -function ${method.name}(${method.params.list}) { - - const transforms = ${method.transforms} - - return Transport.send('${info.title}', '${method.name}', { ${method.params.list} }, transforms) -} \ No newline at end of file diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c new file mode 100644 index 00000000..8f301bea --- /dev/null +++ b/languages/c/templates/methods/property.c @@ -0,0 +1,12 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.title}_Get${method.Name}(${method.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { + const string method = _T("${info.title}.${method.name}"); + FireboltSDK::${info.title}::${method.result.type} jsonResult; + + uint32_t status = FireboltSDK::Properties::Get(method, jsonResult); + if (status == FireboltSDKErrorNone) { + WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); + *${method.result.name} = static_cast<${info.title}_${method.result.type}Handle>(resultPtr); + } + return status; +} diff --git a/languages/c/templates/modules/include/Common/Module.h b/languages/c/templates/modules/include/Common/Module.h index 4cee1781..22c25143 100644 --- a/languages/c/templates/modules/include/Common/Module.h +++ b/languages/c/templates/modules/include/Common/Module.h @@ -16,8 +16,19 @@ * SPDX-License-Identifier: Apache-2.0 */ -namespace FireboltSDK { +#ifndef _COMMON_${info.TITLE}_H +#define _COMMON_${info.TITLE}_H - /* ${DECLARATIONS} */ +#include "Firebolt.h" +#ifdef __cplusplus +extern "C" { +#endif + + /* ${SCHEMAS} */ + +#ifdef __cplusplus } +#endif + +#endif // Header Include Guard \ No newline at end of file diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h index 60a75f5f..92bab4f7 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/Module.h @@ -16,10 +16,22 @@ * SPDX-License-Identifier: Apache-2.0 */ -namespace FireboltSDK { +#ifndef _${info.TITLE}_H +#define _${info.TITLE}_H + +#include "Firebolt.h" +#include "Common/${info.title}.h" + +#ifdef __cplusplus +extern "C" { +#endif /* ${SCHEMAS} */ /* ${DECLARATIONS} */ +#ifdef __cplusplus } +#endif + +#endif // Header Include Guard \ No newline at end of file diff --git a/languages/c/templates/modules/src/JsonData_Module.h b/languages/c/templates/modules/src/JsonData_Module.h index 4cee1781..2c7ca8c8 100644 --- a/languages/c/templates/modules/src/JsonData_Module.h +++ b/languages/c/templates/modules/src/JsonData_Module.h @@ -16,8 +16,14 @@ * SPDX-License-Identifier: Apache-2.0 */ +#pragma once + +#include "Firebolt.h" + namespace FireboltSDK { + namespace ${info.title} { - /* ${DECLARATIONS} */ + /* ${SCHEMAS}} */ + } } diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 26a26050..2417f708 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -16,14 +16,17 @@ * SPDX-License-Identifier: Apache-2.0 */ -/* ${IMPORTS} */ +#include "FireboltSDK.h" +#include "${info.title}.h" +#include "Common/${info.title}.h" +#include "JsonData_${info.title}.h" +#ifdef __cplusplus +extern "C" { +#endif -namespace FireboltSDK { - - namespace ${info.title} { + /* ${METHODS} */ - /* ${METHODS} */ - - } +#ifdef __cplusplus } +#endif diff --git a/languages/c/templates/modules/src/Module_Common.cpp b/languages/c/templates/modules/src/Module_Common.cpp index 8460c52a..bce775ff 100644 --- a/languages/c/templates/modules/src/Module_Common.cpp +++ b/languages/c/templates/modules/src/Module_Common.cpp @@ -16,11 +16,16 @@ * SPDX-License-Identifier: Apache-2.0 */ -/* ${IMPORTS} */ - - -namespace FireboltSDK { +#include "FireboltSDK.h" +#include "Common/${info.title}.h" +#include "JsonData_${info.title}.h" +} +#ifdef __cplusplus +extern "C" { +#endif - /* ${METHODS} */ + /* ${SCHEMAS}} */ +#ifdef __cplusplus } +#endif \ No newline at end of file diff --git a/languages/c/templates/parameters/default.c b/languages/c/templates/parameters/default.c new file mode 100644 index 00000000..e6e3b8ba --- /dev/null +++ b/languages/c/templates/parameters/default.c @@ -0,0 +1 @@ +${method.param.type} ${method.param.name} \ No newline at end of file diff --git a/languages/c/templates/parameters/default.js b/languages/c/templates/parameters/default.js deleted file mode 100644 index 916a8adf..00000000 --- a/languages/c/templates/parameters/default.js +++ /dev/null @@ -1 +0,0 @@ -${method.params.list} \ No newline at end of file diff --git a/languages/c/templates/parameters/json.c b/languages/c/templates/parameters/json.c new file mode 100644 index 00000000..5ee36bec --- /dev/null +++ b/languages/c/templates/parameters/json.c @@ -0,0 +1,3 @@ + ${json.param.type} ${method.param.Name} = ${method.param.name}; + jsonParameters.Add("_T(${method.param.name})", &${method.param.Name}); + diff --git a/languages/javascript/templates/methods/property.js b/languages/javascript/templates/methods/property.js index df748ecd..0b1e1359 100644 --- a/languages/javascript/templates/methods/property.js +++ b/languages/javascript/templates/methods/property.js @@ -1,4 +1,4 @@ function ${method.name}(${method.params.list}) { const callbackOrValue = arguments[${method.params.count}] - return Prop.prop('${info.title}', '${method.name}', { ${method.params} }, callbackOrValue, ${method.property.immutable}, ${method.property.readonly}, ${method.params.count}) + return Prop.prop('${info.title}', '${method.name}', { ${method.params.list} }, callbackOrValue, ${method.property.immutable}, ${method.property.readonly}, ${method.params.count}) } \ No newline at end of file diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index cc2f9051..77541d85 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -51,7 +51,8 @@ let types = { getMethodSignature: ()=>null, getMethodSignatureParams: ()=>null, getSchemaShape: ()=>null, - getSchemaType: ()=>null + getSchemaType: ()=>null, + getJsonType: ()=>null } let config = { @@ -877,12 +878,15 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { } } + const paramDelimiter = config.operators ? config.operators.paramDelimiter : ', ' + const temporalItemName = isTemporalSetMethod(methodObj) ? methodObj.result.schema.items && methodObj.result.schema.items.title || 'Item' : '' const temporalAddName = isTemporalSetMethod(methodObj) ? `on${temporalItemName}Available` : '' const temporalRemoveName = isTemporalSetMethod(methodObj) ? `on${temporalItemName}Unvailable` : '' - const params = methodObj.params && methodObj.params.length ? getTemplate('/sections/parameters', templates) + methodObj.params.map(p => insertParameterMacros(getTemplate('/parameters/default', templates), p, methodObj, json)).join('') : '' + const params = methodObj.params && methodObj.params.length ? getTemplate('/sections/parameters', templates) + methodObj.params.map(p => insertParameterMacros(getTemplate('/parameters/default', templates), p, methodObj, json)).join(paramDelimiter) : '' const paramsRows = methodObj.params && methodObj.params.length ? methodObj.params.map(p => insertParameterMacros(getTemplate('/parameters/default', templates), p, methodObj, json)).join('') : '' const paramsAnnotations = methodObj.params && methodObj.params.length ? methodObj.params.map(p => insertParameterMacros(getTemplate('/parameters/annotations', templates), p, methodObj, json)).join('') : '' + const paramsJson = methodObj.params && methodObj.params.length ? methodObj.params.map(p => insertParameterMacros(getTemplate('/parameters/json', templates), p, methodObj, json)).join('') : '' const deprecated = methodObj.tags && methodObj.tags.find(t => t.name === 'deprecated') const deprecation = deprecated ? deprecated['x-since'] ? `since version ${deprecated['x-since']}` : '' : '' @@ -945,10 +949,11 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{method\.params\}/g, params) .replace(/\$\{method\.params\.table\.rows\}/g, paramsRows) .replace(/\$\{method\.params\.annotations\}/g, paramsAnnotations) + .replace(/\$\{method\.params\.json\}/g, paramsJson) .replace(/\$\{method\.params\.list\}/g, method.params) .replace(/\$\{method\.params\.array\}/g, JSON.stringify(methodObj.params.map(p => p.name))) .replace(/\$\{method\.params\.count}/g, methodObj.params ? methodObj.params.length : 0) - .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/g, method.params.length ? '$1' : '') + .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/gms, method.params.length ? '$1' : '') .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event.params.length ? '$1' : '') // Typed signature stuff .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination })) @@ -962,6 +967,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{event\.params\.table\.rows\}/g, eventParamsRows) .replace(/\$\{event\.signature\.params\}/g, types.getMethodSignatureParams(event, json, { destination: state.destination })) .replace(/\$\{info\.title\}/g, info.title) + .replace(/\$\{info\.TITLE\}/g, info.title.toUpperCase()) .replace(/\$\{method\.property\.immutable\}/g, hasTag(methodObj, 'property:immutable')) .replace(/\$\{method\.property\.readonly\}/g, !getSetterFor(methodObj.name, json)) .replace(/\$\{method\.temporalset\.add\}/g, temporalAddName) @@ -974,8 +980,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{method\.result\.name\}/g, result.name) .replace(/\$\{method\.result\.summary\}/g, result.summary) .replace(/\$\{method\.result\.link\}/g, getLinkForSchema(result, json)) //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result, json, {title: true, asPath: false, destination: state.destination })) //, baseUrl: options.baseUrl - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result, json, { destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result.schema, json, {title: true, asPath: false, destination: state.destination })) //, baseUrl: options.baseUrl + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates)) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) @@ -1153,20 +1159,23 @@ 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, module, { destination: state.destination, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl + let type = types.getSchemaType(param.schema, module, { destination: state.destination, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl let typeLink = getLinkForSchema(param, module) + let jsonType = types.getJsonType(param.schema, module, { destination: state.destination, code: false, link: false, title: true, asPath: false, expandEnums: false }) if (constraints && type) { constraints = '
' + constraints } return template - .replace(/\$\{method.param.name\}/, param.name) - .replace(/\$\{method.param.summary\}/, param.summary || '') - .replace(/\$\{method.param.required\}/, param.required || 'false') - .replace(/\$\{method.param.type\}/, type) //getType(param)) - .replace(/\$\{method.param.link\}/, getLinkForSchema(param, module)) //getType(param)) - .replace(/\$\{method.param.constraints\}/, constraints) //getType(param)) + .replace(/\$\{method.param.name\}/g, param.name) + .replace(/\$\{method.param.Name\}/g, param.name[0].toUpperCase() + param.name.substring(1)) + .replace(/\$\{method.param.summary\}/g, param.summary || '') + .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, module)) //getType(param)) + .replace(/\$\{method.param.constraints\}/g, constraints) //getType(param)) } function insertCapabilityMacros(template, capabilities, method, module) { diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 89c194e2..29cf7ba4 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -68,10 +68,13 @@ const macrofy = async ( let typer try { + console.log(path.join(sharedTemplates, '..', 'Types.mjs')) const typerModule = await import(path.join(sharedTemplates, '..', 'Types.mjs')) typer = typerModule.default } catch (_) { + console.log("Using default Typer") + console.dir(_) typer = (await import('../shared/typescript.mjs')).default } diff --git a/src/shared/typescript.mjs b/src/shared/typescript.mjs index aa6e21f5..e53747cd 100644 --- a/src/shared/typescript.mjs +++ b/src/shared/typescript.mjs @@ -199,10 +199,6 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, } function getSchemaType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - if (schema.schema) { - schema = schema.schema - } - const wrap = (str, wrapper) => wrapper + str + wrapper if (schema['$ref']) { @@ -327,6 +323,10 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, return wrap('void', code ? '`' : '') } } + + function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + return '' + } function getTypeScriptType(jsonType) { if (jsonType === 'integer') { @@ -350,5 +350,6 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, getMethodSignature, getMethodSignatureParams, getSchemaShape, - getSchemaType + getSchemaType, + getJsonType } \ No newline at end of file From dcc5d6be3bd9440ce7bdbbe4905c1474e022fb7d Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 26 Apr 2023 14:43:51 -0400 Subject: [PATCH 003/137] chore: Dropped debug logs --- src/macrofier/index.mjs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 29cf7ba4..89c194e2 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -68,13 +68,10 @@ const macrofy = async ( let typer try { - console.log(path.join(sharedTemplates, '..', 'Types.mjs')) const typerModule = await import(path.join(sharedTemplates, '..', 'Types.mjs')) typer = typerModule.default } catch (_) { - console.log("Using default Typer") - console.dir(_) typer = (await import('../shared/typescript.mjs')).default } From 64688fa58d4c8665c557266d8a368e2fe8ca7b65 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 26 Apr 2023 14:49:28 -0400 Subject: [PATCH 004/137] fix: Stop passing non-schemas in to getSchemaType --- src/macrofier/engine.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 77541d85..6404a059 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -1007,7 +1007,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const matches = [...template.matchAll(/\$\{method\.params\[([0-9]+)\]\.type\}/g)] matches.forEach(match => { const index = parseInt(match[1]) - template = template.replace(/\$\{method\.params\[([0-9]+)\]\.type\}/g, types.getSchemaType(methodObj.params[index], json, { destination: state.destination })) + template = template.replace(/\$\{method\.params\[([0-9]+)\]\.type\}/g, types.getSchemaType(methodObj.params[index].schema, json, { destination: state.destination })) template = template.replace(/\$\{method\.params\[([0-9]+)\]\.name\}/g, methodObj.params[index].name) }) From bc47db57c3c168a618744fbc4fc6392b5bc20b99 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Fri, 28 Apr 2023 12:44:35 -0400 Subject: [PATCH 005/137] feat(accessors): New macro section for schema property accessors --- languages/c/Types.mjs | 397 ++++++-- languages/c/src/types/CommonCppTypes.mjs | 60 -- languages/c/src/types/CommonHeaderTypes.mjs | 55 -- languages/c/src/types/CppTypes.mjs | 55 -- languages/c/src/types/HeaderTypes.mjs | 55 -- languages/c/src/types/ImplHelpers.mjs | 294 ++++++ languages/c/src/types/JSONHelpers.mjs | 61 ++ languages/c/src/types/JSONTypes.mjs | 56 -- languages/c/src/types/NativeHelpers.mjs | 264 +----- .../codeblocks/{export.mjs => export.c} | 0 .../{mock-import.mjs => mock-import.c} | 0 .../{mock-parameter.mjs => mock-parameter.c} | 0 .../clear.js => codeblocks/module.c} | 0 languages/c/templates/codeblocks/module.mjs | 11 - .../declarations/{listen.js => clear.c} | 0 .../declarations/{default.js => default.c} | 2 +- .../declarations/{once.js => listen.c} | 0 .../declarations/{provide.js => once.c} | 0 ...rphic-reducer.js => polymorphic-reducer.c} | 0 .../declarations/{rpc-only.js => provide.c} | 0 .../listen.js => declarations/rpc-only.c} | 0 .../defaults/{default.mjs => default.c} | 0 .../defaults/{property.mjs => property.c} | 0 languages/c/templates/examples/default.md | 6 - languages/c/templates/examples/event.md | 5 - .../examples/polymorphic-pull-event.md | 9 - .../c/templates/examples/polymorphic-pull.md | 6 - languages/c/templates/examples/provider.md | 10 - languages/c/templates/examples/setter.md | 6 - languages/c/templates/examples/subscriber.md | 7 - languages/c/templates/examples/synchronous.md | 4 - .../c/templates/examples/temporal-set.md | 13 - .../c/templates/imports/context-event.mjs | 1 - languages/c/templates/imports/default.c | 1 + languages/c/templates/imports/event.mjs | 2 - languages/c/templates/imports/property.mjs | 1 - languages/c/templates/imports/provider.mjs | 2 - languages/c/templates/imports/rpc.mjs | 1 - .../c/templates/imports/temporal-set.mjs | 1 - languages/c/templates/imports/x-method.mjs | 1 - .../templates/initializations/deprecated.mjs | 1 - .../c/templates/initializations/event.mjs | 1 - .../c/templates/initializations/provider.mjs | 1 - languages/c/templates/methods/default.c | 2 +- .../c/templates/methods/{once.js => listen.c} | 0 .../templates/methods/{rpc-only.js => once.c} | 0 ...rphic-reducer.js => polymorphic-reducer.c} | 0 .../methods/{provide.js => provide.c} | 0 languages/c/templates/methods/rpc-only.c | 0 .../templates/modules/include/Common/Module.h | 6 + .../c/templates/modules/include/Module.h | 3 +- languages/c/templates/modules/src/Module.cpp | 11 +- .../schemas/{default.js => default.c} | 0 .../templates/schemas/include/Common/Module.h | 21 +- .../c/templates/schemas/src/Module_Common.cpp | 14 +- languages/c/templates/sdk/CMakeLists.txt | 49 + .../c/templates/sdk/build/CMakeCache.txt | 407 ++++++++ .../CMakeFiles/3.25.3/CMakeCCompiler.cmake | 72 ++ .../CMakeFiles/3.25.3/CMakeCXXCompiler.cmake | 83 ++ .../3.25.3/CMakeDetermineCompilerABI_C.bin | Bin 0 -> 16999 bytes .../3.25.3/CMakeDetermineCompilerABI_CXX.bin | Bin 0 -> 16983 bytes .../build/CMakeFiles/3.25.3/CMakeSystem.cmake | 15 + .../3.25.3/CompilerIdC/CMakeCCompilerId.c | 868 +++++++++++++++++ .../3.25.3/CompilerIdC/CMakeCCompilerId.o | Bin 0 -> 1712 bytes .../CompilerIdCXX/CMakeCXXCompilerId.cpp | 857 +++++++++++++++++ .../3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o | Bin 0 -> 1712 bytes .../sdk/build/CMakeFiles/CMakeError.log | 0 .../sdk/build/CMakeFiles/CMakeOutput.log | 266 ++++++ .../sdk/build/CMakeFiles/cmake.check_cache | 1 + .../c/templates/sdk/cmake/CopySymlink.cmake | 17 + .../templates/sdk/cmake/HelperFunctions.cmake | 139 +++ .../c/templates/sdk/cmake/project.cmake.in | 30 + languages/c/templates/sdk/include/Error.h | 41 + languages/c/templates/sdk/include/Types.h | 43 + languages/c/templates/sdk/scripts/install.js | 32 + .../c/templates/sdk/src/Accessor/Accessor.cpp | 134 +++ .../c/templates/sdk/src/Accessor/Accessor.h | 79 ++ .../c/templates/sdk/src/Accessor/Config.h | 41 + .../c/templates/sdk/src/Accessor/WorkerPool.h | 72 ++ languages/c/templates/sdk/src/CMakeLists.txt | 93 ++ languages/c/templates/sdk/src/Config.cmake | 34 + languages/c/templates/sdk/src/Event/Event.cpp | 148 +++ languages/c/templates/sdk/src/Event/Event.h | 154 +++ languages/c/templates/sdk/src/Firebolt.h | 25 + .../c/templates/sdk/src/FireboltSDK.conf.in | 3 + .../c/templates/sdk/src/Logger/Logger.cpp | 84 ++ languages/c/templates/sdk/src/Logger/Logger.h | 85 ++ .../templates/{schemas => sdk}/src/Module.cpp | 12 +- .../templates/sdk/{main.cpp => src/Module.h} | 21 +- languages/c/templates/sdk/src/Params.config | 3 + .../templates/sdk/src/Properties/Properties.h | 90 ++ .../src/Transport/Transport.cpp} | 5 +- .../c/templates/sdk/src/Transport/Transport.h | 897 ++++++++++++++++++ languages/c/templates/sdk/src/Types.cpp | 41 + languages/c/templates/sdk/src/TypesPriv.h | 55 ++ .../templates/sdk/src/cmake/CopySymlink.cmake | 1 + languages/c/templates/sdk/test/CMakeLists.txt | 86 ++ languages/c/templates/sdk/test/Main.c | 44 + languages/c/templates/sdk/test/Module.cpp | 21 + .../Module_Common.cpp => sdk/test/Module.h} | 18 +- .../c/templates/sdk/test/OpenRPCCTests.h | 42 + .../c/templates/sdk/test/OpenRPCTests.cpp | 385 ++++++++ languages/c/templates/sdk/test/OpenRPCTests.h | 99 ++ languages/c/templates/sdk/test/TestUtils.h | 38 + languages/c/templates/sections/accessors.c | 3 + .../{declarations.js => declarations.c} | 0 .../sections/{events.js => events.c} | 0 .../sections/{methods.js => methods.c} | 0 ...er-interfaces.js => provider-interfaces.c} | 0 languages/c/templates/sections/schemas.c | 3 + .../sections/{schemas.js => types.c} | 0 languages/c/templates/types/enum.c | 3 + languages/c/templates/types/enum.mjs | 3 - src/macrofier/engine.mjs | 73 +- 114 files changed, 6485 insertions(+), 776 deletions(-) delete mode 100644 languages/c/src/types/CommonCppTypes.mjs delete mode 100644 languages/c/src/types/CommonHeaderTypes.mjs delete mode 100644 languages/c/src/types/CppTypes.mjs delete mode 100644 languages/c/src/types/HeaderTypes.mjs create mode 100644 languages/c/src/types/ImplHelpers.mjs create mode 100644 languages/c/src/types/JSONHelpers.mjs delete mode 100644 languages/c/src/types/JSONTypes.mjs rename languages/c/templates/codeblocks/{export.mjs => export.c} (100%) rename languages/c/templates/codeblocks/{mock-import.mjs => mock-import.c} (100%) rename languages/c/templates/codeblocks/{mock-parameter.mjs => mock-parameter.c} (100%) rename languages/c/templates/{declarations/clear.js => codeblocks/module.c} (100%) delete mode 100644 languages/c/templates/codeblocks/module.mjs rename languages/c/templates/declarations/{listen.js => clear.c} (100%) rename languages/c/templates/declarations/{default.js => default.c} (68%) rename languages/c/templates/declarations/{once.js => listen.c} (100%) rename languages/c/templates/declarations/{provide.js => once.c} (100%) rename languages/c/templates/declarations/{polymorphic-reducer.js => polymorphic-reducer.c} (100%) rename languages/c/templates/declarations/{rpc-only.js => provide.c} (100%) rename languages/c/templates/{methods/listen.js => declarations/rpc-only.c} (100%) rename languages/c/templates/defaults/{default.mjs => default.c} (100%) rename languages/c/templates/defaults/{property.mjs => property.c} (100%) delete mode 100644 languages/c/templates/examples/default.md delete mode 100644 languages/c/templates/examples/event.md delete mode 100644 languages/c/templates/examples/polymorphic-pull-event.md delete mode 100644 languages/c/templates/examples/polymorphic-pull.md delete mode 100644 languages/c/templates/examples/provider.md delete mode 100644 languages/c/templates/examples/setter.md delete mode 100644 languages/c/templates/examples/subscriber.md delete mode 100644 languages/c/templates/examples/synchronous.md delete mode 100644 languages/c/templates/examples/temporal-set.md delete mode 100644 languages/c/templates/imports/context-event.mjs create mode 100644 languages/c/templates/imports/default.c delete mode 100644 languages/c/templates/imports/event.mjs delete mode 100644 languages/c/templates/imports/property.mjs delete mode 100644 languages/c/templates/imports/provider.mjs delete mode 100644 languages/c/templates/imports/rpc.mjs delete mode 100644 languages/c/templates/imports/temporal-set.mjs delete mode 100644 languages/c/templates/imports/x-method.mjs delete mode 100644 languages/c/templates/initializations/deprecated.mjs delete mode 100644 languages/c/templates/initializations/event.mjs delete mode 100644 languages/c/templates/initializations/provider.mjs rename languages/c/templates/methods/{once.js => listen.c} (100%) rename languages/c/templates/methods/{rpc-only.js => once.c} (100%) rename languages/c/templates/methods/{polymorphic-reducer.js => polymorphic-reducer.c} (100%) rename languages/c/templates/methods/{provide.js => provide.c} (100%) create mode 100644 languages/c/templates/methods/rpc-only.c rename languages/c/templates/schemas/{default.js => default.c} (100%) create mode 100644 languages/c/templates/sdk/CMakeLists.txt create mode 100644 languages/c/templates/sdk/build/CMakeCache.txt create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake create mode 100755 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin create mode 100755 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_CXX.bin create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeSystem.cmake create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.c create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.cpp create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o create mode 100644 languages/c/templates/sdk/build/CMakeFiles/CMakeError.log create mode 100644 languages/c/templates/sdk/build/CMakeFiles/CMakeOutput.log create mode 100644 languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache create mode 100644 languages/c/templates/sdk/cmake/CopySymlink.cmake create mode 100644 languages/c/templates/sdk/cmake/HelperFunctions.cmake create mode 100644 languages/c/templates/sdk/cmake/project.cmake.in create mode 100644 languages/c/templates/sdk/include/Error.h create mode 100644 languages/c/templates/sdk/include/Types.h create mode 100644 languages/c/templates/sdk/scripts/install.js create mode 100644 languages/c/templates/sdk/src/Accessor/Accessor.cpp create mode 100644 languages/c/templates/sdk/src/Accessor/Accessor.h create mode 100644 languages/c/templates/sdk/src/Accessor/Config.h create mode 100644 languages/c/templates/sdk/src/Accessor/WorkerPool.h create mode 100644 languages/c/templates/sdk/src/CMakeLists.txt create mode 100644 languages/c/templates/sdk/src/Config.cmake create mode 100644 languages/c/templates/sdk/src/Event/Event.cpp create mode 100644 languages/c/templates/sdk/src/Event/Event.h create mode 100644 languages/c/templates/sdk/src/Firebolt.h create mode 100644 languages/c/templates/sdk/src/FireboltSDK.conf.in create mode 100644 languages/c/templates/sdk/src/Logger/Logger.cpp create mode 100644 languages/c/templates/sdk/src/Logger/Logger.h rename languages/c/templates/{schemas => sdk}/src/Module.cpp (85%) rename languages/c/templates/sdk/{main.cpp => src/Module.h} (61%) create mode 100644 languages/c/templates/sdk/src/Params.config create mode 100644 languages/c/templates/sdk/src/Properties/Properties.h rename languages/c/templates/{schemas/include/Module.h => sdk/src/Transport/Transport.cpp} (96%) create mode 100644 languages/c/templates/sdk/src/Transport/Transport.h create mode 100644 languages/c/templates/sdk/src/Types.cpp create mode 100644 languages/c/templates/sdk/src/TypesPriv.h create mode 100644 languages/c/templates/sdk/src/cmake/CopySymlink.cmake create mode 100644 languages/c/templates/sdk/test/CMakeLists.txt create mode 100644 languages/c/templates/sdk/test/Main.c create mode 100644 languages/c/templates/sdk/test/Module.cpp rename languages/c/templates/{modules/src/Module_Common.cpp => sdk/test/Module.h} (79%) create mode 100644 languages/c/templates/sdk/test/OpenRPCCTests.h create mode 100644 languages/c/templates/sdk/test/OpenRPCTests.cpp create mode 100644 languages/c/templates/sdk/test/OpenRPCTests.h create mode 100644 languages/c/templates/sdk/test/TestUtils.h create mode 100644 languages/c/templates/sections/accessors.c rename languages/c/templates/sections/{declarations.js => declarations.c} (100%) rename languages/c/templates/sections/{events.js => events.c} (100%) rename languages/c/templates/sections/{methods.js => methods.c} (100%) rename languages/c/templates/sections/{provider-interfaces.js => provider-interfaces.c} (100%) create mode 100644 languages/c/templates/sections/schemas.c rename languages/c/templates/sections/{schemas.js => types.c} (100%) create mode 100644 languages/c/templates/types/enum.c delete mode 100644 languages/c/templates/types/enum.mjs diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index aa209ad4..e44b4a78 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -16,122 +16,367 @@ * SPDX-License-Identifier: Apache-2.0 */ -import jsonTypes from './src/types/JSONTypes.mjs' -import commonTypes from './src/types/CommonCppTypes.mjs' -import headerCommonTypes from './src/types/CommonHeaderTypes.mjs' -import headerTypes from './src/types/HeaderTypes.mjs' -import cppTypes from './src/types/CppTypes.mjs' -import typeScriptTypes from '../../src/shared/typescript.mjs' -import { getNativeType } from './src/types/NativeHelpers.mjs' - -import path from "path" - -const isSynchronous = m => !m.tags ? false : m.tags.map(t => t.name).find(s => s === 'synchronous') - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) - -function getMethodSignature(method, module, { destination = '' } = {}) { - const returnType = getNativeType(method.result.schema) - const useHandle = !returnType - const extraParam = useHandle ? '${info.title}_${method.result.type}Handle* ${method.result.name}' : '' - - - return (returnType || 'uint32_t') + ' ${info.title}_Get${method.Name}(' + extraParam + ')' -} +import deepmerge from 'deepmerge' +import { getPath } from '../../src/shared/json-schema.mjs' +import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors } from './src/types/NativeHelpers.mjs' +import { getObjectHandleManagementImpl, getPropertyAccessorsImpl } from './src/types/ImplHelpers.mjs' +import { getJsonContainerDefinition } from './src/types/JSONHelpers.mjs' + +function getMethodSignature(method, module, { destination, isInterface = false }) { + const extraParam = '${method.result.type}* ${method.result.name}' -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return routeToDestination('getMethodSignatureParams', arguments) + const prefix = method.tags.find(t => t.name.split(":")[0] === "property") ? "Get" : "" + + return 'uint32_t ${info.title}_' + prefix + '${method.Name}(' + extraParam + ')' } -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - return routeToDestination('getSchemaShape', arguments) +function getMethodSignatureParams(method, module, { destination }) { + return method.params.map(param => param.name + (!param.required ? '?' : '') + ': ' + getSchemaType(param.schema, module, { title: true, destination })).join(', ') } -function getSchemaType(schema, module, { destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - let type = getNativeType(schema) +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaType(schema, module, { name, destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + let type = '' + let theTitle = schema.title || name || ('UnamedSchema' + (Math.floor(Math.random() * 100))) - if (!type) { - type = typeScriptTypes.getSchemaType(...arguments) + if (schema['x-method']) { + console.log(`WARNING UNHANDLED: x-method in ${theTitle}`) + //throw "x-methods not supported yet" + } - const array = type.endsWith('[]') + if (schema['$ref']) { + if (schema['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(schema['$ref'], module) + let tName = definition.title || schema['$ref'].split('/').pop() + return getSchemaType(definition, module, { name: tName, destination, link, title, code, asPath, event, expandEnums, baseUrl }) + } + } + else if (schema.const) { + type = getNativeType(schema) + return type + } + else if (schema.type === 'string' && schema.enum) { + //Enum + let typeName = getTypeName(getModuleName(module), theTitle) + return typeName + } + else if (Array.isArray(schema.type)) { + let type = schema.type.find(t => t !== 'null') + console.log(`WARNING UNHANDLED: type is an array containing ${schema.type}`) + } + else if (schema.type === 'array' && schema.items) { + let res + if (Array.isArray(schema.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(schema.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getSchemaType(schema.items[0], module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) + } + else { + // grab the type for the non-array schema + res = getSchemaType(schema.items, module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) + } - if (array) { - type = type.substring(0, type.length-2) - type = `${type}ObjectArrayHandle` + if (!schema.title && !name) { + console.log(`WARNING: generated name for ${module.info.title} schema w/ no title: ${theTitle}`) + console.dir(schema) } - type = `${module.info.title}_${type}` + let n = getTypeName(getModuleName(module), theTitle) + return n + 'ArrayHandle' + } + else if (schema.allOf) { + let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x)]) + if (theTitle) { + union['title'] = theTitle + } + delete union['$ref'] + return getSchemaType(union, module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) + } + else if (schema.oneOf || schema.anyOf) { + return type + //TODO + } + else if (schema.type === 'object') { + if (!schema.title && !name) { + console.log(`WARNING: generated name for ${module.info.title} schema w/ no title: ${theTitle}`) + console.dir(schema) + } + return getTypeName(getModuleName(module), theTitle) + 'Handle' + //TODO + } + else if (schema.type) { + type = getNativeType(schema) + return type } + + // TODO: deal with dependencies return type } -function getJsonType(schema, module, { destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - let type = getSchemaType(...arguments) +//function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, summary, descriptions = true, destination, enums = true } = {}) +// function getSchemaType() +function getSchemaShape(schema, module, { name = '', level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { + const isHeader = destination.endsWith(".h") + const isCPP = (destination.endsWith(".cpp") && section !== 'accessors') + + schema = JSON.parse(JSON.stringify(schema)) - // FireboltSDK::JSON::String&, etc. - // FireboltSDK::::& - // WPEFramework::Core::JSON::Boolean + let shape = '' - const array = type.endsWith('[]') + name = schema.title || name - if (array) { - type = type.substring(0, type.length-2) + if (!name) { + console.log(`WARNING: schema without a name in ${module.info.title}`) + return shape } - let jsonType + if (schema['$ref']) { + if (schema['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType - if (type === 'string') { - jsonType = 'FireboltSDK::JSON::String' + const schema = getPath(schema['$ref'], module) + const tname = name || schema['$ref'].split('/').pop() + return getSchemaShape(schema, module, { name: tname, descriptions: descriptions, level: level }) + } } - else if (type === 'boolean') { - jsonType = 'WPEFramework::Core::JSON::Boolean' + //If the schema is a const, + else if (schema.hasOwnProperty('const') && !isCPP) { + if (level > 0) { + + let t = description(name, schema.description) + typeName = getTypeName(getModuleName(module), name) + t += (isHeader ? getPropertyAccessors(typeName, capitalize(name), typeof schema.const, { level: level, readonly: true, optional: false }) : getPropertyAccessorsImpl(typeName, capitalize(name), getJsonType(schema, module, { level, name }), typeof schema.const, { level: level, readonly: true, optional: false })) + shape += '\n' + t + } } - else { - jsonType = `FireboltSDK::${module.info.title}::${getSchemaType(...arguments)}` + else if (schema.type === 'object') { + if (!name) { + console.log(`WARNING: unnamed schema in ${module.info.title}.`) + console.dir(schema) + shape = '' + } + else if (schema.properties) { + let tName = getTypeName(getModuleName(module), name) + let c_shape = description(name, schema.description) + let cpp_shape = '' + c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(schema, module, { name }))) + Object.entries(schema.properties).forEach(([pname, prop]) => { + c_shape += '\n' + description(pname, prop.description) + let res + if (prop.type === 'array') { + if (Array.isArray(prop.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(prop.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getSchemaType(prop.items[0], module, { name: pname, level: level, descriptions: descriptions, title: true }) + } + else { + // grab the type for the non-array schema + res = getSchemaType(prop.items, module, { name: pname, level: level, descriptions: descriptions, title: true }) + } + if (res && res.length > 0) { + let n = tName + '_' + capitalize(pname || prop.title) + let def = getArrayAccessors(n + 'Array', res) + c_shape += '\n' + def + } + else { + console.log(`a. WARNING: Type undetermined for ${name}:${pname}`) + } + } else { + res = getSchemaType(prop, module, { name: pname, descriptions: descriptions, level: level + 1, title: true }) + if (res && res.length > 0) { + c_shape += '\n' + (isHeader ? getPropertyAccessors(tName, capitalize(pname), res, { level: level, readonly: false, optional: isOptional(pname, schema) }) : getPropertyAccessorsImpl(tName, capitalize(pname), getJsonType(prop, module, { level, name }), res, { level: level, readonly: false, optional: isOptional(pname, schema) })) + } + else { + console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) + } + } + }) + cpp_shape += getJsonContainerDefinition(tName, Object.entries(schema.properties).map(([name, prop]) => ({ name, type: getJsonType(prop, module) }))) + + if (isCPP) { + shape += '\n' + cpp_shape + } + else { + shape += '\n' + c_shape + } + } + else if (schema.propertyNames && schema.propertyNames.enum) { + //propertyNames in object not handled yet + } + else if (schema.additionalProperties && (typeof schema.additionalProperties === 'object') && !isCPP) { + //This is a map of string to type in schema + //Get the Type + let type = getSchemaType(schema.additionalProperties, module, { name: name }) + if (type && type.length > 0) { + let tName = getTypeName(getModuleName(module), name) + // type.deps.forEach(dep => structure.deps.add(dep)) + let t = description(name, schema.description) + t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(schema, module, { name }))) + t += getMapAccessors(getTypeName(getModuleName(module), name), type, { descriptions: descriptions, level: level }) + shape += '\n' + t + } + else { + console.log(`c. WARNING: Type undetermined for ${name}`) + } + } + else if (schema.patternProperties) { + console.log(`WARNING: patternProperties not supported yet...`) + // throw "patternProperties are not supported by Firebolt" + } + } + else if (schema.anyOf) { + } + else if (schema.oneOf) { - if (array) { - jsonType = `WPEFramework::Core::JSON::ArrayType<${jsonType}>` } + else if (schema.allOf) { + let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x)]) + if (name) { + union['title'] = name + } + delete union['$ref'] + return getSchemaShape(union, module, { name, level, title, summary, descriptions, destination, section, enums }) + + } + else if (schema.type === 'array') { + let res = getSchemaType(schema, module, { name, level: 0, descriptions: descriptions }) + // res.deps.forEach(dep => structure.deps.add(dep)) + } + else { + let res = getSchemaType(schema, module, { name, level: level, descriptions: descriptions }) + // res.deps.forEach(dep => structure.deps.add(dep)) + } + // console.dir(structure.deps) + return shape +} + +// function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - return `${jsonType}&` +const getJsonDataStructName = (modName, name) => `${capitalize(modName)}::${capitalize(name)}` + +const getJsonNativeType = json => { + let type + let jsonType = json.const ? typeof json.const : json.type + + if (jsonType === 'string') { + type = 'WPEFramework::Core::JSON::String' + } + else if (jsonType === 'number' || json.type === 'integer') { //Lets keep it simple for now + type = 'WPEFramework::Core::JSON::Number' + } + else if (jsonType === 'boolean') { + type = 'WPEFramework::Core::JSON::Boolean' + } + else { + throw 'Unknown JSON Native Type !!!' + } + return type } -function routeToDestination(method, args) { - const destination = args[args.length-1].destination || '' +function getJsonType(schema = {}, module = {}, { name = '', descriptions = false, level = 0 } = {}) { - if ( path.basename(destination) === 'JsonData_Module.h') { - return jsonTypes[method](...args) + let type = '' + + if (schema['$ref']) { + if (schema['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(schema['$ref'], module) + let tName = definition.title || schema['$ref'].split('/').pop() + return getJsonType(definition, module, { name: tName, descriptions: descriptions, level: level }) + } } - else if (path.basename(destination) === 'Module.cpp') { - return cppTypes[method](...args) + else if (schema.const) { + return getJsonNativeType(schema) } - else if (path.basename(destination) === 'Module_Common.cpp') { - return commonTypes[method](...args) + else if (schema['x-method']) { + console.log(`WARNING: x-methods are not supported yet...`) + return type + //throw "x-methods not supported yet" } - else if (path.basename(destination) === 'Module.h' && path.dirname(destination).endsWith(path.sep + 'Common')) { - return headerCommonTypes[method](...args) + else if (schema.type === 'string' && schema.enum) { + //Enum + let t = getSchemaType(schema, module, { name }) + return 'WPEFramework::Core::JSON::EnumType<::' + t + '>' } - else if (path.basename(destination) === 'Module.h') { - return headerTypes[method](...args) + else if (Array.isArray(schema.type)) { + let type = schema.type.find(t => t !== 'null') + console.log(`WARNING UNHANDLED: type is an array containing ${schema.type}`) } + else if (schema.type === 'array' && schema.items) { + let res + if (Array.isArray(schema.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(schema.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getJsonType(schema.items[0], module, { name: '' }) + } + else { + // grab the type for the non-array schema + res = getJsonType(schema.items, module, { name: '' }) + } - return '' + return `WPEFramework::Core::JSON::ArrayType<${res}>` + } + else if (schema.allOf) { + let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)]) + if (schema.title) { + union['title'] = schema.title + } + else { + union['title'] = name + } + delete union['$ref'] + return getJsonType(union, module, { name: '', level, descriptions }) + } + else if (schema.oneOf || schema.anyOf) { + return type + //TODO + } + else if (schema.type === 'object') { + if (!schema.title && !name) { + console.log(`WARNING: schema with no name`) + console.dir(schema) + return 'Unknown' + } + return getJsonDataStructName(getModuleName(module), schema.title || name) + //TODO + } + else if (schema.type) { + return getJsonNativeType(schema) + } + return type } -function getPrimativeType(schema) { - if (schema.type === "boolean") { - return "bool" +function getTypeScriptType(jsonType) { + if (jsonType === 'integer') { + return 'number' } - else if (schema.type === "integer") { - return "uint32_t" + else { + return jsonType } - else if (schema.type === "number") { - return +} + +const enumReducer = (acc, val, i, arr) => { + const keyName = val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + acc = acc + ` ${keyName} = '${val}'` + if (i < arr.length - 1) { + acc = acc.concat(',\n') } + return acc } export default { diff --git a/languages/c/src/types/CommonCppTypes.mjs b/languages/c/src/types/CommonCppTypes.mjs deleted file mode 100644 index 863cd77b..00000000 --- a/languages/c/src/types/CommonCppTypes.mjs +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2021 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 - */ - -// import deepmerge from 'deepmerge' -// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' -// import { getLinkFromRef } from '../../src/shared/markdown.mjs' -// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' - - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) - -function getMethodSignature(method, module, { destination = '' } = {}) { - return `// Common CPP Signatures for ${module}_${method}` -} - -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return `// Common CPP Signature Params for ${module}_${method}` -} - -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - - return { - dependencies: [], - code: `// Common CPP Schema Shape` - } - return `// Common CPP Schema Shape` -} - -function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - return `// Common CPP Schema Type` -} - - -export default { - getMethodSignature, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, -} \ No newline at end of file diff --git a/languages/c/src/types/CommonHeaderTypes.mjs b/languages/c/src/types/CommonHeaderTypes.mjs deleted file mode 100644 index 9c40c084..00000000 --- a/languages/c/src/types/CommonHeaderTypes.mjs +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2021 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 - */ - -// import deepmerge from 'deepmerge' -// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' -// import { getLinkFromRef } from '../../src/shared/markdown.mjs' -// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' - - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) - -function getMethodSignature(method, module, { destination = '' } = {}) { - return `// common .h Signatures for ${module}_${method}` -} - -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return `// common .h Signature Params for ${module}_${method}` -} - -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - return `// common .h Schema Shape` -} - -function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - return `// common .h Schema Type` -} - - -export default { - getMethodSignature, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, -} \ No newline at end of file diff --git a/languages/c/src/types/CppTypes.mjs b/languages/c/src/types/CppTypes.mjs deleted file mode 100644 index 4b6fa6a8..00000000 --- a/languages/c/src/types/CppTypes.mjs +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2021 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 - */ - -// import deepmerge from 'deepmerge' -// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' -// import { getLinkFromRef } from '../../src/shared/markdown.mjs' -// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' - - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) - -function getMethodSignature(method, module, { destination = '' } = {}) { - return `// CPP Signatures for ${module}_${method}` -} - -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return `// CPP Signature Params for ${module}_${method}` -} - -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - return `// CPP Schema Shape` -} - -function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - return `// CPP Schema Type` -} - - -export default { - getMethodSignature, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, -} \ No newline at end of file diff --git a/languages/c/src/types/HeaderTypes.mjs b/languages/c/src/types/HeaderTypes.mjs deleted file mode 100644 index 9ce0155e..00000000 --- a/languages/c/src/types/HeaderTypes.mjs +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2021 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 - */ - -// import deepmerge from 'deepmerge' -// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' -// import { getLinkFromRef } from '../../src/shared/markdown.mjs' -// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' - - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) - -function getMethodSignature(method, module, { destination = '' } = {}) { - return `// .h Signatures for ${module.info.title}_${method.name}` -} - -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return `// .h Signature Params for ${module.info.title}_${method.name}` -} - -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - return `// .h Schema Shape` -} - -function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - return `// .h Schema Type` -} - - -export default { - getMethodSignature, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, -} \ No newline at end of file diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs new file mode 100644 index 00000000..f3b39cbf --- /dev/null +++ b/languages/c/src/types/ImplHelpers.mjs @@ -0,0 +1,294 @@ +const Indent = '\t' + +const getObjectHandleManagementImpl = (varName, jsonDataName) => { + + let result = ` +${varName}Handle ${varName}Handle_Create(void) { + WPEFramework::Core::ProxyType<${jsonDataName}>* type = new WPEFramework::Core::ProxyType<${jsonDataName}>(); + *type = WPEFramework::Core::ProxyType<${jsonDataName}>::Create(); + return (static_cast<${varName}Handle>(type)); +} +void ${varName}Handle_Addref(${varName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + var->AddRef(); +} +void ${varName}Handle_Release(${varName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + var->Release(); + if(var->IsValid() != true) { + delete var; + } +} +bool ${varName}Handle_IsValid(${varName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + return var->IsValid(); +} +` + return result +} + +const getPropertyAccessorsImpl = (objName, propertyName, jsonDataName, propertyType, json = {}, options = {readonly:false, optional:false}) => { + + let result + if (json.type === 'object') { + result += `${objName}_${propertyName}Handle ${objName}_Get_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyName}>(); + *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); + *(*object) = (*var)->${propertyName}; + return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' + } else if (json.type === 'array') { + result += `${objName}_${propertyName}ArrayHandle ${objName}_Get_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + WPEFramework::Core::ProxyType>* object = new WPEFramework::Core::ProxyType>(); + *object = WPEFramework::Core::ProxyType>::Create(); + *(*object) = (*var)->${propertyName}.Element(); + return (static_cast<${objName}_${propertyType}ArrayHandle>(object));` + '\n' + } else if (json.enum) { + result += `${objName}_${propertyName} ${objName}_Get_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + return static_cast<${propertyType}>((*var)->${propertyName}.Value());` + '\n' + } else { + result += `${propertyType} ${objName}_Get_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid());` + '\n' + if (json.type === 'string') { + result += ` + return static_cast<${propertyType}>((*var)->${propertyName}.Value().c_str());` + '\n' + } else { + result += ` + return static_cast<${propertyType}>((*var)->${propertyName}.Value());` + '\n' + } + } + result += ` +}` + '\n' + if (!options.readonly) { + if (json.type === 'object') { + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName}Handle ${propertyName.toLowerCase()}) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* object = static_cast*>(${propertyName.toLowerCase()}); + (*var)->${propertyName} = *(*object);` + '\n' + } + if (json.type === 'array') { + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName}ArrayHandle ${propertyName.toLowerCase()}) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + WPEFramework::Core::ProxyType>* object = static_cast>*>(${propertyName.toLowerCase()}).Element(); + (*var)->${propertyName} = *(*object);` + '\n' + } if (json.enum) { + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName} ${propertyName.toLowerCase()}) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + (*var)->${propertyName} = static_cast<${propertyType}>(${propertyName.toLowerCase()});` + '\n' + } + else { + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${propertyType} ${propertyName.toLowerCase()}) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + (*var)->${propertyName} = static_cast<${propertyType}>(${propertyName.toLowerCase()});` + '\n' + } +result += `}` + '\n' + } + + if (options.optional === true) { + result += `${Indent.repeat(options.level)}bool ${objName}_has_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + return ((*var)->${propertyName}.IsSet()); +}` + '\n' + result += `${Indent.repeat(options.level)}void ${objName}_clear_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + ((*var)->${propertyName}.Clear()); +}` + '\n' + } + return result +} + +const getArrayAccessors = (objName, propertyName, propertyType, json = {}, options = {readonly:false, optional:false}) => { + let result = ` +uint32_t ${objName}_${propertyName}Array_Size(${objName}::${propertyName}ArrayHandle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + return ((*var)->Length()); +}` + '\n' + + if (json.type === 'object') { +result += `${objName}_${propertyType}Handle ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid()); + WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyType}>(); + *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); + *(*object) = (*var)->Get(index); + return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' + } else if (json.enum) { + result += `${objName}_${propertyType} ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid()); + + return (static_cast<${propertyType}>((*var)->Get(index)));` + '\n' + } else { + result += `${propertyType} ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid());` + '\n' + + if (json.type === 'string') { + result += `return (static_cast<${propertyType}>((*var)->Get(index).Value().c_str()));` + '\n' + } else { + result += `return (static_cast<${propertyType}>((*var)->Get(index)));` + '\n' + } + + } + result += `}` + '\n' + + if (json.type === 'object') { + result += `void ${objName}_${propertyName}Array_Add(${objName}_${propertyName}ArrayHandle handle, ${objName}_${propertyType}Handle value) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid()); + WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = static_cast*>(value); + + (*var)->Add(*(*object));` + '\n' + } else { + result += `void ${objName}_${propertyName}Array_Add(${objName}_${propertyName}ArrayHandle handle, ${propertyType} value) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid());` + '\n' + if (json.type === 'string') { + result += `WPEFramework::Core::JSON::String element(value);` + '\n' + } else if (json.type === 'number') { + result += `WPEFramework::Core::JSON::Number element(value);` + '\n' + } else if (json.enum) { + result += `WPEFramework::Core::JSON::EnumType<${propertyType}> element(value);` + '\n' + } + result += `(*var)->Add(element);` + '\n' + } + result += `}` + '\n' + + result += `void ${objName}_${propertyName}Array_Clear(${objName}_${propertyName}ArrayHandle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid()); + (*var)->Clear(); +}` + '\n' + + return result +} + +const getMapAccessors = (objName, propertyName, propertyType, json = {}, options = {readonly:false, optional:false}) => { + let result = `uint32_t ${objName}_${propertyName}_KeysCount(${objName}_${propertyName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + return (*var)->Size()); + + }` + '\n' + result += `void ${objName}_${propertyName}_AddKey(${objName}_${propertyName}Handle handle, char* key, ${propertyType} value) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid());` + '\n' + + if (json.type === 'object') { + result += ` + (*var)->Add(key, value);` + '\n' + } else if (json.type === 'boolean') { + result += ` + WPEFramework::Core::JSON::Boolean element(value);` + } else if (json.type === 'string') { + result += ` + WPEFramework::Core::JSON::String element(value);` + } else if (json.type === 'number') { + result += ` + WPEFramework::Core::JSON::Number element(value);` + } else if (json.type === 'array') { + result += ` + WPEFramework::Core::JSON::ArrayType element(value);` + } else if (json.enum) { + result += ` + WPEFramework::Core::JSON::EnumType element(value); + (*var)->Add(key, element);` + '\n' + } + result += ` + }` + '\n' + result += `void ${objName}_${propertyName}_RemoveKey(${objName}_${propertyName}Handle handle, char* key) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + (*var)->Remove(key); + }` + '\n' + + if (json.type === 'object') { + result += `${objName}_${propertyType}Handle ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyType}>(); + *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); + *(*object) = (*var)->Find(key); + return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' + + } else if (json.type === 'array') { + result += `${objName}_${propertyType}ArrayHandle ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + WPEFramework::Core::ProxyType>* object = new WPEFramework::Core::ProxyType>(); + *object = WPEFramework::Core::ProxyType>::Create(); + *(*object) = (*var)->Find(key); + return (static_cast<${objName}_${propertyType}ArrayHandle>(object));` + '\n' + + } else { + result += `${propertyType} ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid());` + '\n' + + if (json.type === 'string') { + result += ` + return (static_cast<${propertyType}>((*var)->(Find(key).Value().c_str())));` + '\n' + } else { + result += ` + return (static_cast<${propertyType}>((*var)->(Find(key).Value())));` + '\n' + } + } + result += ` +}` + '\n' + + return result +} + +export { + getObjectHandleManagementImpl, + getPropertyAccessorsImpl +} diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs new file mode 100644 index 00000000..25d1ad3b --- /dev/null +++ b/languages/c/src/types/JSONHelpers.mjs @@ -0,0 +1,61 @@ +const capitalize = str => str[0].toUpperCase() + str.substr(1) + +function getJsonContainerDefinition (name, props) { + name = capitalize(name) + let c = ` class ${name}: public Core::JSON::Container { + public: + ${name}(const ${name}&) = delete; + ${name}& operator=(const ${name}&) = delete; + ~${name}() override = default; + + public: + ${name}() + : Core::JSON::Container() + {` + + props.forEach(prop => { + c += `\n Add(_T("${prop.name}"), &${capitalize(prop.name)});` + }) + + c += `\n }\n\n public:` + + props.forEach(prop => { + c += `\n ${prop.type} ${capitalize(prop.name)};` + }) + + c += '\n };' + return c + } + +/* + +ENUM_CONVERSION_BEGIN(Advertising_SkipRestriction) + { ADVERTISING_SKIPRESTRICTION_NONE, _T("none") }, + { ADVERTISING_SKIPRESTRICTION_ADS_UNWATCHED, _T("adsUnwatched") }, + { ADVERTISING_SKIPRESTRICTION_ADS_ALL, _T("adsAll") }, + { ADVERTISING_SKIPRESTRICTION_ALL, _T("all") }, +ENUM_CONVERSION_END(Advertising_SkipRestriction) + + +*/ + +// TODO - this should be a global function in the main /src/ directory... not part of a language pack +const keyName = val => val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + +function getJsonEnumConversion(schema, module, { name }) { + name = capitalize(schema.title || name) + let e = `ENUM_CONVERSION_BEGIN(${module.info.title}_${name})\n` + + schema.enum.forEach(value => { + e += `{ ${module.info.title.toUpperCase()}_${name.toUpperCase()}_${keyName(value)}, _T("${value}") },` + }) + + e += `ENUM_CONVERSION_END(${module.info.title}_${name})` + + return e +} + +export { + getJsonContainerDefinition, + getJsonEnumConversion +} diff --git a/languages/c/src/types/JSONTypes.mjs b/languages/c/src/types/JSONTypes.mjs deleted file mode 100644 index d2961794..00000000 --- a/languages/c/src/types/JSONTypes.mjs +++ /dev/null @@ -1,56 +0,0 @@ - -/* - * Copyright 2021 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 - */ - -// import deepmerge from 'deepmerge' -// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' -// import { getLinkFromRef } from '../../src/shared/markdown.mjs' -// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' - - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) - -function getMethodSignature(method, module, { destination = '' } = {}) { - return `// JSON Signatures for ${module}_${method}` -} - -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return `// JSON Signature Params for ${module}_${method}` -} - -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - return `// JSON Schema Shape` -} - -function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - return `// JSON Schema Type` -} - - -export default { - getMethodSignature, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, -} \ No newline at end of file diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index e51c47d7..79242d1f 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -201,260 +201,6 @@ const getIncludeDefinitions = (json = {}, jsonData = false) => { .concat([`#include "Firebolt/Types.h"`]) } -function getSchemaType(module = {}, json = {}, name = '', schemas = {}, options = {level: 0, descriptions: true, title: false}) { - if (json.schema) { - json = json.schema - } - - let structure = {} - structure["deps"] = new Set() //To avoid duplication of local ref definitions - structure["type"] = [] - - if (json['$ref']) { - if (json['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType - let definition = getPath(json['$ref'], module, schemas) - let tName = definition.title || json['$ref'].split('/').pop() - const res = getSchemaType(module, definition, tName, schemas, {descriptions: options.descriptions, level: options.level}) - res.deps.forEach(dep => structure.deps.add(dep)) - structure.type = res.type - return structure - } - else { - // External dependency. - // e.g, "https://meta.comcast.com/firebolt/entertainment#/definitions/ProgramType" - - //Get the module of this definition - const schema = getPath(json['$ref'].split('#')[0], schemas) || module - - //Get the schema of the definition - const definition = getPath(json['$ref'], module, schemas) - let tName = definition.title || json['$ref'].split('/').pop() - const res = getSchemaType(schema, definition, tName, schemas, {descriptions: options.descriptions, level: options.level}) - //We are only interested in the type definition for external modules - structure.type = res.type - return structure - } - } - else if (json.const) { - structure.type = getNativeType(json) - return structure - } - else if (json['x-method']) { - console.log(`WARNING UNHANDLED: x-method in ${name}`) - return structure - //throw "x-methods not supported yet" - } - else if (json.type === 'string' && json.enum) { - //Enum - let typeName = getTypeName(getModuleName(module), name || json.title) - let res = description(capitalize(name || json.title), json.description) + '\n' + generateEnum(json, typeName) - structure.deps.add(res) - structure.type.push(typeName) - return structure - } - else if (Array.isArray(json.type)) { - let type = json.type.find(t => t !== 'null') - console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) - } - else if (json.type === 'array' && json.items) { - let res - if (Array.isArray(json.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(json.items)) { - throw 'Heterogenous Arrays not supported yet' - } - res = getSchemaType(module, json.items[0],'',schemas) - } - else { - // grab the type for the non-array schema - res = getSchemaType(module, json.items, '', schemas) - } - - res.deps.forEach(dep => structure.deps.add(dep)) - let n = getTypeName(getModuleName(module), name || json.title) - let def = description(name || json.title, json.description) + '\n' - if (options.level === 0) { - def += getObjectHandleManagement(n + 'Array') + '\n' - } - def += getArrayAccessors(n + 'Array', res.type) - structure.deps.add(def) - structure.type.push(n + 'ArrayHandle') - return structure - } - else if (json.allOf) { - let union = deepmerge.all([...json.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)]) - if (json.title) { - union['title'] = json.title - } - else { - union['title'] = name - } - delete union['$ref'] - return getSchemaType(module, union, '',schemas, options) - } - else if (json.oneOf || json.anyOf) { - return structure - //TODO - } - else if (json.type === 'object') { - let res = getSchemaShape(module, json, schemas, json.title || name, {descriptions: options.descriptions, level: 0}) - res.deps.forEach(dep => structure.deps.add(dep)) - res.type.forEach(t => structure.deps.add(t)) - structure.type.push(getTypeName(getModuleName(module), json.title || name) + 'Handle') - return structure - //TODO - } - else if (json.type) { - structure.type = getNativeType(json) - return structure - } - return structure -} - -function getSchemaShape(moduleJson = {}, json = {}, schemas = {}, name = '', options = {level: 0, descriptions: true}) { - json = JSON.parse(JSON.stringify(json)) - let level = options.level - let descriptions = options.descriptions - - let structure = {} - structure["deps"] = new Set() //To avoid duplication of local ref definitions - structure["type"] = [] - - if (json['$ref']) { - if (json['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType - - const schema = getPath(json['$ref'], module, schemas) - const tname = schema.title || json['$ref'].split('/').pop() - res = getSchemaShape(module, schema, schemas, tname, {descriptions: descriptions, level: level}) - res.deps.forEach(dep => structure.deps.add(dep)) - structure.type = res.type - } - else { - // External dependency. Return only type - // e.g, "https://meta.comcast.com/firebolt/entertainment#/definitions/ProgramType" - - //Get the module of this definition - const schema = getPath(json['$ref'].split('#')[0], schemas) || module - - //Get the schema of the definition - const definition = getPath(json['$ref'], schema, schemas) - const pname = (json.title || name) + (definition.title || json['$ref'].split('/').pop()) - - res = getSchemaShape(schema, definition, schemas, pname,{descriptions: descriptions, level: level}) - //We are only interested in the type definition for external modules - structure.type = res.type - } - } - //If the schema is a const, - else if (json.hasOwnProperty('const')) { - if (level > 0) { - - let t = description(name, json.description) - typeName = getTypeName(getModuleName(moduleJson), name) - t += getPropertyAccessors(typeName, capitalize(name), typeof json.const, {level: level, readonly:true, optional:false}) - structure.type.push(t) - } - } - else if (json.type === 'object') { - - if (json.properties) { - let tName = getTypeName(getModuleName(moduleJson), name) - let t = description(name, json.description) - t += '\n' + getObjectHandleManagement(tName) - Object.entries(json.properties).forEach(([pname, prop]) => { - t += '\n' + description(pname, prop.description) - let res - if (prop.type === 'array') { - if (Array.isArray(prop.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(prop.items)) { - throw 'Heterogenous Arrays not supported yet' - } - res = getSchemaType(moduleJson, prop.items[0],pname, schemas, {level : options.level, descriptions: options.descriptions, title: true}) - } - else { - // grab the type for the non-array schema - res = getSchemaType(moduleJson, prop.items, pname, schemas, {level : options.level, descriptions: options.descriptions, title: true}) - } - if (res.type && res.type.length > 0) { - let n = tName + '_' + capitalize(pname || prop.title) - let def = getArrayAccessors(n + 'Array', res.type) - t += '\n' + def - } - else { - console.log(`WARNING: Type undetermined for ${name}:${pname}`) - } - } else { - res = getSchemaType(moduleJson, prop, pname,schemas, {descriptions: descriptions, level: level + 1, title: true}) - if (res.type && res.type.length > 0) { - t += '\n' + getPropertyAccessors(tName, capitalize(pname), res.type, {level: level, readonly:false, optional:isOptional(pname, json)}) - } - else { - console.log(`WARNING: Type undetermined for ${name}:${pname}`) - } - } - res.deps.forEach(dep => structure.deps.add(dep)) - }) - structure.type.push(t) - } - else if (json.propertyNames && json.propertyNames.enum) { - //propertyNames in object not handled yet - } - else if (json.additionalProperties && (typeof json.additionalProperties === 'object')) { - //This is a map of string to type in schema - //Get the Type - let type = getSchemaType(moduleJson, json.additionalProperties, name,schemas) - if (type.type && type.type.length > 0) { - let tName = getTypeName(getModuleName(moduleJson), name) - type.deps.forEach(dep => structure.deps.add(dep)) - let t = description(name, json.description) - t += '\n' + getObjectHandleManagement(tName) + '\n' - t += getMapAccessors(getTypeName(getModuleName(moduleJson), name), type.type,{descriptions: descriptions, level: level}) - structure.type.push(t) - } - else { - console.log(`WARNING: Type undetermined for ${name}`) - } - } - else if (json.patternProperties) { - throw "patternProperties are not supported by Firebolt" - } - } - else if (json.anyOf) { - - } - else if (json.oneOf) { - - } - else if (json.allOf) { - let union = deepmerge.all([...json.allOf.map(x => x['$ref'] ? getPath(x['$ref'], moduleJson, schemas) || x : x)], options) - if (json.title) { - union['title'] = json.title - } - else { - union['title'] = name - } - delete union['$ref'] - return getSchemaShape(moduleJson, union, schemas, name, options) - - } - else if (json.type === 'array') { - let res = getSchemaType(moduleJson, json, name, schemas, {level: 0, descriptions: descriptions}) - res.deps.forEach(dep => structure.deps.add(dep)) - } - else { - let res = getSchemaType(moduleJson, json, name, schemas, {level: level, descriptions: descriptions}) - res.deps.forEach(dep => structure.deps.add(dep)) - } - return structure - } - function getPropertyGetterSignature(method, module, paramType) { let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` @@ -480,15 +226,19 @@ function getSchemaShape(moduleJson = {}, json = {}, schemas = {}, name = '', opt getStyleGuardClose, getIncludeGuardClose, getNativeType, - getSchemaType, - getSchemaShape, getModuleName, getIncludeDefinitions, getPropertyGetterSignature, getPropertySetterSignature, getPropertyEventCallbackSignature, getPropertyEventSignature, + getMapAccessors, + getArrayAccessors, capitalize, description, - getTypeName + getTypeName, + getObjectHandleManagement, + getPropertyAccessors, + isOptional, + generateEnum } diff --git a/languages/c/templates/codeblocks/export.mjs b/languages/c/templates/codeblocks/export.c similarity index 100% rename from languages/c/templates/codeblocks/export.mjs rename to languages/c/templates/codeblocks/export.c diff --git a/languages/c/templates/codeblocks/mock-import.mjs b/languages/c/templates/codeblocks/mock-import.c similarity index 100% rename from languages/c/templates/codeblocks/mock-import.mjs rename to languages/c/templates/codeblocks/mock-import.c diff --git a/languages/c/templates/codeblocks/mock-parameter.mjs b/languages/c/templates/codeblocks/mock-parameter.c similarity index 100% rename from languages/c/templates/codeblocks/mock-parameter.mjs rename to languages/c/templates/codeblocks/mock-parameter.c diff --git a/languages/c/templates/declarations/clear.js b/languages/c/templates/codeblocks/module.c similarity index 100% rename from languages/c/templates/declarations/clear.js rename to languages/c/templates/codeblocks/module.c diff --git a/languages/c/templates/codeblocks/module.mjs b/languages/c/templates/codeblocks/module.mjs deleted file mode 100644 index 48f6d6bc..00000000 --- a/languages/c/templates/codeblocks/module.mjs +++ /dev/null @@ -1,11 +0,0 @@ -// JEREMY - -export module ${info.title} { - - /* ${SCHEMAS} */ - - /* ${DECLARATIONS} */ - - /* ${PROVIDERS} */ - -} \ No newline at end of file diff --git a/languages/c/templates/declarations/listen.js b/languages/c/templates/declarations/clear.c similarity index 100% rename from languages/c/templates/declarations/listen.js rename to languages/c/templates/declarations/clear.c diff --git a/languages/c/templates/declarations/default.js b/languages/c/templates/declarations/default.c similarity index 68% rename from languages/c/templates/declarations/default.js rename to languages/c/templates/declarations/default.c index bd8b6fcf..72fbf14f 100644 --- a/languages/c/templates/declarations/default.js +++ b/languages/c/templates/declarations/default.c @@ -1,4 +1,4 @@ /** * ${method.summary} ${method.params} */ - ${method.signature} + ${method.signature}; diff --git a/languages/c/templates/declarations/once.js b/languages/c/templates/declarations/listen.c similarity index 100% rename from languages/c/templates/declarations/once.js rename to languages/c/templates/declarations/listen.c diff --git a/languages/c/templates/declarations/provide.js b/languages/c/templates/declarations/once.c similarity index 100% rename from languages/c/templates/declarations/provide.js rename to languages/c/templates/declarations/once.c diff --git a/languages/c/templates/declarations/polymorphic-reducer.js b/languages/c/templates/declarations/polymorphic-reducer.c similarity index 100% rename from languages/c/templates/declarations/polymorphic-reducer.js rename to languages/c/templates/declarations/polymorphic-reducer.c diff --git a/languages/c/templates/declarations/rpc-only.js b/languages/c/templates/declarations/provide.c similarity index 100% rename from languages/c/templates/declarations/rpc-only.js rename to languages/c/templates/declarations/provide.c diff --git a/languages/c/templates/methods/listen.js b/languages/c/templates/declarations/rpc-only.c similarity index 100% rename from languages/c/templates/methods/listen.js rename to languages/c/templates/declarations/rpc-only.c diff --git a/languages/c/templates/defaults/default.mjs b/languages/c/templates/defaults/default.c similarity index 100% rename from languages/c/templates/defaults/default.mjs rename to languages/c/templates/defaults/default.c diff --git a/languages/c/templates/defaults/property.mjs b/languages/c/templates/defaults/property.c similarity index 100% rename from languages/c/templates/defaults/property.mjs rename to languages/c/templates/defaults/property.c diff --git a/languages/c/templates/examples/default.md b/languages/c/templates/examples/default.md deleted file mode 100644 index ecc979ba..00000000 --- a/languages/c/templates/examples/default.md +++ /dev/null @@ -1,6 +0,0 @@ -import { ${module} } from '${package.name}' - -${module}.${method.name}(${example.params}) - .then(${method.result.name} => { - console.log(${method.result.name}) - }) \ No newline at end of file diff --git a/languages/c/templates/examples/event.md b/languages/c/templates/examples/event.md deleted file mode 100644 index 7b78fe76..00000000 --- a/languages/c/templates/examples/event.md +++ /dev/null @@ -1,5 +0,0 @@ -import { ${module} } from '${package.name}' - -${module}.listen('${event.name}', ${method.result.name} => { - console.log(${method.result.name}) -}) \ No newline at end of file diff --git a/languages/c/templates/examples/polymorphic-pull-event.md b/languages/c/templates/examples/polymorphic-pull-event.md deleted file mode 100644 index 7bc2baa7..00000000 --- a/languages/c/templates/examples/polymorphic-pull-event.md +++ /dev/null @@ -1,9 +0,0 @@ -import { ${module} } from '${package.name}' - -${module}.${method.pulls.for}(function(parameters) { - console.log(parameters.entityId) - console.log(parameters.assetId) - return Promise.resolve(${originator.params[1].example.value}) -}).then(success => { - console.log(success) -}) \ No newline at end of file diff --git a/languages/c/templates/examples/polymorphic-pull.md b/languages/c/templates/examples/polymorphic-pull.md deleted file mode 100644 index 7c53080c..00000000 --- a/languages/c/templates/examples/polymorphic-pull.md +++ /dev/null @@ -1,6 +0,0 @@ -import { ${module} } from '${package.name}' - -${module}.${method.name}(${method.params[1].example.value}) - .then(success => { - console.log(success) - }) \ No newline at end of file diff --git a/languages/c/templates/examples/provider.md b/languages/c/templates/examples/provider.md deleted file mode 100644 index d2d16366..00000000 --- a/languages/c/templates/examples/provider.md +++ /dev/null @@ -1,10 +0,0 @@ -import { ${module} } from '${package.name}' - -class MyProvider { - async ${example.providerMethod}(${method.result.name}, responder) { - console.log(JSON.stringify(${method.result.name}, null, 2)) - responder(${example.providerResponse}) - } -} - -${module}.provide(new MyProvider()) \ No newline at end of file diff --git a/languages/c/templates/examples/setter.md b/languages/c/templates/examples/setter.md deleted file mode 100644 index c258314a..00000000 --- a/languages/c/templates/examples/setter.md +++ /dev/null @@ -1,6 +0,0 @@ -import { ${module} } from '${package.name}' - -${module}.${method.setter.for}(${example.params}) - .then(${method.result.name} => { - console.log(${method.result.name}) - }) \ No newline at end of file diff --git a/languages/c/templates/examples/subscriber.md b/languages/c/templates/examples/subscriber.md deleted file mode 100644 index 99c0516f..00000000 --- a/languages/c/templates/examples/subscriber.md +++ /dev/null @@ -1,7 +0,0 @@ -import { ${module} } from '${package.name}' - -${method.alternative}(value => { - console.log(value) -}).then(listenerId => { - console.log(listenerId) -}) \ No newline at end of file diff --git a/languages/c/templates/examples/synchronous.md b/languages/c/templates/examples/synchronous.md deleted file mode 100644 index 6e8e1e82..00000000 --- a/languages/c/templates/examples/synchronous.md +++ /dev/null @@ -1,4 +0,0 @@ -import { ${module} } from '${package.name}' - -const ${method.result.name} = ${module}.${method.name}(${example.params}) -console.log(${method.result.name}) \ No newline at end of file diff --git a/languages/c/templates/examples/temporal-set.md b/languages/c/templates/examples/temporal-set.md deleted file mode 100644 index 4a8e94ea..00000000 --- a/languages/c/templates/examples/temporal-set.md +++ /dev/null @@ -1,13 +0,0 @@ -import { ${module} } from '${package.name}' - -const process = ${module}.${method.name}(function(${example.params}${if.params},${end.if.params} - ${method.item} => { - console.log('Added to temporal set:') - console.dir(${method.item}) - }, - ${method.item} => { - console.log('Removed from temporal set:') - console.dir(${method.item}) - }) - -setTimeout( () => process.stop(), 10000) \ No newline at end of file diff --git a/languages/c/templates/imports/context-event.mjs b/languages/c/templates/imports/context-event.mjs deleted file mode 100644 index fcd3186b..00000000 --- a/languages/c/templates/imports/context-event.mjs +++ /dev/null @@ -1 +0,0 @@ -import { registerEventContext } from '../Events/index.mjs' diff --git a/languages/c/templates/imports/default.c b/languages/c/templates/imports/default.c new file mode 100644 index 00000000..a38b58ef --- /dev/null +++ b/languages/c/templates/imports/default.c @@ -0,0 +1 @@ +#include "Common/${info.title}.h" diff --git a/languages/c/templates/imports/event.mjs b/languages/c/templates/imports/event.mjs deleted file mode 100644 index bc019bca..00000000 --- a/languages/c/templates/imports/event.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import Events from '../Events/index.mjs' -import { registerEvents } from '../Events/index.mjs' diff --git a/languages/c/templates/imports/property.mjs b/languages/c/templates/imports/property.mjs deleted file mode 100644 index 7107a163..00000000 --- a/languages/c/templates/imports/property.mjs +++ /dev/null @@ -1 +0,0 @@ -import Prop from '../Prop/index.mjs' diff --git a/languages/c/templates/imports/provider.mjs b/languages/c/templates/imports/provider.mjs deleted file mode 100644 index b3ea7b4f..00000000 --- a/languages/c/templates/imports/provider.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import ProvideManager from '../ProvideManager/index.mjs' -import { registerProviderInterface } from '../ProvideManager/index.mjs' diff --git a/languages/c/templates/imports/rpc.mjs b/languages/c/templates/imports/rpc.mjs deleted file mode 100644 index af459a1e..00000000 --- a/languages/c/templates/imports/rpc.mjs +++ /dev/null @@ -1 +0,0 @@ -import Transport from '../Transport/index.mjs' diff --git a/languages/c/templates/imports/temporal-set.mjs b/languages/c/templates/imports/temporal-set.mjs deleted file mode 100644 index 089d35b1..00000000 --- a/languages/c/templates/imports/temporal-set.mjs +++ /dev/null @@ -1 +0,0 @@ -import TemporalSet from '../TemporalSet/index.mjs' \ No newline at end of file diff --git a/languages/c/templates/imports/x-method.mjs b/languages/c/templates/imports/x-method.mjs deleted file mode 100644 index 42453ecb..00000000 --- a/languages/c/templates/imports/x-method.mjs +++ /dev/null @@ -1 +0,0 @@ -import Results from '../Results/index.mjs' \ No newline at end of file diff --git a/languages/c/templates/initializations/deprecated.mjs b/languages/c/templates/initializations/deprecated.mjs deleted file mode 100644 index 737d1c25..00000000 --- a/languages/c/templates/initializations/deprecated.mjs +++ /dev/null @@ -1 +0,0 @@ -Transport.registerDeprecatedMethod('${info.title}', '${method.name}', 'Use ${method.alternative} instead.') diff --git a/languages/c/templates/initializations/event.mjs b/languages/c/templates/initializations/event.mjs deleted file mode 100644 index c151f674..00000000 --- a/languages/c/templates/initializations/event.mjs +++ /dev/null @@ -1 +0,0 @@ -registerEvents('${info.title}', ${events.array}) diff --git a/languages/c/templates/initializations/provider.mjs b/languages/c/templates/initializations/provider.mjs deleted file mode 100644 index b113d236..00000000 --- a/languages/c/templates/initializations/provider.mjs +++ /dev/null @@ -1 +0,0 @@ -registerProviderInterface('${capability}', '${info.title}', ${interface}) diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 7d10ba97..49f76ce1 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -1,5 +1,5 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_${method.Name}(${method.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { +uint32_t ${info.title}_${method.Name}(${method.params.list}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { uint32_t status = FireboltSDKErrorUnavailable; FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { diff --git a/languages/c/templates/methods/once.js b/languages/c/templates/methods/listen.c similarity index 100% rename from languages/c/templates/methods/once.js rename to languages/c/templates/methods/listen.c diff --git a/languages/c/templates/methods/rpc-only.js b/languages/c/templates/methods/once.c similarity index 100% rename from languages/c/templates/methods/rpc-only.js rename to languages/c/templates/methods/once.c diff --git a/languages/c/templates/methods/polymorphic-reducer.js b/languages/c/templates/methods/polymorphic-reducer.c similarity index 100% rename from languages/c/templates/methods/polymorphic-reducer.js rename to languages/c/templates/methods/polymorphic-reducer.c diff --git a/languages/c/templates/methods/provide.js b/languages/c/templates/methods/provide.c similarity index 100% rename from languages/c/templates/methods/provide.js rename to languages/c/templates/methods/provide.c diff --git a/languages/c/templates/methods/rpc-only.c b/languages/c/templates/methods/rpc-only.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/modules/include/Common/Module.h b/languages/c/templates/modules/include/Common/Module.h index 22c25143..2834b997 100644 --- a/languages/c/templates/modules/include/Common/Module.h +++ b/languages/c/templates/modules/include/Common/Module.h @@ -25,6 +25,12 @@ extern "C" { #endif + // Enums + + /* ${ENUMS}} */ + + // Schemas + /* ${SCHEMAS} */ #ifdef __cplusplus diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h index 92bab4f7..e24c869f 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/Module.h @@ -20,7 +20,7 @@ #define _${info.TITLE}_H #include "Firebolt.h" -#include "Common/${info.title}.h" +/* ${IMPORTS} */ #ifdef __cplusplus extern "C" { @@ -28,6 +28,7 @@ extern "C" { /* ${SCHEMAS} */ + /* ${ACCESSORS} */ /* ${DECLARATIONS} */ #ifdef __cplusplus diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 2417f708..0783b416 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -16,17 +16,22 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "FireboltSDK.h" +#include "Firebolt.h" #include "${info.title}.h" -#include "Common/${info.title}.h" #include "JsonData_${info.title}.h" +/* ${IMPORTS} */ + + #ifdef __cplusplus extern "C" { #endif - /* ${METHODS} */ +/* ${TYPES} */ #ifdef __cplusplus } #endif + +/* ${ACCESSORS} */ +/* ${METHODS} */ diff --git a/languages/c/templates/schemas/default.js b/languages/c/templates/schemas/default.c similarity index 100% rename from languages/c/templates/schemas/default.js rename to languages/c/templates/schemas/default.c diff --git a/languages/c/templates/schemas/include/Common/Module.h b/languages/c/templates/schemas/include/Common/Module.h index 5582d8ea..50ef1fd9 100644 --- a/languages/c/templates/schemas/include/Common/Module.h +++ b/languages/c/templates/schemas/include/Common/Module.h @@ -16,10 +16,25 @@ * SPDX-License-Identifier: Apache-2.0 */ -namespace FireboltSDK { +#ifndef _COMMON_${info.TITLE}_H +#define _COMMON_${info.TITLE}_H - /* ${DECLARATIONS} */ +#include "Firebolt.h" - /* ${SCHEMAS} */ +#ifdef __cplusplus +extern "C" { +#endif + // Enums + + /* ${ENUMS} */ + + // Types + + /* ${TYPES} */ + +#ifdef __cplusplus } +#endif + +#endif // Header Include Guard \ No newline at end of file diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/Module_Common.cpp index 8460c52a..632f38d6 100644 --- a/languages/c/templates/schemas/src/Module_Common.cpp +++ b/languages/c/templates/schemas/src/Module_Common.cpp @@ -16,11 +16,19 @@ * SPDX-License-Identifier: Apache-2.0 */ -/* ${IMPORTS} */ +#include "Firebolt.h" +#include "${info.title}.h" +#include "Common/${info.title}.h" +#include "JsonData_${info.title}.h" +#ifdef __cplusplus +extern "C" { +#endif -namespace FireboltSDK { - + /* ${TYPES} */ + /* ${ACCESSORS} */ /* ${METHODS} */ +#ifdef __cplusplus } +#endif diff --git a/languages/c/templates/sdk/CMakeLists.txt b/languages/c/templates/sdk/CMakeLists.txt new file mode 100644 index 00000000..a29658f7 --- /dev/null +++ b/languages/c/templates/sdk/CMakeLists.txt @@ -0,0 +1,49 @@ +# 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 + +cmake_minimum_required(VERSION 3.3) + +project(Firebolt) + +set(FIREBOLT_TRANSPORT_WAITTIME 1000 CACHE STRING "Maximum time to wait for Transport layer to get response") +set(FIREBOLT_LOGLEVEL "Info" CACHE STRING "Log level to be enabled") + +option(ENABLE_TESTS "Build openrpc native test" OFF) + +list(APPEND CMAKE_MODULE_PATH + "${CMAKE_SOURCE_DIR}/cmake" + "${SYSROOT_PATH}/usr/lib/cmake" + "${SYSROOT_PATH}/tools/cmake") +include(HelperFunctions) + +if (NOT DEFINED CMAKE_PREFIX_PATH) + set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) +endif() + +set(FIREBOLT_NAMESPACE ${PROJECT_NAME} CACHE STRING "Namespace of the project") + +find_package(WPEFramework CONFIG REQUIRED) + +add_subdirectory(src) + +if (ENABLE_TESTS) + add_subdirectory(test) +endif() + +# make sure others can make use cmake settings of Firebolt OpenRPC +configure_file( "${CMAKE_SOURCE_DIR}/cmake/project.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake" + @ONLY) diff --git a/languages/c/templates/sdk/build/CMakeCache.txt b/languages/c/templates/sdk/build/CMakeCache.txt new file mode 100644 index 00000000..f10d476d --- /dev/null +++ b/languages/c/templates/sdk/build/CMakeCache.txt @@ -0,0 +1,407 @@ +# This is the CMakeCache file. +# For build in directory: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build +# It was generated by CMake: /opt/homebrew/Cellar/cmake/3.25.3/bin/cmake +# You can edit this file to change values found and used by cmake. +# If you do not want to change any of the values, simply exit the editor. +# If you do want to change a value, simply edit, save, and exit the editor. +# The syntax for the file is as follows: +# KEY:TYPE=VALUE +# KEY is the name of a variable in the cache. +# TYPE is a hint to GUIs for the type of VALUE, DO NOT EDIT TYPE!. +# VALUE is the current value for the KEY. + +######################## +# EXTERNAL cache entries +######################## + +//Path to a program. +CMAKE_ADDR2LINE:FILEPATH=CMAKE_ADDR2LINE-NOTFOUND + +//Path to a program. +CMAKE_AR:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ar + +//Choose the type of build, options are: None Debug Release RelWithDebInfo +// MinSizeRel ... +CMAKE_BUILD_TYPE:STRING=Release + +//Enable/Disable color output during build. +CMAKE_COLOR_MAKEFILE:BOOL=ON + +//CXX compiler +CMAKE_CXX_COMPILER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/c++ + +//Flags used by the CXX compiler during all build types. +CMAKE_CXX_FLAGS:STRING=-D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION + +//Flags used by the CXX compiler during DEBUG builds. +CMAKE_CXX_FLAGS_DEBUG:STRING=-g + +//Flags used by the CXX compiler during MINSIZEREL builds. +CMAKE_CXX_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG + +//Flags used by the CXX compiler during RELEASE builds. +CMAKE_CXX_FLAGS_RELEASE:STRING=-O3 -DNDEBUG + +//Flags used by the CXX compiler during RELWITHDEBINFO builds. +CMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG + +//C compiler +CMAKE_C_COMPILER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/cc + +//Flags used by the C compiler during all build types. +CMAKE_C_FLAGS:STRING= + +//Flags used by the C compiler during DEBUG builds. +CMAKE_C_FLAGS_DEBUG:STRING=-g + +//Flags used by the C compiler during MINSIZEREL builds. +CMAKE_C_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG + +//Flags used by the C compiler during RELEASE builds. +CMAKE_C_FLAGS_RELEASE:STRING=-O3 -DNDEBUG + +//Flags used by the C compiler during RELWITHDEBINFO builds. +CMAKE_C_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG + +//Path to a program. +CMAKE_DLLTOOL:FILEPATH=CMAKE_DLLTOOL-NOTFOUND + +//Flags used by the linker during all build types. +CMAKE_EXE_LINKER_FLAGS:STRING= + +//Flags used by the linker during DEBUG builds. +CMAKE_EXE_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during MINSIZEREL builds. +CMAKE_EXE_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during RELEASE builds. +CMAKE_EXE_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during RELWITHDEBINFO builds. +CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//Enable/Disable output of compile commands during generation. +CMAKE_EXPORT_COMPILE_COMMANDS:BOOL= + +//Value Computed by CMake. +CMAKE_FIND_PACKAGE_REDIRECTS_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/pkgRedirects + +//Path to a program. +CMAKE_INSTALL_NAME_TOOL:FILEPATH=/usr/bin/install_name_tool + +//Install path prefix, prepended onto install directories. +CMAKE_INSTALL_PREFIX:PATH=/usr + +//No help, variable specified on the command line. +CMAKE_JS_INC:UNINITIALIZED=/Users/JLaciv000/.cmake-js/node-arm64/v19.6.1/include/node + +//No help, variable specified on the command line. +CMAKE_JS_SRC:UNINITIALIZED= + +//No help, variable specified on the command line. +CMAKE_JS_VERSION:UNINITIALIZED=undefined + +//No help, variable specified on the command line. +CMAKE_LIBRARY_OUTPUT_DIRECTORY:UNINITIALIZED=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/Release + +//Path to a program. +CMAKE_LINKER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ld + +//Path to a program. +CMAKE_MAKE_PROGRAM:FILEPATH=/usr/bin/make + +//Flags used by the linker during the creation of modules during +// all build types. +CMAKE_MODULE_LINKER_FLAGS:STRING= + +//Flags used by the linker during the creation of modules during +// DEBUG builds. +CMAKE_MODULE_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during the creation of modules during +// MINSIZEREL builds. +CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during the creation of modules during +// RELEASE builds. +CMAKE_MODULE_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during the creation of modules during +// RELWITHDEBINFO builds. +CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//No help, variable specified on the command line. +CMAKE_MSVC_RUNTIME_LIBRARY:UNINITIALIZED=MultiThreaded$<$:Debug> + +//Path to a program. +CMAKE_NM:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/nm + +//Path to a program. +CMAKE_OBJCOPY:FILEPATH=CMAKE_OBJCOPY-NOTFOUND + +//Path to a program. +CMAKE_OBJDUMP:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/objdump + +//Build architectures for OSX +CMAKE_OSX_ARCHITECTURES:STRING=arm64 + +//Minimum OS X version to target for deployment (at runtime); newer +// APIs weak linked. Set to empty string for default value. +CMAKE_OSX_DEPLOYMENT_TARGET:STRING= + +//The product will be built against the headers and libraries located +// inside the indicated SDK. +CMAKE_OSX_SYSROOT:PATH=/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk + +//Value Computed by CMake +CMAKE_PROJECT_DESCRIPTION:STATIC= + +//Value Computed by CMake +CMAKE_PROJECT_HOMEPAGE_URL:STATIC= + +//Value Computed by CMake +CMAKE_PROJECT_NAME:STATIC=Firebolt + +//Path to a program. +CMAKE_RANLIB:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ranlib + +//Path to a program. +CMAKE_READELF:FILEPATH=CMAKE_READELF-NOTFOUND + +//Flags used by the linker during the creation of shared libraries +// during all build types. +CMAKE_SHARED_LINKER_FLAGS:STRING=-undefined dynamic_lookup + +//Flags used by the linker during the creation of shared libraries +// during DEBUG builds. +CMAKE_SHARED_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during the creation of shared libraries +// during MINSIZEREL builds. +CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during the creation of shared libraries +// during RELEASE builds. +CMAKE_SHARED_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during the creation of shared libraries +// during RELWITHDEBINFO builds. +CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//If set, runtime paths are not added when installing shared libraries, +// but are added when building. +CMAKE_SKIP_INSTALL_RPATH:BOOL=NO + +//If set, runtime paths are not added when using shared libraries. +CMAKE_SKIP_RPATH:BOOL=NO + +//Flags used by the linker during the creation of static libraries +// during all build types. +CMAKE_STATIC_LINKER_FLAGS:STRING= + +//Flags used by the linker during the creation of static libraries +// during DEBUG builds. +CMAKE_STATIC_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during the creation of static libraries +// during MINSIZEREL builds. +CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during the creation of static libraries +// during RELEASE builds. +CMAKE_STATIC_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during the creation of static libraries +// during RELWITHDEBINFO builds. +CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//Path to a program. +CMAKE_STRIP:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/strip + +//If this value is on, makefiles will be generated without the +// .SILENT directive, and all commands will be echoed to the console +// during the make. This is useful for debugging only. With Visual +// Studio IDE projects all commands are done without /nologo. +CMAKE_VERBOSE_MAKEFILE:BOOL=FALSE + +//Build openrpc native test +ENABLE_TESTS:BOOL=OFF + +//Log level to be enabled +FIREBOLT_LOGLEVEL:STRING=Info + +//Namespace of the project +FIREBOLT_NAMESPACE:STRING=Firebolt + +//Maximum time to wait for Transport layer to get response +FIREBOLT_TRANSPORT_WAITTIME:STRING=1000 + +//Value Computed by CMake +Firebolt_BINARY_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build + +//Value Computed by CMake +Firebolt_IS_TOP_LEVEL:STATIC=ON + +//Value Computed by CMake +Firebolt_SOURCE_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native + +//No help, variable specified on the command line. +GENERATED_CODE_PATH:UNINITIALIZED=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/build/sdk/native-c + +//No help, variable specified on the command line. +NODE_ARCH:UNINITIALIZED=arm64 + +//No help, variable specified on the command line. +NODE_RUNTIME:UNINITIALIZED=node + +//No help, variable specified on the command line. +NODE_RUNTIMEVERSION:UNINITIALIZED=19.6.1 + +//The directory containing a CMake configuration file for WPEFramework. +WPEFramework_DIR:PATH=WPEFramework_DIR-NOTFOUND + + +######################## +# INTERNAL cache entries +######################## + +//ADVANCED property for variable: CMAKE_ADDR2LINE +CMAKE_ADDR2LINE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_AR +CMAKE_AR-ADVANCED:INTERNAL=1 +//This is the directory where this CMakeCache.txt was created +CMAKE_CACHEFILE_DIR:INTERNAL=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build +//Major version of cmake used to create the current loaded cache +CMAKE_CACHE_MAJOR_VERSION:INTERNAL=3 +//Minor version of cmake used to create the current loaded cache +CMAKE_CACHE_MINOR_VERSION:INTERNAL=25 +//Patch version of cmake used to create the current loaded cache +CMAKE_CACHE_PATCH_VERSION:INTERNAL=3 +//ADVANCED property for variable: CMAKE_COLOR_MAKEFILE +CMAKE_COLOR_MAKEFILE-ADVANCED:INTERNAL=1 +//Path to CMake executable. +CMAKE_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake +//Path to cpack program executable. +CMAKE_CPACK_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/cpack +//Path to ctest program executable. +CMAKE_CTEST_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/ctest +//ADVANCED property for variable: CMAKE_CXX_COMPILER +CMAKE_CXX_COMPILER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS +CMAKE_CXX_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_DEBUG +CMAKE_CXX_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_MINSIZEREL +CMAKE_CXX_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELEASE +CMAKE_CXX_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELWITHDEBINFO +CMAKE_CXX_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_COMPILER +CMAKE_C_COMPILER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS +CMAKE_C_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_DEBUG +CMAKE_C_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_MINSIZEREL +CMAKE_C_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_RELEASE +CMAKE_C_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_RELWITHDEBINFO +CMAKE_C_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_DLLTOOL +CMAKE_DLLTOOL-ADVANCED:INTERNAL=1 +//Path to cache edit program executable. +CMAKE_EDIT_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/ccmake +//Executable file format +CMAKE_EXECUTABLE_FORMAT:INTERNAL=MACHO +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS +CMAKE_EXE_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_DEBUG +CMAKE_EXE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_MINSIZEREL +CMAKE_EXE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELEASE +CMAKE_EXE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXPORT_COMPILE_COMMANDS +CMAKE_EXPORT_COMPILE_COMMANDS-ADVANCED:INTERNAL=1 +//Name of external makefile project generator. +CMAKE_EXTRA_GENERATOR:INTERNAL= +//Name of generator. +CMAKE_GENERATOR:INTERNAL=Unix Makefiles +//Generator instance identifier. +CMAKE_GENERATOR_INSTANCE:INTERNAL= +//Name of generator platform. +CMAKE_GENERATOR_PLATFORM:INTERNAL= +//Name of generator toolset. +CMAKE_GENERATOR_TOOLSET:INTERNAL= +//Source directory with the top level CMakeLists.txt file for this +// project +CMAKE_HOME_DIRECTORY:INTERNAL=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native +//ADVANCED property for variable: CMAKE_INSTALL_NAME_TOOL +CMAKE_INSTALL_NAME_TOOL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_LINKER +CMAKE_LINKER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MAKE_PROGRAM +CMAKE_MAKE_PROGRAM-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS +CMAKE_MODULE_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_DEBUG +CMAKE_MODULE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL +CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELEASE +CMAKE_MODULE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_NM +CMAKE_NM-ADVANCED:INTERNAL=1 +//number of local generators +CMAKE_NUMBER_OF_MAKEFILES:INTERNAL=1 +//ADVANCED property for variable: CMAKE_OBJCOPY +CMAKE_OBJCOPY-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_OBJDUMP +CMAKE_OBJDUMP-ADVANCED:INTERNAL=1 +//Platform information initialized +CMAKE_PLATFORM_INFO_INITIALIZED:INTERNAL=1 +CMAKE_PREFIX_PATH:INTERNAL=/usr/lib/cmake +//ADVANCED property for variable: CMAKE_RANLIB +CMAKE_RANLIB-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_READELF +CMAKE_READELF-ADVANCED:INTERNAL=1 +//Path to CMake installation. +CMAKE_ROOT:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/share/cmake +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS +CMAKE_SHARED_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_DEBUG +CMAKE_SHARED_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL +CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELEASE +CMAKE_SHARED_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SKIP_INSTALL_RPATH +CMAKE_SKIP_INSTALL_RPATH-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SKIP_RPATH +CMAKE_SKIP_RPATH-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS +CMAKE_STATIC_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_DEBUG +CMAKE_STATIC_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL +CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELEASE +CMAKE_STATIC_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STRIP +CMAKE_STRIP-ADVANCED:INTERNAL=1 +//uname command +CMAKE_UNAME:INTERNAL=/usr/bin/uname +//ADVANCED property for variable: CMAKE_VERBOSE_MAKEFILE +CMAKE_VERBOSE_MAKEFILE-ADVANCED:INTERNAL=1 + diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake new file mode 100644 index 00000000..dc7a67f2 --- /dev/null +++ b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake @@ -0,0 +1,72 @@ +set(CMAKE_C_COMPILER "/Library/Developer/CommandLineTools/usr/bin/cc") +set(CMAKE_C_COMPILER_ARG1 "") +set(CMAKE_C_COMPILER_ID "AppleClang") +set(CMAKE_C_COMPILER_VERSION "13.1.6.13160021") +set(CMAKE_C_COMPILER_VERSION_INTERNAL "") +set(CMAKE_C_COMPILER_WRAPPER "") +set(CMAKE_C_STANDARD_COMPUTED_DEFAULT "17") +set(CMAKE_C_EXTENSIONS_COMPUTED_DEFAULT "ON") +set(CMAKE_C_COMPILE_FEATURES "c_std_90;c_function_prototypes;c_std_99;c_restrict;c_variadic_macros;c_std_11;c_static_assert;c_std_17;c_std_23") +set(CMAKE_C90_COMPILE_FEATURES "c_std_90;c_function_prototypes") +set(CMAKE_C99_COMPILE_FEATURES "c_std_99;c_restrict;c_variadic_macros") +set(CMAKE_C11_COMPILE_FEATURES "c_std_11;c_static_assert") +set(CMAKE_C17_COMPILE_FEATURES "c_std_17") +set(CMAKE_C23_COMPILE_FEATURES "c_std_23") + +set(CMAKE_C_PLATFORM_ID "Darwin") +set(CMAKE_C_SIMULATE_ID "") +set(CMAKE_C_COMPILER_FRONTEND_VARIANT "") +set(CMAKE_C_SIMULATE_VERSION "") + + + + +set(CMAKE_AR "/Library/Developer/CommandLineTools/usr/bin/ar") +set(CMAKE_C_COMPILER_AR "") +set(CMAKE_RANLIB "/Library/Developer/CommandLineTools/usr/bin/ranlib") +set(CMAKE_C_COMPILER_RANLIB "") +set(CMAKE_LINKER "/Library/Developer/CommandLineTools/usr/bin/ld") +set(CMAKE_MT "") +set(CMAKE_COMPILER_IS_GNUCC ) +set(CMAKE_C_COMPILER_LOADED 1) +set(CMAKE_C_COMPILER_WORKS TRUE) +set(CMAKE_C_ABI_COMPILED TRUE) + +set(CMAKE_C_COMPILER_ENV_VAR "CC") + +set(CMAKE_C_COMPILER_ID_RUN 1) +set(CMAKE_C_SOURCE_FILE_EXTENSIONS c;m) +set(CMAKE_C_IGNORE_EXTENSIONS h;H;o;O;obj;OBJ;def;DEF;rc;RC) +set(CMAKE_C_LINKER_PREFERENCE 10) + +# Save compiler ABI information. +set(CMAKE_C_SIZEOF_DATA_PTR "8") +set(CMAKE_C_COMPILER_ABI "") +set(CMAKE_C_BYTE_ORDER "LITTLE_ENDIAN") +set(CMAKE_C_LIBRARY_ARCHITECTURE "") + +if(CMAKE_C_SIZEOF_DATA_PTR) + set(CMAKE_SIZEOF_VOID_P "${CMAKE_C_SIZEOF_DATA_PTR}") +endif() + +if(CMAKE_C_COMPILER_ABI) + set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_C_COMPILER_ABI}") +endif() + +if(CMAKE_C_LIBRARY_ARCHITECTURE) + set(CMAKE_LIBRARY_ARCHITECTURE "") +endif() + +set(CMAKE_C_CL_SHOWINCLUDES_PREFIX "") +if(CMAKE_C_CL_SHOWINCLUDES_PREFIX) + set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_C_CL_SHOWINCLUDES_PREFIX}") +endif() + + + + + +set(CMAKE_C_IMPLICIT_INCLUDE_DIRECTORIES "/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include") +set(CMAKE_C_IMPLICIT_LINK_LIBRARIES "") +set(CMAKE_C_IMPLICIT_LINK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib") +set(CMAKE_C_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks") diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake new file mode 100644 index 00000000..67dc227a --- /dev/null +++ b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake @@ -0,0 +1,83 @@ +set(CMAKE_CXX_COMPILER "/Library/Developer/CommandLineTools/usr/bin/c++") +set(CMAKE_CXX_COMPILER_ARG1 "") +set(CMAKE_CXX_COMPILER_ID "AppleClang") +set(CMAKE_CXX_COMPILER_VERSION "13.1.6.13160021") +set(CMAKE_CXX_COMPILER_VERSION_INTERNAL "") +set(CMAKE_CXX_COMPILER_WRAPPER "") +set(CMAKE_CXX_STANDARD_COMPUTED_DEFAULT "98") +set(CMAKE_CXX_EXTENSIONS_COMPUTED_DEFAULT "ON") +set(CMAKE_CXX_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters;cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates;cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates;cxx_std_17;cxx_std_20;cxx_std_23") +set(CMAKE_CXX98_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters") +set(CMAKE_CXX11_COMPILE_FEATURES "cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates") +set(CMAKE_CXX14_COMPILE_FEATURES "cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates") +set(CMAKE_CXX17_COMPILE_FEATURES "cxx_std_17") +set(CMAKE_CXX20_COMPILE_FEATURES "cxx_std_20") +set(CMAKE_CXX23_COMPILE_FEATURES "cxx_std_23") + +set(CMAKE_CXX_PLATFORM_ID "Darwin") +set(CMAKE_CXX_SIMULATE_ID "") +set(CMAKE_CXX_COMPILER_FRONTEND_VARIANT "") +set(CMAKE_CXX_SIMULATE_VERSION "") + + + + +set(CMAKE_AR "/Library/Developer/CommandLineTools/usr/bin/ar") +set(CMAKE_CXX_COMPILER_AR "") +set(CMAKE_RANLIB "/Library/Developer/CommandLineTools/usr/bin/ranlib") +set(CMAKE_CXX_COMPILER_RANLIB "") +set(CMAKE_LINKER "/Library/Developer/CommandLineTools/usr/bin/ld") +set(CMAKE_MT "") +set(CMAKE_COMPILER_IS_GNUCXX ) +set(CMAKE_CXX_COMPILER_LOADED 1) +set(CMAKE_CXX_COMPILER_WORKS TRUE) +set(CMAKE_CXX_ABI_COMPILED TRUE) + +set(CMAKE_CXX_COMPILER_ENV_VAR "CXX") + +set(CMAKE_CXX_COMPILER_ID_RUN 1) +set(CMAKE_CXX_SOURCE_FILE_EXTENSIONS C;M;c++;cc;cpp;cxx;m;mm;mpp;CPP;ixx;cppm) +set(CMAKE_CXX_IGNORE_EXTENSIONS inl;h;hpp;HPP;H;o;O;obj;OBJ;def;DEF;rc;RC) + +foreach (lang C OBJC OBJCXX) + if (CMAKE_${lang}_COMPILER_ID_RUN) + foreach(extension IN LISTS CMAKE_${lang}_SOURCE_FILE_EXTENSIONS) + list(REMOVE_ITEM CMAKE_CXX_SOURCE_FILE_EXTENSIONS ${extension}) + endforeach() + endif() +endforeach() + +set(CMAKE_CXX_LINKER_PREFERENCE 30) +set(CMAKE_CXX_LINKER_PREFERENCE_PROPAGATES 1) + +# Save compiler ABI information. +set(CMAKE_CXX_SIZEOF_DATA_PTR "8") +set(CMAKE_CXX_COMPILER_ABI "") +set(CMAKE_CXX_BYTE_ORDER "LITTLE_ENDIAN") +set(CMAKE_CXX_LIBRARY_ARCHITECTURE "") + +if(CMAKE_CXX_SIZEOF_DATA_PTR) + set(CMAKE_SIZEOF_VOID_P "${CMAKE_CXX_SIZEOF_DATA_PTR}") +endif() + +if(CMAKE_CXX_COMPILER_ABI) + set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_CXX_COMPILER_ABI}") +endif() + +if(CMAKE_CXX_LIBRARY_ARCHITECTURE) + set(CMAKE_LIBRARY_ARCHITECTURE "") +endif() + +set(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX "") +if(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX) + set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_CXX_CL_SHOWINCLUDES_PREFIX}") +endif() + + + + + +set(CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1;/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include") +set(CMAKE_CXX_IMPLICIT_LINK_LIBRARIES "c++") +set(CMAKE_CXX_IMPLICIT_LINK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib") +set(CMAKE_CXX_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks") diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin new file mode 100755 index 0000000000000000000000000000000000000000..9b3e67d1d3825990645b4978d3a1e9da0ed43128 GIT binary patch literal 16999 zcmeI3Uuau(6vt1J4mw-bDPw=A+wvq%M%!73vA8vv&DOh>G+QHv1^Joe-nN%DNljAM zl(`jkY7xOI!Vn*PvJ@tW2r~~t@nOEH-NO_gw8E4Y8SKRe>sb7r-@Ug@j7;$P960yf zbI$K~a?a=G^?bX2`(8Vdk05^Nc4#O-beV#9BiaKUgenz}oQR%{o*Cw7qv*?xp(c;( zgm6%)L^PRbOzZpM#u&N&7KB;Rk`|@P)^yo*VE$R}&QWI=?+E)m*M_vv?8ZA@l*$(J zCGT`|J+t4b=e6wl^)>3>m72<*xAUg5^P>e_zj59#+QD&^VNZ&#>~h z;4}Y6w&79`ivJvSPnC+@6LzNCtW22jSvsNI$NH7x4Rex!tKWiOSUF)2!VyE|=*7+mzTkW;b zYDc)*>f743TAy1(u3}IBYc74XDYt?e_^tV+fVyeKjt}>h>=~;ts?5o9G1U`#o+xGv zAJ6oaE6OSsEHhO!j;Rx|s4)CVfjdF!HA3a*weJh$P*jJqFy()F*nK40$e zIUC+Q`%d-|^!D+w?~S}OJLiMg>~HQ(Z{;_1rF6GWd=t0I*kj7dn|3-+O}PoXT%NGJ zG=8gI)_-bW0>NE~aT_c<5JRWF0Qp;Z>6}N&LX(_?VE;T45Bl{=yc4VM6Pqn++5DY9SA;OK&E`)@a62ozG~Gg3vqrwOy?1(}Yo+U07k`F$ z7?Bt+1c@g+5Q2z4kcE(VVk9IUWCXE^ga;BL=A8RyyHz3a>YU`pZ)-|0EOudnCf zw+}yx7_%`DJ7_Uz)WO(6Ccuud$)NS1oHx4HdYU~O8t^n*w9DB?ITq$|K_KUTPr#q; z*6xehXUwoi!7(b7qzUIKr6Xk+u>6|u<4V05GX!nyYgqDF*YF-ToJSJzHZwXmpS()X zXO?W*)*RM7=k4*GYFy@Oyd|OK&+hl8kq?=opq*8pemwjg;qR4v>pgXnS%_#n8myWa zYm<=-nOfgv5o2BBFc9Kgu+$i~3+yVe@!BNN?O-GCURXO|Ed*@@MZq^f#aN8_7a0qe z1W@?TvC8(gWMxbZSIX&_3^qy`DAwVeb!t!?td8y9F?eTu;g@JNoC%I$f4{hdd)E zeq*{VrL>Y5g-CY zfCvx)B0vO)01+SpM1Tko0U|&IhyW2F0z`la5CI}U1c(3;AOb{y2oM1xKm>>Y5g-CY zfCvx)B0vO)01+SpM1Tko0U|&IhyW2F0z}}yA~1A-^$pEnnf@}Cd0EK54mnw7psXtc zGrC9fdsg%mr~|HdPBD{jD=2(t^$mb8t#xUfhTRpuF{#5dIGs{>A}K4$pjYzyy&mrI z)k$t2_;F--s_}Bx6=#}p<{9R_HC14~90hHhmBy**aoTM#1bqZrfGy5MqoP>Hk@fj% z{XFYy<1hnm=dDq$bSRN_C^V{spi(xoHKfMbY%IjVKJGRynH#KiEcnbhdYD7k>`u#^ zJ^D`=Hl}gfa8g>YYl3F$Jz|{#Oz`K{z_l7UZ}u)+f`j>_B0ZR-(lxt1=jV$0r_me)L)enUEBe|6e9e#*%eORpTb7ZmQE>poLc zH~P}0y%($?}6|C|5qI)^f8eSKp>24 & 0x00FF) +# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) +# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) + +#elif defined(__BORLANDC__) +# define COMPILER_ID "Borland" + /* __BORLANDC__ = 0xVRR */ +# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) +# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) + +#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 +# define COMPILER_ID "Watcom" + /* __WATCOMC__ = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__WATCOMC__) +# define COMPILER_ID "OpenWatcom" + /* __WATCOMC__ = VVRP + 1100 */ +# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__SUNPRO_C) +# define COMPILER_ID "SunPro" +# if __SUNPRO_C >= 0x5100 + /* __SUNPRO_C = 0xVRRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>12) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xFF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) +# else + /* __SUNPRO_CC = 0xVRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>8) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) +# endif + +#elif defined(__HP_cc) +# define COMPILER_ID "HP" + /* __HP_cc = VVRRPP */ +# define COMPILER_VERSION_MAJOR DEC(__HP_cc/10000) +# define COMPILER_VERSION_MINOR DEC(__HP_cc/100 % 100) +# define COMPILER_VERSION_PATCH DEC(__HP_cc % 100) + +#elif defined(__DECC) +# define COMPILER_ID "Compaq" + /* __DECC_VER = VVRRTPPPP */ +# define COMPILER_VERSION_MAJOR DEC(__DECC_VER/10000000) +# define COMPILER_VERSION_MINOR DEC(__DECC_VER/100000 % 100) +# define COMPILER_VERSION_PATCH DEC(__DECC_VER % 10000) + +#elif defined(__IBMC__) && defined(__COMPILER_VER__) +# define COMPILER_ID "zOS" + /* __IBMC__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) + +#elif defined(__open_xl__) && defined(__clang__) +# define COMPILER_ID "IBMClang" +# define COMPILER_VERSION_MAJOR DEC(__open_xl_version__) +# define COMPILER_VERSION_MINOR DEC(__open_xl_release__) +# define COMPILER_VERSION_PATCH DEC(__open_xl_modification__) +# define COMPILER_VERSION_TWEAK DEC(__open_xl_ptf_fix_level__) + + +#elif defined(__ibmxl__) && defined(__clang__) +# define COMPILER_ID "XLClang" +# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) +# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) +# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) +# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) + + +#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ >= 800 +# define COMPILER_ID "XL" + /* __IBMC__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) + +#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ < 800 +# define COMPILER_ID "VisualAge" + /* __IBMC__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) + +#elif defined(__NVCOMPILER) +# define COMPILER_ID "NVHPC" +# define COMPILER_VERSION_MAJOR DEC(__NVCOMPILER_MAJOR__) +# define COMPILER_VERSION_MINOR DEC(__NVCOMPILER_MINOR__) +# if defined(__NVCOMPILER_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__NVCOMPILER_PATCHLEVEL__) +# endif + +#elif defined(__PGI) +# define COMPILER_ID "PGI" +# define COMPILER_VERSION_MAJOR DEC(__PGIC__) +# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) +# if defined(__PGIC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) +# endif + +#elif defined(_CRAYC) +# define COMPILER_ID "Cray" +# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) +# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) + +#elif defined(__TI_COMPILER_VERSION__) +# define COMPILER_ID "TI" + /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ +# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) +# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) +# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) + +#elif defined(__CLANG_FUJITSU) +# define COMPILER_ID "FujitsuClang" +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# define COMPILER_VERSION_INTERNAL_STR __clang_version__ + + +#elif defined(__FUJITSU) +# define COMPILER_ID "Fujitsu" +# if defined(__FCC_version__) +# define COMPILER_VERSION __FCC_version__ +# elif defined(__FCC_major__) +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# endif +# if defined(__fcc_version) +# define COMPILER_VERSION_INTERNAL DEC(__fcc_version) +# elif defined(__FCC_VERSION) +# define COMPILER_VERSION_INTERNAL DEC(__FCC_VERSION) +# endif + + +#elif defined(__ghs__) +# define COMPILER_ID "GHS" +/* __GHS_VERSION_NUMBER = VVVVRP */ +# ifdef __GHS_VERSION_NUMBER +# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) +# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) +# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) +# endif + +#elif defined(__TASKING__) +# define COMPILER_ID "Tasking" + # define COMPILER_VERSION_MAJOR DEC(__VERSION__/1000) + # define COMPILER_VERSION_MINOR DEC(__VERSION__ % 100) +# define COMPILER_VERSION_INTERNAL DEC(__VERSION__) + +#elif defined(__TINYC__) +# define COMPILER_ID "TinyCC" + +#elif defined(__BCC__) +# define COMPILER_ID "Bruce" + +#elif defined(__SCO_VERSION__) +# define COMPILER_ID "SCO" + +#elif defined(__ARMCC_VERSION) && !defined(__clang__) +# define COMPILER_ID "ARMCC" +#if __ARMCC_VERSION >= 1000000 + /* __ARMCC_VERSION = VRRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#else + /* __ARMCC_VERSION = VRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#endif + + +#elif defined(__clang__) && defined(__apple_build_version__) +# define COMPILER_ID "AppleClang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif +# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) + +#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) +# define COMPILER_ID "ARMClang" + # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) +# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) + +#elif defined(__clang__) +# define COMPILER_ID "Clang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif + +#elif defined(__LCC__) && (defined(__GNUC__) || defined(__GNUG__) || defined(__MCST__)) +# define COMPILER_ID "LCC" +# define COMPILER_VERSION_MAJOR DEC(1) +# if defined(__LCC__) +# define COMPILER_VERSION_MINOR DEC(__LCC__- 100) +# endif +# if defined(__LCC_MINOR__) +# define COMPILER_VERSION_PATCH DEC(__LCC_MINOR__) +# endif +# if defined(__GNUC__) && defined(__GNUC_MINOR__) +# define SIMULATE_ID "GNU" +# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) +# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) +# if defined(__GNUC_PATCHLEVEL__) +# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif +# endif + +#elif defined(__GNUC__) +# define COMPILER_ID "GNU" +# define COMPILER_VERSION_MAJOR DEC(__GNUC__) +# if defined(__GNUC_MINOR__) +# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) +# endif +# if defined(__GNUC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif + +#elif defined(_MSC_VER) +# define COMPILER_ID "MSVC" + /* _MSC_VER = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) +# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) +# if defined(_MSC_FULL_VER) +# if _MSC_VER >= 1400 + /* _MSC_FULL_VER = VVRRPPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) +# else + /* _MSC_FULL_VER = VVRRPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) +# endif +# endif +# if defined(_MSC_BUILD) +# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) +# endif + +#elif defined(_ADI_COMPILER) +# define COMPILER_ID "ADSP" +#if defined(__VERSIONNUM__) + /* __VERSIONNUM__ = 0xVVRRPPTT */ +# define COMPILER_VERSION_MAJOR DEC(__VERSIONNUM__ >> 24 & 0xFF) +# define COMPILER_VERSION_MINOR DEC(__VERSIONNUM__ >> 16 & 0xFF) +# define COMPILER_VERSION_PATCH DEC(__VERSIONNUM__ >> 8 & 0xFF) +# define COMPILER_VERSION_TWEAK DEC(__VERSIONNUM__ & 0xFF) +#endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# define COMPILER_ID "IAR" +# if defined(__VER__) && defined(__ICCARM__) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) +# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) +# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__) || defined(__ICCSTM8__)) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) +# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) +# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# endif + +#elif defined(__SDCC_VERSION_MAJOR) || defined(SDCC) +# define COMPILER_ID "SDCC" +# if defined(__SDCC_VERSION_MAJOR) +# define COMPILER_VERSION_MAJOR DEC(__SDCC_VERSION_MAJOR) +# define COMPILER_VERSION_MINOR DEC(__SDCC_VERSION_MINOR) +# define COMPILER_VERSION_PATCH DEC(__SDCC_VERSION_PATCH) +# else + /* SDCC = VRP */ +# define COMPILER_VERSION_MAJOR DEC(SDCC/100) +# define COMPILER_VERSION_MINOR DEC(SDCC/10 % 10) +# define COMPILER_VERSION_PATCH DEC(SDCC % 10) +# endif + + +/* These compilers are either not known or too old to define an + identification macro. Try to identify the platform and guess that + it is the native compiler. */ +#elif defined(__hpux) || defined(__hpua) +# define COMPILER_ID "HP" + +#else /* unknown compiler */ +# define COMPILER_ID "" +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; +#ifdef SIMULATE_ID +char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; +#endif + +#ifdef __QNXNTO__ +char const* qnxnto = "INFO" ":" "qnxnto[]"; +#endif + +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) +char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; +#endif + +#define STRINGIFY_HELPER(X) #X +#define STRINGIFY(X) STRINGIFY_HELPER(X) + +/* Identify known platforms by name. */ +#if defined(__linux) || defined(__linux__) || defined(linux) +# define PLATFORM_ID "Linux" + +#elif defined(__MSYS__) +# define PLATFORM_ID "MSYS" + +#elif defined(__CYGWIN__) +# define PLATFORM_ID "Cygwin" + +#elif defined(__MINGW32__) +# define PLATFORM_ID "MinGW" + +#elif defined(__APPLE__) +# define PLATFORM_ID "Darwin" + +#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) +# define PLATFORM_ID "Windows" + +#elif defined(__FreeBSD__) || defined(__FreeBSD) +# define PLATFORM_ID "FreeBSD" + +#elif defined(__NetBSD__) || defined(__NetBSD) +# define PLATFORM_ID "NetBSD" + +#elif defined(__OpenBSD__) || defined(__OPENBSD) +# define PLATFORM_ID "OpenBSD" + +#elif defined(__sun) || defined(sun) +# define PLATFORM_ID "SunOS" + +#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) +# define PLATFORM_ID "AIX" + +#elif defined(__hpux) || defined(__hpux__) +# define PLATFORM_ID "HP-UX" + +#elif defined(__HAIKU__) +# define PLATFORM_ID "Haiku" + +#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) +# define PLATFORM_ID "BeOS" + +#elif defined(__QNX__) || defined(__QNXNTO__) +# define PLATFORM_ID "QNX" + +#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) +# define PLATFORM_ID "Tru64" + +#elif defined(__riscos) || defined(__riscos__) +# define PLATFORM_ID "RISCos" + +#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) +# define PLATFORM_ID "SINIX" + +#elif defined(__UNIX_SV__) +# define PLATFORM_ID "UNIX_SV" + +#elif defined(__bsdos__) +# define PLATFORM_ID "BSDOS" + +#elif defined(_MPRAS) || defined(MPRAS) +# define PLATFORM_ID "MP-RAS" + +#elif defined(__osf) || defined(__osf__) +# define PLATFORM_ID "OSF1" + +#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) +# define PLATFORM_ID "SCO_SV" + +#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) +# define PLATFORM_ID "ULTRIX" + +#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) +# define PLATFORM_ID "Xenix" + +#elif defined(__WATCOMC__) +# if defined(__LINUX__) +# define PLATFORM_ID "Linux" + +# elif defined(__DOS__) +# define PLATFORM_ID "DOS" + +# elif defined(__OS2__) +# define PLATFORM_ID "OS2" + +# elif defined(__WINDOWS__) +# define PLATFORM_ID "Windows3x" + +# elif defined(__VXWORKS__) +# define PLATFORM_ID "VxWorks" + +# else /* unknown platform */ +# define PLATFORM_ID +# endif + +#elif defined(__INTEGRITY) +# if defined(INT_178B) +# define PLATFORM_ID "Integrity178" + +# else /* regular Integrity */ +# define PLATFORM_ID "Integrity" +# endif + +# elif defined(_ADI_COMPILER) +# define PLATFORM_ID "ADSP" + +#else /* unknown platform */ +# define PLATFORM_ID + +#endif + +/* For windows compilers MSVC and Intel we can determine + the architecture of the compiler being used. This is because + the compilers do not have flags that can change the architecture, + but rather depend on which compiler is being used +*/ +#if defined(_WIN32) && defined(_MSC_VER) +# if defined(_M_IA64) +# define ARCHITECTURE_ID "IA64" + +# elif defined(_M_ARM64EC) +# define ARCHITECTURE_ID "ARM64EC" + +# elif defined(_M_X64) || defined(_M_AMD64) +# define ARCHITECTURE_ID "x64" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# elif defined(_M_ARM64) +# define ARCHITECTURE_ID "ARM64" + +# elif defined(_M_ARM) +# if _M_ARM == 4 +# define ARCHITECTURE_ID "ARMV4I" +# elif _M_ARM == 5 +# define ARCHITECTURE_ID "ARMV5I" +# else +# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) +# endif + +# elif defined(_M_MIPS) +# define ARCHITECTURE_ID "MIPS" + +# elif defined(_M_SH) +# define ARCHITECTURE_ID "SHx" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__WATCOMC__) +# if defined(_M_I86) +# define ARCHITECTURE_ID "I86" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# if defined(__ICCARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__ICCRX__) +# define ARCHITECTURE_ID "RX" + +# elif defined(__ICCRH850__) +# define ARCHITECTURE_ID "RH850" + +# elif defined(__ICCRL78__) +# define ARCHITECTURE_ID "RL78" + +# elif defined(__ICCRISCV__) +# define ARCHITECTURE_ID "RISCV" + +# elif defined(__ICCAVR__) +# define ARCHITECTURE_ID "AVR" + +# elif defined(__ICC430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__ICCV850__) +# define ARCHITECTURE_ID "V850" + +# elif defined(__ICC8051__) +# define ARCHITECTURE_ID "8051" + +# elif defined(__ICCSTM8__) +# define ARCHITECTURE_ID "STM8" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__ghs__) +# if defined(__PPC64__) +# define ARCHITECTURE_ID "PPC64" + +# elif defined(__ppc__) +# define ARCHITECTURE_ID "PPC" + +# elif defined(__ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__x86_64__) +# define ARCHITECTURE_ID "x64" + +# elif defined(__i386__) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__TI_COMPILER_VERSION__) +# if defined(__TI_ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__MSP430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__TMS320C28XX__) +# define ARCHITECTURE_ID "TMS320C28x" + +# elif defined(__TMS320C6X__) || defined(_TMS320C6X) +# define ARCHITECTURE_ID "TMS320C6x" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +# elif defined(__ADSPSHARC__) +# define ARCHITECTURE_ID "SHARC" + +# elif defined(__ADSPBLACKFIN__) +# define ARCHITECTURE_ID "Blackfin" + +#elif defined(__TASKING__) + +# if defined(__CTC__) || defined(__CPTC__) +# define ARCHITECTURE_ID "TriCore" + +# elif defined(__CMCS__) +# define ARCHITECTURE_ID "MCS" + +# elif defined(__CARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__CARC__) +# define ARCHITECTURE_ID "ARC" + +# elif defined(__C51__) +# define ARCHITECTURE_ID "8051" + +# elif defined(__CPCP__) +# define ARCHITECTURE_ID "PCP" + +# else +# define ARCHITECTURE_ID "" +# endif + +#else +# define ARCHITECTURE_ID +#endif + +/* Convert integer to decimal digit literals. */ +#define DEC(n) \ + ('0' + (((n) / 10000000)%10)), \ + ('0' + (((n) / 1000000)%10)), \ + ('0' + (((n) / 100000)%10)), \ + ('0' + (((n) / 10000)%10)), \ + ('0' + (((n) / 1000)%10)), \ + ('0' + (((n) / 100)%10)), \ + ('0' + (((n) / 10)%10)), \ + ('0' + ((n) % 10)) + +/* Convert integer to hex digit literals. */ +#define HEX(n) \ + ('0' + ((n)>>28 & 0xF)), \ + ('0' + ((n)>>24 & 0xF)), \ + ('0' + ((n)>>20 & 0xF)), \ + ('0' + ((n)>>16 & 0xF)), \ + ('0' + ((n)>>12 & 0xF)), \ + ('0' + ((n)>>8 & 0xF)), \ + ('0' + ((n)>>4 & 0xF)), \ + ('0' + ((n) & 0xF)) + +/* Construct a string literal encoding the version number. */ +#ifdef COMPILER_VERSION +char const* info_version = "INFO" ":" "compiler_version[" COMPILER_VERSION "]"; + +/* Construct a string literal encoding the version number components. */ +#elif defined(COMPILER_VERSION_MAJOR) +char const info_version[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', + COMPILER_VERSION_MAJOR, +# ifdef COMPILER_VERSION_MINOR + '.', COMPILER_VERSION_MINOR, +# ifdef COMPILER_VERSION_PATCH + '.', COMPILER_VERSION_PATCH, +# ifdef COMPILER_VERSION_TWEAK + '.', COMPILER_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct a string literal encoding the internal version number. */ +#ifdef COMPILER_VERSION_INTERNAL +char const info_version_internal[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', + 'i','n','t','e','r','n','a','l','[', + COMPILER_VERSION_INTERNAL,']','\0'}; +#elif defined(COMPILER_VERSION_INTERNAL_STR) +char const* info_version_internal = "INFO" ":" "compiler_version_internal[" COMPILER_VERSION_INTERNAL_STR "]"; +#endif + +/* Construct a string literal encoding the version number components. */ +#ifdef SIMULATE_VERSION_MAJOR +char const info_simulate_version[] = { + 'I', 'N', 'F', 'O', ':', + 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', + SIMULATE_VERSION_MAJOR, +# ifdef SIMULATE_VERSION_MINOR + '.', SIMULATE_VERSION_MINOR, +# ifdef SIMULATE_VERSION_PATCH + '.', SIMULATE_VERSION_PATCH, +# ifdef SIMULATE_VERSION_TWEAK + '.', SIMULATE_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; +char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; + + + +#if !defined(__STDC__) && !defined(__clang__) +# if defined(_MSC_VER) || defined(__ibmxl__) || defined(__IBMC__) +# define C_VERSION "90" +# else +# define C_VERSION +# endif +#elif __STDC_VERSION__ > 201710L +# define C_VERSION "23" +#elif __STDC_VERSION__ >= 201710L +# define C_VERSION "17" +#elif __STDC_VERSION__ >= 201000L +# define C_VERSION "11" +#elif __STDC_VERSION__ >= 199901L +# define C_VERSION "99" +#else +# define C_VERSION "90" +#endif +const char* info_language_standard_default = + "INFO" ":" "standard_default[" C_VERSION "]"; + +const char* info_language_extensions_default = "INFO" ":" "extensions_default[" +#if (defined(__clang__) || defined(__GNUC__) || defined(__xlC__) || \ + defined(__TI_COMPILER_VERSION__)) && \ + !defined(__STRICT_ANSI__) + "ON" +#else + "OFF" +#endif +"]"; + +/*--------------------------------------------------------------------------*/ + +#ifdef ID_VOID_MAIN +void main() {} +#else +# if defined(__CLASSIC_C__) +int main(argc, argv) int argc; char *argv[]; +# else +int main(int argc, char* argv[]) +# endif +{ + int require = 0; + require += info_compiler[argc]; + require += info_platform[argc]; + require += info_arch[argc]; +#ifdef COMPILER_VERSION_MAJOR + require += info_version[argc]; +#endif +#ifdef COMPILER_VERSION_INTERNAL + require += info_version_internal[argc]; +#endif +#ifdef SIMULATE_ID + require += info_simulate[argc]; +#endif +#ifdef SIMULATE_VERSION_MAJOR + require += info_simulate_version[argc]; +#endif +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) + require += info_cray[argc]; +#endif + require += info_language_standard_default[argc]; + require += info_language_extensions_default[argc]; + (void)argv; + return require; +} +#endif diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o new file mode 100644 index 0000000000000000000000000000000000000000..537fbf261a76f93972038901b25169a2bbc47274 GIT binary patch literal 1712 zcmb_cJ!n%=6uz;wrbZJ52c@6^7pIWdlqyOfp;1&q+aW_FlnbM8Iw+;_kGKK=Uf`-Bi7 z0i(w>M)3$9aSYfwjIS!I=z&L%dbCZ%s}_<rdz)YvA0HYv+3-?QBs2c#UYr|Wo}&rIo+0dl*8pp+HUHwP5`=CXzCkY{+GmpJqe z^{C`F`qO(H&ZhmA8*Xd3;mQ8ix!yHi)SKvUv=;ePuiiAvzHGbqZMPz2J~uk&HP?%C zFpj>cWEaS(u`SOdcNQbasV}Tn(j%)}% za%=g<%2hfV+p)Y-w%K&7CC7AYYeHq3j_Fq$UcHnvJscZHO|QIOV!!2^ZpHK}vSL-u zw&RzK%bdY|vD}so84YqP%WHr6vB&z8_biVJmXgYhR3dPahISScM#@-BCg+Wb7peOc zS66bZgO^}XPkuYV^b_Do@J9iro4^>j6JVM&1pVam0j3v#QSfAdY0@6FmOm3y4i@8<*X7~Z$a`P`qk_SaKIb%|g!jTF5YI&NLI#U*ukag2`Ii@wwl*BF^ czusKnN(nfiDNW&k&T9$>)X)?TD9J>24 & 0x00FF) +# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) +# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) + +#elif defined(__BORLANDC__) +# define COMPILER_ID "Borland" + /* __BORLANDC__ = 0xVRR */ +# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) +# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) + +#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 +# define COMPILER_ID "Watcom" + /* __WATCOMC__ = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__WATCOMC__) +# define COMPILER_ID "OpenWatcom" + /* __WATCOMC__ = VVRP + 1100 */ +# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__SUNPRO_CC) +# define COMPILER_ID "SunPro" +# if __SUNPRO_CC >= 0x5100 + /* __SUNPRO_CC = 0xVRRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>12) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xFF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) +# else + /* __SUNPRO_CC = 0xVRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>8) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) +# endif + +#elif defined(__HP_aCC) +# define COMPILER_ID "HP" + /* __HP_aCC = VVRRPP */ +# define COMPILER_VERSION_MAJOR DEC(__HP_aCC/10000) +# define COMPILER_VERSION_MINOR DEC(__HP_aCC/100 % 100) +# define COMPILER_VERSION_PATCH DEC(__HP_aCC % 100) + +#elif defined(__DECCXX) +# define COMPILER_ID "Compaq" + /* __DECCXX_VER = VVRRTPPPP */ +# define COMPILER_VERSION_MAJOR DEC(__DECCXX_VER/10000000) +# define COMPILER_VERSION_MINOR DEC(__DECCXX_VER/100000 % 100) +# define COMPILER_VERSION_PATCH DEC(__DECCXX_VER % 10000) + +#elif defined(__IBMCPP__) && defined(__COMPILER_VER__) +# define COMPILER_ID "zOS" + /* __IBMCPP__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) + +#elif defined(__open_xl__) && defined(__clang__) +# define COMPILER_ID "IBMClang" +# define COMPILER_VERSION_MAJOR DEC(__open_xl_version__) +# define COMPILER_VERSION_MINOR DEC(__open_xl_release__) +# define COMPILER_VERSION_PATCH DEC(__open_xl_modification__) +# define COMPILER_VERSION_TWEAK DEC(__open_xl_ptf_fix_level__) + + +#elif defined(__ibmxl__) && defined(__clang__) +# define COMPILER_ID "XLClang" +# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) +# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) +# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) +# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) + + +#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ >= 800 +# define COMPILER_ID "XL" + /* __IBMCPP__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) + +#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ < 800 +# define COMPILER_ID "VisualAge" + /* __IBMCPP__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) + +#elif defined(__NVCOMPILER) +# define COMPILER_ID "NVHPC" +# define COMPILER_VERSION_MAJOR DEC(__NVCOMPILER_MAJOR__) +# define COMPILER_VERSION_MINOR DEC(__NVCOMPILER_MINOR__) +# if defined(__NVCOMPILER_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__NVCOMPILER_PATCHLEVEL__) +# endif + +#elif defined(__PGI) +# define COMPILER_ID "PGI" +# define COMPILER_VERSION_MAJOR DEC(__PGIC__) +# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) +# if defined(__PGIC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) +# endif + +#elif defined(_CRAYC) +# define COMPILER_ID "Cray" +# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) +# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) + +#elif defined(__TI_COMPILER_VERSION__) +# define COMPILER_ID "TI" + /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ +# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) +# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) +# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) + +#elif defined(__CLANG_FUJITSU) +# define COMPILER_ID "FujitsuClang" +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# define COMPILER_VERSION_INTERNAL_STR __clang_version__ + + +#elif defined(__FUJITSU) +# define COMPILER_ID "Fujitsu" +# if defined(__FCC_version__) +# define COMPILER_VERSION __FCC_version__ +# elif defined(__FCC_major__) +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# endif +# if defined(__fcc_version) +# define COMPILER_VERSION_INTERNAL DEC(__fcc_version) +# elif defined(__FCC_VERSION) +# define COMPILER_VERSION_INTERNAL DEC(__FCC_VERSION) +# endif + + +#elif defined(__ghs__) +# define COMPILER_ID "GHS" +/* __GHS_VERSION_NUMBER = VVVVRP */ +# ifdef __GHS_VERSION_NUMBER +# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) +# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) +# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) +# endif + +#elif defined(__TASKING__) +# define COMPILER_ID "Tasking" + # define COMPILER_VERSION_MAJOR DEC(__VERSION__/1000) + # define COMPILER_VERSION_MINOR DEC(__VERSION__ % 100) +# define COMPILER_VERSION_INTERNAL DEC(__VERSION__) + +#elif defined(__SCO_VERSION__) +# define COMPILER_ID "SCO" + +#elif defined(__ARMCC_VERSION) && !defined(__clang__) +# define COMPILER_ID "ARMCC" +#if __ARMCC_VERSION >= 1000000 + /* __ARMCC_VERSION = VRRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#else + /* __ARMCC_VERSION = VRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#endif + + +#elif defined(__clang__) && defined(__apple_build_version__) +# define COMPILER_ID "AppleClang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif +# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) + +#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) +# define COMPILER_ID "ARMClang" + # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) +# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) + +#elif defined(__clang__) +# define COMPILER_ID "Clang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif + +#elif defined(__LCC__) && (defined(__GNUC__) || defined(__GNUG__) || defined(__MCST__)) +# define COMPILER_ID "LCC" +# define COMPILER_VERSION_MAJOR DEC(1) +# if defined(__LCC__) +# define COMPILER_VERSION_MINOR DEC(__LCC__- 100) +# endif +# if defined(__LCC_MINOR__) +# define COMPILER_VERSION_PATCH DEC(__LCC_MINOR__) +# endif +# if defined(__GNUC__) && defined(__GNUC_MINOR__) +# define SIMULATE_ID "GNU" +# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) +# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) +# if defined(__GNUC_PATCHLEVEL__) +# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif +# endif + +#elif defined(__GNUC__) || defined(__GNUG__) +# define COMPILER_ID "GNU" +# if defined(__GNUC__) +# define COMPILER_VERSION_MAJOR DEC(__GNUC__) +# else +# define COMPILER_VERSION_MAJOR DEC(__GNUG__) +# endif +# if defined(__GNUC_MINOR__) +# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) +# endif +# if defined(__GNUC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif + +#elif defined(_MSC_VER) +# define COMPILER_ID "MSVC" + /* _MSC_VER = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) +# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) +# if defined(_MSC_FULL_VER) +# if _MSC_VER >= 1400 + /* _MSC_FULL_VER = VVRRPPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) +# else + /* _MSC_FULL_VER = VVRRPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) +# endif +# endif +# if defined(_MSC_BUILD) +# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) +# endif + +#elif defined(_ADI_COMPILER) +# define COMPILER_ID "ADSP" +#if defined(__VERSIONNUM__) + /* __VERSIONNUM__ = 0xVVRRPPTT */ +# define COMPILER_VERSION_MAJOR DEC(__VERSIONNUM__ >> 24 & 0xFF) +# define COMPILER_VERSION_MINOR DEC(__VERSIONNUM__ >> 16 & 0xFF) +# define COMPILER_VERSION_PATCH DEC(__VERSIONNUM__ >> 8 & 0xFF) +# define COMPILER_VERSION_TWEAK DEC(__VERSIONNUM__ & 0xFF) +#endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# define COMPILER_ID "IAR" +# if defined(__VER__) && defined(__ICCARM__) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) +# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) +# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__) || defined(__ICCSTM8__)) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) +# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) +# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# endif + + +/* These compilers are either not known or too old to define an + identification macro. Try to identify the platform and guess that + it is the native compiler. */ +#elif defined(__hpux) || defined(__hpua) +# define COMPILER_ID "HP" + +#else /* unknown compiler */ +# define COMPILER_ID "" +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; +#ifdef SIMULATE_ID +char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; +#endif + +#ifdef __QNXNTO__ +char const* qnxnto = "INFO" ":" "qnxnto[]"; +#endif + +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) +char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; +#endif + +#define STRINGIFY_HELPER(X) #X +#define STRINGIFY(X) STRINGIFY_HELPER(X) + +/* Identify known platforms by name. */ +#if defined(__linux) || defined(__linux__) || defined(linux) +# define PLATFORM_ID "Linux" + +#elif defined(__MSYS__) +# define PLATFORM_ID "MSYS" + +#elif defined(__CYGWIN__) +# define PLATFORM_ID "Cygwin" + +#elif defined(__MINGW32__) +# define PLATFORM_ID "MinGW" + +#elif defined(__APPLE__) +# define PLATFORM_ID "Darwin" + +#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) +# define PLATFORM_ID "Windows" + +#elif defined(__FreeBSD__) || defined(__FreeBSD) +# define PLATFORM_ID "FreeBSD" + +#elif defined(__NetBSD__) || defined(__NetBSD) +# define PLATFORM_ID "NetBSD" + +#elif defined(__OpenBSD__) || defined(__OPENBSD) +# define PLATFORM_ID "OpenBSD" + +#elif defined(__sun) || defined(sun) +# define PLATFORM_ID "SunOS" + +#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) +# define PLATFORM_ID "AIX" + +#elif defined(__hpux) || defined(__hpux__) +# define PLATFORM_ID "HP-UX" + +#elif defined(__HAIKU__) +# define PLATFORM_ID "Haiku" + +#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) +# define PLATFORM_ID "BeOS" + +#elif defined(__QNX__) || defined(__QNXNTO__) +# define PLATFORM_ID "QNX" + +#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) +# define PLATFORM_ID "Tru64" + +#elif defined(__riscos) || defined(__riscos__) +# define PLATFORM_ID "RISCos" + +#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) +# define PLATFORM_ID "SINIX" + +#elif defined(__UNIX_SV__) +# define PLATFORM_ID "UNIX_SV" + +#elif defined(__bsdos__) +# define PLATFORM_ID "BSDOS" + +#elif defined(_MPRAS) || defined(MPRAS) +# define PLATFORM_ID "MP-RAS" + +#elif defined(__osf) || defined(__osf__) +# define PLATFORM_ID "OSF1" + +#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) +# define PLATFORM_ID "SCO_SV" + +#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) +# define PLATFORM_ID "ULTRIX" + +#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) +# define PLATFORM_ID "Xenix" + +#elif defined(__WATCOMC__) +# if defined(__LINUX__) +# define PLATFORM_ID "Linux" + +# elif defined(__DOS__) +# define PLATFORM_ID "DOS" + +# elif defined(__OS2__) +# define PLATFORM_ID "OS2" + +# elif defined(__WINDOWS__) +# define PLATFORM_ID "Windows3x" + +# elif defined(__VXWORKS__) +# define PLATFORM_ID "VxWorks" + +# else /* unknown platform */ +# define PLATFORM_ID +# endif + +#elif defined(__INTEGRITY) +# if defined(INT_178B) +# define PLATFORM_ID "Integrity178" + +# else /* regular Integrity */ +# define PLATFORM_ID "Integrity" +# endif + +# elif defined(_ADI_COMPILER) +# define PLATFORM_ID "ADSP" + +#else /* unknown platform */ +# define PLATFORM_ID + +#endif + +/* For windows compilers MSVC and Intel we can determine + the architecture of the compiler being used. This is because + the compilers do not have flags that can change the architecture, + but rather depend on which compiler is being used +*/ +#if defined(_WIN32) && defined(_MSC_VER) +# if defined(_M_IA64) +# define ARCHITECTURE_ID "IA64" + +# elif defined(_M_ARM64EC) +# define ARCHITECTURE_ID "ARM64EC" + +# elif defined(_M_X64) || defined(_M_AMD64) +# define ARCHITECTURE_ID "x64" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# elif defined(_M_ARM64) +# define ARCHITECTURE_ID "ARM64" + +# elif defined(_M_ARM) +# if _M_ARM == 4 +# define ARCHITECTURE_ID "ARMV4I" +# elif _M_ARM == 5 +# define ARCHITECTURE_ID "ARMV5I" +# else +# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) +# endif + +# elif defined(_M_MIPS) +# define ARCHITECTURE_ID "MIPS" + +# elif defined(_M_SH) +# define ARCHITECTURE_ID "SHx" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__WATCOMC__) +# if defined(_M_I86) +# define ARCHITECTURE_ID "I86" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# if defined(__ICCARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__ICCRX__) +# define ARCHITECTURE_ID "RX" + +# elif defined(__ICCRH850__) +# define ARCHITECTURE_ID "RH850" + +# elif defined(__ICCRL78__) +# define ARCHITECTURE_ID "RL78" + +# elif defined(__ICCRISCV__) +# define ARCHITECTURE_ID "RISCV" + +# elif defined(__ICCAVR__) +# define ARCHITECTURE_ID "AVR" + +# elif defined(__ICC430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__ICCV850__) +# define ARCHITECTURE_ID "V850" + +# elif defined(__ICC8051__) +# define ARCHITECTURE_ID "8051" + +# elif defined(__ICCSTM8__) +# define ARCHITECTURE_ID "STM8" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__ghs__) +# if defined(__PPC64__) +# define ARCHITECTURE_ID "PPC64" + +# elif defined(__ppc__) +# define ARCHITECTURE_ID "PPC" + +# elif defined(__ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__x86_64__) +# define ARCHITECTURE_ID "x64" + +# elif defined(__i386__) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__TI_COMPILER_VERSION__) +# if defined(__TI_ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__MSP430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__TMS320C28XX__) +# define ARCHITECTURE_ID "TMS320C28x" + +# elif defined(__TMS320C6X__) || defined(_TMS320C6X) +# define ARCHITECTURE_ID "TMS320C6x" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +# elif defined(__ADSPSHARC__) +# define ARCHITECTURE_ID "SHARC" + +# elif defined(__ADSPBLACKFIN__) +# define ARCHITECTURE_ID "Blackfin" + +#elif defined(__TASKING__) + +# if defined(__CTC__) || defined(__CPTC__) +# define ARCHITECTURE_ID "TriCore" + +# elif defined(__CMCS__) +# define ARCHITECTURE_ID "MCS" + +# elif defined(__CARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__CARC__) +# define ARCHITECTURE_ID "ARC" + +# elif defined(__C51__) +# define ARCHITECTURE_ID "8051" + +# elif defined(__CPCP__) +# define ARCHITECTURE_ID "PCP" + +# else +# define ARCHITECTURE_ID "" +# endif + +#else +# define ARCHITECTURE_ID +#endif + +/* Convert integer to decimal digit literals. */ +#define DEC(n) \ + ('0' + (((n) / 10000000)%10)), \ + ('0' + (((n) / 1000000)%10)), \ + ('0' + (((n) / 100000)%10)), \ + ('0' + (((n) / 10000)%10)), \ + ('0' + (((n) / 1000)%10)), \ + ('0' + (((n) / 100)%10)), \ + ('0' + (((n) / 10)%10)), \ + ('0' + ((n) % 10)) + +/* Convert integer to hex digit literals. */ +#define HEX(n) \ + ('0' + ((n)>>28 & 0xF)), \ + ('0' + ((n)>>24 & 0xF)), \ + ('0' + ((n)>>20 & 0xF)), \ + ('0' + ((n)>>16 & 0xF)), \ + ('0' + ((n)>>12 & 0xF)), \ + ('0' + ((n)>>8 & 0xF)), \ + ('0' + ((n)>>4 & 0xF)), \ + ('0' + ((n) & 0xF)) + +/* Construct a string literal encoding the version number. */ +#ifdef COMPILER_VERSION +char const* info_version = "INFO" ":" "compiler_version[" COMPILER_VERSION "]"; + +/* Construct a string literal encoding the version number components. */ +#elif defined(COMPILER_VERSION_MAJOR) +char const info_version[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', + COMPILER_VERSION_MAJOR, +# ifdef COMPILER_VERSION_MINOR + '.', COMPILER_VERSION_MINOR, +# ifdef COMPILER_VERSION_PATCH + '.', COMPILER_VERSION_PATCH, +# ifdef COMPILER_VERSION_TWEAK + '.', COMPILER_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct a string literal encoding the internal version number. */ +#ifdef COMPILER_VERSION_INTERNAL +char const info_version_internal[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', + 'i','n','t','e','r','n','a','l','[', + COMPILER_VERSION_INTERNAL,']','\0'}; +#elif defined(COMPILER_VERSION_INTERNAL_STR) +char const* info_version_internal = "INFO" ":" "compiler_version_internal[" COMPILER_VERSION_INTERNAL_STR "]"; +#endif + +/* Construct a string literal encoding the version number components. */ +#ifdef SIMULATE_VERSION_MAJOR +char const info_simulate_version[] = { + 'I', 'N', 'F', 'O', ':', + 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', + SIMULATE_VERSION_MAJOR, +# ifdef SIMULATE_VERSION_MINOR + '.', SIMULATE_VERSION_MINOR, +# ifdef SIMULATE_VERSION_PATCH + '.', SIMULATE_VERSION_PATCH, +# ifdef SIMULATE_VERSION_TWEAK + '.', SIMULATE_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; +char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; + + + +#if defined(__INTEL_COMPILER) && defined(_MSVC_LANG) && _MSVC_LANG < 201403L +# if defined(__INTEL_CXX11_MODE__) +# if defined(__cpp_aggregate_nsdmi) +# define CXX_STD 201402L +# else +# define CXX_STD 201103L +# endif +# else +# define CXX_STD 199711L +# endif +#elif defined(_MSC_VER) && defined(_MSVC_LANG) +# define CXX_STD _MSVC_LANG +#else +# define CXX_STD __cplusplus +#endif + +const char* info_language_standard_default = "INFO" ":" "standard_default[" +#if CXX_STD > 202002L + "23" +#elif CXX_STD > 201703L + "20" +#elif CXX_STD >= 201703L + "17" +#elif CXX_STD >= 201402L + "14" +#elif CXX_STD >= 201103L + "11" +#else + "98" +#endif +"]"; + +const char* info_language_extensions_default = "INFO" ":" "extensions_default[" +#if (defined(__clang__) || defined(__GNUC__) || defined(__xlC__) || \ + defined(__TI_COMPILER_VERSION__)) && \ + !defined(__STRICT_ANSI__) + "ON" +#else + "OFF" +#endif +"]"; + +/*--------------------------------------------------------------------------*/ + +int main(int argc, char* argv[]) +{ + int require = 0; + require += info_compiler[argc]; + require += info_platform[argc]; + require += info_arch[argc]; +#ifdef COMPILER_VERSION_MAJOR + require += info_version[argc]; +#endif +#ifdef COMPILER_VERSION_INTERNAL + require += info_version_internal[argc]; +#endif +#ifdef SIMULATE_ID + require += info_simulate[argc]; +#endif +#ifdef SIMULATE_VERSION_MAJOR + require += info_simulate_version[argc]; +#endif +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) + require += info_cray[argc]; +#endif + require += info_language_standard_default[argc]; + require += info_language_extensions_default[argc]; + (void)argv; + return require; +} diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o new file mode 100644 index 0000000000000000000000000000000000000000..aacee10dfddc5e3114bb159eee743a03c1b12206 GIT binary patch literal 1712 zcmb_cJ#5oZ5PqShqzWV;F@P#TBo?M9PO7SaA|+}-fULGdhCoz3ti(wzIgaHx(6I;x z1_sK?QX~e%#7HI>vr!hr7?|3DoiY%1^Z6O|W@vfbVNlAN;TuDUd5eWoVTAL%&&wQohkn#@ z7xSq-j;d+D)t1v9ZFqXVP40J%U+PcIH{OeU>eqCQsxLdv1IwvNsTapLka_697F8IR1n^Z*cJ-l}YwvWy2!N#ELP!jS<=b%*cH!^r6J`FC4Zht{^ zzsAJjAR)R@A)ZAe`NM;S?e4sFu)LqhccYQ{*#1A{s8`rm?EJ5ueawaVcRtL>&$m`@ ztX-vFW7(!xDY&j}uGogt*bqU+wGF@C@|u;R;o-M&)bOgC753Y{;nWPTCTnKh=-7Vc z$}(qgUQDNLfkwmJ+Umw1e(Z_)ySp2^@ z#c`j+Ps4(Dam47{VX1)UfyFv=G-sR%Pq{mU!DV&cx`aV;sv}u}j^j6kad6amf6w`E zuq1DxRR1GDLcC-=%WFPoe1Y)`!ei?{C5*wsqwOppCjtl9ou4RJe%qk(9hUIXb hB0fW6ys-VIyU6WQZ~(Ik!U4=E2nSG85Dp-5 search starts here: + /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include + /Library/Developer/CommandLineTools/usr/include + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory) +End of search list. +Linking C executable cmTC_5913a +/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_5913a.dir/link.txt --verbose=1 +/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names -v -Wl,-v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -o cmTC_5913a +Apple clang version 13.1.6 (clang-1316.0.21.2.5) +Target: arm64-apple-darwin21.6.0 +Thread model: posix +InstalledDir: /Library/Developer/CommandLineTools/usr/bin + "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_5913a -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a +@(#)PROGRAM:ld PROJECT:ld64-764 +BUILD 11:22:55 Apr 28 2022 +configured to support archs: armv6 armv7 armv7s arm64 arm64e arm64_32 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em +Library search paths: + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib +Framework search paths: + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/ + + + +Parsed C implicit include dir info from above output: rv=done + found start of include info + found start of implicit include info + add: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + add: [/Library/Developer/CommandLineTools/usr/include] + end of search list found + collapse include dir [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] ==> [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + collapse include dir [/Library/Developer/CommandLineTools/usr/include] ==> [/Library/Developer/CommandLineTools/usr/include] + implicit include dirs: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include] + + +Parsed C implicit link information from above output: + link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] + ignore line: [Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-LcrFWX] + ignore line: [] + ignore line: [Run Build Command(s):/usr/bin/make -f Makefile cmTC_5913a/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_5913a.dir/build.make CMakeFiles/cmTC_5913a.dir/build] + ignore line: [Building C object CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o] + ignore line: [/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl -v -MD -MT CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -MF CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o.d -o CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCCompilerABI.c] + ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] + ignore line: [Target: arm64-apple-darwin21.6.0] + ignore line: [Thread model: posix] + ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] + ignore line: [clang: warning: -Wl -v: 'linker' input unused [-Wunused-command-line-argument]] + ignore line: [ "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCCompilerABI.c -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-LcrFWX -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -x c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCCompilerABI.c] + ignore line: [clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0] + ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include"] + ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks"] + ignore line: [#include "..." search starts here:] + ignore line: [#include <...> search starts here:] + ignore line: [ /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + ignore line: [ /Library/Developer/CommandLineTools/usr/include] + ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory)] + ignore line: [End of search list.] + ignore line: [Linking C executable cmTC_5913a] + ignore line: [/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_5913a.dir/link.txt --verbose=1] + ignore line: [/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl -search_paths_first -Wl -headerpad_max_install_names -v -Wl -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -o cmTC_5913a ] + ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] + ignore line: [Target: arm64-apple-darwin21.6.0] + ignore line: [Thread model: posix] + ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] + link line: [ "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_5913a -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + arg [/Library/Developer/CommandLineTools/usr/bin/ld] ==> ignore + arg [-demangle] ==> ignore + arg [-lto_library] ==> ignore, skip following value + arg [/Library/Developer/CommandLineTools/usr/lib/libLTO.dylib] ==> skip value of -lto_library + arg [-dynamic] ==> ignore + arg [-arch] ==> ignore + arg [arm64] ==> ignore + arg [-platform_version] ==> ignore + arg [macos] ==> ignore + arg [12.0.0] ==> ignore + arg [12.3] ==> ignore + arg [-syslibroot] ==> ignore + arg [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk] ==> ignore + arg [-o] ==> ignore + arg [cmTC_5913a] ==> ignore + arg [-search_paths_first] ==> ignore + arg [-headerpad_max_install_names] ==> ignore + arg [-v] ==> ignore + arg [CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o] ==> ignore + arg [-lSystem] ==> lib [System] + arg [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] ==> lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + Library search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + Framework search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] + remove lib [System] + remove lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + collapse library dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + collapse framework dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] + implicit libs: [] + implicit objs: [] + implicit dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + implicit fwks: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] + + +Detecting CXX compiler ABI info compiled with the following output: +Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C + +Run Build Command(s):/usr/bin/make -f Makefile cmTC_48750/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_48750.dir/build.make CMakeFiles/cmTC_48750.dir/build +Building CXX object CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o +/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl,-v -MD -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -MF CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp +Apple clang version 13.1.6 (clang-1316.0.21.2.5) +Target: arm64-apple-darwin21.6.0 +Thread model: posix +InstalledDir: /Library/Developer/CommandLineTools/usr/bin +clang: warning: -Wl,-v: 'linker' input unused [-Wunused-command-line-argument] + "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -D _DARWIN_USE_64_BIT_INODE=1 -D _LARGEFILE_SOURCE -D _FILE_OFFSET_BITS=64 -D BUILDING_NODE_EXTENSION -stdlib=libc++ -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdeprecated-macro -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fno-cxx-modules -fcxx-exceptions -fexceptions -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -x c++ /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp +clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0 +ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include" +ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks" +#include "..." search starts here: +#include <...> search starts here: + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 + /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include + /Library/Developer/CommandLineTools/usr/include + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory) +End of search list. +Linking CXX executable cmTC_48750 +/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_48750.dir/link.txt --verbose=1 +/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names -v -Wl,-v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_48750 +Apple clang version 13.1.6 (clang-1316.0.21.2.5) +Target: arm64-apple-darwin21.6.0 +Thread model: posix +InstalledDir: /Library/Developer/CommandLineTools/usr/bin + "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_48750 -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -lc++ -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a +@(#)PROGRAM:ld PROJECT:ld64-764 +BUILD 11:22:55 Apr 28 2022 +configured to support archs: armv6 armv7 armv7s arm64 arm64e arm64_32 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em +Library search paths: + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib +Framework search paths: + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/ + + + +Parsed CXX implicit include dir info from above output: rv=done + found start of include info + found start of implicit include info + add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] + add: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + add: [/Library/Developer/CommandLineTools/usr/include] + end of search list found + collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] + collapse include dir [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] ==> [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + collapse include dir [/Library/Developer/CommandLineTools/usr/include] ==> [/Library/Developer/CommandLineTools/usr/include] + implicit include dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1;/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include] + + +Parsed CXX implicit link information from above output: + link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] + ignore line: [Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C] + ignore line: [] + ignore line: [Run Build Command(s):/usr/bin/make -f Makefile cmTC_48750/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_48750.dir/build.make CMakeFiles/cmTC_48750.dir/build] + ignore line: [Building CXX object CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o] + ignore line: [/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl -v -MD -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -MF CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp] + ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] + ignore line: [Target: arm64-apple-darwin21.6.0] + ignore line: [Thread model: posix] + ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] + ignore line: [clang: warning: -Wl -v: 'linker' input unused [-Wunused-command-line-argument]] + ignore line: [ "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -D _DARWIN_USE_64_BIT_INODE=1 -D _LARGEFILE_SOURCE -D _FILE_OFFSET_BITS=64 -D BUILDING_NODE_EXTENSION -stdlib=libc++ -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdeprecated-macro -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fno-cxx-modules -fcxx-exceptions -fexceptions -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -x c++ /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp] + ignore line: [clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0] + ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include"] + ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks"] + ignore line: [#include "..." search starts here:] + ignore line: [#include <...> search starts here:] + ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] + ignore line: [ /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + ignore line: [ /Library/Developer/CommandLineTools/usr/include] + ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory)] + ignore line: [End of search list.] + ignore line: [Linking CXX executable cmTC_48750] + ignore line: [/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_48750.dir/link.txt --verbose=1] + ignore line: [/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl -search_paths_first -Wl -headerpad_max_install_names -v -Wl -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_48750 ] + ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] + ignore line: [Target: arm64-apple-darwin21.6.0] + ignore line: [Thread model: posix] + ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] + link line: [ "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_48750 -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -lc++ -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + arg [/Library/Developer/CommandLineTools/usr/bin/ld] ==> ignore + arg [-demangle] ==> ignore + arg [-lto_library] ==> ignore, skip following value + arg [/Library/Developer/CommandLineTools/usr/lib/libLTO.dylib] ==> skip value of -lto_library + arg [-dynamic] ==> ignore + arg [-arch] ==> ignore + arg [arm64] ==> ignore + arg [-platform_version] ==> ignore + arg [macos] ==> ignore + arg [12.0.0] ==> ignore + arg [12.3] ==> ignore + arg [-syslibroot] ==> ignore + arg [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk] ==> ignore + arg [-o] ==> ignore + arg [cmTC_48750] ==> ignore + arg [-search_paths_first] ==> ignore + arg [-headerpad_max_install_names] ==> ignore + arg [-v] ==> ignore + arg [CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o] ==> ignore + arg [-lc++] ==> lib [c++] + arg [-lSystem] ==> lib [System] + arg [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] ==> lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + Library search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + Framework search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] + remove lib [System] + remove lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + collapse library dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + collapse framework dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] + implicit libs: [c++] + implicit objs: [] + implicit dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + implicit fwks: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] + + diff --git a/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache b/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache new file mode 100644 index 00000000..3dccd731 --- /dev/null +++ b/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache @@ -0,0 +1 @@ +# This file is generated by cmake for dependency checking of the CMakeCache.txt file diff --git a/languages/c/templates/sdk/cmake/CopySymlink.cmake b/languages/c/templates/sdk/cmake/CopySymlink.cmake new file mode 100644 index 00000000..b25a5e22 --- /dev/null +++ b/languages/c/templates/sdk/cmake/CopySymlink.cmake @@ -0,0 +1,17 @@ +# 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 + +file(COPY "${LIBRARY}" DESTINATION "${DESTINATION}" FOLLOW_SYMLINK_CHAIN) diff --git a/languages/c/templates/sdk/cmake/HelperFunctions.cmake b/languages/c/templates/sdk/cmake/HelperFunctions.cmake new file mode 100644 index 00000000..bbd7ce65 --- /dev/null +++ b/languages/c/templates/sdk/cmake/HelperFunctions.cmake @@ -0,0 +1,139 @@ +# 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 + +macro(GetSubDirs subdirs currentdir) + file(GLOB subdirectories RELATIVE ${currentdir} ${currentdir}/*) + set(subdirs "") + foreach(subdir ${subdirectories}) + if (IS_DIRECTORY ${currentdir}/${subdir}) + list(APPEND subdirs ${subdir}) + endif() + endforeach() +endmacro() + +function(InstallHeaders) + set(optionsArgs EXCLUDE_ROOT_DIR) + set(oneValueArgs TARGET NAMESPACE SOURCE DESTINATION) + set(multiValueArgs HEADERS) + + cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) + if (Argument_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to InstallHeaders(): \"${Argument_UNPARSED_ARGUMENTS}\"") + endif() + if (Argument_HEADERS) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMENT "=================== Installing Headers ======================" + ) + foreach(directory ${Argument_HEADERS}) + if (Argument_EXCLUDE_ROOT_DIR) + set(destination ${Argument_DESTINATION}) + else() + set(destination ${Argument_DESTINATION}/${directory}) + endif() + + if (Argument_SOURCE) + set(source ${Argument_SOURCE}) + else() + set(source ${CMAKE_CURRENT_LIST_DIR}) + endif() + + GetSubDirs(subdirs ${source}/${directory}) + list(APPEND subdirs ${directory}) + + foreach(subdir ${subdirs}) + set(dest ${destination}/${subdir}) + file(GLOB headers "${source}/${directory}/${subdir}/*.h") + if (headers) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_NAMESPACE}/usr/include/${dest} + COMMAND ${CMAKE_COMMAND} -E copy ${source}/${directory}/${subdir}/*.h ${CMAKE_BINARY_DIR}/${Argument_NAMESPACE}/usr/include/${dest} + ) + endif() + endforeach(subdir) + endforeach(directory) + endif() +endfunction(InstallHeaders) + +function(InstallLibraries) + set(optionsArgs SHARED) + set(oneValueArgs TARGET DESTINATION) + set(multiValueArgs LIBRARIES) + + cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) + if (Argument_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to InstallLibraries(): \"${Argument_UNPARSED_ARGUMENTS}\"") + endif() + if (Argument_LIBRARIES) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMENT "=================== Installing Libraries ======================" + ) + foreach(LIBRARY ${Argument_LIBRARIES}) + if (Argument_SHARED) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + COMMAND ${CMAKE_COMMAND} -D "LIBRARY=${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR}" -D "DESTINATION=${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib" -P ${CMAKE_SOURCE_DIR}/cmake/CopySymlink.cmake + COMMAND ${CMAKE_COMMAND} -D "LIBRARY=${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so" -D "DESTINATION=${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib" -P ${CMAKE_SOURCE_DIR}/cmake/CopySymlink.cmake + ) + else() + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/lib${LIBRARY}.a ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + ) + + endif() + endforeach(LIBRARY) + endif() +endfunction(InstallLibraries) + +function(InstallCMakeConfigs) + set(optionsArgs) + set(oneValueArgs TARGET DESTINATION) + set(multiValueArgs) + + cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) + if (Argument_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to InstallCMakeConfigs(): \"${Argument_UNPARSED_ARGUMENTS}\"") + endif() + if (Argument_TARGET) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMENT "=================== Installing CMakeConfigs ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}Config*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Export/lib/cmake/${Argument_TARGET}/${Argument_TARGET}Targets*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} + ) + if (EXISTS ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}.pc) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/pkgconfig + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}.pc ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/pkgconfig + ) + endif() + endif() +endfunction(InstallCMakeConfigs) diff --git a/languages/c/templates/sdk/cmake/project.cmake.in b/languages/c/templates/sdk/cmake/project.cmake.in new file mode 100644 index 00000000..0855ca12 --- /dev/null +++ b/languages/c/templates/sdk/cmake/project.cmake.in @@ -0,0 +1,30 @@ +# 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 + +set(FIREBOLT_NAMESPACE "@FIREBOLT_NAMESPACE@" CACHE INTERNAL "" FORCE) +set("${FIREBOLT_NAMESPACE}_FOUND" TRUE CACHE INTERNAL "" FORCE) + +list(APPEND CMAKE_MODULE_PATH + "${CMAKE_SOURCE_DIR}/cmake" + "${SYSROOT_PATH}/usr/lib/cmake" + "${SYSROOT_PATH}/usr/lib/cmake/Firebolt" + "${SYSROOT_PATH}/tools/cmake") + +if (NOT DEFINED CMAKE_PREFIX_PATH) + set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) +endif() + + diff --git a/languages/c/templates/sdk/include/Error.h b/languages/c/templates/sdk/include/Error.h new file mode 100644 index 00000000..87cda9dd --- /dev/null +++ b/languages/c/templates/sdk/include/Error.h @@ -0,0 +1,41 @@ +/* + * 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 + */ + +#ifndef _FIREBOLT_ERROR_H +#define _FIREBOLT_ERROR_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum FireboltSDKError { + FireboltSDKErrorNone = 0, + FireboltSDKErrorGeneral = 1, + FireboltSDKErrorUnavailable = 2, + FireboltSDKErrorTimedout = 3, + FireboltSDKErrorNotSubscribed = 4, + FireboltSDKErrorUnknown = 5, + FireboltSDKErrorInUse = 6, + FireboltSDKErrorNotSupported = 7 +} FireboltSDKError_t; + +#ifdef __cplusplus +} +#endif + +#endif // _FIREBOLT_ERROR_H diff --git a/languages/c/templates/sdk/include/Types.h b/languages/c/templates/sdk/include/Types.h new file mode 100644 index 00000000..e7456cdd --- /dev/null +++ b/languages/c/templates/sdk/include/Types.h @@ -0,0 +1,43 @@ +/* + * 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 + */ + +#ifndef _FIREBOLT_TYPES_H +#define _FIREBOLT_TYPES_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + Test1, + Test2, + Test3, + Test4 +} TestEnum; + +typedef void* FireboltTypes_StringHandle; +const char* FireboltTypes_String(FireboltTypes_StringHandle handle); +void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle); + +#ifdef __cplusplus +} +#endif + +#endif // _FIREBOLT_TYPES_H diff --git a/languages/c/templates/sdk/scripts/install.js b/languages/c/templates/sdk/scripts/install.js new file mode 100644 index 00000000..5c332ceb --- /dev/null +++ b/languages/c/templates/sdk/scripts/install.js @@ -0,0 +1,32 @@ +import { createRequire } from 'module'; +const require = createRequire(import.meta.url); +const fs = require('fs'); +const path = require('path'); + +var dest = process.env.NODE_INSTALL_PATH; +var src = 'src/native/build/' + process.env.TARGET_NAME; + +installFiles(src, dest); +function installFiles(src, dest) { + if (!fs.existsSync(dest)) { + fs.mkdirSync(dest); + } + + var entries = fs.readdirSync(src); + entries.forEach((entry) => { + const srcPath = path.join(src, entry); + const destPath = path.join(dest, entry); + const stat = fs.lstatSync(srcPath); + + if (stat.isFile()) { + fs.copyFileSync(srcPath, destPath); + } else if (stat.isDirectory()) { + installFiles(srcPath, destPath); + } else if (stat.isSymbolicLink()) { + if (fs.existsSync(destPath)) { + fs.unlinkSync(destPath); + } + fs.symlinkSync(fs.readlinkSync(srcPath), destPath); + } + }); +} diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.cpp b/languages/c/templates/sdk/src/Accessor/Accessor.cpp new file mode 100644 index 00000000..b4cada4b --- /dev/null +++ b/languages/c/templates/sdk/src/Accessor/Accessor.cpp @@ -0,0 +1,134 @@ +/* + * 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 "Accessor.h" + +namespace FireboltSDK { + + Accessor* Accessor::_singleton = nullptr; + Accessor::Accessor() + : _threadCount(DefaultThreadCount) + , _queueSize(DefaultQueueSize) + , _workerPool() + , _transport(nullptr) + { + _singleton = this; + Config config; + LoadConfigs(config); + + Logger::SetLogLevel(WPEFramework::Core::EnumerateType(config.LogLevel.Value().c_str()).Value()); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Url = %s", config.Url.Value().c_str()); + CreateTransport(config.Url.Value(), config.WaitTime.Value()); + CreateEventHandler(); + + _workerPool = WPEFramework::Core::ProxyType::Create(_threadCount, WPEFramework::Core::Thread::DefaultStackSize(), _queueSize); + WPEFramework::Core::WorkerPool::Assign(&(*_workerPool)); + _workerPool->Run(); + } + + Accessor::~Accessor() + { + DestroyTransport(); + DestroyEventHandler(); + WPEFramework::Core::IWorkerPool::Assign(nullptr); + _workerPool->Stop(); + _singleton = nullptr; + } + + void Accessor::LoadConfigs(Config& config) + { + string prefixPath; + WPEFramework::Core::SystemInfo::GetEnvironment("OPENRPC_NATIVE_SDK_PREFIX", prefixPath); + string configFilePath = (prefixPath.empty() != true) ? + (prefixPath + '/' + Accessor::ConfigFile) : Accessor::ConfigFile; + WPEFramework::Core::File configFile(configFilePath); + + if (configFile.Open(true) == true) { + WPEFramework::Core::OptionalType error; + config.IElement::FromFile(configFile, error); + if (error.IsSet() == true) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in reading config"); + } + } + } + + uint32_t Accessor::CreateEventHandler() + { + Event::Instance().Configure(_transport); + return FireboltSDKErrorNone; + } + + uint32_t Accessor::DestroyEventHandler() + { + Event::Dispose(); + return FireboltSDKErrorNone; + } + + Event& Accessor::GetEventManager() + { + return Event::Instance(); + } + + uint32_t Accessor::CreateTransport(const string& url, const uint32_t waitTime) + { + if (_transport != nullptr) { + delete _transport; + } + + _transport = new Transport(static_cast(url), waitTime); + if (WaitForLinkReady(_transport, DefaultWaitTime) != FireboltSDKErrorNone) { + delete _transport; + _transport = nullptr; + } + + ASSERT(_transport != nullptr); + return ((_transport != nullptr) ? FireboltSDKErrorNone : FireboltSDKErrorUnavailable); + } + + uint32_t Accessor::DestroyTransport() + { + if (_transport != nullptr) { + delete _transport; + _transport = nullptr; + } + return FireboltSDKErrorNone; + } + + Transport* Accessor::GetTransport() + { + ASSERT(_transport != nullptr); + return _transport; + } + + uint32_t Accessor::WaitForLinkReady(Transport* transport, const uint32_t waitTime = DefaultWaitTime) { + uint32_t waiting = (waitTime == WPEFramework::Core::infinite ? WPEFramework::Core::infinite : waitTime); + static constexpr uint32_t SLEEPSLOT_TIME = 100; + + // Right, a wait till connection is closed is requested.. + while ((waiting > 0) && (transport->IsOpen() == false)) { + + uint32_t sleepSlot = (waiting > SLEEPSLOT_TIME ? SLEEPSLOT_TIME : waiting); + + // Right, lets sleep in slices of 100 ms + SleepMs(sleepSlot); + + waiting -= (waiting == WPEFramework::Core::infinite ? 0 : sleepSlot); + } + return (((waiting == 0) || (transport->IsOpen() == true)) ? FireboltSDKErrorNone : FireboltSDKErrorTimedout); + } +} diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.h b/languages/c/templates/sdk/src/Accessor/Accessor.h new file mode 100644 index 00000000..3e9b8784 --- /dev/null +++ b/languages/c/templates/sdk/src/Accessor/Accessor.h @@ -0,0 +1,79 @@ +/* + * 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 "Module.h" +#include "Config.h" +#include "WorkerPool.h" +#include "Transport/Transport.h" +#include "Event/Event.h" +#include "Logger/Logger.h" + +namespace FireboltSDK { + class Accessor { + private: + static constexpr uint8_t JSONVersion = 2; + static constexpr const TCHAR* ConfigFile = _T("/etc/Firebolt/config.json"); + static constexpr uint32_t DefaultWaitTime = 1000; + static constexpr uint8_t DefaultQueueSize = 8; + static constexpr uint8_t DefaultThreadCount = 3; + + public: + Accessor(const Accessor&) = delete; + Accessor& operator= (const Accessor&) = delete; + + Accessor(); + ~Accessor(); + + static Accessor& Instance() + { + static Accessor *instance = new Accessor(); + ASSERT(instance != nullptr); + return *instance; + } + + static void Dispose() + { + ASSERT(_singleton != nullptr); + + if (_singleton != nullptr) { + delete _singleton; + } + } + + uint32_t CreateEventHandler(); + uint32_t DestroyEventHandler(); + Event& GetEventManager(); + + uint32_t CreateTransport(const string& url, const uint32_t waitTime); + uint32_t DestroyTransport(); + Transport* GetTransport(); + uint32_t WaitForLinkReady(Transport* transport, const uint32_t waitTime); + + private: + void LoadConfigs(Config& config); + + private: + uint8_t _threadCount; + uint8_t _queueSize; + WPEFramework::Core::ProxyType _workerPool; + Transport* _transport; + static Accessor* _singleton; + }; +} diff --git a/languages/c/templates/sdk/src/Accessor/Config.h b/languages/c/templates/sdk/src/Accessor/Config.h new file mode 100644 index 00000000..f8389bf6 --- /dev/null +++ b/languages/c/templates/sdk/src/Accessor/Config.h @@ -0,0 +1,41 @@ +/* + * 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 + */ + +namespace FireboltSDK { + class EXTERNAL Config : public WPEFramework::Core::JSON::Container { + public: + Config(const Config&) = delete; + Config& operator=(const Config&) = delete; + + Config() + : WPEFramework::Core::JSON::Container() + , Url(_T("")) + , WaitTime(1000) + , LogLevel(_T("Info")) + { + Add(_T("url"), &Url); + Add(_T("waittime"), &WaitTime); + Add(_T("loglevel"), &LogLevel); + } + + public: + WPEFramework::Core::JSON::String Url; + WPEFramework::Core::JSON::DecUInt32 WaitTime; + WPEFramework::Core::JSON::String LogLevel; + }; +} diff --git a/languages/c/templates/sdk/src/Accessor/WorkerPool.h b/languages/c/templates/sdk/src/Accessor/WorkerPool.h new file mode 100644 index 00000000..521ccc65 --- /dev/null +++ b/languages/c/templates/sdk/src/Accessor/WorkerPool.h @@ -0,0 +1,72 @@ +/* + * 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 "Module.h" + +namespace FireboltSDK { + + class WorkerPoolImplementation : public WPEFramework::Core::WorkerPool { + public: + WorkerPoolImplementation() = delete; + WorkerPoolImplementation(const WorkerPoolImplementation&) = delete; + WorkerPoolImplementation& operator=(const WorkerPoolImplementation&) = delete; + + WorkerPoolImplementation(const uint8_t threads, const uint32_t stackSize, const uint32_t queueSize) + : WorkerPool(threads, stackSize, queueSize, &_dispatcher) + { + } + + ~WorkerPoolImplementation() + { + // Diable the queue so the minions can stop, even if they are processing and waiting for work.. + Stop(); + } + + public: + void Stop() + { + WPEFramework::Core::WorkerPool::Stop(); + } + + void Run() + { + WPEFramework::Core::WorkerPool::Run(); + } + + private: + class Dispatcher : public WPEFramework::Core::ThreadPool::IDispatcher { + public: + Dispatcher(const Dispatcher&) = delete; + Dispatcher& operator=(const Dispatcher&) = delete; + + Dispatcher() = default; + ~Dispatcher() override = default; + + private: + void Initialize() override { } + void Deinitialize() override { } + void Dispatch(WPEFramework::Core::IDispatch* job) override + { job->Dispatch(); } + }; + + Dispatcher _dispatcher; + }; + +} diff --git a/languages/c/templates/sdk/src/CMakeLists.txt b/languages/c/templates/sdk/src/CMakeLists.txt new file mode 100644 index 00000000..c411582a --- /dev/null +++ b/languages/c/templates/sdk/src/CMakeLists.txt @@ -0,0 +1,93 @@ +# 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 + +cmake_minimum_required(VERSION 3.3) + +project(FireboltSDK) +project_version(1.0.0) +set(TARGET ${PROJECT_NAME}) +message("Setup ${TARGET} v${PROJECT_VERSION}") + +add_library(${TARGET} SHARED + Types.cpp + Module.cpp + Logger/Logger.cpp + Transport/Transport.cpp + Accessor/Accessor.cpp + Event/Event.cpp) + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +find_package(${NAMESPACE}Core CONFIG REQUIRED) +find_package(${NAMESPACE}WebSocket CONFIG REQUIRED) + +target_link_libraries(${TARGET} + PUBLIC + ${NAMESPACE}Core::${NAMESPACE}Core + ${NAMESPACE}WebSocket::${NAMESPACE}WebSocket +) + +target_include_directories(${TARGET} + PRIVATE + $ + $ + $ +) + +set_target_properties(${TARGET} PROPERTIES + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED YES + FRAMEWORK FALSE + LINK_WHAT_YOU_USE TRUE + VERSION ${PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} +) + +install( + TARGETS ${TARGET} EXPORT ${TARGET}Targets + LIBRARY DESTINATION lib COMPONENT libs + PUBLIC_HEADER DESTINATION include/${TARGET} COMPONENT devel # headers for mac (note the different component -> different package) + INCLUDES DESTINATION include/${TARGET} # headers +) + +InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION ${FIREBOLT_NAMESPACE}SDK) +InstallHeaders(TARGET ${TARGET} EXCLUDE_ROOT_DIR HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} + SOURCE ${GENERATED_CODE_PATH}/include DESTINATION ${FIREBOLT_NAMESPACE}/generated) +InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} + SOURCE ${CMAKE_SOURCE_DIR}/include DESTINATION ${FIREBOLT_NAMESPACE}) + +InstallLibraries(TARGET ${TARGET} SHARED LIBRARIES ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallCMakeConfig(TARGETS ${TARGET}) +InstallPackageConfig(TARGETS ${TARGET} DESCRIPTION "Firebolt SDK Library") +InstallCMakeConfigs(TARGET ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) + +add_custom_command( + TARGET ${TARGET} + POST_BUILD + COMMENT "=================== Installing JsonConfig ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/etc/${FIREBOLT_NAMESPACE} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/config/${TARGET}.json ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/etc/${FIREBOLT_NAMESPACE}/config.json +) + +add_custom_command( + TARGET ${TARGET} + POST_BUILD + COMMENT "=================== Installing FireboltConfig & Helper CMakes ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/cmake/*.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} +) + +include(Config.cmake) diff --git a/languages/c/templates/sdk/src/Config.cmake b/languages/c/templates/sdk/src/Config.cmake new file mode 100644 index 00000000..a420ce32 --- /dev/null +++ b/languages/c/templates/sdk/src/Config.cmake @@ -0,0 +1,34 @@ +# 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 + +set(SERVER_PORT 9998 CACHE STRING "The port of the server") +set(SERVER_ADDRESS "127.0.0.1" CACHE STRING "The address of the server") + + #[[ ================================ Add additional config above this line ================================ ]] + + +find_package(ConfigGenerator REQUIRED) + +write_config( + SKIP_COMPARE + SKIP_CLASSNAME + SKIP_LOCATOR + DISABLE_LEGACY_GENERATOR + CUSTOM_PARAMS_WHITELIST "${CMAKE_CURRENT_LIST_DIR}/Params.config" + INSTALL_PATH "${CMAKE_INSTALL_PREFIX}/../etc/" + INSTALL_NAME "config.json" +) + diff --git a/languages/c/templates/sdk/src/Event/Event.cpp b/languages/c/templates/sdk/src/Event/Event.cpp new file mode 100644 index 00000000..69b448f6 --- /dev/null +++ b/languages/c/templates/sdk/src/Event/Event.cpp @@ -0,0 +1,148 @@ +/* + * 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 "Transport/Transport.h" +#include "Event.h" + +namespace FireboltSDK { + Event* Event::_singleton = nullptr; + Event::Event() + : _id(0) + , _eventMap() + , _adminLock() + , _transport(nullptr) + { + ASSERT(_singleton == nullptr); + _singleton = this; + } + + Event::~Event() /* override */ + { + _transport->SetEventHandler(nullptr); + _transport = nullptr; + + _singleton = nullptr; + } + + /* static */ Event& Event::Instance() + { + static Event *instance = new Event(); + ASSERT(instance != nullptr); + return *instance; + } + + /* static */ void Event::Dispose() + { + ASSERT(_singleton != nullptr); + + if (_singleton != nullptr) { + delete _singleton; + } + } + + void Event::Configure(Transport* transport) + { + _transport = transport; + _transport->SetEventHandler(this); + } + + uint32_t Event::Unsubscribe(const string& eventName, const uint32_t id) + { + uint32_t status = Revoke(eventName, id); + + if (status == FireboltSDKErrorNone) { + if (_transport != nullptr) { + + const string parameters("{\"listen\":false}"); + status = _transport->Unsubscribe(eventName, parameters); + } + } + return ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone: status); + } + + uint32_t Event::ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) /* override */ + { + uint32_t result = FireboltSDKErrorGeneral; + Response response; + _transport->FromMessage((WPEFramework::Core::JSON::IElement*)&response, *jsonResponse); + if (response.Listening.IsSet() == true) { + result = FireboltSDKErrorNone; + enabled = response.Listening.Value(); + } + return result; + } + + uint32_t Event::Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) /* override */ + { + string response = jsonResponse->Result.Value(); + _adminLock.Lock(); + EventMap::iterator eventIndex = _eventMap.find(eventName); + if (eventIndex != _eventMap.end()) { + IdMap::iterator idIndex = eventIndex->second.begin(); + while(idIndex != eventIndex->second.end()) { + State state; + if (idIndex->second.state != State::REVOKED) { + idIndex->second.state = State::EXECUTING; + } + state = idIndex->second.state; + _adminLock.Unlock(); + if (state == State::EXECUTING) { + idIndex->second.lambda(idIndex->second.userdata, (jsonResponse->Result.Value())); + } + _adminLock.Lock(); + if (idIndex->second.state == State::REVOKED) { + idIndex = eventIndex->second.erase(idIndex); + if (eventIndex->second.size() == 0) { + _eventMap.erase(eventIndex); + } + } else { + idIndex->second.state = State::IDLE; + idIndex++; + } + } + } + _adminLock.Unlock(); + + return FireboltSDKErrorNone;; + } + + uint32_t Event::Revoke(const string& eventName, const uint32_t id) + { + uint32_t status = FireboltSDKErrorNone; + _adminLock.Lock(); + EventMap::iterator eventIndex = _eventMap.find(eventName); + if (eventIndex != _eventMap.end()) { + IdMap::iterator idIndex = eventIndex->second.find(id); + if (idIndex->second.state != State::EXECUTING) { + if (idIndex != eventIndex->second.end()) { + eventIndex->second.erase(idIndex); + } + } else { + idIndex->second.state = State::REVOKED; + } + if (eventIndex->second.size() == 0) { + _eventMap.erase(eventIndex); + } else { + status = FireboltSDKErrorInUse; + } + } + _adminLock.Unlock(); + + return status; + } +} diff --git a/languages/c/templates/sdk/src/Event/Event.h b/languages/c/templates/sdk/src/Event/Event.h new file mode 100644 index 00000000..df9b1dc9 --- /dev/null +++ b/languages/c/templates/sdk/src/Event/Event.h @@ -0,0 +1,154 @@ +/* + * 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 "Module.h" + +namespace FireboltSDK { + + static constexpr uint32_t DefaultWaitTime = 1000; + + class Event : public IEventHandler { + public: + typedef std::function DispatchFunction; + private: + enum State : uint8_t { + IDLE, + EXECUTING, + REVOKED + }; + + struct CallbackData { + const DispatchFunction lambda; + const void* userdata; + State state; + }; + using IdMap = std::map; + using EventMap = std::map; + + + class Response : public WPEFramework::Core::JSON::Container { + public: + Response& operator=(const Response&) = delete; + Response() + : WPEFramework::Core::JSON::Container() + , Listening(false) + { + Add(_T("listening"), &Listening); + } + Response(const Response& copy) + : WPEFramework::Core::JSON::Container() + , Listening(copy.Listening) + { + Add(_T("listening"), &Listening); + } + ~Response() override = default; + + public: + WPEFramework::Core::JSON::Boolean Listening; + }; + + public: + Event(); + ~Event() override; + static Event& Instance(); + static void Dispose(); + void Configure(Transport* transport); + + public: + template + uint32_t Subscribe(const string& eventName, const CALLBACK& callback, const void* userdata, uint32_t& id) + { + uint32_t status = FireboltSDKErrorUnavailable; + if (_transport != nullptr) { + + status = Assign(eventName, callback, userdata, id); + if (status == FireboltSDKErrorNone) { + const string parameters("{\"listen\":true}"); + Response response; + status = _transport->Subscribe(eventName, parameters, response); + + if (status != FireboltSDKErrorNone) { + Revoke(eventName, id); + } else if ((response.Listening.IsSet() == true) && + (response.Listening.Value() == true)) { + status = FireboltSDKErrorNone; + } else { + status = FireboltSDKErrorNotSubscribed; + } + } + } + + return ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone: status); + } + + uint32_t Unsubscribe(const string& eventName, const uint32_t id); + + private: + template + uint32_t Assign(const string& eventName, const CALLBACK& callback, const void* userdata, uint32_t& id) + { + uint32_t status = FireboltSDKErrorNone; + id = Id(); + std::function actualCallback = callback; + DispatchFunction implementation = [actualCallback](const void* userdata, const string& parameters) -> uint32_t { + + WPEFramework::Core::ProxyType inbound = WPEFramework::Core::ProxyType::Create(); + inbound->FromString(parameters); + actualCallback(userdata, static_cast(&inbound)); + return (FireboltSDKErrorNone); + }; + CallbackData callbackData = {implementation, userdata, State::IDLE}; + + _adminLock.Lock(); + EventMap::iterator eventIndex = _eventMap.find(eventName); + if (eventIndex != _eventMap.end()) { + // Already registered, no need to register again; + status = FireboltSDKErrorInUse; + eventIndex->second.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(callbackData)); + } else { + + IdMap idMap; + idMap.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(callbackData)); + _eventMap.emplace(std::piecewise_construct, std::forward_as_tuple(eventName), std::forward_as_tuple(idMap)); + + } + + _adminLock.Unlock(); + return status; + } + uint32_t Revoke(const string& eventName, const uint32_t id); + + private: + uint32_t Id() const + { + return (++_id); + } + uint32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) override; + uint32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) override; + + private: + mutable std::atomic _id; + EventMap _eventMap; + WPEFramework::Core::CriticalSection _adminLock; + Transport* _transport; + + static Event* _singleton; + }; +} diff --git a/languages/c/templates/sdk/src/Firebolt.h b/languages/c/templates/sdk/src/Firebolt.h new file mode 100644 index 00000000..6a8f51a2 --- /dev/null +++ b/languages/c/templates/sdk/src/Firebolt.h @@ -0,0 +1,25 @@ +/* + * 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 "Transport/Transport.h" +#include "Properties/Properties.h" +#include "Accessor/Accessor.h" +#include "Logger/Logger.h" +#include "Types.h" diff --git a/languages/c/templates/sdk/src/FireboltSDK.conf.in b/languages/c/templates/sdk/src/FireboltSDK.conf.in new file mode 100644 index 00000000..6964a7bc --- /dev/null +++ b/languages/c/templates/sdk/src/FireboltSDK.conf.in @@ -0,0 +1,3 @@ +url = "@FIREBOLT_SERVER_URL@" +waittime = "@FIREBOLT_TRANSPORT_WAITTIME@" +loglevel = "@FIREBOLT_LOGLEVEL@" diff --git a/languages/c/templates/sdk/src/Logger/Logger.cpp b/languages/c/templates/sdk/src/Logger/Logger.cpp new file mode 100644 index 00000000..8acd8a14 --- /dev/null +++ b/languages/c/templates/sdk/src/Logger/Logger.cpp @@ -0,0 +1,84 @@ +/* + * 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 "Module.h" +#include "Error.h" +#include "Logger.h" + +namespace WPEFramework { + +ENUM_CONVERSION_BEGIN(FireboltSDK::Logger::LogLevel) + + { FireboltSDK::Logger::LogLevel::Error, _TXT("Error") }, + { FireboltSDK::Logger::LogLevel::Warning, _TXT("Warning") }, + { FireboltSDK::Logger::LogLevel::Info, _TXT("Info") }, + { FireboltSDK::Logger::LogLevel::Debug, _TXT("Debug") }, + +ENUM_CONVERSION_END(FireboltSDK::Logger::LogLevel) + +ENUM_CONVERSION_BEGIN(FireboltSDK::Logger::Category) + + { FireboltSDK::Logger::Category::OpenRPC, _TXT("FireboltSDK::OpenRPC") }, + { FireboltSDK::Logger::Category::Core, _TXT("FireboltSDK::Core") }, + { FireboltSDK::Logger::Category::Management, _TXT("FireboltSDK::Management") }, + { FireboltSDK::Logger::Category::Discovery, _TXT("FireboltSDK::Discovery") }, + +ENUM_CONVERSION_END(FireboltSDK::Logger::Category) + +} + +namespace FireboltSDK { + /* static */ Logger::LogLevel Logger::_logLevel = Logger::LogLevel::Error; + + uint32_t Logger::SetLogLevel(Logger::LogLevel logLevel) + { + ASSERT(logLevel < Logger::LogLevel::MaxLevel); + uint32_t status = FireboltSDKErrorNotSupported; + if (logLevel < Logger::LogLevel::MaxLevel) { + _logLevel = logLevel; + status = FireboltSDKErrorNone; + } + printf("logLevel = %d _logLevel = %d\n", logLevel, _logLevel); + return status; + } + + void Logger::Log(LogLevel logLevel, Category category, const std::string& module, const std::string file, const std::string function, const uint16_t line, const std::string& format, ...) + { + if (logLevel <= _logLevel) { + va_list arg; + char msg[Logger::MaxBufSize]; + va_start(arg, format); + int length = vsnprintf(msg, Logger::MaxBufSize, format.c_str(), arg); + va_end(arg); + + uint32_t position = (length >= Logger::MaxBufSize) ? (Logger::MaxBufSize - 1) : length; + msg[position] = '\0'; + + char formattedMsg[Logger::MaxBufSize]; + const string time = WPEFramework::Core::Time::Now().ToTimeOnly(true); + const string categoryName = WPEFramework::Core::EnumerateType(category).Data(); + if (categoryName.empty() != true) { + sprintf(formattedMsg, "--->\033[1;32m[%s]:[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), categoryName.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); + } else { + sprintf(formattedMsg, "--->\033[1;32m[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); + } + LOG_MESSAGE(formattedMsg); + } + } +} + diff --git a/languages/c/templates/sdk/src/Logger/Logger.h b/languages/c/templates/sdk/src/Logger/Logger.h new file mode 100644 index 00000000..cffeff54 --- /dev/null +++ b/languages/c/templates/sdk/src/Logger/Logger.h @@ -0,0 +1,85 @@ +/* + * 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 "Types.h" + +namespace FireboltSDK { + + class Logger { + private: + static constexpr uint16_t MaxBufSize = 512; + + public: + enum class LogLevel : uint8_t { + Error, + Warning, + Info, + Debug, + MaxLevel + }; + + enum class Category : uint8_t { + OpenRPC, + Core, + Management, + Discovery + }; + + public: + Logger() = default; + Logger(const Logger&) = delete; + Logger& operator=(const Logger&) = delete; + ~Logger() = default; + + public: + static uint32_t SetLogLevel(LogLevel logLevel); + static void Log(LogLevel logLevel, Category category, const std::string& module, const std::string file, const std::string function, const uint16_t line, const std::string& format, ...); + + public: + template + static const string Module() + { + return WPEFramework::Core::ClassNameOnly(typeid(CLASS).name()).Text(); + } + + private: + static LogLevel _logLevel; + }; +} + +#define FIREBOLT_LOG(level, category, module, ...) \ + FireboltSDK::Logger::Log(level, category, module, __FILE__, __func__, __LINE__, __VA_ARGS__) + +#define FIREBOLT_LOG_ERROR(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Error, category, module, __VA_ARGS__) +#define FIREBOLT_LOG_WARNING(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Warning, category, module, __VA_ARGS__) +#define FIREBOLT_LOG_INFO(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Info, category, module, __VA_ARGS__) +#define FIREBOLT_LOG_DEBUG(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Debug, category, module, __VA_ARGS__) + +#ifdef ENABLE_SYSLOG +#define LOG_MESSAGE(message) \ + syslog(sLOG_NOTIC, "%s", message); +#else +#define LOG_MESSAGE(message) \ + fprintf(stderr, "%s", message); fflush(stdout); +#endif diff --git a/languages/c/templates/schemas/src/Module.cpp b/languages/c/templates/sdk/src/Module.cpp similarity index 85% rename from languages/c/templates/schemas/src/Module.cpp rename to languages/c/templates/sdk/src/Module.cpp index 26a26050..d63badc4 100644 --- a/languages/c/templates/schemas/src/Module.cpp +++ b/languages/c/templates/sdk/src/Module.cpp @@ -16,14 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 */ -/* ${IMPORTS} */ +#include "Module.h" - -namespace FireboltSDK { - - namespace ${info.title} { - - /* ${METHODS} */ - - } -} +MODULE_NAME_DECLARATION(BUILD_REFERENCE) diff --git a/languages/c/templates/sdk/main.cpp b/languages/c/templates/sdk/src/Module.h similarity index 61% rename from languages/c/templates/sdk/main.cpp rename to languages/c/templates/sdk/src/Module.h index a9f2f5ca..5107d93e 100644 --- a/languages/c/templates/sdk/main.cpp +++ b/languages/c/templates/sdk/src/Module.h @@ -1,5 +1,5 @@ /* - * Copyright 2021 Comcast Cable Communications Management, LLC + * 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. @@ -16,15 +16,16 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { setMockResponses } from './Transport/MockTransport.mjs' +#pragma once -/* ${MOCK_IMPORTS} */ +#ifndef MODULE_NAME +#define MODULE_NAME OpenRPCNativeSDK +#endif -setMockResponses({ - /* ${MOCK_OBJECTS} */ -}) +#include +#include +#include +#include -/* ${EXPORTS} */ -export { default as Log } from './Log/index.mjs' -export { default as Events } from './Events/index.mjs' -export { default as Settings } from './Settings/index.mjs' +#undef EXTERNAL +#define EXTERNAL diff --git a/languages/c/templates/sdk/src/Params.config b/languages/c/templates/sdk/src/Params.config new file mode 100644 index 00000000..71a58750 --- /dev/null +++ b/languages/c/templates/sdk/src/Params.config @@ -0,0 +1,3 @@ +url +waittime +loglevel diff --git a/languages/c/templates/sdk/src/Properties/Properties.h b/languages/c/templates/sdk/src/Properties/Properties.h new file mode 100644 index 00000000..611811f8 --- /dev/null +++ b/languages/c/templates/sdk/src/Properties/Properties.h @@ -0,0 +1,90 @@ +/* + * 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 "Accessor/Accessor.h" +#include "Event/Event.h" + +namespace FireboltSDK { + + class Properties { + public: + Properties(const Properties&) = delete; + Properties& operator= (const Properties&) = delete; + + Properties() = default; + ~Properties() = default; + + public: + template + static uint32_t Get(const string& propertyName, WPEFramework::Core::ProxyType& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject parameters; + RESPONSETYPE responseType; + status = transport->Invoke(propertyName, parameters, responseType); + if (status == FireboltSDKErrorNone) { + ASSERT(response.IsValid() == false); + if (response.IsValid() == true) { + response.Release(); + } + response = WPEFramework::Core::ProxyType::Create(); + (*response) = responseType; + } + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static uint32_t Set(const string& propertyName, const PARAMETERS& parameters) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject responseType; + status = transport->Invoke(propertyName, parameters, responseType); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static uint32_t Subscribe(const string& propertyName, const CALLBACK& callback, const void* userdata, uint32_t& id) + { + return Event::Instance().Subscribe(EventName(propertyName), callback, userdata, id); + } + + static uint32_t Unsubscribe(const string& propertyName, const uint32_t id) + { + return Event::Instance().Unsubscribe(EventName(propertyName), id); + } + private: + static inline string EventName(const string& propertyName) { + size_t pos = propertyName.find_first_of('.'); + return string(propertyName.substr(0, pos + 1) + "on" + propertyName.substr(pos + 1) + "Changed"); + } + }; +} diff --git a/languages/c/templates/schemas/include/Module.h b/languages/c/templates/sdk/src/Transport/Transport.cpp similarity index 96% rename from languages/c/templates/schemas/include/Module.h rename to languages/c/templates/sdk/src/Transport/Transport.cpp index 4cee1781..280944c6 100644 --- a/languages/c/templates/schemas/include/Module.h +++ b/languages/c/templates/sdk/src/Transport/Transport.cpp @@ -16,8 +16,9 @@ * SPDX-License-Identifier: Apache-2.0 */ -namespace FireboltSDK { +#include "Transport.h" - /* ${DECLARATIONS} */ +namespace FireboltSDK { } + diff --git a/languages/c/templates/sdk/src/Transport/Transport.h b/languages/c/templates/sdk/src/Transport/Transport.h new file mode 100644 index 00000000..e0bff38c --- /dev/null +++ b/languages/c/templates/sdk/src/Transport/Transport.h @@ -0,0 +1,897 @@ +/* + * 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 "Module.h" +#include "Error.h" + +namespace FireboltSDK { + + using namespace WPEFramework::Core::TypeTraits; + + template + class CommunicationChannel { + public: + typedef std::function Callback; + class Entry { + private: + Entry(const Entry&) = delete; + Entry& operator=(const Entry& rhs) = delete; + struct Synchronous { + Synchronous() + : _signal(false, true) + , _response() + { + } + WPEFramework::Core::Event _signal; + std::list> _response; + }; + struct ASynchronous { + ASynchronous(const uint32_t waitTime, const Callback& completed) + : _waitTime(WPEFramework::Core::Time::Now().Add(waitTime).Ticks()) + , _completed(completed) + { + } + uint64_t _waitTime; + Callback _completed; + }; + + public: + Entry() + : _synchronous(true) + , _info() + { + } + Entry(const uint32_t waitTime, const Callback& completed) + : _synchronous(false) + , _info(waitTime, completed) + { + } + ~Entry() + { + if (_synchronous == true) { + _info.sync.~Synchronous(); + } + else { + _info.async.~ASynchronous(); + } + } + + public: + const WPEFramework::Core::ProxyType& Response() const + { + return (*(_info.sync._response.begin())); + } + bool Signal(const WPEFramework::Core::ProxyType& response) + { + if (_synchronous == true) { + _info.sync._response.push_back(response); + _info.sync._signal.SetEvent(); + } + else { + _info.async._completed(*response); + } + + return (_synchronous == false); + } + const uint64_t& Expiry() const + { + return (_info.async._waitTime); + } + void Abort(const uint32_t id) + { + if (_synchronous == true) { + _info.sync._signal.SetEvent(); + } + else { + MESSAGETYPE message; + ToMessage(id, message, WPEFramework::Core::ERROR_ASYNC_ABORTED); + _info.async._completed(message); + } + } + bool Expired(const uint32_t id, const uint64_t& currentTime, uint64_t& nextTime) + { + bool expired = false; + + if (_synchronous == false) { + if (_info.async._waitTime > currentTime) { + if (_info.async._waitTime < nextTime) { + nextTime = _info.async._waitTime; + } + } + else { + MESSAGETYPE message; + ToMessage(id, message, WPEFramework::Core::ERROR_TIMEDOUT); + _info.async._completed(message); + expired = true; + } + } + return (expired); + } + bool WaitForResponse(const uint32_t waitTime) + { + return (_info.sync._signal.Lock(waitTime) == WPEFramework::Core::ERROR_NONE); + } + + private: + void ToMessage(const uint32_t id, WPEFramework::Core::JSONRPC::Message& message, uint32_t error) + { + message.Id = id; + message.Error.Code = error; + switch (error) { + case WPEFramework::Core::ERROR_ASYNC_ABORTED: { + message.Error.Text = _T("Pending a-sync call has been aborted"); + break; + } + case WPEFramework::Core::ERROR_TIMEDOUT: { + message.Error.Text = _T("Pending a-sync call has timed out"); + break; + } + } + } + + bool _synchronous; + union Info { + public: + Info() + : sync() + { + } + Info(const uint32_t waitTime, const Callback& completed) + : async(waitTime, completed) + { + } + ~Info() + { + } + Synchronous sync; + ASynchronous async; + } _info; + }; + + + + private: + class FactoryImpl { + private: + FactoryImpl(const FactoryImpl&) = delete; + FactoryImpl& operator=(const FactoryImpl&) = delete; + + class WatchDog { + private: + WatchDog() = delete; + WatchDog& operator=(const WatchDog&) = delete; + + public: + WatchDog(CLIENT* client) + : _client(client) + { + } + WatchDog(const WatchDog& copy) + : _client(copy._client) + { + } + ~WatchDog() + { + } + + bool operator==(const WatchDog& rhs) const + { + return (rhs._client == _client); + } + bool operator!=(const WatchDog& rhs) const + { + return (!operator==(rhs)); + } + + public: + uint64_t Timed(const uint64_t scheduledTime) { + return (_client->Timed()); + } + + private: + CLIENT* _client; + }; + + friend WPEFramework::Core::SingletonType; + + FactoryImpl() + : _messageFactory(2) + , _watchDog(WPEFramework::Core::Thread::DefaultStackSize(), _T("TransportCleaner")) + { + } + + public: + static FactoryImpl& Instance() + { + return (WPEFramework::Core::SingletonType::Instance()); + } + + ~FactoryImpl() + { + } + + public: + WPEFramework::Core::ProxyType Element(const string&) + { + return (_messageFactory.Element()); + } + void Trigger(const uint64_t& time, CLIENT* client) + { + _watchDog.Trigger(time, client); + } + void Revoke(CLIENT* client) + { + _watchDog.Revoke(client); + } + private: + WPEFramework::Core::ProxyPoolType _messageFactory; + WPEFramework::Core::TimerType _watchDog; + }; + + class ChannelImpl : public WPEFramework::Core::StreamJSONType, FactoryImpl&, INTERFACE> { + private: + ChannelImpl(const ChannelImpl&) = delete; + ChannelImpl& operator=(const ChannelImpl&) = delete; + + typedef WPEFramework::Core::StreamJSONType, FactoryImpl&, INTERFACE> BaseClass; + + public: + ChannelImpl(CommunicationChannel* parent, const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask) + : BaseClass(5, FactoryImpl::Instance(), path, _T("JSON"), query, "", false, mask, false, remoteNode.AnyInterface(), remoteNode, 256, 256) + , _parent(*parent) + { + } + ~ChannelImpl() override = default; + + public: + void Received(WPEFramework::Core::ProxyType& response) override + { + WPEFramework::Core::ProxyType inbound(response); + + ASSERT(inbound.IsValid() == true); + if (inbound.IsValid() == true) { + _parent.Inbound(inbound); + } + } + void Send(WPEFramework::Core::ProxyType& msg) override + { +#ifdef __DEBUG__ + string message; + ToMessage(msg, message); + TRACE_L1("Message: %s send", message.c_str()); +#endif + } + void StateChange() override + { + _parent.StateChange(); + } + bool IsIdle() const override + { + return (true); + } + + private: + void ToMessage(const WPEFramework::Core::ProxyType& jsonObject, string& message) const + { + WPEFramework::Core::ProxyType inbound(jsonObject); + + ASSERT(inbound.IsValid() == true); + if (inbound.IsValid() == true) { + inbound->ToString(message); + } + } + void ToMessage(const WPEFramework::Core::ProxyType& jsonObject, string& message) const + { + WPEFramework::Core::ProxyType inbound(jsonObject); + + ASSERT(inbound.IsValid() == true); + if (inbound.IsValid() == true) { + std::vector values; + inbound->ToBuffer(values); + if (values.empty() != true) { + WPEFramework::Core::ToString(values.data(), static_cast(values.size()), false, message); + } + } + } + + private: + CommunicationChannel& _parent; + }; + + protected: + CommunicationChannel(const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask) + : _channel(this, remoteNode, path, query, mask) + , _sequence(0) + { + } + + public: + ~CommunicationChannel() = default; + static WPEFramework::Core::ProxyType Instance(const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask = true) + { + static WPEFramework::Core::ProxyMapType channelMap; + + string searchLine = remoteNode.HostAddress() + '@' + path; + + return (channelMap.template Instance(searchLine, remoteNode, path, query, mask)); + } + + public: + static void Trigger(const uint64_t& time, CLIENT* client) + { + FactoryImpl::Instance().Trigger(time, client); + } + static WPEFramework::Core::ProxyType Message() + { + return (FactoryImpl::Instance().Element(string())); + } + uint32_t Sequence() const + { + return (++_sequence); + } + void Register(CLIENT& client) + { + _adminLock.Lock(); + ASSERT(std::find(_observers.begin(), _observers.end(), &client) == _observers.end()); + _observers.push_back(&client); + if (_channel.IsOpen() == true) { + client.Opened(); + } + _adminLock.Unlock(); + } + void Unregister(CLIENT& client) + { + _adminLock.Lock(); + typename std::list::iterator index(std::find(_observers.begin(), _observers.end(), &client)); + if (index != _observers.end()) { + _observers.erase(index); + } + FactoryImpl::Instance().Revoke(&client); + _adminLock.Unlock(); + } + + void Submit(const WPEFramework::Core::ProxyType& message) + { + _channel.Submit(message); + } + bool IsSuspended() const + { + return (_channel.IsSuspended()); + } + uint32_t Initialize() + { + return (Open(0)); + } + void Deinitialize() + { + Close(); + } + bool IsOpen() + { + return (_channel.IsOpen() == true); + } + + protected: + void StateChange() + { + _adminLock.Lock(); + typename std::list::iterator index(_observers.begin()); + while (index != _observers.end()) { + if (_channel.IsOpen() == true) { + (*index)->Opened(); + } + else { + (*index)->Closed(); + } + index++; + } + _adminLock.Unlock(); + } + bool Open(const uint32_t waitTime) + { + bool result = true; + if (_channel.IsClosed() == true) { + result = (_channel.Open(waitTime) == WPEFramework::Core::ERROR_NONE); + } + return (result); + } + void Close() + { + _channel.Close(WPEFramework::Core::infinite); + } + + private: + uint32_t Inbound(const WPEFramework::Core::ProxyType& inbound) + { + uint32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + _adminLock.Lock(); + typename std::list::iterator index(_observers.begin()); + while ((result != WPEFramework::Core::ERROR_NONE) && (index != _observers.end())) { + result = (*index)->Submit(inbound); + index++; + } + _adminLock.Unlock(); + + return (result); + } + + private: + WPEFramework::Core::CriticalSection _adminLock; + ChannelImpl _channel; + mutable std::atomic _sequence; + std::list _observers; + }; + + class IEventHandler { + public: + virtual uint32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) = 0; + virtual uint32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) = 0; + virtual ~IEventHandler() = default; + }; + + template + class Transport { + private: + using Channel = CommunicationChannel; + using Entry = typename CommunicationChannel::Entry; + using PendingMap = std::unordered_map; + using EventMap = std::map; + typedef std::function& jsonResponse, bool& enabled)> EventResponseValidatioionFunction; + + class Job : public WPEFramework::Core::IDispatch { + protected: + Job(const WPEFramework::Core::ProxyType& inbound, class Transport* parent) + : _inbound(inbound) + , _parent(parent) + { + } + + public: + Job() = delete; + Job(const Job&) = delete; + Job& operator=(const Job&) = delete; + + ~Job() = default; + + public: + static WPEFramework::Core::ProxyType Create(const WPEFramework::Core::ProxyType& inbound, class Transport* parent); + + void Dispatch() override + { + _parent->Inbound(_inbound); + } + + private: + const WPEFramework::Core::ProxyType _inbound; + class Transport* _parent; + }; + + protected: + static constexpr uint32_t DefaultWaitTime = 10000; + + inline void Announce() { + _channel->Register(*this); + } + + private: + static constexpr const TCHAR* PathPrefix = _T("/"); + public: + Transport() = delete; + Transport(const Transport&) = delete; + Transport& operator=(Transport&) = delete; + Transport(const WPEFramework::Core::URL& url, const uint32_t waitTime) + : _adminLock() + , _connectId(WPEFramework::Core::NodeId(url.Host().Value().c_str(), url.Port().Value())) + , _channel(Channel::Instance(_connectId, ((url.Path().Value().rfind(PathPrefix, 0) == 0) ? url.Path().Value() : string(PathPrefix + url.Path().Value())), url.Query().Value(), true)) + , _eventHandler(nullptr) + , _pendingQueue() + , _scheduledTime(0) + , _waitTime(waitTime) + { + _channel->Register(*this); + } + + virtual ~Transport() + { + _channel->Unregister(*this); + + for (auto& element : _pendingQueue) { + element.second.Abort(element.first); + } + } + + public: + inline bool IsOpen() + { + _channel->IsOpen(); + } + + void Revoke(const string& eventName) + { + _adminLock.Lock(); + _eventMap.erase(eventName); + _adminLock.Unlock(); + } + + void SetEventHandler(IEventHandler* eventHandler) + { + _eventHandler = eventHandler; + } + + template + uint32_t Invoke(const string& method, const PARAMETERS& parameters, RESPONSE& response) + { + Entry slot; + uint32_t id = _channel->Sequence(); + uint32_t result = Send(method, parameters, id); + if (result == WPEFramework::Core::ERROR_NONE) { + result = WaitForResponse(id, response, _waitTime); + } + + return (FireboltErrorValue(result)); + } + + template + uint32_t Subscribe(const string& eventName, const string& parameters, RESPONSE& response) + { + Entry slot; + uint32_t id = _channel->Sequence(); + uint32_t result = Send(eventName, parameters, id); + if (result == WPEFramework::Core::ERROR_NONE) { + _adminLock.Lock(); + _eventMap.emplace(std::piecewise_construct, + std::forward_as_tuple(eventName), + std::forward_as_tuple(~0)); + _adminLock.Unlock(); + + result = WaitForEventResponse(id, eventName, response, _waitTime); + } + + return (FireboltErrorValue(result)); + } + + uint32_t Unsubscribe(const string& eventName, const string& parameters) + { + Revoke(eventName); + Entry slot; + uint32_t id = _channel->Sequence(); + uint32_t result = Send(eventName, parameters, id); + + return (FireboltErrorValue(result)); + } + + private: + friend Channel; + inline bool IsEvent(const uint32_t id, string& eventName) + { + _adminLock.Lock(); + for (auto& event : _eventMap) { + if (event.second == id) { + eventName = event.first; + break; + } + } + _adminLock.Unlock(); + return (eventName.empty() != true); + } + uint64_t Timed() + { + uint64_t result = ~0; + uint64_t currentTime = WPEFramework::Core::Time::Now().Ticks(); + + // Lets see if some callback are expire. If so trigger and remove... + _adminLock.Lock(); + + typename PendingMap::iterator index = _pendingQueue.begin(); + + while (index != _pendingQueue.end()) { + + if (index->second.Expired(index->first, currentTime, result) == true) { + index = _pendingQueue.erase(index); + } + else { + index++; + } + } + _scheduledTime = (result != static_cast(~0) ? result : 0); + + _adminLock.Unlock(); + + return (_scheduledTime); + } + + virtual void Opened() + { + // Nice to know :-) + } + + void Closed() + { + // Abort any in progress RPC command: + _adminLock.Lock(); + + // See if we issued anything, if so abort it.. + while (_pendingQueue.size() != 0) { + + _pendingQueue.begin()->second.Abort(_pendingQueue.begin()->first); + _pendingQueue.erase(_pendingQueue.begin()); + } + + _adminLock.Unlock(); + } + + uint32_t Submit(const WPEFramework::Core::ProxyType& inbound) + { + uint32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(inbound, this)); + WPEFramework::Core::IWorkerPool::Instance().Submit(job); + return result; + } + + uint32_t Inbound(const WPEFramework::Core::ProxyType& inbound) + { + uint32_t result = WPEFramework::Core::ERROR_INVALID_SIGNATURE; + + ASSERT(inbound.IsValid() == true); + + if ((inbound->Id.IsSet() == true) && (inbound->Result.IsSet() || inbound->Error.IsSet())) { + // Looks like this is a response.. + ASSERT(inbound->Parameters.IsSet() == false); + ASSERT(inbound->Designator.IsSet() == false); + + _adminLock.Lock(); + + // See if we issued this.. + typename PendingMap::iterator index = _pendingQueue.find(inbound->Id.Value()); + + if (index != _pendingQueue.end()) { + + if (index->second.Signal(inbound) == true) { + _pendingQueue.erase(index); + } + + result = WPEFramework::Core::ERROR_NONE; + } else { + + string eventName; + if (IsEvent(inbound->Id.Value(), eventName)) { + _eventHandler->Dispatch(eventName, inbound); + } + + } + _adminLock.Unlock(); + } + + return (result); + } + + + template + uint32_t Send(const string& method, const PARAMETERS& parameters, const uint32_t& id) + { + uint32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + + if ((_channel.IsValid() == true) && (_channel->IsSuspended() == true)) { + result = WPEFramework::Core::ERROR_ASYNC_FAILED; + } + else if (_channel.IsValid() == true) { + + result = WPEFramework::Core::ERROR_ASYNC_FAILED; + + WPEFramework::Core::ProxyType message(Channel::Message()); + message->Id = id; + message->Designator = method; + ToMessage(parameters, message); + + _adminLock.Lock(); + + typename std::pair< typename PendingMap::iterator, bool> newElement = + _pendingQueue.emplace(std::piecewise_construct, + std::forward_as_tuple(id), + std::forward_as_tuple()); + ASSERT(newElement.second == true); + + if (newElement.second == true) { + + _adminLock.Unlock(); + + _channel->Submit(WPEFramework::Core::ProxyType(message)); + + message.Release(); + result = WPEFramework::Core::ERROR_NONE; + } + } + return result; + } + + template + uint32_t WaitForResponse(const uint32_t& id, RESPONSE& response, const uint32_t waitTime) + { + uint32_t result = WPEFramework::Core::ERROR_TIMEDOUT; + _adminLock.Lock(); + typename PendingMap::iterator index = _pendingQueue.find(id); + Entry& slot(index->second); + _adminLock.Unlock(); + + if (slot.WaitForResponse(waitTime) == true) { + WPEFramework::Core::ProxyType jsonResponse = slot.Response(); + + // See if we have a jsonResponse, maybe it was just the connection + // that closed? + if (jsonResponse.IsValid() == true) { + if (jsonResponse->Error.IsSet() == true) { + result = jsonResponse->Error.Code.Value(); + } + else { + result = WPEFramework::Core::ERROR_NONE; + if ((jsonResponse->Result.IsSet() == true) + && (jsonResponse->Result.Value().empty() == false)) { + FromMessage((INTERFACE*)&response, *jsonResponse); + } + } + } + } else { + result = WPEFramework::Core::ERROR_TIMEDOUT; + } + _adminLock.Lock(); + _pendingQueue.erase(id); + _adminLock.Unlock(); + return result; + } + + static constexpr uint32_t WAITSLOT_TIME = 100; + template + uint32_t WaitForEventResponse(const uint32_t& id, const string& eventName, RESPONSE& response, const uint32_t waitTime) + { + uint32_t result = WPEFramework::Core::ERROR_TIMEDOUT; + _adminLock.Lock(); + typename PendingMap::iterator index = _pendingQueue.find(id); + Entry& slot(index->second); + _adminLock.Unlock(); + + uint8_t waiting = waitTime; + do { + uint32_t waitSlot = (waiting > WAITSLOT_TIME ? WAITSLOT_TIME : waiting); + if (slot.WaitForResponse(waitSlot) == true) { + WPEFramework::Core::ProxyType jsonResponse = slot.Response(); + + // See if we have a jsonResponse, maybe it was just the connection + // that closed? + if (jsonResponse.IsValid() == true) { + if (jsonResponse->Error.IsSet() == true) { + result = jsonResponse->Error.Code.Value(); + } else { + if ((jsonResponse->Result.IsSet() == true) + && (jsonResponse->Result.Value().empty() == false)) { + result = WPEFramework::Core::ERROR_NONE; + bool enabled; + result = _eventHandler->ValidateResponse(jsonResponse, enabled); + if (result == WPEFramework::Core::ERROR_NONE) { + FromMessage((INTERFACE*)&response, *jsonResponse); + if (enabled) { + _adminLock.Lock(); + typename EventMap::iterator index = _eventMap.find(eventName); + if (index != _eventMap.end()) { + index->second = id; + } + _adminLock.Unlock(); + } + } + } + } + } + } else { + result = WPEFramework::Core::ERROR_TIMEDOUT; + } + waiting -= (waiting == WPEFramework::Core::infinite ? 0 : waitSlot); + } while ((result != WPEFramework::Core::ERROR_NONE) && (waiting > 0 )); + _adminLock.Lock(); + _pendingQueue.erase(id); + _adminLock.Unlock(); + + return result; + } + + public: + void FromMessage(WPEFramework::Core::JSON::IElement* response, const WPEFramework::Core::JSONRPC::Message& message) const + { + response->FromString(message.Result.Value()); + } + + void FromMessage(WPEFramework::Core::JSON::IMessagePack* response, const WPEFramework::Core::JSONRPC::Message& message) const + { + string value = message.Result.Value(); + std::vector result(value.begin(), value.end()); + response->FromBuffer(result); + } + + + private: + + void ToMessage(const string& parameters, WPEFramework::Core::ProxyType& message) const + { + if (parameters.empty() != true) { + message->Parameters = parameters; + } + } + + template + void ToMessage(PARAMETERS& parameters, WPEFramework::Core::ProxyType& message) const + { + ToMessage((INTERFACE*)(¶meters), message); + return; + } + + void ToMessage(WPEFramework::Core::JSON::IMessagePack* parameters, WPEFramework::Core::ProxyType& message) const + { + std::vector values; + parameters->ToBuffer(values); + if (values.empty() != true) { + string strValues(values.begin(), values.end()); + message->Parameters = strValues; + } + return; + } + + void ToMessage(WPEFramework::Core::JSON::IElement* parameters, WPEFramework::Core::ProxyType& message) const + { + string values; + parameters->ToString(values); + if (values.empty() != true) { + message->Parameters = values; + } + return; + } + + uint32_t FireboltErrorValue(const uint32_t error) + { + + uint32_t fireboltError = FireboltSDKErrorUnknown; + switch (error) { + case WPEFramework::Core::ERROR_NONE: + fireboltError = FireboltSDKErrorNone; + break; + case WPEFramework::Core::ERROR_GENERAL: + fireboltError = FireboltSDKErrorGeneral; + break; + case WPEFramework::Core::ERROR_UNAVAILABLE: + fireboltError = FireboltSDKErrorUnavailable; + break; + case WPEFramework::Core::ERROR_TIMEDOUT: + fireboltError = FireboltSDKErrorTimedout; + break; + default: + break; + } + + return fireboltError; + } + + private: + WPEFramework::Core::CriticalSection _adminLock; + WPEFramework::Core::NodeId _connectId; + WPEFramework::Core::ProxyType _channel; + IEventHandler* _eventHandler; + PendingMap _pendingQueue; + EventMap _eventMap; + uint64_t _scheduledTime; + uint32_t _waitTime; + }; +} diff --git a/languages/c/templates/sdk/src/Types.cpp b/languages/c/templates/sdk/src/Types.cpp new file mode 100644 index 00000000..e573c0c9 --- /dev/null +++ b/languages/c/templates/sdk/src/Types.cpp @@ -0,0 +1,41 @@ +/* + * 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 "Module.h" +#include "Types.h" +#include "TypesPriv.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// String Type Handler Interfaces +const char* FireboltTypes_String(FireboltTypes_StringHandle handle) +{ + FireboltSDK::String* str = static_cast(handle); + return (str->Value().c_str()); +} +void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle) +{ + FireboltSDK::String* str = static_cast(handle); + delete str; +} + +#ifdef __cplusplus +} +#endif diff --git a/languages/c/templates/sdk/src/TypesPriv.h b/languages/c/templates/sdk/src/TypesPriv.h new file mode 100644 index 00000000..eda9547f --- /dev/null +++ b/languages/c/templates/sdk/src/TypesPriv.h @@ -0,0 +1,55 @@ +/* + * 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 + +namespace FireboltSDK { +class String { + public: + String() + : _value() + { + } + String(const std::string& value) + : _value(value) + { + } + String(const String& copy) + : _value(copy._value) + { + + } + inline ~String() = default; + String& operator=(const String& RHS) + { + _value = RHS._value; + return (*this); + } + + public: + const std::string& Value() const + { + return _value; + } + + private: + std::string _value; + }; +} diff --git a/languages/c/templates/sdk/src/cmake/CopySymlink.cmake b/languages/c/templates/sdk/src/cmake/CopySymlink.cmake new file mode 100644 index 00000000..8ac3c1f8 --- /dev/null +++ b/languages/c/templates/sdk/src/cmake/CopySymlink.cmake @@ -0,0 +1 @@ +file(COPY "${LIBRARY}" DESTINATION "${DESTINATION}" FOLLOW_SYMLINK_CHAIN) diff --git a/languages/c/templates/sdk/test/CMakeLists.txt b/languages/c/templates/sdk/test/CMakeLists.txt new file mode 100644 index 00000000..a56ca20a --- /dev/null +++ b/languages/c/templates/sdk/test/CMakeLists.txt @@ -0,0 +1,86 @@ +# 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 + +cmake_minimum_required(VERSION 3.3) + +project(FireboltSDKTests) +project_version(1.0.0) + +set(TESTLIB ${PROJECT_NAME}) + +message("Setup ${TESTLIB} v${PROJECT_VERSION}") + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +find_package(${NAMESPACE}Core CONFIG REQUIRED) + +add_library(${TESTLIB} STATIC OpenRPCTests.cpp) + +target_link_libraries(${TESTLIB} + PUBLIC + ${NAMESPACE}Core::${NAMESPACE}Core + ${FIREBOLT_NAMESPACE}SDK +) + +target_include_directories(${TESTLIB} + PRIVATE + $ + $ +) + +set_target_properties(${TESTLIB} PROPERTIES + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED YES + LINK_WHAT_YOU_USE TRUE + FRAMEWORK FALSE +) + +install( + TARGETS ${TESTLIB} EXPORT ${TESTLIB}Targets + LIBRARY DESTINATION lib COMPONENT libs + PUBLIC_HEADER DESTINATION include/${FIREBOLT_NAMESPACE}Test COMPONENT devel # headers for mac (note the different component -> different package) + INCLUDES DESTINATION include/${FIREBOLT_NAMESPACE}Test # headers +) + +InstallCMakeConfig(TARGETS ${TESTLIB}) +InstallCMakeConfigs(TARGET ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallHeaders(TARGET ${TESTLIB} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION FireboltTest) +InstallLibraries(TARGET ${TESTLIB} LIBRARIES ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) + +set(TESTAPP "FireboltSDKTestApp") + +message("Setup ${TESTAPP}") + +add_executable(${TESTAPP} Main.c) + +target_link_libraries(${TESTAPP} + PRIVATE + ${TESTLIB} +) + +target_include_directories(${TESTAPP} + PRIVATE + $ + $ +) + +add_custom_command( + TARGET ${TESTAPP} + POST_BUILD + COMMENT "=================== Installing TestApp ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/bin + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${TESTAPP} ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/bin +) + diff --git a/languages/c/templates/sdk/test/Main.c b/languages/c/templates/sdk/test/Main.c new file mode 100644 index 00000000..7c4c94a5 --- /dev/null +++ b/languages/c/templates/sdk/test/Main.c @@ -0,0 +1,44 @@ +/* + * 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 "OpenRPCCTests.h" + +int __cnt = 0; +int __pass = 0; + +int TotalTests = 0; +int TotalTestsPassed = 0; + +int main() +{ + test_firebolt_create_instance(); + test_firebolt_main(); + + // Calling C function sequences + printf("%s:%s:%d Calling C function tests\n", __FILE__, __func__, __LINE__); + EXECUTE("test_properties_get_device_id", test_properties_get_device_id); + EXECUTE("test_properties_set", test_properties_set); + EXECUTE("test_eventregister_by_providing_callback", test_eventregister_by_providing_callback); + EXECUTE("test_eventregister", test_eventregister); + EXECUTE("test_string_set_get_value", test_string_set_get_value); + + test_firebolt_dispose_instance(); + + printf("TOTAL: %i tests; %i PASSED, %i FAILED\n", TotalTests, TotalTestsPassed, (TotalTests - TotalTestsPassed)); +} + diff --git a/languages/c/templates/sdk/test/Module.cpp b/languages/c/templates/sdk/test/Module.cpp new file mode 100644 index 00000000..d63badc4 --- /dev/null +++ b/languages/c/templates/sdk/test/Module.cpp @@ -0,0 +1,21 @@ +/* + * 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 "Module.h" + +MODULE_NAME_DECLARATION(BUILD_REFERENCE) diff --git a/languages/c/templates/modules/src/Module_Common.cpp b/languages/c/templates/sdk/test/Module.h similarity index 79% rename from languages/c/templates/modules/src/Module_Common.cpp rename to languages/c/templates/sdk/test/Module.h index bce775ff..d5340b68 100644 --- a/languages/c/templates/modules/src/Module_Common.cpp +++ b/languages/c/templates/sdk/test/Module.h @@ -16,16 +16,14 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "FireboltSDK.h" -#include "Common/${info.title}.h" -#include "JsonData_${info.title}.h" -} -#ifdef __cplusplus -extern "C" { +#pragma once + +#ifndef MODULE_NAME +#define MODULE_NAME OpenRPCTestApp #endif - /* ${SCHEMAS}} */ +#include +#include -#ifdef __cplusplus -} -#endif \ No newline at end of file +#undef EXTERNAL +#define EXTERNAL diff --git a/languages/c/templates/sdk/test/OpenRPCCTests.h b/languages/c/templates/sdk/test/OpenRPCCTests.h new file mode 100644 index 00000000..7f2fb59e --- /dev/null +++ b/languages/c/templates/sdk/test/OpenRPCCTests.h @@ -0,0 +1,42 @@ +/* + * 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 + */ + +#ifndef _OPENRPC_C_TESTS_H +#define _OPENRPC_C_TESTS_H + +#include "TestUtils.h" + +#ifdef __cplusplus +extern "C" { +#endif + +uint32_t test_firebolt_create_instance(); +uint32_t test_firebolt_dispose_instance(); + +uint32_t test_firebolt_main(); +uint32_t test_properties_get_device_id(); +uint32_t test_properties_set(); +uint32_t test_eventregister(); +uint32_t test_eventregister_by_providing_callback(); +uint32_t test_string_set_get_value(); + +#ifdef __cplusplus +} +#endif + +#endif // _OPENRPC_C_TESTS_H diff --git a/languages/c/templates/sdk/test/OpenRPCTests.cpp b/languages/c/templates/sdk/test/OpenRPCTests.cpp new file mode 100644 index 00000000..cf9ea5a0 --- /dev/null +++ b/languages/c/templates/sdk/test/OpenRPCTests.cpp @@ -0,0 +1,385 @@ +/* + * 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 "Module.h" +#include "OpenRPCTests.h" +#include "OpenRPCCTests.h" + +namespace WPEFramework { + +ENUM_CONVERSION_BEGIN(::JsonValue::type) + + { JsonValue::type::EMPTY, _TXT("empty") }, + { JsonValue::type::BOOLEAN, _TXT("boolean") }, + { JsonValue::type::NUMBER, _TXT("number") }, + { JsonValue::type::STRING, _TXT("string") }, + +ENUM_CONVERSION_END(::JsonValue::type) + +ENUM_CONVERSION_BEGIN(TestEnum) + { TestEnum::Test1, _TXT("Test1ValueCheck") }, + { TestEnum::Test2, _TXT("Test2ValueCheck") }, + { TestEnum::Test3, _TXT("Test3ValueCheck") }, + { TestEnum::Test4, _TXT("Test4ValueCheck") }, +ENUM_CONVERSION_END(TestEnum) +} +namespace FireboltSDK { + Tests::Tests() + { + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEventWithMultipleCallback"), + std::forward_as_tuple(&SubscribeEventWithMultipleCallback)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEvent"), + std::forward_as_tuple(&SubscribeEvent)); + + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Set UnKnown Method"), + std::forward_as_tuple(&SetUnKnownMethod)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Set LifeCycle Close"), + std::forward_as_tuple(&SetLifeCycleClose)); + + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Get UnKnown Method"), + std::forward_as_tuple(&GetUnKnownMethod)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Get Device Version"), + std::forward_as_tuple(&GetDeviceVersion)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Get Device Id"), + std::forward_as_tuple(&GetDeviceId)); + } + + /* static */ void Tests::PrintJsonObject(const JsonObject::Iterator& iterator) + { + JsonObject::Iterator index = iterator; + while (index.Next() == true) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "Element [%s]: <%s> = \"%s\"\n", + index.Label(), + WPEFramework::Core::EnumerateType(index.Current().Content()).Data(), + index.Current().Value().c_str()); + } + } + + /* static */ uint32_t Tests::GetDeviceId() + { + const string method = _T("device.id"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "DeviceId : %s", response->Value().c_str()); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d\n", method.c_str(), status); + } + + return status; + } + + /*static */ uint32_t Tests::GetDeviceVersion() + { + const string method = _T("device.version"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "DeviceVersion"); + PrintJsonObject(response->Variants()); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d", method.c_str(), status); + } + + return status; + } + + /* static */ uint32_t Tests::GetUnKnownMethod() + { + const string method = _T("get.unknownMethod"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_NE(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d\n", method.c_str(), status); + } + + return status; + } + + /* static */ uint32_t Tests::SetLifeCycleClose() + { + const string method = _T("lifecycle.close"); + JsonObject parameters; + parameters["reason"] = "remoteButton"; + uint32_t status = FireboltSDK::Properties::Set(method, parameters); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d\n", method.c_str(), status); + } + + return status; + } + + /* static */ uint32_t Tests::SetUnKnownMethod() + { + const string method = _T("set.unknownMethod"); + JsonObject parameters; + uint32_t status = FireboltSDK::Properties::Set(method, parameters); + + EXPECT_NE(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", method.c_str(), status); + } + + return status; + } + + static void deviceNameChangeCallback(const void* userData, void* response) + { + WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Received a new event: %s", jsonResponse->Value().c_str()); + jsonResponse.Release(); + FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + eventControl->NotifyEvent(); + } + + /* static */ uint32_t Tests::SubscribeEvent() + { + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + + uint32_t id = 0; + + eventControl->ResetEvent(); + uint32_t status = Properties::Subscribe(eventName, deviceNameChangeCallback, userdata, id); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), + "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered successfully", __func__); + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + EXPECT_EQ(Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + delete eventControl; + + return status; + } + + template + /* static */ uint32_t Tests::SubscribeEventForC(const string& eventName, CALLBACK& callbackFunc, const void* userdata, uint32_t& id) + { + return Properties::Subscribe(eventName, callbackFunc, userdata, id);; + } + + static void deviceNameChangeMultipleCallback(const void* userData, void* response) + { + WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "Received a new event from deviceNameChangeMultipleCallback: %s", jsonResponse->Value().c_str()); + jsonResponse.Release(); + FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + eventControl->NotifyEvent(); + } + + /* static */ uint32_t Tests::SubscribeEventWithMultipleCallback() + { + FireboltSDK::Tests::EventControl* eventControl1 = new FireboltSDK::Tests::EventControl(); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl1); + uint32_t id1 = 0, id2 = 0; + + eventControl1->ResetEvent(); + uint32_t status = Properties::Subscribe(eventName, deviceNameChangeCallback, userdata, id1); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), + "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered successfully", __func__); + } + + if (status == FireboltSDKErrorNone) { + FireboltSDK::Tests::EventControl* eventControl2 = new FireboltSDK::Tests::EventControl(); + userdata = static_cast(eventControl2); + + status = Properties::Subscribe(eventName, deviceNameChangeMultipleCallback, userdata, id2); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered second callback also successfully", __func__); + eventControl1->WaitForEvent(WPEFramework::Core::infinite); + eventControl2->WaitForEvent(WPEFramework::Core::infinite); + } + EXPECT_EQ(Properties::Unsubscribe(eventName, id1), FireboltSDKErrorNone); + delete eventControl2; + } + EXPECT_EQ(Properties::Unsubscribe(eventName, id2), FireboltSDKErrorNone); + + delete eventControl1; + return status; + } + +} + +#ifdef __cplusplus +extern "C" { +#endif + +uint32_t test_firebolt_create_instance() +{ + FireboltSDK::Accessor::Instance(); +} + +uint32_t test_firebolt_dispose_instance() +{ + FireboltSDK::Accessor::Dispose(); +} + +uint32_t test_firebolt_main() +{ + return FireboltSDK::Tests::Main(); +} + +uint32_t test_properties_get_device_id() +{ + const string method = _T("device.id"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "DeviceId : %s", response->Value().c_str()); + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "Get %s status = %d", method.c_str(), status); + } + + return status; +} + +uint32_t test_properties_set() +{ + const string method = _T("lifecycle.close"); + JsonObject parameters; + parameters["reason"] = "remoteButton"; + uint32_t status = FireboltSDK::Properties::Set(method, parameters); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "Set %s status = %d", method.c_str(), status); + } + + return status; +} + +static void deviceNameChangeCallbackForC(const void* userData, void* response) +{ + WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "Received a new event--->: %s", jsonResponse->Value().c_str()); + jsonResponse.Release(); + + FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + eventControl->NotifyEvent(); +} + +uint32_t test_eventregister() +{ + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + JsonObject parameters; + + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + uint32_t id = 0; + + eventControl->ResetEvent(); + uint32_t status = FireboltSDK::Properties::Subscribe(eventName, deviceNameChangeCallbackForC, userdata, id); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Set %s status = %d", __func__, eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes registered successfully", __func__); + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + delete eventControl; + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + + return status; +} + +uint32_t test_eventregister_by_providing_callback() +{ + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + uint32_t id = 0; + + eventControl->ResetEvent(); + uint32_t status = FireboltSDK::Tests::SubscribeEventForC(eventName, deviceNameChangeCallbackForC, userdata, id); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Set %s status = %d", __func__, eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes registered successfully", __func__); + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + delete eventControl; + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); +} + +#include "TypesPriv.h" +uint32_t test_string_set_get_value() +{ + uint32_t status = FireboltSDKErrorNone; + FireboltSDK::String* str = new FireboltSDK::String("testString"); + void* handle = static_cast(str); + + const char* value = FireboltTypes_String(handle); + EXPECT_EQ(strncmp(value, str->Value().c_str(), str->Value().length()), 0); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + " ---> type name = %s %s", str->Value().c_str(), value); + + WPEFramework::Core::JSON::EnumType<::TestEnum> testEnum = Test4; + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + " EnumTest = %d %s", testEnum.Value(), testEnum.Data()); + FireboltTypes_StringHandle_Release(handle); + return status; +} + +#ifdef __cplusplus +} +#endif diff --git a/languages/c/templates/sdk/test/OpenRPCTests.h b/languages/c/templates/sdk/test/OpenRPCTests.h new file mode 100644 index 00000000..00abd364 --- /dev/null +++ b/languages/c/templates/sdk/test/OpenRPCTests.h @@ -0,0 +1,99 @@ +/* + * 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 "TestUtils.h" +#include "Firebolt.h" + +namespace FireboltSDK { + typedef uint32_t (*Func)(); + + class Tests { + public: + class EventControl { + public: + EventControl() + : _event(false, true) + { + } + ~EventControl() = default; + + public: + void NotifyEvent() + { + _event.SetEvent(); + } + uint32_t WaitForEvent(uint32_t waitTime) + { + return _event.Lock(waitTime); + } + void ResetEvent() + { + _event.ResetEvent(); + } + private: + WPEFramework::Core::Event _event; + }; + + private: + typedef std::unordered_map TestFunctionMap; + + public: + Tests(); + virtual ~Tests() = default; + + inline TestFunctionMap& TestList() + { + return _functionMap; + } + + template + static uint32_t Main() + { + TESTS fireboltTest; + for (auto i = fireboltTest.TestList().begin(); i != fireboltTest.TestList().end(); i++) { + EXECUTE(i->first.c_str(), i->second); + } + + printf("TOTAL: %i tests; %i PASSED, %i FAILED\n", TotalTests, TotalTestsPassed, (TotalTests - TotalTestsPassed)); + + return 0; + } + + static uint32_t GetDeviceId(); + static uint32_t GetDeviceVersion(); + static uint32_t GetUnKnownMethod(); + + static uint32_t SetLifeCycleClose(); + static uint32_t SetUnKnownMethod(); + + static uint32_t SubscribeEvent(); + static uint32_t SubscribeEventWithMultipleCallback(); + + template + static uint32_t SubscribeEventForC(const string& eventName, CALLBACK& callbackFunc, const void* userdata, uint32_t& id); + + protected: + static void PrintJsonObject(const JsonObject::Iterator& iterator); + + protected: + std::list menu; + TestFunctionMap _functionMap; + }; +} diff --git a/languages/c/templates/sdk/test/TestUtils.h b/languages/c/templates/sdk/test/TestUtils.h new file mode 100644 index 00000000..8c3cb732 --- /dev/null +++ b/languages/c/templates/sdk/test/TestUtils.h @@ -0,0 +1,38 @@ +#ifndef _TEST_UTILS_H +#define _TEST_UTILS_H + +#include +#include +#include + +#define MAX(x, y) (((x) > (y)) ? (x) : (y)) +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) + +#define _RESULT(expr, exprorig, result) if (expr) { printf(" SUCCESS: %s\n", #exprorig); __pass++; } else printf(" FAILED: %s, actual: %u\n", #exprorig, result) +#define _EVAL(result, expected, op) do { __cnt++; uint32_t resval = ((uint32_t)(result)); uint32_t expval = ((uint32_t)(expected)); _RESULT(resval op expval, result op expected, resval); } while(0) +#define _HEAD(name) printf("\n======== %s\n", name); __cnt = 0; __pass = 0 +#define _FOOT(name) printf("\n======== %s - %i PASSED, %i FAILED\n", name, __pass, (__cnt - __pass)); TotalTests += __cnt; TotalTestsPassed += __pass; + +#define EXECUTE(name, test) do { _HEAD(name); test(); _FOOT(name); printf("\n"); } while(0) +#define EXPECT_EQ(result, expected) _EVAL(result, expected, ==) +#define EXPECT_NE(result, expected) _EVAL(result, expected, !=) +#define EXPECT_LT(result, expected) _EVAL(result, expected, <) +#define EXPECT_LE(result, expected) _EVAL(result, expected, <=) +#define EXPECT_GT(result, expected) _EVAL(result, expected, >) +#define EXPECT_GE(result, expected) _EVAL(result, expected, >=) + +#ifdef __cplusplus +extern "C" { +#endif + +extern int __cnt; +extern int __pass; + +extern int TotalTests ; +extern int TotalTestsPassed; + +#ifdef __cplusplus +} +#endif + +#endif // _TEST_UTILS_H diff --git a/languages/c/templates/sections/accessors.c b/languages/c/templates/sections/accessors.c new file mode 100644 index 00000000..0586b2a5 --- /dev/null +++ b/languages/c/templates/sections/accessors.c @@ -0,0 +1,3 @@ +// Accessors + +${schema.list} diff --git a/languages/c/templates/sections/declarations.js b/languages/c/templates/sections/declarations.c similarity index 100% rename from languages/c/templates/sections/declarations.js rename to languages/c/templates/sections/declarations.c diff --git a/languages/c/templates/sections/events.js b/languages/c/templates/sections/events.c similarity index 100% rename from languages/c/templates/sections/events.js rename to languages/c/templates/sections/events.c diff --git a/languages/c/templates/sections/methods.js b/languages/c/templates/sections/methods.c similarity index 100% rename from languages/c/templates/sections/methods.js rename to languages/c/templates/sections/methods.c diff --git a/languages/c/templates/sections/provider-interfaces.js b/languages/c/templates/sections/provider-interfaces.c similarity index 100% rename from languages/c/templates/sections/provider-interfaces.js rename to languages/c/templates/sections/provider-interfaces.c diff --git a/languages/c/templates/sections/schemas.c b/languages/c/templates/sections/schemas.c new file mode 100644 index 00000000..a1847009 --- /dev/null +++ b/languages/c/templates/sections/schemas.c @@ -0,0 +1,3 @@ +// Types & Enums + +${schema.list} diff --git a/languages/c/templates/sections/schemas.js b/languages/c/templates/sections/types.c similarity index 100% rename from languages/c/templates/sections/schemas.js rename to languages/c/templates/sections/types.c diff --git a/languages/c/templates/types/enum.c b/languages/c/templates/types/enum.c new file mode 100644 index 00000000..2a8e94d7 --- /dev/null +++ b/languages/c/templates/types/enum.c @@ -0,0 +1,3 @@ +typedef enum { + ${info.TITLE}_${NAME}_${key}, +} ${info.title}_${name}; diff --git a/languages/c/templates/types/enum.mjs b/languages/c/templates/types/enum.mjs deleted file mode 100644 index 907fb37d..00000000 --- a/languages/c/templates/types/enum.mjs +++ /dev/null @@ -1,3 +0,0 @@ -${name}: { - ${key}: '${value}', -}, diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 6404a059..f0b5959c 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -60,7 +60,8 @@ let config = { } const state = { - destination: undefined + destination: undefined, + section: undefined } const setTyper = (t) => { @@ -106,7 +107,7 @@ const getLinkForSchema = (schema, json) => { schema = schema.schema } - const type = types.getSchemaType(schema, json, { destination: state.destination }) + const type = types.getSchemaType(schema, json, { 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]) { @@ -337,8 +338,12 @@ const generateMacros = (obj, templates, languages, options = {}) => { 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 schemasArray = generateSchemas(obj, templates, { baseUrl: '' }).filter(s => (options.copySchemasIntoModules || !s.uri)) + const schemasArray = generateSchemas(obj, templates, { baseUrl: '', section: 'schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) + const accessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).join('\n')) : '' + const typesArray = schemasArray.filter(x => !x.enum) + const types = typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).join('\n')) : '' + const accessors = accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).join('\n')) : '' const module = getTemplate('/codeblocks/module', templates) const macros = { @@ -350,10 +355,12 @@ const generateMacros = (obj, templates, languages, options = {}) => { eventsEnum, methods, methodList, + accessors, declarations, defaults, examples, schemas, + types, providerInterfaces, version: getSemanticVersion(obj), title: obj.info.title, @@ -385,12 +392,14 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{module.list\}/g, macros.module) fContents = fContents.replace(/[ \t]*\/\* \$\{METHODS\} \*\/[ \t]*\n/, macros.methods) + fContents = fContents.replace(/[ \t]*\/\* \$\{ACCESSORS\} \*\/[ \t]*\n/, macros.accessors) fContents = fContents.replace(/[ \t]*\/\* \$\{DECLARATIONS\} \*\/[ \t]*\n/, macros.declarations) 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) fContents = fContents.replace(/[ \t]*\/\* \$\{SCHEMAS\} \*\/[ \t]*\n/, macros.schemas) + fContents = fContents.replace(/[ \t]*\/\* \$\{TYPES\} \*\/[ \t]*\n/, macros.types) fContents = fContents.replace(/[ \t]*\/\* \$\{PROVIDERS\} \*\/[ \t]*\n/, macros.providerInterfaces) fContents = fContents.replace(/[ \t]*\/\* \$\{ENUMS\} \*\/[ \t]*\n/, macros.enums) fContents = fContents.replace(/[ \t]*\/\* \$\{IMPORTS\} \*\/[ \t]*\n/, macros.imports) @@ -402,6 +411,7 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{minor\}/g, macros.version.minor) fContents = fContents.replace(/\$\{patch\}/g, macros.version.patch) fContents = fContents.replace(/\$\{info\.title\}/g, macros.title) + fContents = fContents.replace(/\$\{info\.TITLE\}/g, macros.title.toUpperCase()) fContents = fContents.replace(/\$\{info\.description\}/g, macros.description) fContents = fContents.replace(/\$\{info\.version\}/g, macros.version.readable) @@ -492,11 +502,12 @@ const generateEnums = (json, templates) => { if (template[i].indexOf('${key}') >= 0) { template[i] = schema.enum.map(value => { const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() - return template[i].replace(/\$\{key\}/g, safeName).replace(/\$\{value\}/g, value) + return template[i].replace(/\$\{key\}/g, safeName) + .replace(/\$\{value\}/g, value) }).join('\n') } } - return template.join('\n').replace(/\$\{name\}/g, schema.title) + return template.join('\n').replace(/\$\{name\}/g, schema.title).replace(/\$\{NAME\}/g, schema.title.toUpperCase()) })), map(enumFinder), getSchemas @@ -579,7 +590,7 @@ function generateSchemas(json, templates, options) { else { content = content.replace(/\$\{if\.description\}(.*?)\{end\.if\.description\}/gms, '$1') } - const schemaShape = types.getSchemaShape(schema, json, { name, destination: state.destination }) + const schemaShape = types.getSchemaShape(schema, json, { name, destination: state.destination, section: options.section }) content = content .replace(/\$\{schema.title\}/, (schema.title || name)) @@ -598,13 +609,17 @@ function generateSchemas(json, templates, options) { content = content.replace(/.*\$\{schema.seeAlso\}/, '') } + const isEnum = x => x.type === 'string' && Array.isArray(x.enum) && x.title + const result = uri ? { uri: uri, name: schema.title || name, - body: content + body: content, + enum: isEnum(schema) } : { name: schema.title || name, - body: content + body: content, + enum: isEnum(schema) } results.push(result) @@ -641,7 +656,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, { destination: state.destination }) + '](' + getLinkForSchema(schema, json, true) + ')') // need full module here, not just the schema + .map(schema => '[' + types.getSchemaType(schema, json, { destination: state.destination, section: state.section }) + '](' + getLinkForSchema(schema, json, true) + ')') // need full module here, not just the schema .filter(link => link) .join('\n') @@ -679,6 +694,12 @@ const generateImports = (json, templates) => { imports += getTemplate('/imports/x-method', templates) } + + + if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0) { + imports += Object.keys(json['x-schemas']).map(shared => getTemplate('/imports/default', templates).replace(/\$\{info.title\}/g, shared)).join('\n') + } + return imports } @@ -919,13 +940,13 @@ function insertMethodMacros(template, methodObj, json, templates, 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 - const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination }) - const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination }) - const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination }) : '' + const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) + const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) + const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' let seeAlso = '' - if (isPolymorphicPullMethod(methodObj)) { + if (isPolymorphicPullMethod(methodObj) && pullsForType) { seeAlso = `See also: [${pullsForType}](#${pullsForType.toLowerCase()}-1)` // this assumes the schema will be after the method... } else if (methodObj.tags.find(t => t.name === 'polymorphic-pull')) { @@ -936,7 +957,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { if (isTemporalSetMethod(methodObj)) { itemName = result.schema.items.title || 'item' itemName = itemName.charAt(0).toLowerCase() + itemName.substring(1) - itemType = types.getSchemaType(result.schema.items, json, { destination: state.destination }) + itemType = types.getSchemaType(result.schema.items, json, { destination: state.destination, section: state.section }) } template = insertExampleMacros(template, examples[methodObj.name] || [], methodObj, json, templates) @@ -956,8 +977,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/gms, method.params.length ? '$1' : '') .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event.params.length ? '$1' : '') // Typed signature stuff - .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination })) - .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination })) + .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) + .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(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\.deprecation\}/g, deprecation) @@ -965,7 +986,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{event\.name\}/g, method.name.toLowerCase()[2] + method.name.substr(3)) .replace(/\$\{event\.params\}/g, eventParams) .replace(/\$\{event\.params\.table\.rows\}/g, eventParamsRows) - .replace(/\$\{event\.signature\.params\}/g, types.getMethodSignatureParams(event, json, { destination: state.destination })) + .replace(/\$\{event\.signature\.params\}/g, types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section })) .replace(/\$\{info\.title\}/g, info.title) .replace(/\$\{info\.TITLE\}/g, info.title.toUpperCase()) .replace(/\$\{method\.property\.immutable\}/g, hasTag(methodObj, 'property:immutable')) @@ -1111,7 +1132,7 @@ function insertExampleMacros(template, examples, method, json, templates) { } function generateResult(result, json, templates) { - const type = types.getSchemaType(result, json, { destination: state.destination }) + const type = types.getSchemaType(result, json, { destination: state.destination, section: state.section }) if (result.type === 'object' && result.properties) { let content = getTemplate('/types/object', templates).split('\n') @@ -1132,7 +1153,7 @@ function generateResult(result, json, templates) { // if we get a real link use it if (link !== '#') { - return `[${types.getSchemaType(result, json, { destination: state.destination })}](${link})` + return `[${types.getSchemaType(result, json, { destination: state.destination, section: state.section })}](${link})` } // otherwise this was a schema with no title, and we'll just copy it here else { @@ -1148,7 +1169,7 @@ function generateResult(result, json, templates) { function insertSchemaMacros(template, title, schema, module) { return template.replace(/\$\{property\}/g, title) - .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { destination: state.destination, code: false })) + .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { destination: state.destination, section: state.section, code: false })) .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module)) .replace(/\$\{description\}/g, schema.description || '') .replace(/\$\{name\}/g, title || '') @@ -1159,9 +1180,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, { destination: state.destination, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl + let type = types.getSchemaType(param.schema, module, { destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl let typeLink = getLinkForSchema(param, module) - let jsonType = types.getJsonType(param.schema, module, { destination: state.destination, code: false, link: false, title: true, asPath: false, expandEnums: false }) + let jsonType = types.getJsonType(param.schema, module, { destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) if (constraints && type) { constraints = '
' + constraints @@ -1210,7 +1231,7 @@ function generateProviderInterfaces(json, templates) { } function insertProviderInterfaceMacros(template, capability, moduleJson = {}, templates) { - const iface = getProviderInterface(capability, moduleJson, { destination: state.destination })//.map(method => { method.name = method.name.charAt(9).toLowerCase() + method.name.substr(10); return method } ) + const iface = getProviderInterface(capability, moduleJson, { destination: state.destination, section: state.section })//.map(method => { method.name = method.name.charAt(9).toLowerCase() + method.name.substr(10); return method } ) const capitalize = str => str[0].toUpperCase() + str.substr(1) const uglyName = capability.split(":").slice(-2).map(capitalize).reverse().join('') + "Provider" @@ -1224,7 +1245,7 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te interfaceShape = interfaceShape.replace(/\$\{name\}/g, name) .replace(/\$\{capability\}/g, capability) - .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => `\t${types.getMethodSignature(method, moduleJson, { destination: state.destination, isInterface: true })}`).join('\n') + '\n') + .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => `\t${types.getMethodSignature(method, moduleJson, { destination: state.destination, section: state.section, isInterface: true })}`).join('\n') + '\n') if (iface.length === 0) { template = template.replace(/\$\{provider\.methods\}/gms, '') @@ -1243,7 +1264,7 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te name: 'provider' }) const parametersSchema = method.params[0].schema - const parametersShape = types.getSchemaShape(parametersSchema, moduleJson, { destination: state.destination }) + const parametersShape = types.getSchemaShape(parametersSchema, moduleJson, { destination: state.destination, section: state.section }) let methodBlock = insertMethodMacros(getTemplateForMethod(method, templates), method, moduleJson, templates) methodBlock = methodBlock.replace(/\${parameters\.shape\}/g, parametersShape) const hasProviderParameters = parametersSchema && parametersSchema.properties && Object.keys(parametersSchema.properties).length > 0 @@ -1335,7 +1356,7 @@ function insertProviderParameterMacros(data = '', parameters, module = {}, optio Object.entries(parameters.properties).forEach(([name, param]) => { let constraints = getSchemaConstraints(param, module) - let type = types.getSchemaType(param, module, { destination: state.destination, code: true, link: true, title: true, asPath: options.asPath, baseUrl: options.baseUrl }) + let type = types.getSchemaType(param, module, { destination: state.destination, section: state.section, code: true, link: true, title: true, asPath: options.asPath, baseUrl: options.baseUrl }) if (constraints && type) { constraints = '
' + constraints From 9d6047f12782faa716aa3bb909e54f9a124e14d8 Mon Sep 17 00:00:00 2001 From: sramani-metro <71630728+sramani-metro@users.noreply.github.com> Date: Tue, 23 May 2023 12:33:26 +0530 Subject: [PATCH 006/137] fix: Sort the macrofied schemas based on schema refs (#90) * fix: Sort the macrofied schemas based on schema refs * fix: Sort the schemas before macrofying * fix: Handle the schemas part --- languages/c/templates/modules/src/Module.cpp | 15 ++++++++-- src/macrofier/engine.mjs | 29 ++++++++++++-------- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 0783b416..b5522fd6 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -22,16 +22,25 @@ /* ${IMPORTS} */ +namespace FireboltSDK { + namespace ${info.title} { + + /* ${TYPES} */ + + } +} + #ifdef __cplusplus extern "C" { #endif -/* ${TYPES} */ +/* ${ACCESSORS} */ +/* ${METHODS} */ + #ifdef __cplusplus } #endif -/* ${ACCESSORS} */ -/* ${METHODS} */ + diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index f0b5959c..958f0bea 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -31,7 +31,7 @@ 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 isEmpty from 'crocks/core/isEmpty.js' -import { getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies } from '../shared/json-schema.mjs' +import { getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies, isDefinitionReferencedBySchema } from '../shared/json-schema.mjs' // util for visually debugging crocks ADTs const _inspector = obj => { @@ -564,6 +564,8 @@ function generateDefaults(json = {}, templates) { return reducer(json) } +const isEnum = x => x.type && x.type === 'string' && Array.isArray(x.enum) && x.title + function generateSchemas(json, templates, options) { let results = [] @@ -609,8 +611,6 @@ function generateSchemas(json, templates, options) { content = content.replace(/.*\$\{schema.seeAlso\}/, '') } - const isEnum = x => x.type === 'string' && Array.isArray(x.enum) && x.title - const result = uri ? { uri: uri, name: schema.title || name, @@ -625,21 +625,28 @@ function generateSchemas(json, templates, options) { results.push(result) } + const list = [] + // schemas may be 1 or 2 levels deeps Object.entries(schemas).forEach( ([name, schema]) => { if (isSchema(schema)) { - generate(name, schema) + list.push([name, schema]) } - else if (typeof schema === 'object') { - const uri = schema.uri - Object.entries(schema).forEach( ([name, schema]) => { - if (name !== 'uri') { - generate(name, schema, uri) - } - }) + }) + + list.sort((a, b) => { + const aInB = isDefinitionReferencedBySchema('#/components/schemas/' + a[0], b[1]) + const bInA = isDefinitionReferencedBySchema('#/components/schemas/' + b[0], a[1]) + if(isEnum(a[1]) || (aInB && !bInA)) { + return -1 + } else if(isEnum(b[1]) || (!aInB && bInA)) { + return 1 } + return 0; }) + list.forEach(item => generate(...item)) + return results } From 717b777c1f12a428a50543ee1edd89516b371e7e Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 1 Jun 2023 20:08:21 +0530 Subject: [PATCH 007/137] Enum fixes (#93) Enum fixes : 1. missing description added 2. alignment fixes 3. implementation added for enum inside properties 4. Enum to String value Conversion logic added for C --- languages/c/src/types/JSONHelpers.mjs | 31 +------ languages/c/templates/declarations/default.c | 9 +- .../declarations/polymorphic-reducer.c | 11 ++- .../templates/modules/include/Common/Module.h | 10 +- .../c/templates/modules/include/Module.h | 15 ++- languages/c/templates/modules/src/Module.cpp | 6 +- languages/c/templates/schemas/default.c | 7 +- .../templates/schemas/include/Common/Module.h | 10 +- .../c/templates/schemas/src/JsonData_Module.h | 6 +- .../c/templates/schemas/src/Module_Common.cpp | 3 +- languages/c/templates/sections/enum.cpp | 5 + languages/c/templates/sections/schemas.c | 2 - languages/c/templates/sections/types.c | 2 - languages/c/templates/types/enum.cpp | 4 + .../c/templates/types/{enum.c => enum.h} | 1 + src/macrofier/engine.mjs | 92 ++++++++++++++----- 16 files changed, 125 insertions(+), 89 deletions(-) create mode 100644 languages/c/templates/sections/enum.cpp create mode 100644 languages/c/templates/types/enum.cpp rename languages/c/templates/types/{enum.c => enum.h} (71%) diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index 25d1ad3b..97a9385a 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -27,35 +27,6 @@ function getJsonContainerDefinition (name, props) { return c } -/* - -ENUM_CONVERSION_BEGIN(Advertising_SkipRestriction) - { ADVERTISING_SKIPRESTRICTION_NONE, _T("none") }, - { ADVERTISING_SKIPRESTRICTION_ADS_UNWATCHED, _T("adsUnwatched") }, - { ADVERTISING_SKIPRESTRICTION_ADS_ALL, _T("adsAll") }, - { ADVERTISING_SKIPRESTRICTION_ALL, _T("all") }, -ENUM_CONVERSION_END(Advertising_SkipRestriction) - - -*/ - -// TODO - this should be a global function in the main /src/ directory... not part of a language pack -const keyName = val => val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() - -function getJsonEnumConversion(schema, module, { name }) { - name = capitalize(schema.title || name) - let e = `ENUM_CONVERSION_BEGIN(${module.info.title}_${name})\n` - - schema.enum.forEach(value => { - e += `{ ${module.info.title.toUpperCase()}_${name.toUpperCase()}_${keyName(value)}, _T("${value}") },` - }) - - e += `ENUM_CONVERSION_END(${module.info.title}_${name})` - - return e -} - export { - getJsonContainerDefinition, - getJsonEnumConversion + getJsonContainerDefinition } diff --git a/languages/c/templates/declarations/default.c b/languages/c/templates/declarations/default.c index 72fbf14f..be0b1e14 100644 --- a/languages/c/templates/declarations/default.c +++ b/languages/c/templates/declarations/default.c @@ -1,4 +1,5 @@ - /** - * ${method.summary} - ${method.params} */ - ${method.signature}; +/* + * ${method.summary} + * ${method.params} + */ +${method.signature}; diff --git a/languages/c/templates/declarations/polymorphic-reducer.c b/languages/c/templates/declarations/polymorphic-reducer.c index 979832b2..cf974e1a 100644 --- a/languages/c/templates/declarations/polymorphic-reducer.c +++ b/languages/c/templates/declarations/polymorphic-reducer.c @@ -1,6 +1,7 @@ - /** - * ${method.summary} - ${method.params} */ - ${method.signature} +/* + * ${method.summary} + * ${method.params} + */ +${method.signature} -// TODO: generate reducer signature \ No newline at end of file +// TODO: generate reducer signature diff --git a/languages/c/templates/modules/include/Common/Module.h b/languages/c/templates/modules/include/Common/Module.h index 2834b997..809418a2 100644 --- a/languages/c/templates/modules/include/Common/Module.h +++ b/languages/c/templates/modules/include/Common/Module.h @@ -25,16 +25,16 @@ extern "C" { #endif - // Enums +// Enums - /* ${ENUMS}} */ +/* ${ENUMS} */ - // Schemas +// Schemas - /* ${SCHEMAS} */ +/* ${SCHEMAS} */ #ifdef __cplusplus } #endif -#endif // Header Include Guard \ No newline at end of file +#endif // Header Include Guard diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h index e24c869f..ee034605 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/Module.h @@ -26,13 +26,20 @@ extern "C" { #endif - /* ${SCHEMAS} */ +// Enums - /* ${ACCESSORS} */ - /* ${DECLARATIONS} */ +/* ${ENUMS} */ + +// Types + +/* ${TYPES} */ + +/* ${ACCESSORS} */ + +/* ${DECLARATIONS} */ #ifdef __cplusplus } #endif -#endif // Header Include Guard \ No newline at end of file +#endif // Header Include Guard diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index b5522fd6..346d07cd 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -24,12 +24,13 @@ namespace FireboltSDK { namespace ${info.title} { + // Types - /* ${TYPES} */ - + /* ${TYPES} */ } } +/* ${ENUMS} */ #ifdef __cplusplus extern "C" { @@ -38,7 +39,6 @@ extern "C" { /* ${ACCESSORS} */ /* ${METHODS} */ - #ifdef __cplusplus } #endif diff --git a/languages/c/templates/schemas/default.c b/languages/c/templates/schemas/default.c index bc9ab873..a2058da5 100644 --- a/languages/c/templates/schemas/default.c +++ b/languages/c/templates/schemas/default.c @@ -1,5 +1,4 @@ - /** - * ${schema.description} - */ - +/* + * ${schema.description} + */ ${schema.shape} diff --git a/languages/c/templates/schemas/include/Common/Module.h b/languages/c/templates/schemas/include/Common/Module.h index 50ef1fd9..0326c220 100644 --- a/languages/c/templates/schemas/include/Common/Module.h +++ b/languages/c/templates/schemas/include/Common/Module.h @@ -25,16 +25,14 @@ extern "C" { #endif - // Enums +// Enums - /* ${ENUMS} */ +/* ${ENUMS} */ - // Types - - /* ${TYPES} */ +/* ${TYPES} */ #ifdef __cplusplus } #endif -#endif // Header Include Guard \ No newline at end of file +#endif // Header Include Guard diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/JsonData_Module.h index 4cee1781..9ba90428 100644 --- a/languages/c/templates/schemas/src/JsonData_Module.h +++ b/languages/c/templates/schemas/src/JsonData_Module.h @@ -17,7 +17,9 @@ */ namespace FireboltSDK { + namespace ${info.title} { + // Types - /* ${DECLARATIONS} */ - + /* ${SCHEMAS}*/ + } } diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/Module_Common.cpp index 632f38d6..9dc2ee0a 100644 --- a/languages/c/templates/schemas/src/Module_Common.cpp +++ b/languages/c/templates/schemas/src/Module_Common.cpp @@ -21,11 +21,12 @@ #include "Common/${info.title}.h" #include "JsonData_${info.title}.h" +/* ${ENUMS} */ + #ifdef __cplusplus extern "C" { #endif - /* ${TYPES} */ /* ${ACCESSORS} */ /* ${METHODS} */ diff --git a/languages/c/templates/sections/enum.cpp b/languages/c/templates/sections/enum.cpp new file mode 100644 index 00000000..e5165c61 --- /dev/null +++ b/languages/c/templates/sections/enum.cpp @@ -0,0 +1,5 @@ +namespace WPEFramework { + +${schema.list} + +} diff --git a/languages/c/templates/sections/schemas.c b/languages/c/templates/sections/schemas.c index a1847009..9295133c 100644 --- a/languages/c/templates/sections/schemas.c +++ b/languages/c/templates/sections/schemas.c @@ -1,3 +1 @@ -// Types & Enums - ${schema.list} diff --git a/languages/c/templates/sections/types.c b/languages/c/templates/sections/types.c index a2d20dbb..9295133c 100644 --- a/languages/c/templates/sections/types.c +++ b/languages/c/templates/sections/types.c @@ -1,3 +1 @@ -// Types - ${schema.list} diff --git a/languages/c/templates/types/enum.cpp b/languages/c/templates/types/enum.cpp new file mode 100644 index 00000000..ddda2ae9 --- /dev/null +++ b/languages/c/templates/types/enum.cpp @@ -0,0 +1,4 @@ + /* ${title} ${description} */ + ENUM_CONVERSION_BEGIN(${info.title}_${name}) + { ${info.TITLE}_${NAME}_${key}, _T("${value}") }, + ENUM_CONVERSION_END(${info.title}_${name}) diff --git a/languages/c/templates/types/enum.c b/languages/c/templates/types/enum.h similarity index 71% rename from languages/c/templates/types/enum.c rename to languages/c/templates/types/enum.h index 2a8e94d7..6926fa77 100644 --- a/languages/c/templates/types/enum.c +++ b/languages/c/templates/types/enum.h @@ -1,3 +1,4 @@ +/* ${title} ${description} */ typedef enum { ${info.TITLE}_${NAME}_${key}, } ${info.title}_${name}; diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 958f0bea..2e5e4f93 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -64,6 +64,8 @@ const state = { section: undefined } +const capitalize = str => str[0].toUpperCase() + str.substr(1) + const setTyper = (t) => { types = t } @@ -73,7 +75,7 @@ const setConfig = (c) => { } const getTemplate = (name, templates) => { - return templates[Object.keys(templates).find(k => k.startsWith(name + '.'))] || '' + return templates[Object.keys(templates).find(k => k === name)] || templates[Object.keys(templates).find(k => k.startsWith(name + '.'))] || '' } const getTemplateTypeForMethod = (method, type, templates) => { @@ -322,7 +324,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { const imports = generateImports(obj, templates) const initialization = generateInitialization(obj, templates) - const enums = generateEnums(obj, templates) + const enums = generateEnums(obj, templates, { destination : (options.destination ? options.destination : '') }) const eventsEnum = generateEvents(obj, templates) const examples = generateExamples(obj, templates, languages) @@ -486,29 +488,80 @@ function insertTableofContents(content) { return content } +const isEnumType = x => x.type !== 'undefined' && x.type === 'string' && Array.isArray(x.enum) + +const getProperties = x => { + return Array.isArray(x.properties) ? x.properties[0] : x.properties +} + +const isEnumProperties = schema => compose( + getProperties, + filter(enm => enm), + map(filter(enm => enm)), + map(props => props.map(([k, v]) => ((v.type === 'object') ? isEnumProperties(v) : ((v.type === 'array') ? isEnumType(v.items[0] ? v.items[0] : v.items): isEnumType(v))))), + map(Object.entries), + filter(schema => isObject(schema)) +)(schema) + +const getEnumProperties = schema => compose( + getProperties, + filter(enm => enm), + map(filter(isEnumType)), + map(props => props.map(([k, v]) => { + let enm = v + if (isEnumType(v) == true) { + enm = Object.assign({}, v) + enm.title = k + } else if (v.type === 'object') { + enm = getEnumProperties(v) + } else if (v.type === 'array') { + enm = Object.assign({}, (v.items[0] ? v.items[0] : v.items)) + enm.title = k + } + return enm + })), + map(Object.entries), + filter(schema => isObject(schema)) +)(schema) + +const convertEnumTemplate = (sch, templateName, templates) => { + const template = getTemplate(templateName, templates).split('\n') + let schema = isEnumType(sch) ? sch : getEnumProperties(sch) + for (var i = 0; i < template.length; i++) { + if (template[i].indexOf('${key}') >= 0) { + template[i] = schema.enum.map(value => { + const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + return template[i].replace(/\$\{key\}/g, safeName) + .replace(/\$\{value\}/g, value) + }).join('\n') + if (!templateName.includes(".cpp")) { + template[i] = template[i].replace(/,*$/, ''); + } + } + } + return template.join('\n') + .replace(/\$\{title\}/g, capitalize(schema.title)) + .replace(/\$\{description\}/g, schema.description ? ('- ' + schema.description) : '') + .replace(/\$\{name\}/g, schema.title) + .replace(/\$\{NAME\}/g, schema.title.toUpperCase()) +} + const enumFinder = compose( - filter(x => x.type === 'string' && Array.isArray(x.enum) && x.title), + filter(x => ((isEnumType(x) && x.title) || isEnumProperties(x))), map(([_, val]) => val), filter(([_key, val]) => isObject(val)) ) -const generateEnums = (json, templates) => { +const generateEnums = (json, templates, options = { destination: '' }) => { + const suffix = options.destination.split('.').pop() return compose( option(''), + map(val => { + let template = getTemplate(`/sections/enum.${suffix}`, templates) + return template ? template.replace(/\$\{schema.list\}/g, val.trimEnd()) : val + }), map(reduce((acc, val) => acc.concat(val).concat('\n'), '')), - map(map((schema) => { - const template = getTemplate('/types/enum', templates).split('\n') - for (var i = 0; i < template.length; i++) { - if (template[i].indexOf('${key}') >= 0) { - template[i] = schema.enum.map(value => { - const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() - return template[i].replace(/\$\{key\}/g, safeName) - .replace(/\$\{value\}/g, value) - }).join('\n') - } - } - return template.join('\n').replace(/\$\{name\}/g, schema.title).replace(/\$\{NAME\}/g, schema.title.toUpperCase()) - })), + map(map((schema) => convertEnumTemplate(schema, suffix ? `/types/enum.${suffix}` : '/types/enum', templates))), map(enumFinder), getSchemas )(json) @@ -701,8 +754,6 @@ const generateImports = (json, templates) => { imports += getTemplate('/imports/x-method', templates) } - - if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0) { imports += Object.keys(json['x-schemas']).map(shared => getTemplate('/imports/default', templates).replace(/\$\{info.title\}/g, shared)).join('\n') } @@ -1240,7 +1291,6 @@ function generateProviderInterfaces(json, templates) { function insertProviderInterfaceMacros(template, capability, moduleJson = {}, templates) { const iface = getProviderInterface(capability, moduleJson, { destination: state.destination, section: state.section })//.map(method => { method.name = method.name.charAt(9).toLowerCase() + method.name.substr(10); return method } ) - const capitalize = str => str[0].toUpperCase() + str.substr(1) const uglyName = capability.split(":").slice(-2).map(capitalize).reverse().join('') + "Provider" let name = iface.length === 1 ? iface[0].name.charAt(0).toUpperCase() + iface[0].name.substr(1) + "Provider" : uglyName @@ -1394,4 +1444,4 @@ export default { insertAggregateMacros, setTyper, setConfig -} \ No newline at end of file +} From bd7db6caf50489a438ab7d54538abb245cc3d717 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 5 Jun 2023 21:54:53 +0530 Subject: [PATCH 008/137] Types and Accessor related fixes (#94) Types and Accessor related fixes: 1. Accessor creation 2. JsonContainer creation 3. Types order placed based on depenedencies 4. filtered redundant new lines 5. UnamedSchema issue fixes 6. Types and Accessors: generation added for objects inside methods result/params 7. AnyOf support added --- languages/c/Types.mjs | 915 ++++++++++++------ languages/c/src/types/ImplHelpers.mjs | 392 ++++---- languages/c/src/types/JSONHelpers.mjs | 67 +- languages/c/src/types/NativeHelpers.mjs | 141 +-- languages/c/templates/methods/property.c | 16 +- .../c/templates/modules/include/Module.h | 4 - languages/c/templates/modules/src/Module.cpp | 1 - languages/c/templates/schemas/default.c | 3 - .../c/templates/schemas/src/JsonData_Module.h | 2 +- languages/c/templates/sections/accessors.c | 1 - languages/c/templates/sections/methods.c | 3 +- .../c/templates/sections/methods_accessors.c | 1 + .../c/templates/sections/methods_types.c | 1 + src/macrofier/engine.mjs | 79 +- src/macrofier/index.mjs | 4 +- 15 files changed, 993 insertions(+), 637 deletions(-) create mode 100644 languages/c/templates/sections/methods_accessors.c create mode 100644 languages/c/templates/sections/methods_types.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index e44b4a78..0bb6cc59 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -18,365 +18,660 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' -import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors } from './src/types/NativeHelpers.mjs' -import { getObjectHandleManagementImpl, getPropertyAccessorsImpl } from './src/types/ImplHelpers.mjs' -import { getJsonContainerDefinition } from './src/types/JSONHelpers.mjs' +import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema } from './src/types/NativeHelpers.mjs' +import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getPropertyAccessorsImpl } from './src/types/ImplHelpers.mjs' +import { getJsonContainerDefinition, getJsonDataStructName } from './src/types/JSONHelpers.mjs' -function getMethodSignature(method, module, { destination, isInterface = false }) { - const extraParam = '${method.result.type}* ${method.result.name}' - - const prefix = method.tags.find(t => t.name.split(":")[0] === "property") ? "Get" : "" +const getSdkNameSpace = () => 'FireboltSDK' +const getJsonNativeTypeForOpaqueString = () => getSdkNameSpace() + '::JSON::String' +const getEnumName = (name, prefix) => ((prefix.length > 0) ? (prefix + '_' + name) : name) - return 'uint32_t ${info.title}_' + prefix + '${method.Name}(' + extraParam + ')' +const getRefModule = (title) => { + let module = { + info: { + title: `${title}` + } + } + return module } -function getMethodSignatureParams(method, module, { destination }) { - return method.params.map(param => param.name + (!param.required ? '?' : '') + ': ' + getSchemaType(param.schema, module, { title: true, destination })).join(', ') +const hasProperties = (prop) => { + let hasProperty = false + if (prop.properties) { + hasProperty = true + } else if (prop.additionalProperties && ( prop.additionalProperties.type && (((prop.additionalProperties.type === 'object') && prop.additionalProperties.properties) || (prop.additionalProperties.type !== 'object')))) { + hasProperty = true + } + return hasProperty } -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaType(schema, module, { name, destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - let type = '' - let theTitle = schema.title || name || ('UnamedSchema' + (Math.floor(Math.random() * 100))) +function validJsonObjectProperties(json = {}) { - if (schema['x-method']) { - console.log(`WARNING UNHANDLED: x-method in ${theTitle}`) - //throw "x-methods not supported yet" - } - - if (schema['$ref']) { - if (schema['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType - let definition = getPath(schema['$ref'], module) - let tName = definition.title || schema['$ref'].split('/').pop() - return getSchemaType(definition, module, { name: tName, destination, link, title, code, asPath, event, expandEnums, baseUrl }) + let valid = true + if (json.type === 'object' || (json.additonalProperties && typeof json.additonalProperties.type === 'object')) { + if (json.properties || json.additonalProperties) { + Object.entries(json.properties || json.additonalProperties).every(([pname, prop]) => { + if (!prop['$ref'] && (pname !== 'additionalProperties') && + ((!prop.type && !prop.const && (prop.schema && !prop.schema.type)) || (Array.isArray(prop.type) && (prop.type.find(t => t === 'null'))))) { + valid = false } + return valid + }) } - else if (schema.const) { - type = getNativeType(schema) - return type - } - else if (schema.type === 'string' && schema.enum) { - //Enum - let typeName = getTypeName(getModuleName(module), theTitle) - return typeName - } - else if (Array.isArray(schema.type)) { - let type = schema.type.find(t => t !== 'null') - console.log(`WARNING UNHANDLED: type is an array containing ${schema.type}`) - } - else if (schema.type === 'array' && schema.items) { - let res - if (Array.isArray(schema.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(schema.items)) { - throw 'Heterogenous Arrays not supported yet' - } - res = getSchemaType(schema.items[0], module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) - } - else { - // grab the type for the non-array schema - res = getSchemaType(schema.items, module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) - } + } + return valid +} - if (!schema.title && !name) { - console.log(`WARNING: generated name for ${module.info.title} schema w/ no title: ${theTitle}`) - console.dir(schema) +function union(schemas, module, commonSchemas) { + + const result = {}; + for (const schema of schemas) { + for (const [key, value] of Object.entries(schema)) { + if (!result.hasOwnProperty(key)) { + // If the key does not already exist in the result schema, add it + if (value && value.anyOf) { + result[key] = union(value.anyOf, module, commonSchemas) + } else if (key === 'title' || key === 'description' || key === 'required') { + //console.warn(`Ignoring "${key}"`) + } else { + result[key] = value; } - - let n = getTypeName(getModuleName(module), theTitle) - return n + 'ArrayHandle' - } - else if (schema.allOf) { - let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x)]) - if (theTitle) { - union['title'] = theTitle + } else if (key === 'type') { + // If the key is 'type', merge the types of the two schemas + if(result[key] === value) { + //console.warn(`Ignoring "${key}" that is already present and same`) + } else { + console.warn(`ERROR "${key}" is not same -${JSON.stringify(result, null, 4)} ${key} ${result[key]} - ${value}`); + throw "ERROR: type is not same" } - delete union['$ref'] - return getSchemaType(union, module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) - } - else if (schema.oneOf || schema.anyOf) { - return type - //TODO - } - else if (schema.type === 'object') { - if (!schema.title && !name) { - console.log(`WARNING: generated name for ${module.info.title} schema w/ no title: ${theTitle}`) - console.dir(schema) + } else { + //If the Key is a const then merge them into an enum + if(value && value.const) { + if(result[key].enum) { + result[key].enum = Array.from(new Set([...result[key].enum, value.const])) + } + else { + result[key].enum = Array.from(new Set([result[key].const, value.const])) + delete result[key].const + } } - return getTypeName(getModuleName(module), theTitle) + 'Handle' - //TODO - } - else if (schema.type) { - type = getNativeType(schema) - return type + // If the key exists in both schemas and is not 'type', merge the values + else if (Array.isArray(result[key])) { + // If the value is an array, concatenate the arrays and remove duplicates + result[key] = Array.from(new Set([...result[key], ...value])) + } else if (result[key] && result[key].enum && value && value.enum) { + //If the value is an enum, merge the enums together and remove duplicates + result[key].enum = Array.from(new Set([...result[key].enum, ...value.enum])) + } else if (typeof result[key] === 'object' && typeof value === 'object') { + // If the value is an object, recursively merge the objects + result[key] = union([result[key], value], module, commonSchemas); + } else if (result[key] !== value) { + // If the value is a primitive and is not the same in both schemas, ignore it + //console.warn(`Ignoring conflicting value for key "${key}"`) + } + } } - - // TODO: deal with dependencies - return type + } + return result; } -//function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, summary, descriptions = true, destination, enums = true } = {}) -// function getSchemaType() -function getSchemaShape(schema, module, { name = '', level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { - const isHeader = destination.endsWith(".h") - const isCPP = (destination.endsWith(".cpp") && section !== 'accessors') +function getMergedSchema(module, json, name, schemas) { + let refsResolved = [...json.anyOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)] + let allOfsResolved = refsResolved.map(sch => sch.allOf ? deepmerge.all([...sch.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)]) : sch) - schema = JSON.parse(JSON.stringify(schema)) + let mergedSchema = union(allOfsResolved, module, schemas) + if (json.title) { + mergedSchema['title'] = json.title + } + else { + mergedSchema['title'] = name + } - let shape = '' + delete mergedSchema['$ref'] + return mergedSchema +} - name = schema.title || name +const deepMergeAll = (module, name, schema, schemas, options) => { + let nonRefsProperty = [...schema.allOf.map(x => x['$ref'] ? '' : x)].filter(elm => elm) + let refsProperty = [...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) : '')].filter(elm => elm) + let mergedProperty = [] + let mergedParamSchema = { + type: "object", + properties: {} + } + + nonRefsProperty.forEach(p => { + if (p.properties) { + Object.entries(p.properties).every(([pname, prop]) => { + let present = false + refsProperty.forEach(refP => { + if (refP.properties) { + Object.entries(refP.properties).every(([refname, refprop]) => { + if (refname == pname) { + present = true + } + return !present + }) + } + }) + let prefixedName = (present == false) ? (name + capitalize(pname)) : pname + mergedParamSchema.properties[prefixedName] = prop + return true + }) + mergedProperty.push(mergedParamSchema) + } + }) + refsProperty.forEach(ref => mergedProperty.push(ref)) + let union = deepmerge.all(mergedProperty) + + return union +} - if (!name) { - console.log(`WARNING: schema without a name in ${module.info.title}`) - return shape - } +function getMethodSignature(method, module, { destination, isInterface = false }) { + const extraParam = '${method.result.type}* ${method.result.name}' - if (schema['$ref']) { - if (schema['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType + const prefix = method.tags.find(t => t.name.split(":")[0] === "property") ? "Get" : "" - const schema = getPath(schema['$ref'], module) - const tname = name || schema['$ref'].split('/').pop() - return getSchemaShape(schema, module, { name: tname, descriptions: descriptions, level: level }) - } - } - //If the schema is a const, - else if (schema.hasOwnProperty('const') && !isCPP) { - if (level > 0) { + return 'uint32_t ${info.title}_' + prefix + '${method.Name}(' + extraParam + ')' +} - let t = description(name, schema.description) - typeName = getTypeName(getModuleName(module), name) - t += (isHeader ? getPropertyAccessors(typeName, capitalize(name), typeof schema.const, { level: level, readonly: true, optional: false }) : getPropertyAccessorsImpl(typeName, capitalize(name), getJsonType(schema, module, { level, name }), typeof schema.const, { level: level, readonly: true, optional: false })) - shape += '\n' + t - } - } - else if (schema.type === 'object') { - if (!name) { - console.log(`WARNING: unnamed schema in ${module.info.title}.`) - console.dir(schema) - shape = '' - } - else if (schema.properties) { - let tName = getTypeName(getModuleName(module), name) - let c_shape = description(name, schema.description) - let cpp_shape = '' - c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(schema, module, { name }))) - Object.entries(schema.properties).forEach(([pname, prop]) => { - c_shape += '\n' + description(pname, prop.description) - let res - if (prop.type === 'array') { - if (Array.isArray(prop.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(prop.items)) { - throw 'Heterogenous Arrays not supported yet' - } - res = getSchemaType(prop.items[0], module, { name: pname, level: level, descriptions: descriptions, title: true }) - } - else { - // grab the type for the non-array schema - res = getSchemaType(prop.items, module, { name: pname, level: level, descriptions: descriptions, title: true }) - } - if (res && res.length > 0) { - let n = tName + '_' + capitalize(pname || prop.title) - let def = getArrayAccessors(n + 'Array', res) - c_shape += '\n' + def - } - else { - console.log(`a. WARNING: Type undetermined for ${name}:${pname}`) - } - } else { - res = getSchemaType(prop, module, { name: pname, descriptions: descriptions, level: level + 1, title: true }) - if (res && res.length > 0) { - c_shape += '\n' + (isHeader ? getPropertyAccessors(tName, capitalize(pname), res, { level: level, readonly: false, optional: isOptional(pname, schema) }) : getPropertyAccessorsImpl(tName, capitalize(pname), getJsonType(prop, module, { level, name }), res, { level: level, readonly: false, optional: isOptional(pname, schema) })) - } - else { - console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) - } - } - }) - cpp_shape += getJsonContainerDefinition(tName, Object.entries(schema.properties).map(([name, prop]) => ({ name, type: getJsonType(prop, module) }))) +function getMethodSignatureParams(method, module, { destination }) { - if (isCPP) { - shape += '\n' + cpp_shape - } - else { - shape += '\n' + c_shape - } - } - else if (schema.propertyNames && schema.propertyNames.enum) { - //propertyNames in object not handled yet - } - else if (schema.additionalProperties && (typeof schema.additionalProperties === 'object') && !isCPP) { - //This is a map of string to type in schema - //Get the Type - let type = getSchemaType(schema.additionalProperties, module, { name: name }) - if (type && type.length > 0) { - let tName = getTypeName(getModuleName(module), name) - // type.deps.forEach(dep => structure.deps.add(dep)) - let t = description(name, schema.description) - t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(schema, module, { name }))) - t += getMapAccessors(getTypeName(getModuleName(module), name), type, { descriptions: descriptions, level: level }) - shape += '\n' + t - } - else { - console.log(`c. WARNING: Type undetermined for ${name}`) - } - } - else if (schema.patternProperties) { - console.log(`WARNING: patternProperties not supported yet...`) - // throw "patternProperties are not supported by Firebolt" - } - } - else if (schema.anyOf) { + return method.params.map(param => param.name + (!param.required ? '?' : '') + ': ' + getSchemaType(param.schema, module, { name: param.name, title: true, destination })).join(', ') +} - } - else if (schema.oneOf) { +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - } - else if (schema.allOf) { - let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x)]) - if (name) { - union['title'] = name - } - delete union['$ref'] - return getSchemaShape(union, module, { name, level, title, summary, descriptions, destination, section, enums }) +function getSchemaType(schema, module, { name, prefix = '', destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + let info = getSchemaTypeInfo(module, schema, name, module['x-schemas'], prefix, { title: title }) + return info.type +} - } - else if (schema.type === 'array') { - let res = getSchemaType(schema, module, { name, level: 0, descriptions: descriptions }) - // res.deps.forEach(dep => structure.deps.add(dep)) +function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = {level: 0, descriptions: true, title: false}) { + + if (json.schema) { + json = json.schema + } + + let structure = {} + structure["type"] = '' + structure["json"] = [] + structure["name"] = {} + structure["namespace"] = {} + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(json['$ref'], module, schemas) + let tName = definition.title || json['$ref'].split('/').pop() + let schema = module + if (json['$ref'].includes('x-schemas')) { + schema = (getRefModule(json['$ref'].split('/')[2])) + } + + const res = getSchemaTypeInfo(schema, definition, tName, schemas, '', options) + structure.type = res.type + structure.json = res.json + structure.name = res.name + structure.namespace = res.namespace + return structure + } + } + else if (json.const) { + structure.type = getNativeType(json) + structure.json = json + return structure + } + else if (json['x-method']) { + console.log(`WARNING UNHANDLED: x-method in ${name}`) + return structure + //throw "x-methods not supported yet" + } + else if (json.type === 'string' && json.enum) { + //Enum + structure.name = name || json.title + let typeName = getTypeName(getModuleName(module), name || json.title, prefix, false, false) + let res = description(capitalize(name || json.title), json.description) + '\n' + generateEnum(json, typeName) + structure.json = json + structure.type = typeName + structure.namespace = getModuleName(module) + return structure + } + else if (Array.isArray(json.type)) { + let type = json.type.find(t => t !== 'null') + console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) + } + else if (json.type === 'array' && json.items && (validJsonObjectProperties(json) === true)) { + let res = '' + if (Array.isArray(json.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(json.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getSchemaTypeInfo(module, json.items[0], json.items[0].name || name, schemas, prefix) } else { - let res = getSchemaType(schema, module, { name, level: level, descriptions: descriptions }) - // res.deps.forEach(dep => structure.deps.add(dep)) + // grab the type for the non-array schema + res = getSchemaTypeInfo(module, json.items, json.items.name || name, schemas, prefix) + } + + let arrayName = capitalize(res.name) + capitalize(res.json.type) + let n = getTypeName(getModuleName(module), arrayName, prefix) + structure.name = res.name || name && (capitalize(name)) + structure.type = n + 'ArrayHandle' + structure.json = json + structure.namespace = getModuleName(module) + return structure + } + else if (json.allOf) { + let title = json.title ? json.title : name + let union = deepMergeAll(module, title, json, schemas, options) + union['title'] = title + + delete union['$ref'] + return getSchemaTypeInfo(module, union, '', schemas, '', options) + } + else if (json.oneOf) { + structure.type = 'char*' + structure.json.type = 'string' + return structure + } + else if (json.anyOf) { + let mergedSchema = getMergedSchema(module, json, name, schemas) + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + return getSchemaTypeInfo(module, mergedSchema, '', schemas, prefixName, options) + } + else if (json.type === 'object') { + structure.json = json + if (hasProperties(json)) { + structure.type = getTypeName(getModuleName(module), json.title || name, prefix) + 'Handle' + structure.name = (json.name ? json.name : (json.title ? json.title : name)) + structure.namespace = (json.namespace ? json.namespace : getModuleName(module)) } - // console.dir(structure.deps) - return shape -} - -// function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - -const getJsonDataStructName = (modName, name) => `${capitalize(modName)}::${capitalize(name)}` - -const getJsonNativeType = json => { - let type - let jsonType = json.const ? typeof json.const : json.type - - if (jsonType === 'string') { - type = 'WPEFramework::Core::JSON::String' - } - else if (jsonType === 'number' || json.type === 'integer') { //Lets keep it simple for now - type = 'WPEFramework::Core::JSON::Number' + else { + structure.type = 'char*' } - else if (jsonType === 'boolean') { - type = 'WPEFramework::Core::JSON::Boolean' + if (name) { + structure.name = capitalize(name) } - else { - throw 'Unknown JSON Native Type !!!' + + return structure + } + else if (json.type) { + structure.type = getNativeType(json) + structure.json = json + if (name || json.title) { + structure.name = capitalize(name || json.title) } - return type -} + structure.namespace = getModuleName(module) -function getJsonType(schema = {}, module = {}, { name = '', descriptions = false, level = 0 } = {}) { + return structure + } + return structure +} - let type = '' +function getSchemaShape(json, module, { name = '', prefix = '', level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { - if (schema['$ref']) { - if (schema['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType - let definition = getPath(schema['$ref'], module) - let tName = definition.title || schema['$ref'].split('/').pop() - return getJsonType(definition, module, { name: tName, descriptions: descriptions, level: level }) - } - } - else if (schema.const) { - return getJsonNativeType(schema) - } - else if (schema['x-method']) { - console.log(`WARNING: x-methods are not supported yet...`) - return type - //throw "x-methods not supported yet" - } - else if (schema.type === 'string' && schema.enum) { - //Enum - let t = getSchemaType(schema, module, { name }) - return 'WPEFramework::Core::JSON::EnumType<::' + t + '>' - } - else if (Array.isArray(schema.type)) { - let type = schema.type.find(t => t !== 'null') - console.log(`WARNING UNHANDLED: type is an array containing ${schema.type}`) + let shape = getSchemaShapeInfo(json, module, module['x-schemas'], { name, prefix, merged: false, level, title, summary, descriptions, destination, section, enums }) + return shape +} +function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '', merged = false, level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { + const isHeader = (destination.includes("JsonData_") !== true) && destination.endsWith(".h") + const isCPP = ((destination.endsWith(".cpp") || destination.includes("JsonData_")) && (section.includes('accessors') !== true)) + json = JSON.parse(JSON.stringify(json)) + + name = json.title || name + let shape = '' + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + const schema = getPath(json['$ref'], module, schemas) + const tname = schema.title || json['$ref'].split('/').pop() + if (json['$ref'].includes('x-schemas')) { + schema = (getRefModule(json['$ref'].split('/')[2])) + } + + shape = getSchemaShapeInfo(schema, module, schemas, { name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) + } + } + //If the schema is a const, + else if (json.hasOwnProperty('const') && !isCPP) { + if (level > 0) { + + let t = description(capitalize(name), json.description) + typeName = getTypeName(getModuleName(module), name, prefix) + t += (isHeader ? getPropertyAccessors(typeName, capitalize(name), typeof schema.const, { level: level, readonly: true, optional: false }) : getPropertyAccessorsImpl(typeName, getJsonType(schema, module, { level, name }), typeof schema.const, { level: level, readonly: true, optional: false })) + shape += '\n' + t } - else if (schema.type === 'array' && schema.items) { - let res - if (Array.isArray(schema.items)) { + } + else if (json.type === 'object') { + if (!name) { + console.log(`WARNING: unnamed schema in ${module.info.title}.`) + console.dir(json) + shape = '' + } + else if (json.properties && (validJsonObjectProperties(json) === true)) { + let c_shape = description(capitalize(name), json.description) + let cpp_shape = '' + let tName = getTypeName(getModuleName(module), name, prefix) + c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(json, module, { name }))) + let props = [] + let containerName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? (prefix + '_' + capitalize(name)) : capitalize(name) + Object.entries(json.properties).forEach(([pname, prop]) => { + let items + var desc = '\n' + description(capitalize(pname), prop.description) + if (prop.type === 'array') { + if (Array.isArray(prop.items)) { //TODO - const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(schema.items)) { - throw 'Heterogenous Arrays not supported yet' + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(prop.items)) { + throw 'Heterogenous Arrays not supported yet' } - res = getJsonType(schema.items[0], module, { name: '' }) - } - else { + items = prop.items[0] + } + else { // grab the type for the non-array schema - res = getJsonType(schema.items, module, { name: '' }) + items = prop.items + } + let info = getSchemaTypeInfo(module, items, items.name || pname, schemas, prefix, {level : level, descriptions: descriptions, title: true}) + if (info.type && info.type.length > 0) { + let objName = tName + '_' + capitalize(prop.title || pname) + let moduleName = info.namespace + info.json.namespace = info.namespace + let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) + let prefixName = ((prefix.length > 0) && items['$ref']) ? '' : prefix + let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, schemas, prefix) + + let t = description(capitalize(info.name), json.description) + '\n' + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) + c_shape += '\n' + t + props.push({name: `${pname}`, type: `WPEFramework::Core::JSON::ArrayType<${subModuleProperty.type}>`}) + } + else { + console.log(`a. WARNING: Type undetermined for ${name}:${pname}`) + } + } else { + if (((merged === false) || ((merged === true) && (pname.includes(name)))) && (prop.type === 'object' || prop.anyOf || prop.allOf)) { + shape += getSchemaShapeInfo(prop, module, schemas, { name : pname, prefix, merged: false, level: 1, title, summary, descriptions, destination, section, enums }) + } + let info = getSchemaTypeInfo(module, prop, pname, module['x-schemas'], prefix, {descriptions: descriptions, level: level + 1, title: true}) + if (info.type && info.type.length > 0) { + let subPropertyName = ((pname.length !== 0) ? capitalize(pname) : info.name) + let moduleProperty = getJsonTypeInfo(module, json, name, schemas, prefix) + let subProperty = getJsonTypeInfo(module, prop, pname, schemas, prefix) + c_shape += '\n' + description(capitalize(pname), info.json.description) + c_shape += '\n' + (isHeader ? getPropertyAccessors(tName, capitalize(pname), info.type, { level: 0, readonly: false, optional: isOptional(pname, json) }) : getPropertyAccessorsImpl(tName, moduleProperty.type, subProperty.type, subPropertyName, info.type, info.json, {readonly:false, optional:isOptional(pname, json)})) + let property = getJsonType(prop, module, { name : pname, prefix }) + props.push({name: `${pname}`, type: `${property}`}) + } + else { + console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) + } } - - return `WPEFramework::Core::JSON::ArrayType<${res}>` + }) + + cpp_shape += getJsonContainerDefinition(json, containerName, props) + + if (isCPP) { + shape += '\n' + cpp_shape + } + else { + shape += '\n' + c_shape + } + } + else if (json.propertyNames && json.propertyNames.enum) { + //propertyNames in object not handled yet + } + else if (json.additionalProperties && (typeof json.additionalProperties === 'object') && (validJsonObjectProperties(json) === true) && !isCPP) { + let info = getSchemaTypeInfo(module, json.additionalProperties, name, module['x-schemas'], prefix) + if (!info.type || (info.type.length === 0)) { + info.type = 'char*' + info.json = json.additionalProperties + info.json.type = 'string' + } + + let tName = getTypeName(getModuleName(module), name, prefix) + let t = description(capitalize(name), json.description) + '\n' + let containerType = 'WPEFramework::Core::JSON::VariantContainer' + + let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, module['x-schemas']) + if (isCPP && ((info.json.type === 'object' && info.json.properties) || info.json.type === 'array')) { + // Handle Container generation here + } + + t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, containerType)) + t += (isHeader ? getMapAccessors(tName, info.type, { descriptions: descriptions, level: level }) : getMapAccessorsImpl(tName, containerType, subModuleProperty.type, info.type, info.json, { readonly: true, optional: false })) + shape += '\n' + t + } + else if (json.patternProperties) { + console.log(`WARNING: patternProperties are not supported by Firebolt(inside getModuleName(module):${name})`) + } + } + else if (json.anyOf) { + if (level > 0) { + let mergedSchema = getMergedSchema(module, json, name, schemas) + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + shape += getSchemaShapeInfo(mergedSchema, module, schemas, { name, prefix: prefixName, merged, level, title, summary, descriptions, destination, section, enums }) + } + } + else if (json.oneOf) { + //Just ignore schema shape, since this has to be treated as string + } + else if (json.allOf) { + let title = (json.title ? json.title : name) + let union = deepMergeAll(module, title, json, schemas) + union.title = title + + delete union['$ref'] + + return getSchemaShapeInfo(union, module, schemas, { name, prefix, merged: true, level, title, summary, descriptions, destination, section, enums }) + } + else if (json.type === 'array' && !isCPP) { + let j + if (Array.isArray(json.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(json.items)) { + throw 'Heterogenous Arrays not supported yet' + } + j = json.items[0] } - else if (schema.allOf) { - let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)]) - if (schema.title) { - union['title'] = schema.title - } - else { - union['title'] = name - } - delete union['$ref'] - return getJsonType(union, module, { name: '', level, descriptions }) - } - else if (schema.oneOf || schema.anyOf) { - return type - //TODO - } - else if (schema.type === 'object') { - if (!schema.title && !name) { - console.log(`WARNING: schema with no name`) - console.dir(schema) - return 'Unknown' - } - return getJsonDataStructName(getModuleName(module), schema.title || name) - //TODO - } - else if (schema.type) { - return getJsonNativeType(schema) - } - return type + else { + j = json.items + } + + let info = getSchemaTypeInfo(module, j, j.name || name, schemas, prefix, {level : level, descriptions: descriptions, title: true}) + + if (info.type && info.type.length > 0) { + let type = getArrayElementSchema(json, module, schemas, info.name) + let arrayName = capitalize(info.name) + capitalize(type.type) + let objName = getTypeName(info.namespace, arrayName, prefix) + let tName = objName + 'Array' + let moduleName = info.namespace + info.json.namespace = info.namespace + let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) + let t = '' + if (level === 0) { + t += description(capitalize(info.name), json.description) + '\n' + t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, moduleProperty.type)) + } + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + 'Handle'), getJsonNativeType(type), '', info.type, info.json)) + shape += '\n' + t + } + } + else { + shape += '\n' + getSchemaType(module, json, name, schemas, prefix, {level: level, descriptions: descriptions}) + } + + return shape } -function getTypeScriptType(jsonType) { - if (jsonType === 'integer') { - return 'number' +const getJsonNativeType = json => { + let type + let jsonType = json.const ? typeof json.const : json.type + + if (jsonType === 'string') { + type = getSdkNameSpace() + '::JSON::String' + } + else if (jsonType === 'number') { + type = 'WPEFramework::Core::JSON::Float' + } + else if (json.type === 'integer') { + type = 'WPEFramework::Core::JSON::DecSInt32' + } + else if (jsonType === 'boolean') { + type = 'WPEFramework::Core::JSON::Boolean' + } + else { + throw 'Unknown JSON Native Type !!!' + } + return type +} + +function getJsonType(schema = {}, module = {}, { name = '', prefix = '', descriptions = false, level = 0 } = {}) { + let info = getJsonTypeInfo(module, schema, name, module['x-schemas'], prefix, { descriptions: descriptions, level: level }) + return info.type +} + +function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '', {descriptions = false, level = 0} = {}) { + + if (json.schema) { + json = json.schema + } + + let structure = {} + structure["deps"] = new Set() //To avoid duplication of local ref definitions + structure["type"] = [] + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(json['$ref'], module, schemas) + let tName = definition.title || json['$ref'].split('/').pop() + + let schema = module + if (json['$ref'].includes('x-schemas')) { + schema = (getRefModule(json['$ref'].split('/')[2])) + } + + const res = getJsonTypeInfo(schema, definition, tName, schemas, '', {descriptions, level}) + structure.deps = res.deps + structure.type = res.type + return structure + } + } + else if (json.const) { + structure.type = getJsonNativeType(json) + return structure + } + else if (json['x-method']) { + return structure + //throw "x-methods not supported yet" + } + else if (json.additionalProperties && (typeof json.additionalProperties === 'object')) { + //This is a map of string to type in schema + //Get the Type + let type = getJsonTypeInfo(module, json.additionalProperties, name, schemas, prefix) + if (type.type && type.type.length > 0) { + structure.type = 'WPEFramework::Core::JSON::VariantContainer'; + return structure + } + else { + console.log(`WARNING: Type undetermined for ${name}`) + } + } + else if (json.type === 'string' && json.enum) { + //Enum + let t = 'WPEFramework::Core::JSON::EnumType<' + (json.namespace ? json.namespace : getModuleName(module)) + '_' + (getEnumName(name, prefix)) + '>' + structure.type.push(t) + return structure + } + else if (Array.isArray(json.type)) { + let type = json.type.find(t => t !== 'null') + console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) + } + else if (json.type === 'array' && json.items) { + let res + let items + if (Array.isArray(json.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(json.items)) { + throw 'Heterogenous Arrays not supported yet' + } + items = json.items[0] } else { - return jsonType + items = json.items + // grab the type for the non-array schema + } + res = getJsonTypeInfo(module, items, items.name || name, schemas, prefix) + structure.deps = res.deps + structure.type.push(`WPEFramework::Core::JSON::ArrayType<${res.type}>`) + + return structure + } + else if (json.allOf) { + let title = json.title ? json.title : name + let union = deepMergeAll(module, title, json, schemas) + union['title'] = title + + delete union['$ref'] + return getJsonTypeInfo(module, union, '', schemas, '', {descriptions, level}) + } + else if (json.oneOf) { + structure.type = getJsonNativeTypeForOpaqueString() + return structure + } + else if (json.patternProperties) { + structure.type = getJsonNativeTypeForOpaqueString() + return structure + } + else if (json.anyOf) { + let mergedSchema = getMergedSchema(module, json, name, schemas) + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + structure = getJsonTypeInfo(module, mergedSchema, name, schemas, prefixName, {descriptions, level}) + } + else if (json.type === 'object') { + if (hasProperties(json) !== true) { + structure.type = getJsonNativeTypeForOpaqueString() } + else { + let schema = getSchemaTypeInfo(module, json, name, module['x-schemas'], prefix) + if (schema.namespace && schema.namespace.length > 0) { + structure.type.push(getJsonDataStructName(schema.namespace, json.title || name, prefix)) + } + } + return structure + } + else if (json.type) { + structure.type = getJsonNativeType(json) + return structure + } + return structure +} + +function getTypeScriptType(jsonType) { + if (jsonType === 'integer') { + return 'number' + } + else { + return jsonType + } } const enumReducer = (acc, val, i, arr) => { - const keyName = val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() - acc = acc + ` ${keyName} = '${val}'` - if (i < arr.length - 1) { - acc = acc.concat(',\n') - } - return acc + const keyName = val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + acc = acc + ` ${keyName} = '${val}'` + if (i < arr.length - 1) { + acc = acc.concat(',\n') + } + return acc } export default { @@ -385,4 +680,4 @@ export default { getSchemaShape, getSchemaType, getJsonType -} \ No newline at end of file +} diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index f3b39cbf..47852c9e 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -1,28 +1,35 @@ const Indent = '\t' +const getSdkNameSpace = () => 'FireboltSDK' +const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' +const getFireboltStringType = () => 'FireboltTypes_StringHandle' + const getObjectHandleManagementImpl = (varName, jsonDataName) => { - let result = ` -${varName}Handle ${varName}Handle_Create(void) { + let result = `${varName}Handle ${varName}Handle_Create(void) +{ WPEFramework::Core::ProxyType<${jsonDataName}>* type = new WPEFramework::Core::ProxyType<${jsonDataName}>(); *type = WPEFramework::Core::ProxyType<${jsonDataName}>::Create(); return (static_cast<${varName}Handle>(type)); } -void ${varName}Handle_Addref(${varName}Handle handle) { +void ${varName}Handle_Addref(${varName}Handle handle) +{ ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); ASSERT(var->IsValid()); var->AddRef(); } -void ${varName}Handle_Release(${varName}Handle handle) { +void ${varName}Handle_Release(${varName}Handle handle) +{ ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); var->Release(); - if(var->IsValid() != true) { + if (var->IsValid() != true) { delete var; } } -bool ${varName}Handle_IsValid(${varName}Handle handle) { +bool ${varName}Handle_IsValid(${varName}Handle handle) +{ ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); ASSERT(var->IsValid()); @@ -32,263 +39,258 @@ bool ${varName}Handle_IsValid(${varName}Handle handle) { return result } -const getPropertyAccessorsImpl = (objName, propertyName, jsonDataName, propertyType, json = {}, options = {readonly:false, optional:false}) => { - - let result - if (json.type === 'object') { - result += `${objName}_${propertyName}Handle ${objName}_Get_${propertyName}(${objName}Handle handle) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); - - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyName}>(); - *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); - *(*object) = (*var)->${propertyName}; - return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' - } else if (json.type === 'array') { - result += `${objName}_${propertyName}ArrayHandle ${objName}_Get_${propertyName}(${objName}Handle handle) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); - - WPEFramework::Core::ProxyType>* object = new WPEFramework::Core::ProxyType>(); - *object = WPEFramework::Core::ProxyType>::Create(); - *(*object) = (*var)->${propertyName}.Element(); - return (static_cast<${objName}_${propertyType}ArrayHandle>(object));` + '\n' - } else if (json.enum) { - result += `${objName}_${propertyName} ${objName}_Get_${propertyName}(${objName}Handle handle) { +const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, subPropertyName, accessorPropertyType, json = {}, options = {readonly:false, optional:false}) => { + let result = '' + result += `${accessorPropertyType} ${objName}_Get_${subPropertyName}(${objName}Handle handle) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - - return static_cast<${propertyType}>((*var)->${propertyName}.Value());` + '\n' - } else { - result += `${propertyType} ${objName}_Get_${propertyName}(${objName}Handle handle) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid());` + '\n' - if (json.type === 'string') { - result += ` - return static_cast<${propertyType}>((*var)->${propertyName}.Value().c_str());` + '\n' - } else { - result += ` - return static_cast<${propertyType}>((*var)->${propertyName}.Value());` + '\n' +` + '\n' + if ((json.type === 'object') && (accessorPropertyType !== 'char*')) { + result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); + *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); + *(*element) = (*var)->${subPropertyName}; + return (static_cast<${accessorPropertyType}>(element));` + '\n' + } + else { + if ((typeof json.const === 'string') || (json.type === 'string' && !json.enum) || (accessorPropertyType === 'char*')) { + result += ` return (const_cast<${accessorPropertyType}>((*var)->${subPropertyName}.Value().c_str()));` + '\n' + } + else { + result += ` return (static_cast<${accessorPropertyType}>((*var)->${subPropertyName}.Value()));` + '\n' } } - result += ` -}` + '\n' - if (!options.readonly) { - if (json.type === 'object') { - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName}Handle ${propertyName.toLowerCase()}) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); + result += `}` + '\n' - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* object = static_cast*>(${propertyName.toLowerCase()}); - (*var)->${propertyName} = *(*object);` + '\n' - } - if (json.type === 'array') { - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName}ArrayHandle ${propertyName.toLowerCase()}) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); - WPEFramework::Core::ProxyType>* object = static_cast>*>(${propertyName.toLowerCase()}).Element(); - (*var)->${propertyName} = *(*object);` + '\n' - } if (json.enum) { - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName} ${propertyName.toLowerCase()}) { + if (!options.readonly) { + let type = (accessorPropertyType === getFireboltStringType()) ? 'char*' : accessorPropertyType + result += `void ${objName}_Set_${subPropertyName}(${objName}Handle handle, ${type} value)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); +` + '\n' - (*var)->${propertyName} = static_cast<${propertyType}>(${propertyName.toLowerCase()});` + '\n' + if (json.type === 'object' && (accessorPropertyType !== 'char*')) { + result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* object = static_cast*>(value); + (*var)->${subPropertyName} = *(*object);` + '\n' } else { - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${propertyType} ${propertyName.toLowerCase()}) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); - - (*var)->${propertyName} = static_cast<${propertyType}>(${propertyName.toLowerCase()});` + '\n' + result += ` (*var)->${subPropertyName} = value;` + '\n' } -result += `}` + '\n' + result += `}` + '\n' } if (options.optional === true) { - result += `${Indent.repeat(options.level)}bool ${objName}_has_${propertyName}(${objName}Handle handle) { + result += `bool ${objName}_Has_${subPropertyName}(${objName}Handle handle)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - return ((*var)->${propertyName}.IsSet()); + + return ((*var)->${subPropertyName}.IsSet()); }` + '\n' - result += `${Indent.repeat(options.level)}void ${objName}_clear_${propertyName}(${objName}Handle handle) { + result += `void ${objName}_Clear_${subPropertyName}(${objName}Handle handle)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - ((*var)->${propertyName}.Clear()); + ((*var)->${subPropertyName}.Clear()); }` + '\n' } + return result } +const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPropertyType, subPropertyName, accessorPropertyType, json = {}) => { + + let propertyName + if (subPropertyName) { + propertyName = '(*var)->' + `${subPropertyName}` + objName = objName + '_' + subPropertyName + } + else { + propertyName = '(*(*var))' + } -const getArrayAccessors = (objName, propertyName, propertyType, json = {}, options = {readonly:false, optional:false}) => { - let result = ` -uint32_t ${objName}_${propertyName}Array_Size(${objName}::${propertyName}ArrayHandle handle) { + let result = `uint32_t ${objName}Array_Size(${objHandleType} handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - return ((*var)->Length()); + return (${propertyName}.Length()); }` + '\n' - if (json.type === 'object') { -result += `${objName}_${propertyType}Handle ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { + result += `${accessorPropertyType} ${objName}Array_Get(${objHandleType} handle, uint32_t index) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); - ASSERT(var->IsValid()); - WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyType}>(); - *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); - *(*object) = (*var)->Get(index); - return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' - } else if (json.enum) { - result += `${objName}_${propertyType} ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); - ASSERT(var->IsValid()); - - return (static_cast<${propertyType}>((*var)->Get(index)));` + '\n' - } else { - result += `${propertyType} ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid());` + '\n' - if (json.type === 'string') { - result += `return (static_cast<${propertyType}>((*var)->Get(index).Value().c_str()));` + '\n' - } else { - result += `return (static_cast<${propertyType}>((*var)->Get(index)));` + '\n' - } + if ((json.type === 'object') || (json.type === 'array')) { + result += `WPEFramework::Core::ProxyType<${subPropertyType}>* object = new WPEFramework::Core::ProxyType<${subPropertyType}>(); + *object = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); + *(*object) = ${propertyName}.Get(index); + return (static_cast<${accessorPropertyType}>(object));` + '\n' + } + else { + if ((typeof json.const === 'string') || (json.type === 'string' && !json.enum)) { + result += ` return (const_cast<${accessorPropertyType}>(${propertyName}.Get(index).Value().c_str()));` + '\n' + } + else { + result += ` return (static_cast<${accessorPropertyType}>(${propertyName}.Get(index)));` + '\n' + } } result += `}` + '\n' - if (json.type === 'object') { - result += `void ${objName}_${propertyName}Array_Add(${objName}_${propertyName}ArrayHandle handle, ${objName}_${propertyType}Handle value) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); - ASSERT(var->IsValid()); - WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = static_cast*>(value); - - (*var)->Add(*(*object));` + '\n' - } else { - result += `void ${objName}_${propertyName}Array_Add(${objName}_${propertyName}ArrayHandle handle, ${propertyType} value) { + let type = (accessorPropertyType === getFireboltStringType()) ? 'char*' : accessorPropertyType + result += `void ${objName}Array_Add(${objHandleType} handle, ${type} value) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid());` + '\n' - if (json.type === 'string') { - result += `WPEFramework::Core::JSON::String element(value);` + '\n' - } else if (json.type === 'number') { - result += `WPEFramework::Core::JSON::Number element(value);` + '\n' - } else if (json.enum) { - result += `WPEFramework::Core::JSON::EnumType<${propertyType}> element(value);` + '\n' - } - result += `(*var)->Add(element);` + '\n' + + if ((json.type === 'object') || (json.type === 'array')) { + result += ` ${subPropertyType}& element = *(*(static_cast*>(value)));` + '\n' } - result += `}` + '\n' + else { + result += ` ${subPropertyType} element(value);` + '\n' + } + result += ` + ${propertyName}.Add(element); +}` + '\n' - result += `void ${objName}_${propertyName}Array_Clear(${objName}_${propertyName}ArrayHandle handle) { + result += `void ${objName}Array_Clear(${objHandleType} handle) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - (*var)->Clear(); + + ${propertyName}.Clear(); }` + '\n' return result } -const getMapAccessors = (objName, propertyName, propertyType, json = {}, options = {readonly:false, optional:false}) => { - let result = `uint32_t ${objName}_${propertyName}_KeysCount(${objName}_${propertyName}Handle handle) { +const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPropertyType, json = {}, options = {readonly:false, optional:false}) => { + let result = `uint32_t ${objName}_KeysCount(${objName}Handle handle) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - return (*var)->Size()); - - }` + '\n' - result += `void ${objName}_${propertyName}_AddKey(${objName}_${propertyName}Handle handle, char* key, ${propertyType} value) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); - ASSERT(var->IsValid());` + '\n' - - if (json.type === 'object') { - result += ` - (*var)->Add(key, value);` + '\n' - } else if (json.type === 'boolean') { - result += ` - WPEFramework::Core::JSON::Boolean element(value);` - } else if (json.type === 'string') { - result += ` - WPEFramework::Core::JSON::String element(value);` - } else if (json.type === 'number') { - result += ` - WPEFramework::Core::JSON::Number element(value);` - } else if (json.type === 'array') { - result += ` - WPEFramework::Core::JSON::ArrayType element(value);` - } else if (json.enum) { - result += ` - WPEFramework::Core::JSON::EnumType element(value); - (*var)->Add(key, element);` + '\n' + ${containerType}::Iterator elements = (*var)->Variants(); + uint32_t count = 0; + while (elements.Next()) { + count++; } - result += ` - }` + '\n' - result += `void ${objName}_${propertyName}_RemoveKey(${objName}_${propertyName}Handle handle, char* key) { + return (count); +}` + '\n' + result += `void ${objName}_AddKey(${objName}Handle handle, char* key, ${accessorPropertyType} value) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - - (*var)->Remove(key); - }` + '\n' +` + '\n' + let elementContainer = subPropertyType + if (containerType.includes('VariantContainer')) { + elementContainer = 'WPEFramework::Core::JSON::Variant' + } + if ((json.type === 'object') || (json.type === 'array' && json.items)) { + if (containerType.includes('VariantContainer')) { + result += ` ${subPropertyType}& container = *(*(static_cast*>(value)));` + '\n' + result += ` string containerStr;` + '\n' + result += ` element.ToString(containerStr);` + '\n' + result += ` WPEFramework::Core::JSON::VariantContainer containerVariant(containerStr);` + '\n' + result += ` WPEFramework::Core::JSON::Variant element = containerVariant;` + '\n' + } + else { + result += ` ${subPropertyType}& element = *(*(static_cast*>(value)));` + '\n' + } + } else { + result += ` ${elementContainer} element(value);` + '\n' + } + result += ` (*var)->Set(const_cast(key), element); +}` + '\n' - if (json.type === 'object') { - result += `${objName}_${propertyType}Handle ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { + result += `void ${objName}_RemoveKey(${objName}Handle handle, char* key) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyType}>(); - *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); - *(*object) = (*var)->Find(key); - return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' - } else if (json.type === 'array') { - result += `${objName}_${propertyType}ArrayHandle ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); - WPEFramework::Core::ProxyType>* object = new WPEFramework::Core::ProxyType>(); - *object = WPEFramework::Core::ProxyType>::Create(); - *(*object) = (*var)->Find(key); - return (static_cast<${objName}_${propertyType}ArrayHandle>(object));` + '\n' + (*var)->Remove(key); +}` + '\n' - } else { - result += `${propertyType} ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { + result += `${accessorPropertyType} ${objName}_FindKey(${objName}Handle handle, char* key) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); ASSERT(var->IsValid());` + '\n' - - if (json.type === 'string') { + if ((json.type === 'object') || (json.type === 'array') || + ((json.type === 'string' || (typeof json.const === 'string')) && !json.enum)) { + result += ` ${accessorPropertyType} status = nullptr;` + '\n' + } + else if (json.type === 'boolean') { + result += ` ${accessorPropertyType} status = false;` + '\n' + } + else { + result += ` ${accessorPropertyType} status = 0;` + '\n' + } + + result += ` + if ((*var)->HasLabel(key) == true) {` + if (json.type === 'object') { + result += ` + string objectStr; + (*var)->Get(key).Object().ToString(objectStr); + ${subPropertyType} objectMap; + objectMap.FromString(objectStr); + + WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); + *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); + *(*element) = objectMap; + + status = (static_cast<${accessorPropertyType}>(element));` + '\n' + } + else if (json.type === 'array' && json.items) { + result += ` + WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); + *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); + *(*element) = (*var)->Get(key).Array(); + status = (static_cast<${accessorPropertyType}>(element));` + '\n' + } + else { + if (json.type === 'string' || (typeof json.const === 'string')) { + if (json.enum) { + result += ` + status = (const_cast<${accessorPropertyType}>((*var)->Get(key).));` + '\n' + } + else { + result += ` + status = (const_cast<${accessorPropertyType}>((*var)->Get(key).String().c_str()));` + '\n' + } + } + else if (json.type === 'boolean') { + result += ` + status = (static_cast<${accessorPropertyType}>((*var)->Get(key).Boolean()));` + '\n' + } + else if (json.type === 'number') { result += ` - return (static_cast<${propertyType}>((*var)->(Find(key).Value().c_str())));` + '\n' - } else { + status = (static_cast<${accessorPropertyType}>((*var)->Get(key).Float()));` + '\n' + } + else if (json.type === 'integer') { result += ` - return (static_cast<${propertyType}>((*var)->(Find(key).Value())));` + '\n' + status = (static_cast<${accessorPropertyType}>((*var)->Get(key).Number()));` + '\n' } } - result += ` -}` + '\n' + result += ` } + return status; +}` return result } export { + getArrayAccessorsImpl, + getMapAccessorsImpl, getObjectHandleManagementImpl, getPropertyAccessorsImpl } diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index 97a9385a..3437c98c 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -1,31 +1,54 @@ const capitalize = str => str[0].toUpperCase() + str.substr(1) +const getSdkNameSpace = () => 'FireboltSDK' +const getJsonDataPrefix = () => 'JsonData_' +const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' -function getJsonContainerDefinition (name, props) { - name = capitalize(name) - let c = ` class ${name}: public Core::JSON::Container { - public: - ${name}(const ${name}&) = delete; - ${name}& operator=(const ${name}&) = delete; - ~${name}() override = default; - - public: - ${name}() - : Core::JSON::Container() - {` +const getJsonDataStructName = (modName, name, prefix = '') => { + let result =((prefix.length > 0) && (!name.startsWith(prefix))) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}_${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` + + return ((result.includes(wpeJsonNameSpace()) === true) ? result : `${getSdkNameSpace()}::${result}`) +} + +function getJsonContainerDefinition (schema, name, props) { + let c = schema.description ? (' /*\n * ${info.title} - ' + `${schema.description}\n */\n`) : '' + name = getJsonDataPrefix() + capitalize(name) + c += ` class ${name}: public WPEFramework::Core::JSON::Container { + public: + ~${name}() override = default; - props.forEach(prop => { - c += `\n Add(_T("${prop.name}"), &${capitalize(prop.name)});` - }) + public: + ${name}() + : WPEFramework::Core::JSON::Container() + {` - c += `\n }\n\n public:` + props.forEach(prop => { + c += `\n Add(_T("${prop.name}"), &${capitalize(prop.name)});` + }) + c += `\n }\n` + c += `\n ${name}(const ${name}& copy) + {` + props.forEach(prop => { + c += `\n Add(_T("${prop.name}"), &${capitalize(prop.name)});` + c += `\n ${capitalize(prop.name)} = copy.${capitalize(prop.name)};` + }) + c += ` + }\n + ${name}& operator=(const ${name}& rhs) + {` + props.forEach(prop => { + c += `\n ${capitalize(prop.name)} = rhs.${capitalize(prop.name)};` + }) + c += `\n return (*this); + }\n + public:` - props.forEach(prop => { - c += `\n ${prop.type} ${capitalize(prop.name)};` - }) + props.forEach(prop => { + c += `\n ${prop.type} ${capitalize(prop.name)};` + }) - c += '\n };' - return c - } + c += '\n };' + return c +} export { getJsonContainerDefinition diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 79242d1f..eac20c16 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -29,6 +29,7 @@ const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = pre const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' +const getFireboltStringType = () => 'FireboltTypes_StringHandle' const getHeaderText = () => { return `/* @@ -83,35 +84,53 @@ const SdkTypesPrefix = 'Firebolt' const Indent = ' ' -const getNativeType = json => { - let type - - if (json.const) { - if (typeof json.const === 'string') { - type = 'char*' - } - else if (typeof json.const === 'number') { - type = 'uint32_t' - if (json.const < 0) - type = 'int32_t' - } else if (typeof json.const === 'boolean'){ - type = 'bool' - } +const getArrayElementSchema = (json, module, schemas = {}, name) => { + let result = '' + if (json.type === 'array' && json.items) { + if (Array.isArray(json.items)) { + result = json.items[0] } - else if (json.type === 'string') { - type = 'char*' + else { + // grab the type for the non-array schema + result = json.items } - else if (json.type === 'number' || json.type === 'integer') { //Lets keep it simple for now - type = 'uint32_t' - if ((json.minimum && json.minimum < 0) - || (json.exclusiveMinimum && json.exclusiveMinimum < 0)) { - type = 'int32_t' - } + if (result['$ref']) { + result = getPath(result['$ref'], module, schemas) } - else if (json.type === 'boolean') { - type = 'bool' + } + else if (json.type == 'object') { + if (json.properties) { + Object.entries(json.properties).every(([pname, prop]) => { + if (prop.type === 'array') { + result = getArrayElementSchema(prop, module, schemas) + if (name === capitalize(pname)) { + return false + } + } + return true + }) } - return type + } + + return result +} + +const getNativeType = json => { + let type = '' + let jsonType = json.const ? typeof json.const : json.type + if (jsonType === 'string') { + type = 'char*' + } + else if (jsonType === 'number') { + type = 'float' + } + else if (jsonType === 'integer') { + type = 'int32_t' + } + else if (jsonType === 'boolean') { + type = 'bool' + } + return type } const getObjectHandleManagement = varName => { @@ -126,46 +145,51 @@ bool ${varName}Handle_IsValid(${varName}Handle handle); } const getPropertyAccessors = (objName, propertyName, propertyType, options = {level:0, readonly:false, optional:false}) => { - let result = `${Indent.repeat(options.level)}${propertyType} ${objName}_Get_${propertyName}(${objName}Handle handle);` + '\n' if (!options.readonly) { - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${propertyType} ${propertyName.toLowerCase()});` + '\n' + let type = (propertyType === getFireboltStringType()) ? 'char*' : propertyType + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${type} ${propertyName.toLowerCase()});` + '\n' } if (options.optional === true) { - result += `${Indent.repeat(options.level)}bool ${objName}_has_${propertyName}(${objName}Handle handle);` + '\n' - result += `${Indent.repeat(options.level)}void ${objName}_clear_${propertyName}(${objName}Handle handle);` + '\n' + result += `${Indent.repeat(options.level)}bool ${objName}_Has_${propertyName}(${objName}Handle handle);` + '\n' + result += `${Indent.repeat(options.level)}void ${objName}_Clear_${propertyName}(${objName}Handle handle);` + '\n' } return result } -const getMapAccessors = (typeName, nativeType, level=0) => { +const getMapAccessors = (typeName, accessorPropertyType, level = 0) => { let res res = `${Indent.repeat(level)}uint32_t ${typeName}_KeysCount(${typeName}Handle handle);` + '\n' - res += `${Indent.repeat(level)}void ${typeName}_AddKey(${typeName}Handle handle, char* key, ${nativeType} value);` + '\n' + res += `${Indent.repeat(level)}void ${typeName}_AddKey(${typeName}Handle handle, char* key, ${accessorPropertyType} value);` + '\n' res += `${Indent.repeat(level)}void ${typeName}_RemoveKey(${typeName}Handle handle, char* key);` + '\n' - res += `${Indent.repeat(level)}${nativeType} ${typeName}_FindKey(${typeName}Handle handle, char* key);` + '\n' + res += `${Indent.repeat(level)}${accessorPropertyType} ${typeName}_FindKey(${typeName}Handle handle, char* key);` + '\n' return res } -const getTypeName = (moduleName, varName, upperCase = false) => { - let mName = upperCase ? moduleName.toUpperCase() : capitalize(moduleName) - let vName = upperCase ? varName.toUpperCase() : capitalize(varName) +const getTypeName = (moduleName, varName, prefix = '', upperCase = false, capitalCase = true) => { - return `${mName}_${vName}` + let mName = upperCase ? moduleName.toUpperCase() : capitalize(moduleName) + let vName = upperCase ? varName.toUpperCase() : capitalCase ? capitalize(varName) : varName + if (prefix.length > 0) { + prefix = (!varName.startsWith(prefix)) ? (upperCase ? prefix.toUpperCase() : capitalize(prefix)) : '' + } + prefix = (prefix.length > 0) ?(upperCase ? prefix.toUpperCase() : capitalize(prefix)) : prefix + let name = (prefix.length > 0) ? `${mName}_${prefix}_${vName}` : `${mName}_${vName}` + return name } -const getArrayAccessors = (arrayName, valueType) => { +const getArrayAccessors = (arrayName, propertyType, valueType) => { - let res = `uint32_t ${arrayName}_Size(${arrayName}Handle handle);` + '\n' - res += `${valueType} ${arrayName}_Get(${arrayName}Handle handle, uint32_t index);` + '\n' - res += `void ${arrayName}_Add(${arrayName}Handle handle, ${valueType} value);` + '\n' - res += `void ${arrayName}_Clear(${arrayName}Handle handle);` + '\n' + let res = `uint32_t ${arrayName}Array_Size(${propertyType}Handle handle);` + '\n' + res += `${valueType} ${arrayName}Array_Get(${propertyType}Handle handle, uint32_t index);` + '\n' + res += `void ${arrayName}Array_Add(${propertyType}Handle handle, ${valueType} value);` + '\n' + res += `void ${arrayName}Array_Clear(${propertyType}Handle handle);` + '\n' return res } @@ -201,25 +225,25 @@ const getIncludeDefinitions = (json = {}, jsonData = false) => { .concat([`#include "Firebolt/Types.h"`]) } - function getPropertyGetterSignature(method, module, paramType) { - let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` - return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` - } +function getPropertyGetterSignature(method, module, paramType) { + let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` + return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` +} - function getPropertySetterSignature(method, module, paramType) { - let m = `${capitalize(getModuleName(module))}_Set${capitalize(method.name)}` - return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType} ${method.result.name || method.name} )` - } +function getPropertySetterSignature(method, module, paramType) { + let m = `${capitalize(getModuleName(module))}_Set${capitalize(method.name)}` + return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType} ${method.result.name || method.name} )` +} - function getPropertyEventCallbackSignature(method, module, paramType) { - return `typedef void (*On${capitalize(method.name)}Changed)(${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType})` - } +function getPropertyEventCallbackSignature(method, module, paramType) { + return `typedef void (*On${capitalize(method.name)}Changed)(${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType})` +} - function getPropertyEventSignature(method, module) { - return `${description(method.name, 'Listen to updates')}\n` + `uint32_t ${capitalize(getModuleName(module))}_Listen${capitalize(method.name)}Update(On${capitalize(method.name)}Changed notification, uint16_t* listenerId)` - } +function getPropertyEventSignature(method, module) { + return `${description(method.name, 'Listen to updates')}\n` + `uint32_t ${capitalize(getModuleName(module))}_Listen${capitalize(method.name)}Update(On${capitalize(method.name)}Changed notification, uint16_t* listenerId)` +} - export { +export { getHeaderText, getIncludeGuardOpen, getStyleGuardOpen, @@ -240,5 +264,6 @@ const getIncludeDefinitions = (json = {}, jsonData = false) => { getObjectHandleManagement, getPropertyAccessors, isOptional, - generateEnum - } + generateEnum, + getArrayElementSchema +} diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 8f301bea..1c70ba29 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,12 +1,12 @@ /* ${method.name} - ${method.description} */ uint32_t ${info.title}_Get${method.Name}(${method.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { - const string method = _T("${info.title}.${method.name}"); - FireboltSDK::${info.title}::${method.result.type} jsonResult; + const string method = _T("${info.title}.${method.name}"); + FireboltSDK::${info.title}::${method.result.type} jsonResult; - uint32_t status = FireboltSDK::Properties::Get(method, jsonResult); - if (status == FireboltSDKErrorNone) { - WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); - *${method.result.name} = static_cast<${info.title}_${method.result.type}Handle>(resultPtr); - } - return status; + uint32_t status = FireboltSDK::Properties::Get(method, jsonResult); + if (status == FireboltSDKErrorNone) { + WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); + *${method.result.name} = static_cast<${info.title}_${method.result.type}Handle>(resultPtr); + } + return status; } diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h index ee034605..a202f643 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/Module.h @@ -30,10 +30,6 @@ extern "C" { /* ${ENUMS} */ -// Types - -/* ${TYPES} */ - /* ${ACCESSORS} */ /* ${DECLARATIONS} */ diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 346d07cd..c412abf2 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -25,7 +25,6 @@ namespace FireboltSDK { namespace ${info.title} { // Types - /* ${TYPES} */ } } diff --git a/languages/c/templates/schemas/default.c b/languages/c/templates/schemas/default.c index a2058da5..9a52cff7 100644 --- a/languages/c/templates/schemas/default.c +++ b/languages/c/templates/schemas/default.c @@ -1,4 +1 @@ -/* - * ${schema.description} - */ ${schema.shape} diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/JsonData_Module.h index 9ba90428..7fa2b6f4 100644 --- a/languages/c/templates/schemas/src/JsonData_Module.h +++ b/languages/c/templates/schemas/src/JsonData_Module.h @@ -20,6 +20,6 @@ namespace FireboltSDK { namespace ${info.title} { // Types - /* ${SCHEMAS}*/ + /* ${SCHEMAS} */ } } diff --git a/languages/c/templates/sections/accessors.c b/languages/c/templates/sections/accessors.c index 0586b2a5..1c790810 100644 --- a/languages/c/templates/sections/accessors.c +++ b/languages/c/templates/sections/accessors.c @@ -1,3 +1,2 @@ // Accessors - ${schema.list} diff --git a/languages/c/templates/sections/methods.c b/languages/c/templates/sections/methods.c index 3f382a63..3ab606c0 100644 --- a/languages/c/templates/sections/methods.c +++ b/languages/c/templates/sections/methods.c @@ -1,3 +1,4 @@ - // Methods +// Methods + ${method.list} diff --git a/languages/c/templates/sections/methods_accessors.c b/languages/c/templates/sections/methods_accessors.c new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/c/templates/sections/methods_accessors.c @@ -0,0 +1 @@ +${schema.list} diff --git a/languages/c/templates/sections/methods_types.c b/languages/c/templates/sections/methods_types.c new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/c/templates/sections/methods_types.c @@ -0,0 +1 @@ +${schema.list} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 2e5e4f93..13ce46f4 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -65,6 +65,7 @@ const state = { } const capitalize = str => str[0].toUpperCase() + str.substr(1) +const hasMethodsSchema = (json, options) => json.methods && json.methods.length const setTyper = (t) => { types = t @@ -101,15 +102,11 @@ const getTemplateForExampleResult = (method, templates) => { return template || JSON.stringify(method.examples[0].result.value, null, '\t') } -const getLinkForSchema = (schema, json) => { +const getLinkForSchema = (schema, json, { name = '' } = {}) => { const dirs = config.createModuleDirectories const copySchemasIntoModules = config.copySchemasIntoModules - if (schema.schema) { - schema = schema.schema - } - - const type = types.getSchemaType(schema, json, { destination: state.destination, section: state.section }) + const type = types.getSchemaType(schema, json, { name: name, 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]) { @@ -336,16 +333,22 @@ const generateMacros = (obj, templates, languages, options = {}) => { const declarations = declarationsArray.length ? getTemplate('/sections/declarations', templates).replace(/\$\{declaration\.list\}/g, declarationsArray.map(m => m.declaration).join('\n')) : '' 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 methodTypesArray = generateSchemas(obj, templates, { baseUrl: '', section: 'methods_schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) + const methodTypes = methodTypesArray.length ? getTemplate('/sections/methods_types', templates).replace(/\$\{schema.list\}/g, methodTypesArray.map(s => s.body).filter(body => body).join('\n')) : '' + const methodAccessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'methods_accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) + const methodAccessors = methodAccessorsArray.length ? getTemplate('/sections/methods_accessors', templates).replace(/\$\{schema.list\}/g, methodAccessorsArray.map(s => s.body).filter(body => body).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 schemasArray = generateSchemas(obj, templates, { baseUrl: '', section: 'schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) const accessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) - const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).join('\n')) : '' + const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).filter(body => body).join('\n')) : '' const typesArray = schemasArray.filter(x => !x.enum) - const types = typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).join('\n')) : '' - const accessors = accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).join('\n')) : '' + const types = (typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodTypes + + const accessors = (accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodAccessors const module = getTemplate('/codeblocks/module', templates) const macros = { @@ -622,9 +625,9 @@ const isEnum = x => x.type && x.type === 'string' && Array.isArray(x.enum) && x. function generateSchemas(json, templates, options) { let results = [] - const schemas = json.definitions || (json.components && json.components.schemas) || {} + const schemas = (options.section.includes('methods') ? (hasMethodsSchema(json) ? json.methods : '') : (json.definitions || (json.components && json.components.schemas) || {})) - const generate = (name, schema, uri) => { + const generate = (name, schema, uri, { prefix = '' } = {}) => { // these are internal schemas used by the firebolt-openrpc tooling, and not meant to be used in code/doc generation if (['ListenResponse', 'ProviderRequest', 'ProviderResponse', 'FederatedResponse', 'FederatedRequest'].includes(name)) { return @@ -645,7 +648,7 @@ function generateSchemas(json, templates, options) { else { content = content.replace(/\$\{if\.description\}(.*?)\{end\.if\.description\}/gms, '$1') } - const schemaShape = types.getSchemaShape(schema, json, { name, destination: state.destination, section: options.section }) + const schemaShape = types.getSchemaShape(schema, json, { name, prefix, destination: state.destination, section: options.section }) content = content .replace(/\$\{schema.title\}/, (schema.title || name)) @@ -663,6 +666,9 @@ function generateSchemas(json, templates, options) { else { content = content.replace(/.*\$\{schema.seeAlso\}/, '') } + content = content.trim().length ? content.trimEnd() : content.trim() + + const isEnum = x => x.type === 'string' && Array.isArray(x.enum) && x.title const result = uri ? { uri: uri, @@ -685,6 +691,18 @@ function generateSchemas(json, templates, options) { if (isSchema(schema)) { list.push([name, schema]) } + else if (schema.tags) { + if (!isDeprecatedMethod(schema)) { + schema.params.forEach(param => { + if (param.schema && (param.schema.type === 'object')) { + list.push([param.name, param.schema, '', { prefix : schema.name}]) + } + }) + if (schema.result.schema && (schema.result.schema.type === 'object')) { + list.push([schema.result.name, schema.result.schema, '', { prefix : schema.name}]) + } + } + } }) list.sort((a, b) => { @@ -716,7 +734,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, { destination: state.destination, section: state.section }) + '](' + getLinkForSchema(schema, json, true) + ')') // need full module here, not just the schema + .map(schema => '[' + types.getSchemaType(schema, json, { name: schema.title, 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') @@ -1058,10 +1076,10 @@ 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, json)) //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result.schema, json, {title: true, asPath: false, destination: state.destination })) //, baseUrl: options.baseUrl - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates)) + .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, title: true, asPath: false, destination: state.destination })) //, baseUrl: options.baseUrl + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name : result.name })) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) .replace(/\$\{method\.alternative.link\}/g, '#'+(method.alternative || "").toLowerCase()) @@ -1189,8 +1207,9 @@ function insertExampleMacros(template, examples, method, json, templates) { return template.replace(/\$\{method\.examples\}/g, content) } -function generateResult(result, json, templates) { - const type = types.getSchemaType(result, json, { destination: state.destination, section: state.section }) +function generateResult(result, json, templates, { name = '' } = {}) { + + const type = types.getSchemaType(result, json, { name: name, destination: state.destination, section: state.section }) if (result.type === 'object' && result.properties) { let content = getTemplate('/types/object', templates).split('\n') @@ -1201,13 +1220,13 @@ function generateResult(result, json, templates) { } } - return insertSchemaMacros(content.join('\n'), result.title, result, json) + return insertSchemaMacros(content.join('\n'), name, result, json) } else if (type === 'string' && Array.isArray(result.enum)) { - return insertSchemaMacros(getTemplate('/types/enum', templates), result, json) + return insertSchemaMacros(getTemplate('/types/enum', templates), name, result, json) } else if (result.$ref) { - const link = getLinkForSchema(result, json) + const link = getLinkForSchema(result, json, { name: name}) // if we get a real link use it if (link !== '#') { @@ -1217,18 +1236,18 @@ function generateResult(result, json, templates) { else { const schema = localizeDependencies(result, json) return getTemplate('/types/default', templates) - .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { name: result.$ref.split("/").pop()})) + .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { name: result.$ref.split("/").pop() })) } } else { - return insertSchemaMacros(getTemplate('/types/default', templates), result.title, result, json) + return insertSchemaMacros(getTemplate('/types/default', templates), name, result, json) } } function insertSchemaMacros(template, title, schema, module) { return template.replace(/\$\{property\}/g, title) - .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { destination: state.destination, section: state.section, code: false })) - .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module)) + .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { name: title, destination: state.destination, section: state.section, code: false })) + .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module, { name: title })) .replace(/\$\{description\}/g, schema.description || '') .replace(/\$\{name\}/g, title || '') } @@ -1238,9 +1257,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, { destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl - let typeLink = getLinkForSchema(param, module) - let jsonType = types.getJsonType(param.schema, module, { destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) + let type = types.getSchemaType(param.schema, module, { name: param.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl + let typeLink = getLinkForSchema(param.schema, module, { name: param.name }) + let jsonType = types.getJsonType(param.schema, module, { name: param.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) if (constraints && type) { constraints = '
' + constraints @@ -1253,7 +1272,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, module)) //getType(param)) + .replace(/\$\{method.param.link\}/g, getLinkForSchema(param.schema, module, { name: param.name} )) //getType(param)) .replace(/\$\{method.param.constraints\}/g, constraints) //getType(param)) } diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 89c194e2..f8acada8 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -199,8 +199,6 @@ const macrofy = async ( delete outputFiles[file] } }) - - console.log() } // Grab all schema groups w/ a URI string. These came from some external json-schema that was bundled into the OpenRPC @@ -271,4 +269,4 @@ const macrofy = async ( }) } -export default macrofy \ No newline at end of file +export default macrofy From 81df47c395100bfbac6626e96ca9a345d861238c Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 8 Jun 2023 09:23:36 +0530 Subject: [PATCH 009/137] Static code implementation updates (#96) Static code implementation updates Co-authored-by: Jeremy LaCivita --- languages/c/templates/modules/src/Module.cpp | 2 - languages/c/templates/sdk/CMakeLists.txt | 24 +- .../c/templates/sdk/build/CMakeCache.txt | 407 -------- .../CMakeFiles/3.25.3/CMakeCCompiler.cmake | 72 -- .../CMakeFiles/3.25.3/CMakeCXXCompiler.cmake | 83 -- .../3.25.3/CMakeDetermineCompilerABI_C.bin | Bin 16999 -> 0 bytes .../3.25.3/CMakeDetermineCompilerABI_CXX.bin | Bin 16983 -> 0 bytes .../build/CMakeFiles/3.25.3/CMakeSystem.cmake | 15 - .../3.25.3/CompilerIdC/CMakeCCompilerId.c | 868 ------------------ .../3.25.3/CompilerIdC/CMakeCCompilerId.o | Bin 1712 -> 0 bytes .../CompilerIdCXX/CMakeCXXCompilerId.cpp | 857 ----------------- .../3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o | Bin 1712 -> 0 bytes .../sdk/build/CMakeFiles/CMakeError.log | 0 .../sdk/build/CMakeFiles/CMakeOutput.log | 266 ------ .../sdk/build/CMakeFiles/cmake.check_cache | 1 - .../c/templates/sdk/cmake/CopySymlink.cmake | 17 - .../templates/sdk/cmake/HelperFunctions.cmake | 19 +- .../c/templates/sdk/cmake/project.cmake.in | 5 + languages/c/templates/sdk/include/Firebolt.h | 65 ++ languages/c/templates/sdk/include/Types.h | 8 +- languages/c/templates/sdk/scripts/build.sh | 11 + .../c/templates/sdk/src/Accessor/Accessor.cpp | 41 +- .../c/templates/sdk/src/Accessor/Accessor.h | 77 +- .../c/templates/sdk/src/Accessor/WorkerPool.h | 30 + languages/c/templates/sdk/src/CMakeLists.txt | 29 +- languages/c/templates/sdk/src/Config.cmake | 34 - languages/c/templates/sdk/src/Event/Event.cpp | 39 +- languages/c/templates/sdk/src/Event/Event.h | 75 +- .../src/{Accessor/Config.h => Firebolt.cpp} | 43 +- .../sdk/src/{Firebolt.h => FireboltSDK.h} | 1 + .../c/templates/sdk/src/Logger/Logger.cpp | 1 - languages/c/templates/sdk/src/Module.h | 2 - languages/c/templates/sdk/src/Params.config | 3 - .../templates/sdk/src/Properties/Properties.h | 72 +- .../c/templates/sdk/src/Transport/Transport.h | 4 +- languages/c/templates/sdk/src/Types.cpp | 7 +- languages/c/templates/sdk/src/TypesPriv.h | 29 +- .../templates/sdk/src/cmake/CopySymlink.cmake | 1 - 38 files changed, 393 insertions(+), 2815 deletions(-) delete mode 100644 languages/c/templates/sdk/build/CMakeCache.txt delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake delete mode 100755 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin delete mode 100755 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_CXX.bin delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeSystem.cmake delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.c delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.cpp delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/CMakeError.log delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/CMakeOutput.log delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache delete mode 100644 languages/c/templates/sdk/cmake/CopySymlink.cmake create mode 100644 languages/c/templates/sdk/include/Firebolt.h create mode 100755 languages/c/templates/sdk/scripts/build.sh delete mode 100644 languages/c/templates/sdk/src/Config.cmake rename languages/c/templates/sdk/src/{Accessor/Config.h => Firebolt.cpp} (50%) rename languages/c/templates/sdk/src/{Firebolt.h => FireboltSDK.h} (97%) delete mode 100644 languages/c/templates/sdk/src/Params.config delete mode 100644 languages/c/templates/sdk/src/cmake/CopySymlink.cmake diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index c412abf2..47a356d6 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -41,5 +41,3 @@ extern "C" { #ifdef __cplusplus } #endif - - diff --git a/languages/c/templates/sdk/CMakeLists.txt b/languages/c/templates/sdk/CMakeLists.txt index a29658f7..5efcad1a 100644 --- a/languages/c/templates/sdk/CMakeLists.txt +++ b/languages/c/templates/sdk/CMakeLists.txt @@ -20,19 +20,31 @@ project(Firebolt) set(FIREBOLT_TRANSPORT_WAITTIME 1000 CACHE STRING "Maximum time to wait for Transport layer to get response") set(FIREBOLT_LOGLEVEL "Info" CACHE STRING "Log level to be enabled") - +option(FIREBOLT_ENABLE_STATIC_LIB "Create Firebolt library as Static library" OFF) option(ENABLE_TESTS "Build openrpc native test" OFF) +if (NOT SYSROOT_PATH) + # Set sysroot to support PC builds, sysroot_path not configured case + set(SYSROOT_PATH "${CMAKE_SOURCE_DIR}/../../firebolt") +endif() + +if (FIREBOLT_ENABLE_STATIC_LIB) + set(FIREBOLT_LIBRARY_TYPE STATIC) +else () + set(FIREBOLT_LIBRARY_TYPE SHARED) +endif () + +if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${SYSROOT_PATH}/usr" CACHE INTERNAL "" FORCE) + set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) +endif() + list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake" "${SYSROOT_PATH}/usr/lib/cmake" "${SYSROOT_PATH}/tools/cmake") include(HelperFunctions) -if (NOT DEFINED CMAKE_PREFIX_PATH) - set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) -endif() - set(FIREBOLT_NAMESPACE ${PROJECT_NAME} CACHE STRING "Namespace of the project") find_package(WPEFramework CONFIG REQUIRED) @@ -45,5 +57,5 @@ endif() # make sure others can make use cmake settings of Firebolt OpenRPC configure_file( "${CMAKE_SOURCE_DIR}/cmake/project.cmake.in" - "${CMAKE_CURRENT_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake" + "${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake" @ONLY) diff --git a/languages/c/templates/sdk/build/CMakeCache.txt b/languages/c/templates/sdk/build/CMakeCache.txt deleted file mode 100644 index f10d476d..00000000 --- a/languages/c/templates/sdk/build/CMakeCache.txt +++ /dev/null @@ -1,407 +0,0 @@ -# This is the CMakeCache file. -# For build in directory: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build -# It was generated by CMake: /opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -# You can edit this file to change values found and used by cmake. -# If you do not want to change any of the values, simply exit the editor. -# If you do want to change a value, simply edit, save, and exit the editor. -# The syntax for the file is as follows: -# KEY:TYPE=VALUE -# KEY is the name of a variable in the cache. -# TYPE is a hint to GUIs for the type of VALUE, DO NOT EDIT TYPE!. -# VALUE is the current value for the KEY. - -######################## -# EXTERNAL cache entries -######################## - -//Path to a program. -CMAKE_ADDR2LINE:FILEPATH=CMAKE_ADDR2LINE-NOTFOUND - -//Path to a program. -CMAKE_AR:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ar - -//Choose the type of build, options are: None Debug Release RelWithDebInfo -// MinSizeRel ... -CMAKE_BUILD_TYPE:STRING=Release - -//Enable/Disable color output during build. -CMAKE_COLOR_MAKEFILE:BOOL=ON - -//CXX compiler -CMAKE_CXX_COMPILER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/c++ - -//Flags used by the CXX compiler during all build types. -CMAKE_CXX_FLAGS:STRING=-D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION - -//Flags used by the CXX compiler during DEBUG builds. -CMAKE_CXX_FLAGS_DEBUG:STRING=-g - -//Flags used by the CXX compiler during MINSIZEREL builds. -CMAKE_CXX_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG - -//Flags used by the CXX compiler during RELEASE builds. -CMAKE_CXX_FLAGS_RELEASE:STRING=-O3 -DNDEBUG - -//Flags used by the CXX compiler during RELWITHDEBINFO builds. -CMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG - -//C compiler -CMAKE_C_COMPILER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/cc - -//Flags used by the C compiler during all build types. -CMAKE_C_FLAGS:STRING= - -//Flags used by the C compiler during DEBUG builds. -CMAKE_C_FLAGS_DEBUG:STRING=-g - -//Flags used by the C compiler during MINSIZEREL builds. -CMAKE_C_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG - -//Flags used by the C compiler during RELEASE builds. -CMAKE_C_FLAGS_RELEASE:STRING=-O3 -DNDEBUG - -//Flags used by the C compiler during RELWITHDEBINFO builds. -CMAKE_C_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG - -//Path to a program. -CMAKE_DLLTOOL:FILEPATH=CMAKE_DLLTOOL-NOTFOUND - -//Flags used by the linker during all build types. -CMAKE_EXE_LINKER_FLAGS:STRING= - -//Flags used by the linker during DEBUG builds. -CMAKE_EXE_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during MINSIZEREL builds. -CMAKE_EXE_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during RELEASE builds. -CMAKE_EXE_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during RELWITHDEBINFO builds. -CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//Enable/Disable output of compile commands during generation. -CMAKE_EXPORT_COMPILE_COMMANDS:BOOL= - -//Value Computed by CMake. -CMAKE_FIND_PACKAGE_REDIRECTS_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/pkgRedirects - -//Path to a program. -CMAKE_INSTALL_NAME_TOOL:FILEPATH=/usr/bin/install_name_tool - -//Install path prefix, prepended onto install directories. -CMAKE_INSTALL_PREFIX:PATH=/usr - -//No help, variable specified on the command line. -CMAKE_JS_INC:UNINITIALIZED=/Users/JLaciv000/.cmake-js/node-arm64/v19.6.1/include/node - -//No help, variable specified on the command line. -CMAKE_JS_SRC:UNINITIALIZED= - -//No help, variable specified on the command line. -CMAKE_JS_VERSION:UNINITIALIZED=undefined - -//No help, variable specified on the command line. -CMAKE_LIBRARY_OUTPUT_DIRECTORY:UNINITIALIZED=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/Release - -//Path to a program. -CMAKE_LINKER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ld - -//Path to a program. -CMAKE_MAKE_PROGRAM:FILEPATH=/usr/bin/make - -//Flags used by the linker during the creation of modules during -// all build types. -CMAKE_MODULE_LINKER_FLAGS:STRING= - -//Flags used by the linker during the creation of modules during -// DEBUG builds. -CMAKE_MODULE_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during the creation of modules during -// MINSIZEREL builds. -CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during the creation of modules during -// RELEASE builds. -CMAKE_MODULE_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during the creation of modules during -// RELWITHDEBINFO builds. -CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//No help, variable specified on the command line. -CMAKE_MSVC_RUNTIME_LIBRARY:UNINITIALIZED=MultiThreaded$<$:Debug> - -//Path to a program. -CMAKE_NM:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/nm - -//Path to a program. -CMAKE_OBJCOPY:FILEPATH=CMAKE_OBJCOPY-NOTFOUND - -//Path to a program. -CMAKE_OBJDUMP:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/objdump - -//Build architectures for OSX -CMAKE_OSX_ARCHITECTURES:STRING=arm64 - -//Minimum OS X version to target for deployment (at runtime); newer -// APIs weak linked. Set to empty string for default value. -CMAKE_OSX_DEPLOYMENT_TARGET:STRING= - -//The product will be built against the headers and libraries located -// inside the indicated SDK. -CMAKE_OSX_SYSROOT:PATH=/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk - -//Value Computed by CMake -CMAKE_PROJECT_DESCRIPTION:STATIC= - -//Value Computed by CMake -CMAKE_PROJECT_HOMEPAGE_URL:STATIC= - -//Value Computed by CMake -CMAKE_PROJECT_NAME:STATIC=Firebolt - -//Path to a program. -CMAKE_RANLIB:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ranlib - -//Path to a program. -CMAKE_READELF:FILEPATH=CMAKE_READELF-NOTFOUND - -//Flags used by the linker during the creation of shared libraries -// during all build types. -CMAKE_SHARED_LINKER_FLAGS:STRING=-undefined dynamic_lookup - -//Flags used by the linker during the creation of shared libraries -// during DEBUG builds. -CMAKE_SHARED_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during the creation of shared libraries -// during MINSIZEREL builds. -CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during the creation of shared libraries -// during RELEASE builds. -CMAKE_SHARED_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during the creation of shared libraries -// during RELWITHDEBINFO builds. -CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//If set, runtime paths are not added when installing shared libraries, -// but are added when building. -CMAKE_SKIP_INSTALL_RPATH:BOOL=NO - -//If set, runtime paths are not added when using shared libraries. -CMAKE_SKIP_RPATH:BOOL=NO - -//Flags used by the linker during the creation of static libraries -// during all build types. -CMAKE_STATIC_LINKER_FLAGS:STRING= - -//Flags used by the linker during the creation of static libraries -// during DEBUG builds. -CMAKE_STATIC_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during the creation of static libraries -// during MINSIZEREL builds. -CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during the creation of static libraries -// during RELEASE builds. -CMAKE_STATIC_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during the creation of static libraries -// during RELWITHDEBINFO builds. -CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//Path to a program. -CMAKE_STRIP:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/strip - -//If this value is on, makefiles will be generated without the -// .SILENT directive, and all commands will be echoed to the console -// during the make. This is useful for debugging only. With Visual -// Studio IDE projects all commands are done without /nologo. -CMAKE_VERBOSE_MAKEFILE:BOOL=FALSE - -//Build openrpc native test -ENABLE_TESTS:BOOL=OFF - -//Log level to be enabled -FIREBOLT_LOGLEVEL:STRING=Info - -//Namespace of the project -FIREBOLT_NAMESPACE:STRING=Firebolt - -//Maximum time to wait for Transport layer to get response -FIREBOLT_TRANSPORT_WAITTIME:STRING=1000 - -//Value Computed by CMake -Firebolt_BINARY_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build - -//Value Computed by CMake -Firebolt_IS_TOP_LEVEL:STATIC=ON - -//Value Computed by CMake -Firebolt_SOURCE_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native - -//No help, variable specified on the command line. -GENERATED_CODE_PATH:UNINITIALIZED=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/build/sdk/native-c - -//No help, variable specified on the command line. -NODE_ARCH:UNINITIALIZED=arm64 - -//No help, variable specified on the command line. -NODE_RUNTIME:UNINITIALIZED=node - -//No help, variable specified on the command line. -NODE_RUNTIMEVERSION:UNINITIALIZED=19.6.1 - -//The directory containing a CMake configuration file for WPEFramework. -WPEFramework_DIR:PATH=WPEFramework_DIR-NOTFOUND - - -######################## -# INTERNAL cache entries -######################## - -//ADVANCED property for variable: CMAKE_ADDR2LINE -CMAKE_ADDR2LINE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_AR -CMAKE_AR-ADVANCED:INTERNAL=1 -//This is the directory where this CMakeCache.txt was created -CMAKE_CACHEFILE_DIR:INTERNAL=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build -//Major version of cmake used to create the current loaded cache -CMAKE_CACHE_MAJOR_VERSION:INTERNAL=3 -//Minor version of cmake used to create the current loaded cache -CMAKE_CACHE_MINOR_VERSION:INTERNAL=25 -//Patch version of cmake used to create the current loaded cache -CMAKE_CACHE_PATCH_VERSION:INTERNAL=3 -//ADVANCED property for variable: CMAKE_COLOR_MAKEFILE -CMAKE_COLOR_MAKEFILE-ADVANCED:INTERNAL=1 -//Path to CMake executable. -CMAKE_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -//Path to cpack program executable. -CMAKE_CPACK_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/cpack -//Path to ctest program executable. -CMAKE_CTEST_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/ctest -//ADVANCED property for variable: CMAKE_CXX_COMPILER -CMAKE_CXX_COMPILER-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_CXX_FLAGS -CMAKE_CXX_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_CXX_FLAGS_DEBUG -CMAKE_CXX_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_CXX_FLAGS_MINSIZEREL -CMAKE_CXX_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELEASE -CMAKE_CXX_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELWITHDEBINFO -CMAKE_CXX_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_COMPILER -CMAKE_C_COMPILER-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS -CMAKE_C_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_DEBUG -CMAKE_C_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_MINSIZEREL -CMAKE_C_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_RELEASE -CMAKE_C_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_RELWITHDEBINFO -CMAKE_C_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_DLLTOOL -CMAKE_DLLTOOL-ADVANCED:INTERNAL=1 -//Path to cache edit program executable. -CMAKE_EDIT_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/ccmake -//Executable file format -CMAKE_EXECUTABLE_FORMAT:INTERNAL=MACHO -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS -CMAKE_EXE_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_DEBUG -CMAKE_EXE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_MINSIZEREL -CMAKE_EXE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELEASE -CMAKE_EXE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXPORT_COMPILE_COMMANDS -CMAKE_EXPORT_COMPILE_COMMANDS-ADVANCED:INTERNAL=1 -//Name of external makefile project generator. -CMAKE_EXTRA_GENERATOR:INTERNAL= -//Name of generator. -CMAKE_GENERATOR:INTERNAL=Unix Makefiles -//Generator instance identifier. -CMAKE_GENERATOR_INSTANCE:INTERNAL= -//Name of generator platform. -CMAKE_GENERATOR_PLATFORM:INTERNAL= -//Name of generator toolset. -CMAKE_GENERATOR_TOOLSET:INTERNAL= -//Source directory with the top level CMakeLists.txt file for this -// project -CMAKE_HOME_DIRECTORY:INTERNAL=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native -//ADVANCED property for variable: CMAKE_INSTALL_NAME_TOOL -CMAKE_INSTALL_NAME_TOOL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_LINKER -CMAKE_LINKER-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MAKE_PROGRAM -CMAKE_MAKE_PROGRAM-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS -CMAKE_MODULE_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_DEBUG -CMAKE_MODULE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL -CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELEASE -CMAKE_MODULE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_NM -CMAKE_NM-ADVANCED:INTERNAL=1 -//number of local generators -CMAKE_NUMBER_OF_MAKEFILES:INTERNAL=1 -//ADVANCED property for variable: CMAKE_OBJCOPY -CMAKE_OBJCOPY-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_OBJDUMP -CMAKE_OBJDUMP-ADVANCED:INTERNAL=1 -//Platform information initialized -CMAKE_PLATFORM_INFO_INITIALIZED:INTERNAL=1 -CMAKE_PREFIX_PATH:INTERNAL=/usr/lib/cmake -//ADVANCED property for variable: CMAKE_RANLIB -CMAKE_RANLIB-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_READELF -CMAKE_READELF-ADVANCED:INTERNAL=1 -//Path to CMake installation. -CMAKE_ROOT:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/share/cmake -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS -CMAKE_SHARED_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_DEBUG -CMAKE_SHARED_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL -CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELEASE -CMAKE_SHARED_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SKIP_INSTALL_RPATH -CMAKE_SKIP_INSTALL_RPATH-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SKIP_RPATH -CMAKE_SKIP_RPATH-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS -CMAKE_STATIC_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_DEBUG -CMAKE_STATIC_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL -CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELEASE -CMAKE_STATIC_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STRIP -CMAKE_STRIP-ADVANCED:INTERNAL=1 -//uname command -CMAKE_UNAME:INTERNAL=/usr/bin/uname -//ADVANCED property for variable: CMAKE_VERBOSE_MAKEFILE -CMAKE_VERBOSE_MAKEFILE-ADVANCED:INTERNAL=1 - diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake deleted file mode 100644 index dc7a67f2..00000000 --- a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake +++ /dev/null @@ -1,72 +0,0 @@ -set(CMAKE_C_COMPILER "/Library/Developer/CommandLineTools/usr/bin/cc") -set(CMAKE_C_COMPILER_ARG1 "") -set(CMAKE_C_COMPILER_ID "AppleClang") -set(CMAKE_C_COMPILER_VERSION "13.1.6.13160021") -set(CMAKE_C_COMPILER_VERSION_INTERNAL "") -set(CMAKE_C_COMPILER_WRAPPER "") -set(CMAKE_C_STANDARD_COMPUTED_DEFAULT "17") -set(CMAKE_C_EXTENSIONS_COMPUTED_DEFAULT "ON") -set(CMAKE_C_COMPILE_FEATURES "c_std_90;c_function_prototypes;c_std_99;c_restrict;c_variadic_macros;c_std_11;c_static_assert;c_std_17;c_std_23") -set(CMAKE_C90_COMPILE_FEATURES "c_std_90;c_function_prototypes") -set(CMAKE_C99_COMPILE_FEATURES "c_std_99;c_restrict;c_variadic_macros") -set(CMAKE_C11_COMPILE_FEATURES "c_std_11;c_static_assert") -set(CMAKE_C17_COMPILE_FEATURES "c_std_17") -set(CMAKE_C23_COMPILE_FEATURES "c_std_23") - -set(CMAKE_C_PLATFORM_ID "Darwin") -set(CMAKE_C_SIMULATE_ID "") -set(CMAKE_C_COMPILER_FRONTEND_VARIANT "") -set(CMAKE_C_SIMULATE_VERSION "") - - - - -set(CMAKE_AR "/Library/Developer/CommandLineTools/usr/bin/ar") -set(CMAKE_C_COMPILER_AR "") -set(CMAKE_RANLIB "/Library/Developer/CommandLineTools/usr/bin/ranlib") -set(CMAKE_C_COMPILER_RANLIB "") -set(CMAKE_LINKER "/Library/Developer/CommandLineTools/usr/bin/ld") -set(CMAKE_MT "") -set(CMAKE_COMPILER_IS_GNUCC ) -set(CMAKE_C_COMPILER_LOADED 1) -set(CMAKE_C_COMPILER_WORKS TRUE) -set(CMAKE_C_ABI_COMPILED TRUE) - -set(CMAKE_C_COMPILER_ENV_VAR "CC") - -set(CMAKE_C_COMPILER_ID_RUN 1) -set(CMAKE_C_SOURCE_FILE_EXTENSIONS c;m) -set(CMAKE_C_IGNORE_EXTENSIONS h;H;o;O;obj;OBJ;def;DEF;rc;RC) -set(CMAKE_C_LINKER_PREFERENCE 10) - -# Save compiler ABI information. -set(CMAKE_C_SIZEOF_DATA_PTR "8") -set(CMAKE_C_COMPILER_ABI "") -set(CMAKE_C_BYTE_ORDER "LITTLE_ENDIAN") -set(CMAKE_C_LIBRARY_ARCHITECTURE "") - -if(CMAKE_C_SIZEOF_DATA_PTR) - set(CMAKE_SIZEOF_VOID_P "${CMAKE_C_SIZEOF_DATA_PTR}") -endif() - -if(CMAKE_C_COMPILER_ABI) - set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_C_COMPILER_ABI}") -endif() - -if(CMAKE_C_LIBRARY_ARCHITECTURE) - set(CMAKE_LIBRARY_ARCHITECTURE "") -endif() - -set(CMAKE_C_CL_SHOWINCLUDES_PREFIX "") -if(CMAKE_C_CL_SHOWINCLUDES_PREFIX) - set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_C_CL_SHOWINCLUDES_PREFIX}") -endif() - - - - - -set(CMAKE_C_IMPLICIT_INCLUDE_DIRECTORIES "/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include") -set(CMAKE_C_IMPLICIT_LINK_LIBRARIES "") -set(CMAKE_C_IMPLICIT_LINK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib") -set(CMAKE_C_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks") diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake deleted file mode 100644 index 67dc227a..00000000 --- a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake +++ /dev/null @@ -1,83 +0,0 @@ -set(CMAKE_CXX_COMPILER "/Library/Developer/CommandLineTools/usr/bin/c++") -set(CMAKE_CXX_COMPILER_ARG1 "") -set(CMAKE_CXX_COMPILER_ID "AppleClang") -set(CMAKE_CXX_COMPILER_VERSION "13.1.6.13160021") -set(CMAKE_CXX_COMPILER_VERSION_INTERNAL "") -set(CMAKE_CXX_COMPILER_WRAPPER "") -set(CMAKE_CXX_STANDARD_COMPUTED_DEFAULT "98") -set(CMAKE_CXX_EXTENSIONS_COMPUTED_DEFAULT "ON") -set(CMAKE_CXX_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters;cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates;cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates;cxx_std_17;cxx_std_20;cxx_std_23") -set(CMAKE_CXX98_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters") -set(CMAKE_CXX11_COMPILE_FEATURES "cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates") -set(CMAKE_CXX14_COMPILE_FEATURES "cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates") -set(CMAKE_CXX17_COMPILE_FEATURES "cxx_std_17") -set(CMAKE_CXX20_COMPILE_FEATURES "cxx_std_20") -set(CMAKE_CXX23_COMPILE_FEATURES "cxx_std_23") - -set(CMAKE_CXX_PLATFORM_ID "Darwin") -set(CMAKE_CXX_SIMULATE_ID "") -set(CMAKE_CXX_COMPILER_FRONTEND_VARIANT "") -set(CMAKE_CXX_SIMULATE_VERSION "") - - - - -set(CMAKE_AR "/Library/Developer/CommandLineTools/usr/bin/ar") -set(CMAKE_CXX_COMPILER_AR "") -set(CMAKE_RANLIB "/Library/Developer/CommandLineTools/usr/bin/ranlib") -set(CMAKE_CXX_COMPILER_RANLIB "") -set(CMAKE_LINKER "/Library/Developer/CommandLineTools/usr/bin/ld") -set(CMAKE_MT "") -set(CMAKE_COMPILER_IS_GNUCXX ) -set(CMAKE_CXX_COMPILER_LOADED 1) -set(CMAKE_CXX_COMPILER_WORKS TRUE) -set(CMAKE_CXX_ABI_COMPILED TRUE) - -set(CMAKE_CXX_COMPILER_ENV_VAR "CXX") - -set(CMAKE_CXX_COMPILER_ID_RUN 1) -set(CMAKE_CXX_SOURCE_FILE_EXTENSIONS C;M;c++;cc;cpp;cxx;m;mm;mpp;CPP;ixx;cppm) -set(CMAKE_CXX_IGNORE_EXTENSIONS inl;h;hpp;HPP;H;o;O;obj;OBJ;def;DEF;rc;RC) - -foreach (lang C OBJC OBJCXX) - if (CMAKE_${lang}_COMPILER_ID_RUN) - foreach(extension IN LISTS CMAKE_${lang}_SOURCE_FILE_EXTENSIONS) - list(REMOVE_ITEM CMAKE_CXX_SOURCE_FILE_EXTENSIONS ${extension}) - endforeach() - endif() -endforeach() - -set(CMAKE_CXX_LINKER_PREFERENCE 30) -set(CMAKE_CXX_LINKER_PREFERENCE_PROPAGATES 1) - -# Save compiler ABI information. -set(CMAKE_CXX_SIZEOF_DATA_PTR "8") -set(CMAKE_CXX_COMPILER_ABI "") -set(CMAKE_CXX_BYTE_ORDER "LITTLE_ENDIAN") -set(CMAKE_CXX_LIBRARY_ARCHITECTURE "") - -if(CMAKE_CXX_SIZEOF_DATA_PTR) - set(CMAKE_SIZEOF_VOID_P "${CMAKE_CXX_SIZEOF_DATA_PTR}") -endif() - -if(CMAKE_CXX_COMPILER_ABI) - set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_CXX_COMPILER_ABI}") -endif() - -if(CMAKE_CXX_LIBRARY_ARCHITECTURE) - set(CMAKE_LIBRARY_ARCHITECTURE "") -endif() - -set(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX "") -if(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX) - set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_CXX_CL_SHOWINCLUDES_PREFIX}") -endif() - - - - - -set(CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1;/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include") -set(CMAKE_CXX_IMPLICIT_LINK_LIBRARIES "c++") -set(CMAKE_CXX_IMPLICIT_LINK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib") -set(CMAKE_CXX_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks") diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin deleted file mode 100755 index 9b3e67d1d3825990645b4978d3a1e9da0ed43128..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 16999 zcmeI3Uuau(6vt1J4mw-bDPw=A+wvq%M%!73vA8vv&DOh>G+QHv1^Joe-nN%DNljAM zl(`jkY7xOI!Vn*PvJ@tW2r~~t@nOEH-NO_gw8E4Y8SKRe>sb7r-@Ug@j7;$P960yf zbI$K~a?a=G^?bX2`(8Vdk05^Nc4#O-beV#9BiaKUgenz}oQR%{o*Cw7qv*?xp(c;( zgm6%)L^PRbOzZpM#u&N&7KB;Rk`|@P)^yo*VE$R}&QWI=?+E)m*M_vv?8ZA@l*$(J zCGT`|J+t4b=e6wl^)>3>m72<*xAUg5^P>e_zj59#+QD&^VNZ&#>~h z;4}Y6w&79`ivJvSPnC+@6LzNCtW22jSvsNI$NH7x4Rex!tKWiOSUF)2!VyE|=*7+mzTkW;b zYDc)*>f743TAy1(u3}IBYc74XDYt?e_^tV+fVyeKjt}>h>=~;ts?5o9G1U`#o+xGv zAJ6oaE6OSsEHhO!j;Rx|s4)CVfjdF!HA3a*weJh$P*jJqFy()F*nK40$e zIUC+Q`%d-|^!D+w?~S}OJLiMg>~HQ(Z{;_1rF6GWd=t0I*kj7dn|3-+O}PoXT%NGJ zG=8gI)_-bW0>NE~aT_c<5JRWF0Qp;Z>6}N&LX(_?VE;T45Bl{=yc4VM6Pqn++5DY9SA;OK&E`)@a62ozG~Gg3vqrwOy?1(}Yo+U07k`F$ z7?Bt+1c@g+5Q2z4kcE(VVk9IUWCXE^ga;BL=A8RyyHz3a>YU`pZ)-|0EOudnCf zw+}yx7_%`DJ7_Uz)WO(6Ccuud$)NS1oHx4HdYU~O8t^n*w9DB?ITq$|K_KUTPr#q; z*6xehXUwoi!7(b7qzUIKr6Xk+u>6|u<4V05GX!nyYgqDF*YF-ToJSJzHZwXmpS()X zXO?W*)*RM7=k4*GYFy@Oyd|OK&+hl8kq?=opq*8pemwjg;qR4v>pgXnS%_#n8myWa zYm<=-nOfgv5o2BBFc9Kgu+$i~3+yVe@!BNN?O-GCURXO|Ed*@@MZq^f#aN8_7a0qe z1W@?TvC8(gWMxbZSIX&_3^qy`DAwVeb!t!?td8y9F?eTu;g@JNoC%I$f4{hdd)E zeq*{VrL>Y5g-CY zfCvx)B0vO)01+SpM1Tko0U|&IhyW2F0z`la5CI}U1c(3;AOb{y2oM1xKm>>Y5g-CY zfCvx)B0vO)01+SpM1Tko0U|&IhyW2F0z}}yA~1A-^$pEnnf@}Cd0EK54mnw7psXtc zGrC9fdsg%mr~|HdPBD{jD=2(t^$mb8t#xUfhTRpuF{#5dIGs{>A}K4$pjYzyy&mrI z)k$t2_;F--s_}Bx6=#}p<{9R_HC14~90hHhmBy**aoTM#1bqZrfGy5MqoP>Hk@fj% z{XFYy<1hnm=dDq$bSRN_C^V{spi(xoHKfMbY%IjVKJGRynH#KiEcnbhdYD7k>`u#^ zJ^D`=Hl}gfa8g>YYl3F$Jz|{#Oz`K{z_l7UZ}u)+f`j>_B0ZR-(lxt1=jV$0r_me)L)enUEBe|6e9e#*%eORpTb7ZmQE>poLc zH~P}0y%($?}6|C|5qI)^f8eSKp>24 & 0x00FF) -# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) -# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) - -#elif defined(__BORLANDC__) -# define COMPILER_ID "Borland" - /* __BORLANDC__ = 0xVRR */ -# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) -# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) - -#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 -# define COMPILER_ID "Watcom" - /* __WATCOMC__ = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__WATCOMC__) -# define COMPILER_ID "OpenWatcom" - /* __WATCOMC__ = VVRP + 1100 */ -# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__SUNPRO_C) -# define COMPILER_ID "SunPro" -# if __SUNPRO_C >= 0x5100 - /* __SUNPRO_C = 0xVRRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>12) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xFF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) -# else - /* __SUNPRO_CC = 0xVRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>8) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) -# endif - -#elif defined(__HP_cc) -# define COMPILER_ID "HP" - /* __HP_cc = VVRRPP */ -# define COMPILER_VERSION_MAJOR DEC(__HP_cc/10000) -# define COMPILER_VERSION_MINOR DEC(__HP_cc/100 % 100) -# define COMPILER_VERSION_PATCH DEC(__HP_cc % 100) - -#elif defined(__DECC) -# define COMPILER_ID "Compaq" - /* __DECC_VER = VVRRTPPPP */ -# define COMPILER_VERSION_MAJOR DEC(__DECC_VER/10000000) -# define COMPILER_VERSION_MINOR DEC(__DECC_VER/100000 % 100) -# define COMPILER_VERSION_PATCH DEC(__DECC_VER % 10000) - -#elif defined(__IBMC__) && defined(__COMPILER_VER__) -# define COMPILER_ID "zOS" - /* __IBMC__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) - -#elif defined(__open_xl__) && defined(__clang__) -# define COMPILER_ID "IBMClang" -# define COMPILER_VERSION_MAJOR DEC(__open_xl_version__) -# define COMPILER_VERSION_MINOR DEC(__open_xl_release__) -# define COMPILER_VERSION_PATCH DEC(__open_xl_modification__) -# define COMPILER_VERSION_TWEAK DEC(__open_xl_ptf_fix_level__) - - -#elif defined(__ibmxl__) && defined(__clang__) -# define COMPILER_ID "XLClang" -# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) -# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) -# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) -# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) - - -#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ >= 800 -# define COMPILER_ID "XL" - /* __IBMC__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) - -#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ < 800 -# define COMPILER_ID "VisualAge" - /* __IBMC__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) - -#elif defined(__NVCOMPILER) -# define COMPILER_ID "NVHPC" -# define COMPILER_VERSION_MAJOR DEC(__NVCOMPILER_MAJOR__) -# define COMPILER_VERSION_MINOR DEC(__NVCOMPILER_MINOR__) -# if defined(__NVCOMPILER_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__NVCOMPILER_PATCHLEVEL__) -# endif - -#elif defined(__PGI) -# define COMPILER_ID "PGI" -# define COMPILER_VERSION_MAJOR DEC(__PGIC__) -# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) -# if defined(__PGIC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) -# endif - -#elif defined(_CRAYC) -# define COMPILER_ID "Cray" -# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) -# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) - -#elif defined(__TI_COMPILER_VERSION__) -# define COMPILER_ID "TI" - /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ -# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) -# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) -# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) - -#elif defined(__CLANG_FUJITSU) -# define COMPILER_ID "FujitsuClang" -# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) -# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) -# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) -# define COMPILER_VERSION_INTERNAL_STR __clang_version__ - - -#elif defined(__FUJITSU) -# define COMPILER_ID "Fujitsu" -# if defined(__FCC_version__) -# define COMPILER_VERSION __FCC_version__ -# elif defined(__FCC_major__) -# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) -# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) -# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) -# endif -# if defined(__fcc_version) -# define COMPILER_VERSION_INTERNAL DEC(__fcc_version) -# elif defined(__FCC_VERSION) -# define COMPILER_VERSION_INTERNAL DEC(__FCC_VERSION) -# endif - - -#elif defined(__ghs__) -# define COMPILER_ID "GHS" -/* __GHS_VERSION_NUMBER = VVVVRP */ -# ifdef __GHS_VERSION_NUMBER -# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) -# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) -# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) -# endif - -#elif defined(__TASKING__) -# define COMPILER_ID "Tasking" - # define COMPILER_VERSION_MAJOR DEC(__VERSION__/1000) - # define COMPILER_VERSION_MINOR DEC(__VERSION__ % 100) -# define COMPILER_VERSION_INTERNAL DEC(__VERSION__) - -#elif defined(__TINYC__) -# define COMPILER_ID "TinyCC" - -#elif defined(__BCC__) -# define COMPILER_ID "Bruce" - -#elif defined(__SCO_VERSION__) -# define COMPILER_ID "SCO" - -#elif defined(__ARMCC_VERSION) && !defined(__clang__) -# define COMPILER_ID "ARMCC" -#if __ARMCC_VERSION >= 1000000 - /* __ARMCC_VERSION = VRRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#else - /* __ARMCC_VERSION = VRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#endif - - -#elif defined(__clang__) && defined(__apple_build_version__) -# define COMPILER_ID "AppleClang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif -# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) - -#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) -# define COMPILER_ID "ARMClang" - # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) -# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) - -#elif defined(__clang__) -# define COMPILER_ID "Clang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif - -#elif defined(__LCC__) && (defined(__GNUC__) || defined(__GNUG__) || defined(__MCST__)) -# define COMPILER_ID "LCC" -# define COMPILER_VERSION_MAJOR DEC(1) -# if defined(__LCC__) -# define COMPILER_VERSION_MINOR DEC(__LCC__- 100) -# endif -# if defined(__LCC_MINOR__) -# define COMPILER_VERSION_PATCH DEC(__LCC_MINOR__) -# endif -# if defined(__GNUC__) && defined(__GNUC_MINOR__) -# define SIMULATE_ID "GNU" -# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) -# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) -# if defined(__GNUC_PATCHLEVEL__) -# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif -# endif - -#elif defined(__GNUC__) -# define COMPILER_ID "GNU" -# define COMPILER_VERSION_MAJOR DEC(__GNUC__) -# if defined(__GNUC_MINOR__) -# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) -# endif -# if defined(__GNUC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif - -#elif defined(_MSC_VER) -# define COMPILER_ID "MSVC" - /* _MSC_VER = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) -# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) -# if defined(_MSC_FULL_VER) -# if _MSC_VER >= 1400 - /* _MSC_FULL_VER = VVRRPPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) -# else - /* _MSC_FULL_VER = VVRRPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) -# endif -# endif -# if defined(_MSC_BUILD) -# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) -# endif - -#elif defined(_ADI_COMPILER) -# define COMPILER_ID "ADSP" -#if defined(__VERSIONNUM__) - /* __VERSIONNUM__ = 0xVVRRPPTT */ -# define COMPILER_VERSION_MAJOR DEC(__VERSIONNUM__ >> 24 & 0xFF) -# define COMPILER_VERSION_MINOR DEC(__VERSIONNUM__ >> 16 & 0xFF) -# define COMPILER_VERSION_PATCH DEC(__VERSIONNUM__ >> 8 & 0xFF) -# define COMPILER_VERSION_TWEAK DEC(__VERSIONNUM__ & 0xFF) -#endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# define COMPILER_ID "IAR" -# if defined(__VER__) && defined(__ICCARM__) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) -# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) -# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__) || defined(__ICCSTM8__)) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) -# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) -# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# endif - -#elif defined(__SDCC_VERSION_MAJOR) || defined(SDCC) -# define COMPILER_ID "SDCC" -# if defined(__SDCC_VERSION_MAJOR) -# define COMPILER_VERSION_MAJOR DEC(__SDCC_VERSION_MAJOR) -# define COMPILER_VERSION_MINOR DEC(__SDCC_VERSION_MINOR) -# define COMPILER_VERSION_PATCH DEC(__SDCC_VERSION_PATCH) -# else - /* SDCC = VRP */ -# define COMPILER_VERSION_MAJOR DEC(SDCC/100) -# define COMPILER_VERSION_MINOR DEC(SDCC/10 % 10) -# define COMPILER_VERSION_PATCH DEC(SDCC % 10) -# endif - - -/* These compilers are either not known or too old to define an - identification macro. Try to identify the platform and guess that - it is the native compiler. */ -#elif defined(__hpux) || defined(__hpua) -# define COMPILER_ID "HP" - -#else /* unknown compiler */ -# define COMPILER_ID "" -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; -#ifdef SIMULATE_ID -char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; -#endif - -#ifdef __QNXNTO__ -char const* qnxnto = "INFO" ":" "qnxnto[]"; -#endif - -#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) -char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; -#endif - -#define STRINGIFY_HELPER(X) #X -#define STRINGIFY(X) STRINGIFY_HELPER(X) - -/* Identify known platforms by name. */ -#if defined(__linux) || defined(__linux__) || defined(linux) -# define PLATFORM_ID "Linux" - -#elif defined(__MSYS__) -# define PLATFORM_ID "MSYS" - -#elif defined(__CYGWIN__) -# define PLATFORM_ID "Cygwin" - -#elif defined(__MINGW32__) -# define PLATFORM_ID "MinGW" - -#elif defined(__APPLE__) -# define PLATFORM_ID "Darwin" - -#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) -# define PLATFORM_ID "Windows" - -#elif defined(__FreeBSD__) || defined(__FreeBSD) -# define PLATFORM_ID "FreeBSD" - -#elif defined(__NetBSD__) || defined(__NetBSD) -# define PLATFORM_ID "NetBSD" - -#elif defined(__OpenBSD__) || defined(__OPENBSD) -# define PLATFORM_ID "OpenBSD" - -#elif defined(__sun) || defined(sun) -# define PLATFORM_ID "SunOS" - -#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) -# define PLATFORM_ID "AIX" - -#elif defined(__hpux) || defined(__hpux__) -# define PLATFORM_ID "HP-UX" - -#elif defined(__HAIKU__) -# define PLATFORM_ID "Haiku" - -#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) -# define PLATFORM_ID "BeOS" - -#elif defined(__QNX__) || defined(__QNXNTO__) -# define PLATFORM_ID "QNX" - -#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) -# define PLATFORM_ID "Tru64" - -#elif defined(__riscos) || defined(__riscos__) -# define PLATFORM_ID "RISCos" - -#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) -# define PLATFORM_ID "SINIX" - -#elif defined(__UNIX_SV__) -# define PLATFORM_ID "UNIX_SV" - -#elif defined(__bsdos__) -# define PLATFORM_ID "BSDOS" - -#elif defined(_MPRAS) || defined(MPRAS) -# define PLATFORM_ID "MP-RAS" - -#elif defined(__osf) || defined(__osf__) -# define PLATFORM_ID "OSF1" - -#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) -# define PLATFORM_ID "SCO_SV" - -#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) -# define PLATFORM_ID "ULTRIX" - -#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) -# define PLATFORM_ID "Xenix" - -#elif defined(__WATCOMC__) -# if defined(__LINUX__) -# define PLATFORM_ID "Linux" - -# elif defined(__DOS__) -# define PLATFORM_ID "DOS" - -# elif defined(__OS2__) -# define PLATFORM_ID "OS2" - -# elif defined(__WINDOWS__) -# define PLATFORM_ID "Windows3x" - -# elif defined(__VXWORKS__) -# define PLATFORM_ID "VxWorks" - -# else /* unknown platform */ -# define PLATFORM_ID -# endif - -#elif defined(__INTEGRITY) -# if defined(INT_178B) -# define PLATFORM_ID "Integrity178" - -# else /* regular Integrity */ -# define PLATFORM_ID "Integrity" -# endif - -# elif defined(_ADI_COMPILER) -# define PLATFORM_ID "ADSP" - -#else /* unknown platform */ -# define PLATFORM_ID - -#endif - -/* For windows compilers MSVC and Intel we can determine - the architecture of the compiler being used. This is because - the compilers do not have flags that can change the architecture, - but rather depend on which compiler is being used -*/ -#if defined(_WIN32) && defined(_MSC_VER) -# if defined(_M_IA64) -# define ARCHITECTURE_ID "IA64" - -# elif defined(_M_ARM64EC) -# define ARCHITECTURE_ID "ARM64EC" - -# elif defined(_M_X64) || defined(_M_AMD64) -# define ARCHITECTURE_ID "x64" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# elif defined(_M_ARM64) -# define ARCHITECTURE_ID "ARM64" - -# elif defined(_M_ARM) -# if _M_ARM == 4 -# define ARCHITECTURE_ID "ARMV4I" -# elif _M_ARM == 5 -# define ARCHITECTURE_ID "ARMV5I" -# else -# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) -# endif - -# elif defined(_M_MIPS) -# define ARCHITECTURE_ID "MIPS" - -# elif defined(_M_SH) -# define ARCHITECTURE_ID "SHx" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__WATCOMC__) -# if defined(_M_I86) -# define ARCHITECTURE_ID "I86" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# if defined(__ICCARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__ICCRX__) -# define ARCHITECTURE_ID "RX" - -# elif defined(__ICCRH850__) -# define ARCHITECTURE_ID "RH850" - -# elif defined(__ICCRL78__) -# define ARCHITECTURE_ID "RL78" - -# elif defined(__ICCRISCV__) -# define ARCHITECTURE_ID "RISCV" - -# elif defined(__ICCAVR__) -# define ARCHITECTURE_ID "AVR" - -# elif defined(__ICC430__) -# define ARCHITECTURE_ID "MSP430" - -# elif defined(__ICCV850__) -# define ARCHITECTURE_ID "V850" - -# elif defined(__ICC8051__) -# define ARCHITECTURE_ID "8051" - -# elif defined(__ICCSTM8__) -# define ARCHITECTURE_ID "STM8" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__ghs__) -# if defined(__PPC64__) -# define ARCHITECTURE_ID "PPC64" - -# elif defined(__ppc__) -# define ARCHITECTURE_ID "PPC" - -# elif defined(__ARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__x86_64__) -# define ARCHITECTURE_ID "x64" - -# elif defined(__i386__) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__TI_COMPILER_VERSION__) -# if defined(__TI_ARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__MSP430__) -# define ARCHITECTURE_ID "MSP430" - -# elif defined(__TMS320C28XX__) -# define ARCHITECTURE_ID "TMS320C28x" - -# elif defined(__TMS320C6X__) || defined(_TMS320C6X) -# define ARCHITECTURE_ID "TMS320C6x" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -# elif defined(__ADSPSHARC__) -# define ARCHITECTURE_ID "SHARC" - -# elif defined(__ADSPBLACKFIN__) -# define ARCHITECTURE_ID "Blackfin" - -#elif defined(__TASKING__) - -# if defined(__CTC__) || defined(__CPTC__) -# define ARCHITECTURE_ID "TriCore" - -# elif defined(__CMCS__) -# define ARCHITECTURE_ID "MCS" - -# elif defined(__CARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__CARC__) -# define ARCHITECTURE_ID "ARC" - -# elif defined(__C51__) -# define ARCHITECTURE_ID "8051" - -# elif defined(__CPCP__) -# define ARCHITECTURE_ID "PCP" - -# else -# define ARCHITECTURE_ID "" -# endif - -#else -# define ARCHITECTURE_ID -#endif - -/* Convert integer to decimal digit literals. */ -#define DEC(n) \ - ('0' + (((n) / 10000000)%10)), \ - ('0' + (((n) / 1000000)%10)), \ - ('0' + (((n) / 100000)%10)), \ - ('0' + (((n) / 10000)%10)), \ - ('0' + (((n) / 1000)%10)), \ - ('0' + (((n) / 100)%10)), \ - ('0' + (((n) / 10)%10)), \ - ('0' + ((n) % 10)) - -/* Convert integer to hex digit literals. */ -#define HEX(n) \ - ('0' + ((n)>>28 & 0xF)), \ - ('0' + ((n)>>24 & 0xF)), \ - ('0' + ((n)>>20 & 0xF)), \ - ('0' + ((n)>>16 & 0xF)), \ - ('0' + ((n)>>12 & 0xF)), \ - ('0' + ((n)>>8 & 0xF)), \ - ('0' + ((n)>>4 & 0xF)), \ - ('0' + ((n) & 0xF)) - -/* Construct a string literal encoding the version number. */ -#ifdef COMPILER_VERSION -char const* info_version = "INFO" ":" "compiler_version[" COMPILER_VERSION "]"; - -/* Construct a string literal encoding the version number components. */ -#elif defined(COMPILER_VERSION_MAJOR) -char const info_version[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', - COMPILER_VERSION_MAJOR, -# ifdef COMPILER_VERSION_MINOR - '.', COMPILER_VERSION_MINOR, -# ifdef COMPILER_VERSION_PATCH - '.', COMPILER_VERSION_PATCH, -# ifdef COMPILER_VERSION_TWEAK - '.', COMPILER_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct a string literal encoding the internal version number. */ -#ifdef COMPILER_VERSION_INTERNAL -char const info_version_internal[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', - 'i','n','t','e','r','n','a','l','[', - COMPILER_VERSION_INTERNAL,']','\0'}; -#elif defined(COMPILER_VERSION_INTERNAL_STR) -char const* info_version_internal = "INFO" ":" "compiler_version_internal[" COMPILER_VERSION_INTERNAL_STR "]"; -#endif - -/* Construct a string literal encoding the version number components. */ -#ifdef SIMULATE_VERSION_MAJOR -char const info_simulate_version[] = { - 'I', 'N', 'F', 'O', ':', - 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', - SIMULATE_VERSION_MAJOR, -# ifdef SIMULATE_VERSION_MINOR - '.', SIMULATE_VERSION_MINOR, -# ifdef SIMULATE_VERSION_PATCH - '.', SIMULATE_VERSION_PATCH, -# ifdef SIMULATE_VERSION_TWEAK - '.', SIMULATE_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; -char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; - - - -#if !defined(__STDC__) && !defined(__clang__) -# if defined(_MSC_VER) || defined(__ibmxl__) || defined(__IBMC__) -# define C_VERSION "90" -# else -# define C_VERSION -# endif -#elif __STDC_VERSION__ > 201710L -# define C_VERSION "23" -#elif __STDC_VERSION__ >= 201710L -# define C_VERSION "17" -#elif __STDC_VERSION__ >= 201000L -# define C_VERSION "11" -#elif __STDC_VERSION__ >= 199901L -# define C_VERSION "99" -#else -# define C_VERSION "90" -#endif -const char* info_language_standard_default = - "INFO" ":" "standard_default[" C_VERSION "]"; - -const char* info_language_extensions_default = "INFO" ":" "extensions_default[" -#if (defined(__clang__) || defined(__GNUC__) || defined(__xlC__) || \ - defined(__TI_COMPILER_VERSION__)) && \ - !defined(__STRICT_ANSI__) - "ON" -#else - "OFF" -#endif -"]"; - -/*--------------------------------------------------------------------------*/ - -#ifdef ID_VOID_MAIN -void main() {} -#else -# if defined(__CLASSIC_C__) -int main(argc, argv) int argc; char *argv[]; -# else -int main(int argc, char* argv[]) -# endif -{ - int require = 0; - require += info_compiler[argc]; - require += info_platform[argc]; - require += info_arch[argc]; -#ifdef COMPILER_VERSION_MAJOR - require += info_version[argc]; -#endif -#ifdef COMPILER_VERSION_INTERNAL - require += info_version_internal[argc]; -#endif -#ifdef SIMULATE_ID - require += info_simulate[argc]; -#endif -#ifdef SIMULATE_VERSION_MAJOR - require += info_simulate_version[argc]; -#endif -#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) - require += info_cray[argc]; -#endif - require += info_language_standard_default[argc]; - require += info_language_extensions_default[argc]; - (void)argv; - return require; -} -#endif diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o deleted file mode 100644 index 537fbf261a76f93972038901b25169a2bbc47274..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1712 zcmb_cJ!n%=6uz;wrbZJ52c@6^7pIWdlqyOfp;1&q+aW_FlnbM8Iw+;_kGKK=Uf`-Bi7 z0i(w>M)3$9aSYfwjIS!I=z&L%dbCZ%s}_<rdz)YvA0HYv+3-?QBs2c#UYr|Wo}&rIo+0dl*8pp+HUHwP5`=CXzCkY{+GmpJqe z^{C`F`qO(H&ZhmA8*Xd3;mQ8ix!yHi)SKvUv=;ePuiiAvzHGbqZMPz2J~uk&HP?%C zFpj>cWEaS(u`SOdcNQbasV}Tn(j%)}% za%=g<%2hfV+p)Y-w%K&7CC7AYYeHq3j_Fq$UcHnvJscZHO|QIOV!!2^ZpHK}vSL-u zw&RzK%bdY|vD}so84YqP%WHr6vB&z8_biVJmXgYhR3dPahISScM#@-BCg+Wb7peOc zS66bZgO^}XPkuYV^b_Do@J9iro4^>j6JVM&1pVam0j3v#QSfAdY0@6FmOm3y4i@8<*X7~Z$a`P`qk_SaKIb%|g!jTF5YI&NLI#U*ukag2`Ii@wwl*BF^ czusKnN(nfiDNW&k&T9$>)X)?TD9J>24 & 0x00FF) -# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) -# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) - -#elif defined(__BORLANDC__) -# define COMPILER_ID "Borland" - /* __BORLANDC__ = 0xVRR */ -# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) -# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) - -#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 -# define COMPILER_ID "Watcom" - /* __WATCOMC__ = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__WATCOMC__) -# define COMPILER_ID "OpenWatcom" - /* __WATCOMC__ = VVRP + 1100 */ -# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__SUNPRO_CC) -# define COMPILER_ID "SunPro" -# if __SUNPRO_CC >= 0x5100 - /* __SUNPRO_CC = 0xVRRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>12) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xFF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) -# else - /* __SUNPRO_CC = 0xVRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>8) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) -# endif - -#elif defined(__HP_aCC) -# define COMPILER_ID "HP" - /* __HP_aCC = VVRRPP */ -# define COMPILER_VERSION_MAJOR DEC(__HP_aCC/10000) -# define COMPILER_VERSION_MINOR DEC(__HP_aCC/100 % 100) -# define COMPILER_VERSION_PATCH DEC(__HP_aCC % 100) - -#elif defined(__DECCXX) -# define COMPILER_ID "Compaq" - /* __DECCXX_VER = VVRRTPPPP */ -# define COMPILER_VERSION_MAJOR DEC(__DECCXX_VER/10000000) -# define COMPILER_VERSION_MINOR DEC(__DECCXX_VER/100000 % 100) -# define COMPILER_VERSION_PATCH DEC(__DECCXX_VER % 10000) - -#elif defined(__IBMCPP__) && defined(__COMPILER_VER__) -# define COMPILER_ID "zOS" - /* __IBMCPP__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) - -#elif defined(__open_xl__) && defined(__clang__) -# define COMPILER_ID "IBMClang" -# define COMPILER_VERSION_MAJOR DEC(__open_xl_version__) -# define COMPILER_VERSION_MINOR DEC(__open_xl_release__) -# define COMPILER_VERSION_PATCH DEC(__open_xl_modification__) -# define COMPILER_VERSION_TWEAK DEC(__open_xl_ptf_fix_level__) - - -#elif defined(__ibmxl__) && defined(__clang__) -# define COMPILER_ID "XLClang" -# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) -# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) -# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) -# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) - - -#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ >= 800 -# define COMPILER_ID "XL" - /* __IBMCPP__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) - -#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ < 800 -# define COMPILER_ID "VisualAge" - /* __IBMCPP__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) - -#elif defined(__NVCOMPILER) -# define COMPILER_ID "NVHPC" -# define COMPILER_VERSION_MAJOR DEC(__NVCOMPILER_MAJOR__) -# define COMPILER_VERSION_MINOR DEC(__NVCOMPILER_MINOR__) -# if defined(__NVCOMPILER_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__NVCOMPILER_PATCHLEVEL__) -# endif - -#elif defined(__PGI) -# define COMPILER_ID "PGI" -# define COMPILER_VERSION_MAJOR DEC(__PGIC__) -# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) -# if defined(__PGIC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) -# endif - -#elif defined(_CRAYC) -# define COMPILER_ID "Cray" -# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) -# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) - -#elif defined(__TI_COMPILER_VERSION__) -# define COMPILER_ID "TI" - /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ -# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) -# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) -# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) - -#elif defined(__CLANG_FUJITSU) -# define COMPILER_ID "FujitsuClang" -# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) -# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) -# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) -# define COMPILER_VERSION_INTERNAL_STR __clang_version__ - - -#elif defined(__FUJITSU) -# define COMPILER_ID "Fujitsu" -# if defined(__FCC_version__) -# define COMPILER_VERSION __FCC_version__ -# elif defined(__FCC_major__) -# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) -# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) -# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) -# endif -# if defined(__fcc_version) -# define COMPILER_VERSION_INTERNAL DEC(__fcc_version) -# elif defined(__FCC_VERSION) -# define COMPILER_VERSION_INTERNAL DEC(__FCC_VERSION) -# endif - - -#elif defined(__ghs__) -# define COMPILER_ID "GHS" -/* __GHS_VERSION_NUMBER = VVVVRP */ -# ifdef __GHS_VERSION_NUMBER -# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) -# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) -# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) -# endif - -#elif defined(__TASKING__) -# define COMPILER_ID "Tasking" - # define COMPILER_VERSION_MAJOR DEC(__VERSION__/1000) - # define COMPILER_VERSION_MINOR DEC(__VERSION__ % 100) -# define COMPILER_VERSION_INTERNAL DEC(__VERSION__) - -#elif defined(__SCO_VERSION__) -# define COMPILER_ID "SCO" - -#elif defined(__ARMCC_VERSION) && !defined(__clang__) -# define COMPILER_ID "ARMCC" -#if __ARMCC_VERSION >= 1000000 - /* __ARMCC_VERSION = VRRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#else - /* __ARMCC_VERSION = VRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#endif - - -#elif defined(__clang__) && defined(__apple_build_version__) -# define COMPILER_ID "AppleClang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif -# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) - -#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) -# define COMPILER_ID "ARMClang" - # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) -# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) - -#elif defined(__clang__) -# define COMPILER_ID "Clang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif - -#elif defined(__LCC__) && (defined(__GNUC__) || defined(__GNUG__) || defined(__MCST__)) -# define COMPILER_ID "LCC" -# define COMPILER_VERSION_MAJOR DEC(1) -# if defined(__LCC__) -# define COMPILER_VERSION_MINOR DEC(__LCC__- 100) -# endif -# if defined(__LCC_MINOR__) -# define COMPILER_VERSION_PATCH DEC(__LCC_MINOR__) -# endif -# if defined(__GNUC__) && defined(__GNUC_MINOR__) -# define SIMULATE_ID "GNU" -# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) -# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) -# if defined(__GNUC_PATCHLEVEL__) -# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif -# endif - -#elif defined(__GNUC__) || defined(__GNUG__) -# define COMPILER_ID "GNU" -# if defined(__GNUC__) -# define COMPILER_VERSION_MAJOR DEC(__GNUC__) -# else -# define COMPILER_VERSION_MAJOR DEC(__GNUG__) -# endif -# if defined(__GNUC_MINOR__) -# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) -# endif -# if defined(__GNUC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif - -#elif defined(_MSC_VER) -# define COMPILER_ID "MSVC" - /* _MSC_VER = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) -# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) -# if defined(_MSC_FULL_VER) -# if _MSC_VER >= 1400 - /* _MSC_FULL_VER = VVRRPPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) -# else - /* _MSC_FULL_VER = VVRRPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) -# endif -# endif -# if defined(_MSC_BUILD) -# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) -# endif - -#elif defined(_ADI_COMPILER) -# define COMPILER_ID "ADSP" -#if defined(__VERSIONNUM__) - /* __VERSIONNUM__ = 0xVVRRPPTT */ -# define COMPILER_VERSION_MAJOR DEC(__VERSIONNUM__ >> 24 & 0xFF) -# define COMPILER_VERSION_MINOR DEC(__VERSIONNUM__ >> 16 & 0xFF) -# define COMPILER_VERSION_PATCH DEC(__VERSIONNUM__ >> 8 & 0xFF) -# define COMPILER_VERSION_TWEAK DEC(__VERSIONNUM__ & 0xFF) -#endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# define COMPILER_ID "IAR" -# if defined(__VER__) && defined(__ICCARM__) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) -# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) -# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__) || defined(__ICCSTM8__)) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) -# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) -# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# endif - - -/* These compilers are either not known or too old to define an - identification macro. Try to identify the platform and guess that - it is the native compiler. */ -#elif defined(__hpux) || defined(__hpua) -# define COMPILER_ID "HP" - -#else /* unknown compiler */ -# define COMPILER_ID "" -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; -#ifdef SIMULATE_ID -char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; -#endif - -#ifdef __QNXNTO__ -char const* qnxnto = "INFO" ":" "qnxnto[]"; -#endif - -#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) -char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; -#endif - -#define STRINGIFY_HELPER(X) #X -#define STRINGIFY(X) STRINGIFY_HELPER(X) - -/* Identify known platforms by name. */ -#if defined(__linux) || defined(__linux__) || defined(linux) -# define PLATFORM_ID "Linux" - -#elif defined(__MSYS__) -# define PLATFORM_ID "MSYS" - -#elif defined(__CYGWIN__) -# define PLATFORM_ID "Cygwin" - -#elif defined(__MINGW32__) -# define PLATFORM_ID "MinGW" - -#elif defined(__APPLE__) -# define PLATFORM_ID "Darwin" - -#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) -# define PLATFORM_ID "Windows" - -#elif defined(__FreeBSD__) || defined(__FreeBSD) -# define PLATFORM_ID "FreeBSD" - -#elif defined(__NetBSD__) || defined(__NetBSD) -# define PLATFORM_ID "NetBSD" - -#elif defined(__OpenBSD__) || defined(__OPENBSD) -# define PLATFORM_ID "OpenBSD" - -#elif defined(__sun) || defined(sun) -# define PLATFORM_ID "SunOS" - -#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) -# define PLATFORM_ID "AIX" - -#elif defined(__hpux) || defined(__hpux__) -# define PLATFORM_ID "HP-UX" - -#elif defined(__HAIKU__) -# define PLATFORM_ID "Haiku" - -#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) -# define PLATFORM_ID "BeOS" - -#elif defined(__QNX__) || defined(__QNXNTO__) -# define PLATFORM_ID "QNX" - -#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) -# define PLATFORM_ID "Tru64" - -#elif defined(__riscos) || defined(__riscos__) -# define PLATFORM_ID "RISCos" - -#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) -# define PLATFORM_ID "SINIX" - -#elif defined(__UNIX_SV__) -# define PLATFORM_ID "UNIX_SV" - -#elif defined(__bsdos__) -# define PLATFORM_ID "BSDOS" - -#elif defined(_MPRAS) || defined(MPRAS) -# define PLATFORM_ID "MP-RAS" - -#elif defined(__osf) || defined(__osf__) -# define PLATFORM_ID "OSF1" - -#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) -# define PLATFORM_ID "SCO_SV" - -#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) -# define PLATFORM_ID "ULTRIX" - -#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) -# define PLATFORM_ID "Xenix" - -#elif defined(__WATCOMC__) -# if defined(__LINUX__) -# define PLATFORM_ID "Linux" - -# elif defined(__DOS__) -# define PLATFORM_ID "DOS" - -# elif defined(__OS2__) -# define PLATFORM_ID "OS2" - -# elif defined(__WINDOWS__) -# define PLATFORM_ID "Windows3x" - -# elif defined(__VXWORKS__) -# define PLATFORM_ID "VxWorks" - -# else /* unknown platform */ -# define PLATFORM_ID -# endif - -#elif defined(__INTEGRITY) -# if defined(INT_178B) -# define PLATFORM_ID "Integrity178" - -# else /* regular Integrity */ -# define PLATFORM_ID "Integrity" -# endif - -# elif defined(_ADI_COMPILER) -# define PLATFORM_ID "ADSP" - -#else /* unknown platform */ -# define PLATFORM_ID - -#endif - -/* For windows compilers MSVC and Intel we can determine - the architecture of the compiler being used. This is because - the compilers do not have flags that can change the architecture, - but rather depend on which compiler is being used -*/ -#if defined(_WIN32) && defined(_MSC_VER) -# if defined(_M_IA64) -# define ARCHITECTURE_ID "IA64" - -# elif defined(_M_ARM64EC) -# define ARCHITECTURE_ID "ARM64EC" - -# elif defined(_M_X64) || defined(_M_AMD64) -# define ARCHITECTURE_ID "x64" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# elif defined(_M_ARM64) -# define ARCHITECTURE_ID "ARM64" - -# elif defined(_M_ARM) -# if _M_ARM == 4 -# define ARCHITECTURE_ID "ARMV4I" -# elif _M_ARM == 5 -# define ARCHITECTURE_ID "ARMV5I" -# else -# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) -# endif - -# elif defined(_M_MIPS) -# define ARCHITECTURE_ID "MIPS" - -# elif defined(_M_SH) -# define ARCHITECTURE_ID "SHx" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__WATCOMC__) -# if defined(_M_I86) -# define ARCHITECTURE_ID "I86" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# if defined(__ICCARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__ICCRX__) -# define ARCHITECTURE_ID "RX" - -# elif defined(__ICCRH850__) -# define ARCHITECTURE_ID "RH850" - -# elif defined(__ICCRL78__) -# define ARCHITECTURE_ID "RL78" - -# elif defined(__ICCRISCV__) -# define ARCHITECTURE_ID "RISCV" - -# elif defined(__ICCAVR__) -# define ARCHITECTURE_ID "AVR" - -# elif defined(__ICC430__) -# define ARCHITECTURE_ID "MSP430" - -# elif defined(__ICCV850__) -# define ARCHITECTURE_ID "V850" - -# elif defined(__ICC8051__) -# define ARCHITECTURE_ID "8051" - -# elif defined(__ICCSTM8__) -# define ARCHITECTURE_ID "STM8" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__ghs__) -# if defined(__PPC64__) -# define ARCHITECTURE_ID "PPC64" - -# elif defined(__ppc__) -# define ARCHITECTURE_ID "PPC" - -# elif defined(__ARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__x86_64__) -# define ARCHITECTURE_ID "x64" - -# elif defined(__i386__) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__TI_COMPILER_VERSION__) -# if defined(__TI_ARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__MSP430__) -# define ARCHITECTURE_ID "MSP430" - -# elif defined(__TMS320C28XX__) -# define ARCHITECTURE_ID "TMS320C28x" - -# elif defined(__TMS320C6X__) || defined(_TMS320C6X) -# define ARCHITECTURE_ID "TMS320C6x" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -# elif defined(__ADSPSHARC__) -# define ARCHITECTURE_ID "SHARC" - -# elif defined(__ADSPBLACKFIN__) -# define ARCHITECTURE_ID "Blackfin" - -#elif defined(__TASKING__) - -# if defined(__CTC__) || defined(__CPTC__) -# define ARCHITECTURE_ID "TriCore" - -# elif defined(__CMCS__) -# define ARCHITECTURE_ID "MCS" - -# elif defined(__CARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__CARC__) -# define ARCHITECTURE_ID "ARC" - -# elif defined(__C51__) -# define ARCHITECTURE_ID "8051" - -# elif defined(__CPCP__) -# define ARCHITECTURE_ID "PCP" - -# else -# define ARCHITECTURE_ID "" -# endif - -#else -# define ARCHITECTURE_ID -#endif - -/* Convert integer to decimal digit literals. */ -#define DEC(n) \ - ('0' + (((n) / 10000000)%10)), \ - ('0' + (((n) / 1000000)%10)), \ - ('0' + (((n) / 100000)%10)), \ - ('0' + (((n) / 10000)%10)), \ - ('0' + (((n) / 1000)%10)), \ - ('0' + (((n) / 100)%10)), \ - ('0' + (((n) / 10)%10)), \ - ('0' + ((n) % 10)) - -/* Convert integer to hex digit literals. */ -#define HEX(n) \ - ('0' + ((n)>>28 & 0xF)), \ - ('0' + ((n)>>24 & 0xF)), \ - ('0' + ((n)>>20 & 0xF)), \ - ('0' + ((n)>>16 & 0xF)), \ - ('0' + ((n)>>12 & 0xF)), \ - ('0' + ((n)>>8 & 0xF)), \ - ('0' + ((n)>>4 & 0xF)), \ - ('0' + ((n) & 0xF)) - -/* Construct a string literal encoding the version number. */ -#ifdef COMPILER_VERSION -char const* info_version = "INFO" ":" "compiler_version[" COMPILER_VERSION "]"; - -/* Construct a string literal encoding the version number components. */ -#elif defined(COMPILER_VERSION_MAJOR) -char const info_version[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', - COMPILER_VERSION_MAJOR, -# ifdef COMPILER_VERSION_MINOR - '.', COMPILER_VERSION_MINOR, -# ifdef COMPILER_VERSION_PATCH - '.', COMPILER_VERSION_PATCH, -# ifdef COMPILER_VERSION_TWEAK - '.', COMPILER_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct a string literal encoding the internal version number. */ -#ifdef COMPILER_VERSION_INTERNAL -char const info_version_internal[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', - 'i','n','t','e','r','n','a','l','[', - COMPILER_VERSION_INTERNAL,']','\0'}; -#elif defined(COMPILER_VERSION_INTERNAL_STR) -char const* info_version_internal = "INFO" ":" "compiler_version_internal[" COMPILER_VERSION_INTERNAL_STR "]"; -#endif - -/* Construct a string literal encoding the version number components. */ -#ifdef SIMULATE_VERSION_MAJOR -char const info_simulate_version[] = { - 'I', 'N', 'F', 'O', ':', - 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', - SIMULATE_VERSION_MAJOR, -# ifdef SIMULATE_VERSION_MINOR - '.', SIMULATE_VERSION_MINOR, -# ifdef SIMULATE_VERSION_PATCH - '.', SIMULATE_VERSION_PATCH, -# ifdef SIMULATE_VERSION_TWEAK - '.', SIMULATE_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; -char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; - - - -#if defined(__INTEL_COMPILER) && defined(_MSVC_LANG) && _MSVC_LANG < 201403L -# if defined(__INTEL_CXX11_MODE__) -# if defined(__cpp_aggregate_nsdmi) -# define CXX_STD 201402L -# else -# define CXX_STD 201103L -# endif -# else -# define CXX_STD 199711L -# endif -#elif defined(_MSC_VER) && defined(_MSVC_LANG) -# define CXX_STD _MSVC_LANG -#else -# define CXX_STD __cplusplus -#endif - -const char* info_language_standard_default = "INFO" ":" "standard_default[" -#if CXX_STD > 202002L - "23" -#elif CXX_STD > 201703L - "20" -#elif CXX_STD >= 201703L - "17" -#elif CXX_STD >= 201402L - "14" -#elif CXX_STD >= 201103L - "11" -#else - "98" -#endif -"]"; - -const char* info_language_extensions_default = "INFO" ":" "extensions_default[" -#if (defined(__clang__) || defined(__GNUC__) || defined(__xlC__) || \ - defined(__TI_COMPILER_VERSION__)) && \ - !defined(__STRICT_ANSI__) - "ON" -#else - "OFF" -#endif -"]"; - -/*--------------------------------------------------------------------------*/ - -int main(int argc, char* argv[]) -{ - int require = 0; - require += info_compiler[argc]; - require += info_platform[argc]; - require += info_arch[argc]; -#ifdef COMPILER_VERSION_MAJOR - require += info_version[argc]; -#endif -#ifdef COMPILER_VERSION_INTERNAL - require += info_version_internal[argc]; -#endif -#ifdef SIMULATE_ID - require += info_simulate[argc]; -#endif -#ifdef SIMULATE_VERSION_MAJOR - require += info_simulate_version[argc]; -#endif -#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) - require += info_cray[argc]; -#endif - require += info_language_standard_default[argc]; - require += info_language_extensions_default[argc]; - (void)argv; - return require; -} diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o deleted file mode 100644 index aacee10dfddc5e3114bb159eee743a03c1b12206..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1712 zcmb_cJ#5oZ5PqShqzWV;F@P#TBo?M9PO7SaA|+}-fULGdhCoz3ti(wzIgaHx(6I;x z1_sK?QX~e%#7HI>vr!hr7?|3DoiY%1^Z6O|W@vfbVNlAN;TuDUd5eWoVTAL%&&wQohkn#@ z7xSq-j;d+D)t1v9ZFqXVP40J%U+PcIH{OeU>eqCQsxLdv1IwvNsTapLka_697F8IR1n^Z*cJ-l}YwvWy2!N#ELP!jS<=b%*cH!^r6J`FC4Zht{^ zzsAJjAR)R@A)ZAe`NM;S?e4sFu)LqhccYQ{*#1A{s8`rm?EJ5ueawaVcRtL>&$m`@ ztX-vFW7(!xDY&j}uGogt*bqU+wGF@C@|u;R;o-M&)bOgC753Y{;nWPTCTnKh=-7Vc z$}(qgUQDNLfkwmJ+Umw1e(Z_)ySp2^@ z#c`j+Ps4(Dam47{VX1)UfyFv=G-sR%Pq{mU!DV&cx`aV;sv}u}j^j6kad6amf6w`E zuq1DxRR1GDLcC-=%WFPoe1Y)`!ei?{C5*wsqwOppCjtl9ou4RJe%qk(9hUIXb hB0fW6ys-VIyU6WQZ~(Ik!U4=E2nSG85Dp-5 search starts here: - /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include - /Library/Developer/CommandLineTools/usr/include - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory) -End of search list. -Linking C executable cmTC_5913a -/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_5913a.dir/link.txt --verbose=1 -/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names -v -Wl,-v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -o cmTC_5913a -Apple clang version 13.1.6 (clang-1316.0.21.2.5) -Target: arm64-apple-darwin21.6.0 -Thread model: posix -InstalledDir: /Library/Developer/CommandLineTools/usr/bin - "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_5913a -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a -@(#)PROGRAM:ld PROJECT:ld64-764 -BUILD 11:22:55 Apr 28 2022 -configured to support archs: armv6 armv7 armv7s arm64 arm64e arm64_32 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em -Library search paths: - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib -Framework search paths: - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/ - - - -Parsed C implicit include dir info from above output: rv=done - found start of include info - found start of implicit include info - add: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - add: [/Library/Developer/CommandLineTools/usr/include] - end of search list found - collapse include dir [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] ==> [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - collapse include dir [/Library/Developer/CommandLineTools/usr/include] ==> [/Library/Developer/CommandLineTools/usr/include] - implicit include dirs: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include] - - -Parsed C implicit link information from above output: - link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] - ignore line: [Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-LcrFWX] - ignore line: [] - ignore line: [Run Build Command(s):/usr/bin/make -f Makefile cmTC_5913a/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_5913a.dir/build.make CMakeFiles/cmTC_5913a.dir/build] - ignore line: [Building C object CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o] - ignore line: [/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl -v -MD -MT CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -MF CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o.d -o CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCCompilerABI.c] - ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] - ignore line: [Target: arm64-apple-darwin21.6.0] - ignore line: [Thread model: posix] - ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] - ignore line: [clang: warning: -Wl -v: 'linker' input unused [-Wunused-command-line-argument]] - ignore line: [ "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCCompilerABI.c -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-LcrFWX -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -x c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCCompilerABI.c] - ignore line: [clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0] - ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include"] - ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks"] - ignore line: [#include "..." search starts here:] - ignore line: [#include <...> search starts here:] - ignore line: [ /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - ignore line: [ /Library/Developer/CommandLineTools/usr/include] - ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory)] - ignore line: [End of search list.] - ignore line: [Linking C executable cmTC_5913a] - ignore line: [/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_5913a.dir/link.txt --verbose=1] - ignore line: [/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl -search_paths_first -Wl -headerpad_max_install_names -v -Wl -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -o cmTC_5913a ] - ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] - ignore line: [Target: arm64-apple-darwin21.6.0] - ignore line: [Thread model: posix] - ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] - link line: [ "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_5913a -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - arg [/Library/Developer/CommandLineTools/usr/bin/ld] ==> ignore - arg [-demangle] ==> ignore - arg [-lto_library] ==> ignore, skip following value - arg [/Library/Developer/CommandLineTools/usr/lib/libLTO.dylib] ==> skip value of -lto_library - arg [-dynamic] ==> ignore - arg [-arch] ==> ignore - arg [arm64] ==> ignore - arg [-platform_version] ==> ignore - arg [macos] ==> ignore - arg [12.0.0] ==> ignore - arg [12.3] ==> ignore - arg [-syslibroot] ==> ignore - arg [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk] ==> ignore - arg [-o] ==> ignore - arg [cmTC_5913a] ==> ignore - arg [-search_paths_first] ==> ignore - arg [-headerpad_max_install_names] ==> ignore - arg [-v] ==> ignore - arg [CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o] ==> ignore - arg [-lSystem] ==> lib [System] - arg [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] ==> lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - Library search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - Framework search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] - remove lib [System] - remove lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - collapse library dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - collapse framework dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] - implicit libs: [] - implicit objs: [] - implicit dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - implicit fwks: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] - - -Detecting CXX compiler ABI info compiled with the following output: -Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C - -Run Build Command(s):/usr/bin/make -f Makefile cmTC_48750/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_48750.dir/build.make CMakeFiles/cmTC_48750.dir/build -Building CXX object CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl,-v -MD -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -MF CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp -Apple clang version 13.1.6 (clang-1316.0.21.2.5) -Target: arm64-apple-darwin21.6.0 -Thread model: posix -InstalledDir: /Library/Developer/CommandLineTools/usr/bin -clang: warning: -Wl,-v: 'linker' input unused [-Wunused-command-line-argument] - "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -D _DARWIN_USE_64_BIT_INODE=1 -D _LARGEFILE_SOURCE -D _FILE_OFFSET_BITS=64 -D BUILDING_NODE_EXTENSION -stdlib=libc++ -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdeprecated-macro -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fno-cxx-modules -fcxx-exceptions -fexceptions -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -x c++ /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp -clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0 -ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include" -ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks" -#include "..." search starts here: -#include <...> search starts here: - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 - /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include - /Library/Developer/CommandLineTools/usr/include - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory) -End of search list. -Linking CXX executable cmTC_48750 -/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_48750.dir/link.txt --verbose=1 -/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names -v -Wl,-v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_48750 -Apple clang version 13.1.6 (clang-1316.0.21.2.5) -Target: arm64-apple-darwin21.6.0 -Thread model: posix -InstalledDir: /Library/Developer/CommandLineTools/usr/bin - "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_48750 -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -lc++ -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a -@(#)PROGRAM:ld PROJECT:ld64-764 -BUILD 11:22:55 Apr 28 2022 -configured to support archs: armv6 armv7 armv7s arm64 arm64e arm64_32 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em -Library search paths: - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib -Framework search paths: - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/ - - - -Parsed CXX implicit include dir info from above output: rv=done - found start of include info - found start of implicit include info - add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] - add: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - add: [/Library/Developer/CommandLineTools/usr/include] - end of search list found - collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] - collapse include dir [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] ==> [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - collapse include dir [/Library/Developer/CommandLineTools/usr/include] ==> [/Library/Developer/CommandLineTools/usr/include] - implicit include dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1;/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include] - - -Parsed CXX implicit link information from above output: - link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] - ignore line: [Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C] - ignore line: [] - ignore line: [Run Build Command(s):/usr/bin/make -f Makefile cmTC_48750/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_48750.dir/build.make CMakeFiles/cmTC_48750.dir/build] - ignore line: [Building CXX object CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o] - ignore line: [/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl -v -MD -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -MF CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp] - ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] - ignore line: [Target: arm64-apple-darwin21.6.0] - ignore line: [Thread model: posix] - ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] - ignore line: [clang: warning: -Wl -v: 'linker' input unused [-Wunused-command-line-argument]] - ignore line: [ "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -D _DARWIN_USE_64_BIT_INODE=1 -D _LARGEFILE_SOURCE -D _FILE_OFFSET_BITS=64 -D BUILDING_NODE_EXTENSION -stdlib=libc++ -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdeprecated-macro -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fno-cxx-modules -fcxx-exceptions -fexceptions -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -x c++ /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp] - ignore line: [clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0] - ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include"] - ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks"] - ignore line: [#include "..." search starts here:] - ignore line: [#include <...> search starts here:] - ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] - ignore line: [ /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - ignore line: [ /Library/Developer/CommandLineTools/usr/include] - ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory)] - ignore line: [End of search list.] - ignore line: [Linking CXX executable cmTC_48750] - ignore line: [/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_48750.dir/link.txt --verbose=1] - ignore line: [/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl -search_paths_first -Wl -headerpad_max_install_names -v -Wl -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_48750 ] - ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] - ignore line: [Target: arm64-apple-darwin21.6.0] - ignore line: [Thread model: posix] - ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] - link line: [ "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_48750 -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -lc++ -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - arg [/Library/Developer/CommandLineTools/usr/bin/ld] ==> ignore - arg [-demangle] ==> ignore - arg [-lto_library] ==> ignore, skip following value - arg [/Library/Developer/CommandLineTools/usr/lib/libLTO.dylib] ==> skip value of -lto_library - arg [-dynamic] ==> ignore - arg [-arch] ==> ignore - arg [arm64] ==> ignore - arg [-platform_version] ==> ignore - arg [macos] ==> ignore - arg [12.0.0] ==> ignore - arg [12.3] ==> ignore - arg [-syslibroot] ==> ignore - arg [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk] ==> ignore - arg [-o] ==> ignore - arg [cmTC_48750] ==> ignore - arg [-search_paths_first] ==> ignore - arg [-headerpad_max_install_names] ==> ignore - arg [-v] ==> ignore - arg [CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o] ==> ignore - arg [-lc++] ==> lib [c++] - arg [-lSystem] ==> lib [System] - arg [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] ==> lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - Library search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - Framework search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] - remove lib [System] - remove lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - collapse library dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - collapse framework dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] - implicit libs: [c++] - implicit objs: [] - implicit dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - implicit fwks: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] - - diff --git a/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache b/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache deleted file mode 100644 index 3dccd731..00000000 --- a/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache +++ /dev/null @@ -1 +0,0 @@ -# This file is generated by cmake for dependency checking of the CMakeCache.txt file diff --git a/languages/c/templates/sdk/cmake/CopySymlink.cmake b/languages/c/templates/sdk/cmake/CopySymlink.cmake deleted file mode 100644 index b25a5e22..00000000 --- a/languages/c/templates/sdk/cmake/CopySymlink.cmake +++ /dev/null @@ -1,17 +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 - -file(COPY "${LIBRARY}" DESTINATION "${DESTINATION}" FOLLOW_SYMLINK_CHAIN) diff --git a/languages/c/templates/sdk/cmake/HelperFunctions.cmake b/languages/c/templates/sdk/cmake/HelperFunctions.cmake index bbd7ce65..b3647c16 100644 --- a/languages/c/templates/sdk/cmake/HelperFunctions.cmake +++ b/languages/c/templates/sdk/cmake/HelperFunctions.cmake @@ -72,8 +72,8 @@ function(InstallHeaders) endfunction(InstallHeaders) function(InstallLibraries) - set(optionsArgs SHARED) - set(oneValueArgs TARGET DESTINATION) + set(optionsArgs SHARED STATIC) + set(oneValueArgs TARGET DESTINATION LIBDIR) set(multiValueArgs LIBRARIES) cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) @@ -92,11 +92,11 @@ function(InstallLibraries) TARGET ${Argument_TARGET} POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib - COMMAND ${CMAKE_COMMAND} -D "LIBRARY=${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR}" -D "DESTINATION=${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib" -P ${CMAKE_SOURCE_DIR}/cmake/CopySymlink.cmake - COMMAND ${CMAKE_COMMAND} -D "LIBRARY=${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so" -D "DESTINATION=${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib" -P ${CMAKE_SOURCE_DIR}/cmake/CopySymlink.cmake + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_LIBDIR}/lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + COMMAND ${CMAKE_COMMAND} -E create_symlink lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR} + COMMAND ${CMAKE_COMMAND} -E create_symlink lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/lib${LIBRARY}.so ) - else() + elseif (Argument_STATIC) add_custom_command( TARGET ${Argument_TARGET} POST_BUILD @@ -119,13 +119,18 @@ function(InstallCMakeConfigs) message(FATAL_ERROR "Unknown keywords given to InstallCMakeConfigs(): \"${Argument_UNPARSED_ARGUMENTS}\"") endif() if (Argument_TARGET) + if (${CMAKE_VERSION} VERSION_LESS "3.25.0") + set(EXPORT_CONFIG_PATH "lib/cmake/${Argument_TARGET}") + else () + set(EXPORT_CONFIG_PATH "*") + endif () add_custom_command( TARGET ${Argument_TARGET} POST_BUILD COMMENT "=================== Installing CMakeConfigs ======================" COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}Config*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Export/lib/cmake/${Argument_TARGET}/${Argument_TARGET}Targets*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Export/${EXPORT_CONFIG_PATH}/${Argument_TARGET}Targets*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} ) if (EXISTS ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}.pc) add_custom_command( diff --git a/languages/c/templates/sdk/cmake/project.cmake.in b/languages/c/templates/sdk/cmake/project.cmake.in index 0855ca12..eca32f8c 100644 --- a/languages/c/templates/sdk/cmake/project.cmake.in +++ b/languages/c/templates/sdk/cmake/project.cmake.in @@ -27,4 +27,9 @@ if (NOT DEFINED CMAKE_PREFIX_PATH) set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) endif() +if (FIREBOLT_ENABLE_STATIC_LIB) + set(FIREBOLT_LIBRARY_TYPE STATIC) +else () + set(FIREBOLT_LIBRARY_TYPE SHARED) +endif () diff --git a/languages/c/templates/sdk/include/Firebolt.h b/languages/c/templates/sdk/include/Firebolt.h new file mode 100644 index 00000000..2223bad3 --- /dev/null +++ b/languages/c/templates/sdk/include/Firebolt.h @@ -0,0 +1,65 @@ +/* + * 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 + */ + +#ifndef _FIREBOLT_H +#define _FIREBOLT_H + +#include "Error.h" +#include "Types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Intitialize the Firebolt SDK + * + * @param configLine JSON String with configuration options + * + * CONFIG Format: + * { + * "waitTime": 1000, + * "logLevel": "Info", + * "workerPool":{ + * "queueSize": 8, + * "threadCount": 3 + * }, + * "wsUrl": "ws://127.0.0.1:9998" + * } + * + * + * @return FireboltSDKErrorNone if success, appropriate error otherwise. + * + */ +uint32_t FireboltSDK_Initialize(char* configLine); + + +/** + * @brief Deintitialize the Firebolt SDK + * + * @return FireboltSDKErrorNone if success, appropriate error otherwise. + * + */ +uint32_t FireboltSDK_Deinitialize(void); + +#ifdef __cplusplus +} +#endif + + +#endif // _FIREBOLT_H diff --git a/languages/c/templates/sdk/include/Types.h b/languages/c/templates/sdk/include/Types.h index e7456cdd..4fd16256 100644 --- a/languages/c/templates/sdk/include/Types.h +++ b/languages/c/templates/sdk/include/Types.h @@ -20,18 +20,12 @@ #define _FIREBOLT_TYPES_H #include +#include #ifdef __cplusplus extern "C" { #endif -typedef enum { - Test1, - Test2, - Test3, - Test4 -} TestEnum; - typedef void* FireboltTypes_StringHandle; const char* FireboltTypes_String(FireboltTypes_StringHandle handle); void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle); diff --git a/languages/c/templates/sdk/scripts/build.sh b/languages/c/templates/sdk/scripts/build.sh new file mode 100755 index 00000000..e9b01f20 --- /dev/null +++ b/languages/c/templates/sdk/scripts/build.sh @@ -0,0 +1,11 @@ +#!/bin/bash +SDK_PATH="." +if [ "$1" != "" ] +then + SDK_PATH=$1 + echo "inside ${1}" +fi +echo ${SDK_PATH} +rm -rf ${SDK_PATH}/build +cmake -B${SDK_PATH}/build -S${SDK_PATH} -DSYSROOT_PATH=${SYSROOT_PATH} +cmake --build ${SDK_PATH}/build diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.cpp b/languages/c/templates/sdk/src/Accessor/Accessor.cpp index b4cada4b..e4a5df32 100644 --- a/languages/c/templates/sdk/src/Accessor/Accessor.cpp +++ b/languages/c/templates/sdk/src/Accessor/Accessor.cpp @@ -21,22 +21,22 @@ namespace FireboltSDK { Accessor* Accessor::_singleton = nullptr; - Accessor::Accessor() - : _threadCount(DefaultThreadCount) - , _queueSize(DefaultQueueSize) - , _workerPool() + + Accessor::Accessor(const string& configLine) + : _workerPool() , _transport(nullptr) + , _config() { _singleton = this; - Config config; - LoadConfigs(config); + _config.FromString(configLine); + + Logger::SetLogLevel(WPEFramework::Core::EnumerateType(_config.LogLevel.Value().c_str()).Value()); - Logger::SetLogLevel(WPEFramework::Core::EnumerateType(config.LogLevel.Value().c_str()).Value()); - FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Url = %s", config.Url.Value().c_str()); - CreateTransport(config.Url.Value(), config.WaitTime.Value()); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Url = %s", _config.WsUrl.Value().c_str()); + CreateTransport(_config.WsUrl.Value().c_str(), _config.WaitTime.Value()); CreateEventHandler(); - _workerPool = WPEFramework::Core::ProxyType::Create(_threadCount, WPEFramework::Core::Thread::DefaultStackSize(), _queueSize); + _workerPool = WPEFramework::Core::ProxyType::Create(_config.WorkerPool.ThreadCount.Value(), _config.WorkerPool.StackSize.Value(), _config.WorkerPool.QueueSize.Value()); WPEFramework::Core::WorkerPool::Assign(&(*_workerPool)); _workerPool->Run(); } @@ -50,23 +50,6 @@ namespace FireboltSDK { _singleton = nullptr; } - void Accessor::LoadConfigs(Config& config) - { - string prefixPath; - WPEFramework::Core::SystemInfo::GetEnvironment("OPENRPC_NATIVE_SDK_PREFIX", prefixPath); - string configFilePath = (prefixPath.empty() != true) ? - (prefixPath + '/' + Accessor::ConfigFile) : Accessor::ConfigFile; - WPEFramework::Core::File configFile(configFilePath); - - if (configFile.Open(true) == true) { - WPEFramework::Core::OptionalType error; - config.IElement::FromFile(configFile, error); - if (error.IsSet() == true) { - FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in reading config"); - } - } - } - uint32_t Accessor::CreateEventHandler() { Event::Instance().Configure(_transport); @@ -84,14 +67,14 @@ namespace FireboltSDK { return Event::Instance(); } - uint32_t Accessor::CreateTransport(const string& url, const uint32_t waitTime) + uint32_t Accessor::CreateTransport(const string& url, const uint32_t waitTime = DefaultWaitTime) { if (_transport != nullptr) { delete _transport; } _transport = new Transport(static_cast(url), waitTime); - if (WaitForLinkReady(_transport, DefaultWaitTime) != FireboltSDKErrorNone) { + if (WaitForLinkReady(_transport, waitTime) != FireboltSDKErrorNone) { delete _transport; _transport = nullptr; } diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.h b/languages/c/templates/sdk/src/Accessor/Accessor.h index 3e9b8784..f12dc51c 100644 --- a/languages/c/templates/sdk/src/Accessor/Accessor.h +++ b/languages/c/templates/sdk/src/Accessor/Accessor.h @@ -19,7 +19,6 @@ #pragma once #include "Module.h" -#include "Config.h" #include "WorkerPool.h" #include "Transport/Transport.h" #include "Event/Event.h" @@ -29,21 +28,69 @@ namespace FireboltSDK { class Accessor { private: static constexpr uint8_t JSONVersion = 2; - static constexpr const TCHAR* ConfigFile = _T("/etc/Firebolt/config.json"); - static constexpr uint32_t DefaultWaitTime = 1000; - static constexpr uint8_t DefaultQueueSize = 8; - static constexpr uint8_t DefaultThreadCount = 3; + + private: + //Singleton + Accessor(const string& configLine); public: + class EXTERNAL Config : public WPEFramework::Core::JSON::Container { + public: + Config(const Config&) = delete; + Config& operator=(const Config&) = delete; + + class WorkerPoolConfig : public WPEFramework::Core::JSON::Container { + public: + WorkerPoolConfig& operator=(const WorkerPoolConfig&); + + WorkerPoolConfig() + : WPEFramework::Core::JSON::Container() + , QueueSize(8) + , ThreadCount(3) + , StackSize(WPEFramework::Core::Thread::DefaultStackSize()) + { + Add("queueSize", &QueueSize); + Add("threadCount", &ThreadCount); + Add("stackSize", &StackSize); + } + + virtual ~WorkerPoolConfig() = default; + + public: + WPEFramework::Core::JSON::DecUInt32 QueueSize; + WPEFramework::Core::JSON::DecUInt32 ThreadCount; + WPEFramework::Core::JSON::DecUInt32 StackSize; + }; + + + Config() + : WPEFramework::Core::JSON::Container() + , WaitTime(1000) + , LogLevel(_T("Info")) + , WorkerPool() + , WsUrl(_T("ws://127.0.0.1:9998")) + { + Add(_T("waitTime"), &WaitTime); + Add(_T("logLevel"), &LogLevel); + Add(_T("workerPool"), &WorkerPool); + Add(_T("wsUrl"), &WsUrl); + } + + public: + WPEFramework::Core::JSON::DecUInt32 WaitTime; + WPEFramework::Core::JSON::String LogLevel; + WorkerPoolConfig WorkerPool; + WPEFramework::Core::JSON::String WsUrl; + }; + Accessor(const Accessor&) = delete; Accessor& operator= (const Accessor&) = delete; - - Accessor(); + Accessor() = delete; ~Accessor(); - static Accessor& Instance() + static Accessor& Instance(const string& configLine = "") { - static Accessor *instance = new Accessor(); + static Accessor *instance = new Accessor(configLine); ASSERT(instance != nullptr); return *instance; } @@ -56,24 +103,20 @@ namespace FireboltSDK { delete _singleton; } } + Event& GetEventManager(); + Transport* GetTransport(); + private: uint32_t CreateEventHandler(); uint32_t DestroyEventHandler(); - Event& GetEventManager(); - uint32_t CreateTransport(const string& url, const uint32_t waitTime); uint32_t DestroyTransport(); - Transport* GetTransport(); uint32_t WaitForLinkReady(Transport* transport, const uint32_t waitTime); private: - void LoadConfigs(Config& config); - - private: - uint8_t _threadCount; - uint8_t _queueSize; WPEFramework::Core::ProxyType _workerPool; Transport* _transport; static Accessor* _singleton; + Config _config; }; } diff --git a/languages/c/templates/sdk/src/Accessor/WorkerPool.h b/languages/c/templates/sdk/src/Accessor/WorkerPool.h index 521ccc65..69005a5e 100644 --- a/languages/c/templates/sdk/src/Accessor/WorkerPool.h +++ b/languages/c/templates/sdk/src/Accessor/WorkerPool.h @@ -69,4 +69,34 @@ namespace FireboltSDK { Dispatcher _dispatcher; }; + class Worker : public WPEFramework::Core::IDispatch { + public: + typedef std::function Dispatcher; + + protected: + Worker(const Dispatcher& dispatcher, const void* userData) + : _dispatcher(dispatcher) + , _userData(userData) + { + } + + public: + Worker() = delete; + Worker(const Worker&) = delete; + Worker& operator=(const Worker&) = delete; + + ~Worker() = default; + + public: + static WPEFramework::Core::ProxyType Create(const Dispatcher& dispatcher, const void* userData); + + void Dispatch() override + { + _dispatcher(_userData); + } + + private: + Dispatcher _dispatcher; + const void* _userData; + }; } diff --git a/languages/c/templates/sdk/src/CMakeLists.txt b/languages/c/templates/sdk/src/CMakeLists.txt index c411582a..2f00bdf1 100644 --- a/languages/c/templates/sdk/src/CMakeLists.txt +++ b/languages/c/templates/sdk/src/CMakeLists.txt @@ -20,29 +20,30 @@ project(FireboltSDK) project_version(1.0.0) set(TARGET ${PROJECT_NAME}) message("Setup ${TARGET} v${PROJECT_VERSION}") +file(GLOB GENERATED_SOURCES "${GENERATED_CODE_PATH}/src/*.cpp") -add_library(${TARGET} SHARED - Types.cpp - Module.cpp +file(GLOB SOURCES *.cpp) +add_library(${TARGET} ${FIREBOLT_LIBRARY_TYPE} + ${SOURCES} Logger/Logger.cpp Transport/Transport.cpp Accessor/Accessor.cpp - Event/Event.cpp) + Event/Event.cpp +) set(CMAKE_POSITION_INDEPENDENT_CODE ON) -find_package(${NAMESPACE}Core CONFIG REQUIRED) find_package(${NAMESPACE}WebSocket CONFIG REQUIRED) target_link_libraries(${TARGET} PUBLIC - ${NAMESPACE}Core::${NAMESPACE}Core ${NAMESPACE}WebSocket::${NAMESPACE}WebSocket ) target_include_directories(${TARGET} PRIVATE $ - $ + $ + $ $ ) @@ -66,21 +67,13 @@ InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTIN InstallHeaders(TARGET ${TARGET} EXCLUDE_ROOT_DIR HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} SOURCE ${GENERATED_CODE_PATH}/include DESTINATION ${FIREBOLT_NAMESPACE}/generated) InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} - SOURCE ${CMAKE_SOURCE_DIR}/include DESTINATION ${FIREBOLT_NAMESPACE}) + SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../include DESTINATION ${FIREBOLT_NAMESPACE}) -InstallLibraries(TARGET ${TARGET} SHARED LIBRARIES ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallLibraries(TARGET ${TARGET} ${FIREBOLT_LIBRARY_TYPE} LIBDIR ${LIBDIR} LIBRARIES ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) InstallCMakeConfig(TARGETS ${TARGET}) InstallPackageConfig(TARGETS ${TARGET} DESCRIPTION "Firebolt SDK Library") InstallCMakeConfigs(TARGET ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) -add_custom_command( - TARGET ${TARGET} - POST_BUILD - COMMENT "=================== Installing JsonConfig ======================" - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/etc/${FIREBOLT_NAMESPACE} - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/config/${TARGET}.json ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/etc/${FIREBOLT_NAMESPACE}/config.json -) - add_custom_command( TARGET ${TARGET} POST_BUILD @@ -89,5 +82,3 @@ add_custom_command( COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/cmake/*.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} ) - -include(Config.cmake) diff --git a/languages/c/templates/sdk/src/Config.cmake b/languages/c/templates/sdk/src/Config.cmake deleted file mode 100644 index a420ce32..00000000 --- a/languages/c/templates/sdk/src/Config.cmake +++ /dev/null @@ -1,34 +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 - -set(SERVER_PORT 9998 CACHE STRING "The port of the server") -set(SERVER_ADDRESS "127.0.0.1" CACHE STRING "The address of the server") - - #[[ ================================ Add additional config above this line ================================ ]] - - -find_package(ConfigGenerator REQUIRED) - -write_config( - SKIP_COMPARE - SKIP_CLASSNAME - SKIP_LOCATOR - DISABLE_LEGACY_GENERATOR - CUSTOM_PARAMS_WHITELIST "${CMAKE_CURRENT_LIST_DIR}/Params.config" - INSTALL_PATH "${CMAKE_INSTALL_PREFIX}/../etc/" - INSTALL_NAME "config.json" -) - diff --git a/languages/c/templates/sdk/src/Event/Event.cpp b/languages/c/templates/sdk/src/Event/Event.cpp index 69b448f6..5e98a36f 100644 --- a/languages/c/templates/sdk/src/Event/Event.cpp +++ b/languages/c/templates/sdk/src/Event/Event.cpp @@ -22,8 +22,7 @@ namespace FireboltSDK { Event* Event::_singleton = nullptr; Event::Event() - : _id(0) - , _eventMap() + : _eventMap() , _adminLock() , _transport(nullptr) { @@ -61,9 +60,9 @@ namespace FireboltSDK { _transport->SetEventHandler(this); } - uint32_t Event::Unsubscribe(const string& eventName, const uint32_t id) + uint32_t Event::Unsubscribe(const string& eventName, void* usercb) { - uint32_t status = Revoke(eventName, id); + uint32_t status = Revoke(eventName, usercb); if (status == FireboltSDKErrorNone) { if (_transport != nullptr) { @@ -93,26 +92,26 @@ namespace FireboltSDK { _adminLock.Lock(); EventMap::iterator eventIndex = _eventMap.find(eventName); if (eventIndex != _eventMap.end()) { - IdMap::iterator idIndex = eventIndex->second.begin(); - while(idIndex != eventIndex->second.end()) { + CallbackMap::iterator callbackIndex = eventIndex->second.begin(); + while(callbackIndex != eventIndex->second.end()) { State state; - if (idIndex->second.state != State::REVOKED) { - idIndex->second.state = State::EXECUTING; + if (callbackIndex->second.state != State::REVOKED) { + callbackIndex->second.state = State::EXECUTING; } - state = idIndex->second.state; + state = callbackIndex->second.state; _adminLock.Unlock(); if (state == State::EXECUTING) { - idIndex->second.lambda(idIndex->second.userdata, (jsonResponse->Result.Value())); + callbackIndex->second.lambda(callbackIndex->first, callbackIndex->second.userdata, (jsonResponse->Result.Value())); } _adminLock.Lock(); - if (idIndex->second.state == State::REVOKED) { - idIndex = eventIndex->second.erase(idIndex); + if (callbackIndex->second.state == State::REVOKED) { + callbackIndex = eventIndex->second.erase(callbackIndex); if (eventIndex->second.size() == 0) { _eventMap.erase(eventIndex); } } else { - idIndex->second.state = State::IDLE; - idIndex++; + callbackIndex->second.state = State::IDLE; + callbackIndex++; } } } @@ -121,19 +120,19 @@ namespace FireboltSDK { return FireboltSDKErrorNone;; } - uint32_t Event::Revoke(const string& eventName, const uint32_t id) + uint32_t Event::Revoke(const string& eventName, void* usercb) { uint32_t status = FireboltSDKErrorNone; _adminLock.Lock(); EventMap::iterator eventIndex = _eventMap.find(eventName); if (eventIndex != _eventMap.end()) { - IdMap::iterator idIndex = eventIndex->second.find(id); - if (idIndex->second.state != State::EXECUTING) { - if (idIndex != eventIndex->second.end()) { - eventIndex->second.erase(idIndex); + CallbackMap::iterator callbackIndex = eventIndex->second.find(usercb); + if (callbackIndex->second.state != State::EXECUTING) { + if (callbackIndex != eventIndex->second.end()) { + eventIndex->second.erase(callbackIndex); } } else { - idIndex->second.state = State::REVOKED; + callbackIndex->second.state = State::REVOKED; } if (eventIndex->second.size() == 0) { _eventMap.erase(eventIndex); diff --git a/languages/c/templates/sdk/src/Event/Event.h b/languages/c/templates/sdk/src/Event/Event.h index df9b1dc9..efa8457a 100644 --- a/languages/c/templates/sdk/src/Event/Event.h +++ b/languages/c/templates/sdk/src/Event/Event.h @@ -26,7 +26,7 @@ namespace FireboltSDK { class Event : public IEventHandler { public: - typedef std::function DispatchFunction; + typedef std::function DispatchFunction; private: enum State : uint8_t { IDLE, @@ -39,9 +39,8 @@ namespace FireboltSDK { const void* userdata; State state; }; - using IdMap = std::map; - using EventMap = std::map; - + using CallbackMap = std::map; + using EventMap = std::map; class Response : public WPEFramework::Core::JSON::Container { public: @@ -64,28 +63,41 @@ namespace FireboltSDK { WPEFramework::Core::JSON::Boolean Listening; }; - public: + private: Event(); + public: ~Event() override; static Event& Instance(); static void Dispose(); void Configure(Transport* transport); public: - template - uint32_t Subscribe(const string& eventName, const CALLBACK& callback, const void* userdata, uint32_t& id) + template + uint32_t Subscribe(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) + { + JsonObject jsonParameters; + return Subscribe(eventName, jsonParameters, callback, usercb, userdata); + } + + template + uint32_t Subscribe(const string& eventName, JsonObject& jsonParameters, const CALLBACK& callback, void* usercb, const void* userdata) { uint32_t status = FireboltSDKErrorUnavailable; if (_transport != nullptr) { - status = Assign(eventName, callback, userdata, id); + status = Assign(eventName, callback, usercb, userdata); if (status == FireboltSDKErrorNone) { - const string parameters("{\"listen\":true}"); Response response; - status = _transport->Subscribe(eventName, parameters, response); + + WPEFramework::Core::JSON::Variant Listen = true; + jsonParameters.Set(_T("listen"), Listen); + string parameters; + jsonParameters.ToString(parameters); + + status = _transport->Subscribe(eventName, parameters, response); if (status != FireboltSDKErrorNone) { - Revoke(eventName, id); + Revoke(eventName, usercb); } else if ((response.Listening.IsSet() == true) && (response.Listening.Value() == true)) { status = FireboltSDKErrorNone; @@ -95,23 +107,23 @@ namespace FireboltSDK { } } - return ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone: status); + return status; } - uint32_t Unsubscribe(const string& eventName, const uint32_t id); + uint32_t Unsubscribe(const string& eventName, void* usercb); private: template - uint32_t Assign(const string& eventName, const CALLBACK& callback, const void* userdata, uint32_t& id) + uint32_t Assign(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) { uint32_t status = FireboltSDKErrorNone; - id = Id(); - std::function actualCallback = callback; - DispatchFunction implementation = [actualCallback](const void* userdata, const string& parameters) -> uint32_t { + std::function actualCallback = callback; + DispatchFunction implementation = [actualCallback](void* usercb, const void* userdata, const string& parameters) -> uint32_t { - WPEFramework::Core::ProxyType inbound = WPEFramework::Core::ProxyType::Create(); - inbound->FromString(parameters); - actualCallback(userdata, static_cast(&inbound)); + WPEFramework::Core::ProxyType* inbound = new WPEFramework::Core::ProxyType(); + *inbound = WPEFramework::Core::ProxyType::Create(); + (*inbound)->FromString(parameters); + actualCallback(usercb, userdata, static_cast(inbound)); return (FireboltSDKErrorNone); }; CallbackData callbackData = {implementation, userdata, State::IDLE}; @@ -119,32 +131,31 @@ namespace FireboltSDK { _adminLock.Lock(); EventMap::iterator eventIndex = _eventMap.find(eventName); if (eventIndex != _eventMap.end()) { - // Already registered, no need to register again; - status = FireboltSDKErrorInUse; - eventIndex->second.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(callbackData)); + CallbackMap::iterator callbackIndex = eventIndex->second.find(usercb); + if (callbackIndex == eventIndex->second.end()) { + eventIndex->second.emplace(std::piecewise_construct, std::forward_as_tuple(usercb), std::forward_as_tuple(callbackData)); + } else { + // Already registered, no need to register again; + status = FireboltSDKErrorInUse; + } } else { - IdMap idMap; - idMap.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(callbackData)); - _eventMap.emplace(std::piecewise_construct, std::forward_as_tuple(eventName), std::forward_as_tuple(idMap)); + CallbackMap callbackMap; + callbackMap.emplace(std::piecewise_construct, std::forward_as_tuple(usercb), std::forward_as_tuple(callbackData)); + _eventMap.emplace(std::piecewise_construct, std::forward_as_tuple(eventName), std::forward_as_tuple(callbackMap)); } _adminLock.Unlock(); return status; } - uint32_t Revoke(const string& eventName, const uint32_t id); + uint32_t Revoke(const string& eventName, void* usercb); private: - uint32_t Id() const - { - return (++_id); - } uint32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) override; uint32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) override; private: - mutable std::atomic _id; EventMap _eventMap; WPEFramework::Core::CriticalSection _adminLock; Transport* _transport; diff --git a/languages/c/templates/sdk/src/Accessor/Config.h b/languages/c/templates/sdk/src/Firebolt.cpp similarity index 50% rename from languages/c/templates/sdk/src/Accessor/Config.h rename to languages/c/templates/sdk/src/Firebolt.cpp index f8389bf6..ffc1369a 100644 --- a/languages/c/templates/sdk/src/Accessor/Config.h +++ b/languages/c/templates/sdk/src/Firebolt.cpp @@ -16,26 +16,25 @@ * SPDX-License-Identifier: Apache-2.0 */ -namespace FireboltSDK { - class EXTERNAL Config : public WPEFramework::Core::JSON::Container { - public: - Config(const Config&) = delete; - Config& operator=(const Config&) = delete; - - Config() - : WPEFramework::Core::JSON::Container() - , Url(_T("")) - , WaitTime(1000) - , LogLevel(_T("Info")) - { - Add(_T("url"), &Url); - Add(_T("waittime"), &WaitTime); - Add(_T("loglevel"), &LogLevel); - } - - public: - WPEFramework::Core::JSON::String Url; - WPEFramework::Core::JSON::DecUInt32 WaitTime; - WPEFramework::Core::JSON::String LogLevel; - }; +#include "FireboltSDK.h" + + +#ifdef __cplusplus +extern "C" { +#endif + + + +uint32_t FireboltSDK_Initialize(char* configLine) { + FireboltSDK::Accessor::Instance(configLine); + return FireboltSDKErrorNone; +} + +uint32_t FireboltSDK_Deinitialize(void) { + FireboltSDK::Accessor::Dispose(); + return FireboltSDKErrorNone; +} + +#ifdef __cplusplus } +#endif diff --git a/languages/c/templates/sdk/src/Firebolt.h b/languages/c/templates/sdk/src/FireboltSDK.h similarity index 97% rename from languages/c/templates/sdk/src/Firebolt.h rename to languages/c/templates/sdk/src/FireboltSDK.h index 6a8f51a2..19946126 100644 --- a/languages/c/templates/sdk/src/Firebolt.h +++ b/languages/c/templates/sdk/src/FireboltSDK.h @@ -22,4 +22,5 @@ #include "Properties/Properties.h" #include "Accessor/Accessor.h" #include "Logger/Logger.h" +#include "TypesPriv.h" #include "Types.h" diff --git a/languages/c/templates/sdk/src/Logger/Logger.cpp b/languages/c/templates/sdk/src/Logger/Logger.cpp index 8acd8a14..0e49dfce 100644 --- a/languages/c/templates/sdk/src/Logger/Logger.cpp +++ b/languages/c/templates/sdk/src/Logger/Logger.cpp @@ -53,7 +53,6 @@ namespace FireboltSDK { _logLevel = logLevel; status = FireboltSDKErrorNone; } - printf("logLevel = %d _logLevel = %d\n", logLevel, _logLevel); return status; } diff --git a/languages/c/templates/sdk/src/Module.h b/languages/c/templates/sdk/src/Module.h index 5107d93e..00ea64bb 100644 --- a/languages/c/templates/sdk/src/Module.h +++ b/languages/c/templates/sdk/src/Module.h @@ -23,8 +23,6 @@ #endif #include -#include -#include #include #undef EXTERNAL diff --git a/languages/c/templates/sdk/src/Params.config b/languages/c/templates/sdk/src/Params.config deleted file mode 100644 index 71a58750..00000000 --- a/languages/c/templates/sdk/src/Params.config +++ /dev/null @@ -1,3 +0,0 @@ -url -waittime -loglevel diff --git a/languages/c/templates/sdk/src/Properties/Properties.h b/languages/c/templates/sdk/src/Properties/Properties.h index 611811f8..d75c3ba5 100644 --- a/languages/c/templates/sdk/src/Properties/Properties.h +++ b/languages/c/templates/sdk/src/Properties/Properties.h @@ -52,7 +52,60 @@ namespace FireboltSDK { } else { FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); } - + + return status; + } + + template + static uint32_t Get(const string& propertyName, const PARAMETERS& parameters, WPEFramework::Core::ProxyType& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + RESPONSETYPE responseType; + status = transport->Invoke(propertyName, parameters, responseType); + if (status == FireboltSDKErrorNone) { + ASSERT(response.IsValid() == false); + if (response.IsValid() == true) { + response.Release(); + } + response = WPEFramework::Core::ProxyType::Create(); + (*response) = responseType; + } + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + + template + static uint32_t Get(const string& propertyName, RESPONSETYPE& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject parameters; + status = transport->Invoke(propertyName, parameters, response); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static uint32_t Get(const string& propertyName, const PARAMETERS& parameters, RESPONSETYPE& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + status = transport->Invoke(propertyName, parameters, response); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + return status; } @@ -71,20 +124,25 @@ namespace FireboltSDK { return status; } - template - static uint32_t Subscribe(const string& propertyName, const CALLBACK& callback, const void* userdata, uint32_t& id) + template + static uint32_t Subscribe(const string& propertyName, JsonObject& paramsters, const CALLBACK& callback, void* usercb, const void* userdata) { - return Event::Instance().Subscribe(EventName(propertyName), callback, userdata, id); + return Event::Instance().Subscribe(EventName(propertyName), paramsters, callback, usercb, userdata); } - static uint32_t Unsubscribe(const string& propertyName, const uint32_t id) + static uint32_t Unsubscribe(const string& propertyName, void* usercb) { - return Event::Instance().Unsubscribe(EventName(propertyName), id); + return Event::Instance().Unsubscribe(EventName(propertyName), usercb); } private: static inline string EventName(const string& propertyName) { size_t pos = propertyName.find_first_of('.'); - return string(propertyName.substr(0, pos + 1) + "on" + propertyName.substr(pos + 1) + "Changed"); + string eventName = propertyName; + if (pos != std::string::npos) { + eventName[pos + 1] = std::toupper(eventName[pos + 1]); + eventName = string(eventName.substr(0, pos + 1) + "on" + eventName.substr(pos + 1) + "Changed"); + } + return eventName; } }; } diff --git a/languages/c/templates/sdk/src/Transport/Transport.h b/languages/c/templates/sdk/src/Transport/Transport.h index e0bff38c..2aff350d 100644 --- a/languages/c/templates/sdk/src/Transport/Transport.h +++ b/languages/c/templates/sdk/src/Transport/Transport.h @@ -254,7 +254,7 @@ namespace FireboltSDK { public: ChannelImpl(CommunicationChannel* parent, const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask) - : BaseClass(5, FactoryImpl::Instance(), path, _T("JSON"), query, "", false, mask, false, remoteNode.AnyInterface(), remoteNode, 256, 256) + : BaseClass(5, FactoryImpl::Instance(), path, _T("JSON"), query, "", false, mask, false, remoteNode.AnyInterface(), remoteNode, 1024 * 2, 1024 * 2) //TODO Relook this size issue , _parent(*parent) { } @@ -520,7 +520,7 @@ namespace FireboltSDK { public: inline bool IsOpen() { - _channel->IsOpen(); + return _channel->IsOpen(); } void Revoke(const string& eventName) diff --git a/languages/c/templates/sdk/src/Types.cpp b/languages/c/templates/sdk/src/Types.cpp index e573c0c9..f19cfe63 100644 --- a/languages/c/templates/sdk/src/Types.cpp +++ b/languages/c/templates/sdk/src/Types.cpp @@ -27,13 +27,12 @@ extern "C" { // String Type Handler Interfaces const char* FireboltTypes_String(FireboltTypes_StringHandle handle) { - FireboltSDK::String* str = static_cast(handle); - return (str->Value().c_str()); + return ((static_cast(handle))->Value().c_str()); } + void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle) { - FireboltSDK::String* str = static_cast(handle); - delete str; + delete static_cast(handle); } #ifdef __cplusplus diff --git a/languages/c/templates/sdk/src/TypesPriv.h b/languages/c/templates/sdk/src/TypesPriv.h index eda9547f..6e365ec7 100644 --- a/languages/c/templates/sdk/src/TypesPriv.h +++ b/languages/c/templates/sdk/src/TypesPriv.h @@ -21,35 +21,36 @@ #include namespace FireboltSDK { -class String { +namespace JSON { +class String : public WPEFramework::Core::JSON::String { + using Base = WPEFramework::Core::JSON::String; public: String() - : _value() + : Base() + , _value() { } - String(const std::string& value) - : _value(value) + String(const char value[]) + : Base(value) + , _value(value) { } - String(const String& copy) - : _value(copy._value) + String& operator=(const char RHS[]) { - - } - inline ~String() = default; - String& operator=(const String& RHS) - { - _value = RHS._value; + Base::operator = (RHS); + _value = RHS; return (*this); } public: - const std::string& Value() const + const string& Value() const { + _value = Base::Value(); return _value; } private: - std::string _value; + mutable std::string _value; }; } +} diff --git a/languages/c/templates/sdk/src/cmake/CopySymlink.cmake b/languages/c/templates/sdk/src/cmake/CopySymlink.cmake deleted file mode 100644 index 8ac3c1f8..00000000 --- a/languages/c/templates/sdk/src/cmake/CopySymlink.cmake +++ /dev/null @@ -1 +0,0 @@ -file(COPY "${LIBRARY}" DESTINATION "${DESTINATION}" FOLLOW_SYMLINK_CHAIN) From 47d81ab8c9abff54492f8d758c2acbefc939b0b4 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 15 Jun 2023 09:09:06 +0530 Subject: [PATCH 010/137] Add support to generate file inclusion for common schema also (#97) Add support to generate file inclusion for common schema also --- languages/c/Types.mjs | 336 +++++++++--------- languages/c/src/types/JSONHelpers.mjs | 3 +- languages/c/src/types/NativeHelpers.mjs | 15 - languages/c/templates/imports/default.cpp | 1 + .../imports/{default.c => default.h} | 0 .../c/templates/imports/default.jsondata | 1 + .../templates/modules/include/Common/Module.h | 40 --- .../c/templates/modules/src/JsonData_Module.h | 29 -- languages/c/templates/modules/src/Module.cpp | 6 +- .../templates/schemas/include/Common/Module.h | 1 + .../c/templates/schemas/src/JsonData_Module.h | 5 + .../c/templates/schemas/src/Module_Common.cpp | 5 +- src/macrofier/engine.mjs | 50 ++- src/shared/typescript.mjs | 2 +- 14 files changed, 226 insertions(+), 268 deletions(-) create mode 100644 languages/c/templates/imports/default.cpp rename languages/c/templates/imports/{default.c => default.h} (100%) create mode 100644 languages/c/templates/imports/default.jsondata delete mode 100644 languages/c/templates/modules/include/Common/Module.h delete mode 100644 languages/c/templates/modules/src/JsonData_Module.h diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 0bb6cc59..bbd74eec 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -318,193 +318,201 @@ function getSchemaShape(json, module, { name = '', prefix = '', level = 0, title return shape } function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '', merged = false, level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { - const isHeader = (destination.includes("JsonData_") !== true) && destination.endsWith(".h") - const isCPP = ((destination.endsWith(".cpp") || destination.includes("JsonData_")) && (section.includes('accessors') !== true)) - json = JSON.parse(JSON.stringify(json)) - - name = json.title || name let shape = '' - if (json['$ref']) { - if (json['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType - const schema = getPath(json['$ref'], module, schemas) - const tname = schema.title || json['$ref'].split('/').pop() - if (json['$ref'].includes('x-schemas')) { - schema = (getRefModule(json['$ref'].split('/')[2])) - } - - shape = getSchemaShapeInfo(schema, module, schemas, { name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) - } - } - //If the schema is a const, - else if (json.hasOwnProperty('const') && !isCPP) { - if (level > 0) { + if (destination && section) { + const isHeader = (destination.includes("JsonData_") !== true) && destination.endsWith(".h") + const isCPP = ((destination.endsWith(".cpp") || destination.includes("JsonData_")) && (section.includes('accessors') !== true)) + json = JSON.parse(JSON.stringify(json)) + + name = json.title || name + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + const schema = getPath(json['$ref'], module, schemas) + const tname = schema.title || json['$ref'].split('/').pop() + if (json['$ref'].includes('x-schemas')) { + schema = (getRefModule(json['$ref'].split('/')[2])) + } - let t = description(capitalize(name), json.description) - typeName = getTypeName(getModuleName(module), name, prefix) - t += (isHeader ? getPropertyAccessors(typeName, capitalize(name), typeof schema.const, { level: level, readonly: true, optional: false }) : getPropertyAccessorsImpl(typeName, getJsonType(schema, module, { level, name }), typeof schema.const, { level: level, readonly: true, optional: false })) - shape += '\n' + t + shape = getSchemaShapeInfo(schema, module, schemas, { name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) + } } - } - else if (json.type === 'object') { - if (!name) { - console.log(`WARNING: unnamed schema in ${module.info.title}.`) - console.dir(json) - shape = '' + //If the schema is a const, + else if (json.hasOwnProperty('const') && !isCPP) { + if (level > 0) { + + let t = description(capitalize(name), json.description) + typeName = getTypeName(getModuleName(module), name, prefix) + t += (isHeader ? getPropertyAccessors(typeName, capitalize(name), typeof schema.const, { level: level, readonly: true, optional: false }) : getPropertyAccessorsImpl(typeName, getJsonType(schema, module, { level, name }), typeof schema.const, { level: level, readonly: true, optional: false })) + shape += '\n' + t + } } - else if (json.properties && (validJsonObjectProperties(json) === true)) { - let c_shape = description(capitalize(name), json.description) - let cpp_shape = '' - let tName = getTypeName(getModuleName(module), name, prefix) - c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(json, module, { name }))) - let props = [] - let containerName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? (prefix + '_' + capitalize(name)) : capitalize(name) - Object.entries(json.properties).forEach(([pname, prop]) => { - let items - var desc = '\n' + description(capitalize(pname), prop.description) - if (prop.type === 'array') { - if (Array.isArray(prop.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(prop.items)) { - throw 'Heterogenous Arrays not supported yet' + else if (json.type === 'object') { + if (!name) { + console.log(`WARNING: unnamed schema in ${module.info.title}.`) + console.dir(json) + shape = '' + } + else if (json.properties && (validJsonObjectProperties(json) === true)) { + let c_shape = description(capitalize(name), json.description) + let cpp_shape = '' + let tName = getTypeName(getModuleName(module), name, prefix) + c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(json, module, { name }))) + let props = [] + let containerName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? (prefix + '_' + capitalize(name)) : capitalize(name) + Object.entries(json.properties).forEach(([pname, prop]) => { + let items + var desc = '\n' + description(capitalize(pname), prop.description) + if (prop.type === 'array') { + if (Array.isArray(prop.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(prop.items)) { + throw 'Heterogenous Arrays not supported yet' + } + items = prop.items[0] + } + else { + // grab the type for the non-array schema + items = prop.items + } + + let info = getSchemaTypeInfo(module, items, items.name || pname, schemas, prefix, {level : level, descriptions: descriptions, title: true}) + if (info.type && info.type.length > 0) { + let objName = tName + '_' + capitalize(prop.title || pname) + let moduleName = info.namespace + info.json.namespace = info.namespace + let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) + let prefixName = ((prefix.length > 0) && items['$ref']) ? '' : prefix + let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, schemas, prefix) + + let t = description(capitalize(info.name), json.description) + '\n' + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) + c_shape += '\n' + t + props.push({name: `${pname}`, type: `WPEFramework::Core::JSON::ArrayType<${subModuleProperty.type}>`}) + } + else { + console.log(`a. WARNING: Type undetermined for ${name}:${pname}`) + } + } else { + if (((merged === false) || ((merged === true) && (pname.includes(name)))) && (prop.type === 'object' || prop.anyOf || prop.allOf)) { + shape += getSchemaShapeInfo(prop, module, schemas, { name : pname, prefix, merged: false, level: 1, title, summary, descriptions, destination, section, enums }) + } + let info = getSchemaTypeInfo(module, prop, pname, module['x-schemas'], prefix, {descriptions: descriptions, level: level + 1, title: true}) + if (info.type && info.type.length > 0) { + let subPropertyName = ((pname.length !== 0) ? capitalize(pname) : info.name) + let moduleProperty = getJsonTypeInfo(module, json, name, schemas, prefix) + let subProperty = getJsonTypeInfo(module, prop, pname, schemas, prefix) + c_shape += '\n' + description(capitalize(pname), info.json.description) + c_shape += '\n' + (isHeader ? getPropertyAccessors(tName, capitalize(pname), info.type, { level: 0, readonly: false, optional: isOptional(pname, json) }) : getPropertyAccessorsImpl(tName, moduleProperty.type, subProperty.type, subPropertyName, info.type, info.json, {readonly:false, optional:isOptional(pname, json)})) + let property = getJsonType(prop, module, { name : pname, prefix }) + props.push({name: `${pname}`, type: `${property}`}) + } + else { + console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) } - items = prop.items[0] - } - else { - // grab the type for the non-array schema - items = prop.items - } - let info = getSchemaTypeInfo(module, items, items.name || pname, schemas, prefix, {level : level, descriptions: descriptions, title: true}) - if (info.type && info.type.length > 0) { - let objName = tName + '_' + capitalize(prop.title || pname) - let moduleName = info.namespace - info.json.namespace = info.namespace - let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) - let prefixName = ((prefix.length > 0) && items['$ref']) ? '' : prefix - let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, schemas, prefix) - - let t = description(capitalize(info.name), json.description) + '\n' - t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) - c_shape += '\n' + t - props.push({name: `${pname}`, type: `WPEFramework::Core::JSON::ArrayType<${subModuleProperty.type}>`}) - } - else { - console.log(`a. WARNING: Type undetermined for ${name}:${pname}`) - } - } else { - if (((merged === false) || ((merged === true) && (pname.includes(name)))) && (prop.type === 'object' || prop.anyOf || prop.allOf)) { - shape += getSchemaShapeInfo(prop, module, schemas, { name : pname, prefix, merged: false, level: 1, title, summary, descriptions, destination, section, enums }) - } - let info = getSchemaTypeInfo(module, prop, pname, module['x-schemas'], prefix, {descriptions: descriptions, level: level + 1, title: true}) - if (info.type && info.type.length > 0) { - let subPropertyName = ((pname.length !== 0) ? capitalize(pname) : info.name) - let moduleProperty = getJsonTypeInfo(module, json, name, schemas, prefix) - let subProperty = getJsonTypeInfo(module, prop, pname, schemas, prefix) - c_shape += '\n' + description(capitalize(pname), info.json.description) - c_shape += '\n' + (isHeader ? getPropertyAccessors(tName, capitalize(pname), info.type, { level: 0, readonly: false, optional: isOptional(pname, json) }) : getPropertyAccessorsImpl(tName, moduleProperty.type, subProperty.type, subPropertyName, info.type, info.json, {readonly:false, optional:isOptional(pname, json)})) - let property = getJsonType(prop, module, { name : pname, prefix }) - props.push({name: `${pname}`, type: `${property}`}) - } - else { - console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) } - } - }) + }) - cpp_shape += getJsonContainerDefinition(json, containerName, props) + cpp_shape += getJsonContainerDefinition(json, containerName, props) - if (isCPP) { - shape += '\n' + cpp_shape - } - else { - shape += '\n' + c_shape + if (isCPP) { + shape += '\n' + cpp_shape + } + else { + shape += '\n' + c_shape + } } - } - else if (json.propertyNames && json.propertyNames.enum) { - //propertyNames in object not handled yet - } - else if (json.additionalProperties && (typeof json.additionalProperties === 'object') && (validJsonObjectProperties(json) === true) && !isCPP) { - let info = getSchemaTypeInfo(module, json.additionalProperties, name, module['x-schemas'], prefix) - if (!info.type || (info.type.length === 0)) { - info.type = 'char*' - info.json = json.additionalProperties - info.json.type = 'string' + else if (json.propertyNames && json.propertyNames.enum) { + //propertyNames in object not handled yet } + else if (json.additionalProperties && (typeof json.additionalProperties === 'object') && (validJsonObjectProperties(json) === true) && !isCPP) { + let info = getSchemaTypeInfo(module, json.additionalProperties, name, module['x-schemas'], prefix) + if (!info.type || (info.type.length === 0)) { + info.type = 'char*' + info.json = json.additionalProperties + info.json.type = 'string' + } - let tName = getTypeName(getModuleName(module), name, prefix) - let t = description(capitalize(name), json.description) + '\n' - let containerType = 'WPEFramework::Core::JSON::VariantContainer' + let tName = getTypeName(getModuleName(module), name, prefix) + let t = description(capitalize(name), json.description) + '\n' + let containerType = 'WPEFramework::Core::JSON::VariantContainer' - let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, module['x-schemas']) - if (isCPP && ((info.json.type === 'object' && info.json.properties) || info.json.type === 'array')) { - // Handle Container generation here - } + let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, module['x-schemas']) + if (isCPP && ((info.json.type === 'object' && info.json.properties) || info.json.type === 'array')) { + // Handle Container generation here + } - t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, containerType)) - t += (isHeader ? getMapAccessors(tName, info.type, { descriptions: descriptions, level: level }) : getMapAccessorsImpl(tName, containerType, subModuleProperty.type, info.type, info.json, { readonly: true, optional: false })) - shape += '\n' + t + t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, containerType)) + t += (isHeader ? getMapAccessors(tName, info.type, { descriptions: descriptions, level: level }) : getMapAccessorsImpl(tName, containerType, subModuleProperty.type, info.type, info.json, { readonly: true, optional: false })) + shape += '\n' + t + } + else if (json.patternProperties) { + console.log(`WARNING: patternProperties are not supported by Firebolt(inside getModuleName(module):${name})`) + } } - else if (json.patternProperties) { - console.log(`WARNING: patternProperties are not supported by Firebolt(inside getModuleName(module):${name})`) + else if (json.anyOf) { + if (level > 0) { + let mergedSchema = getMergedSchema(module, json, name, schemas) + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + shape += getSchemaShapeInfo(mergedSchema, module, schemas, { name, prefix: prefixName, merged, level, title, summary, descriptions, destination, section, enums }) + } } - } - else if (json.anyOf) { - if (level > 0) { - let mergedSchema = getMergedSchema(module, json, name, schemas) - let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) - shape += getSchemaShapeInfo(mergedSchema, module, schemas, { name, prefix: prefixName, merged, level, title, summary, descriptions, destination, section, enums }) + else if (json.oneOf) { + //Just ignore schema shape, since this has to be treated as string } - } - else if (json.oneOf) { - //Just ignore schema shape, since this has to be treated as string - } - else if (json.allOf) { - let title = (json.title ? json.title : name) - let union = deepMergeAll(module, title, json, schemas) - union.title = title + else if (json.allOf) { + let title = (json.title ? json.title : name) + let union = deepMergeAll(module, title, json, schemas) + union.title = title - delete union['$ref'] + delete union['$ref'] - return getSchemaShapeInfo(union, module, schemas, { name, prefix, merged: true, level, title, summary, descriptions, destination, section, enums }) - } - else if (json.type === 'array' && !isCPP) { - let j - if (Array.isArray(json.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(json.items)) { - throw 'Heterogenous Arrays not supported yet' + return getSchemaShapeInfo(union, module, schemas, { name, prefix, merged: true, level, title, summary, descriptions, destination, section, enums }) + } + else if (json.type === 'array') { + let j + if (Array.isArray(json.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(json.items)) { + throw 'Heterogenous Arrays not supported yet' + } + j = json.items[0] + } + else { + j = json.items + } + shape += getSchemaShapeInfo(j, module, schemas, { name: j.title || name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) + + if (!isCPP) { + let info = getSchemaTypeInfo(module, j, j.title || name, schemas, prefix, {level : level, descriptions: descriptions, title: true}) + + if (info.type && info.type.length > 0) { + let type = getArrayElementSchema(json, module, schemas, info.name) + let arrayName = capitalize(name) + capitalize(type.type) + let objName = getTypeName(info.namespace, arrayName, prefix) + let tName = objName + 'Array' + let moduleName = info.namespace + info.json.namespace = info.namespace + let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) + let subModuleProperty = getJsonTypeInfo(module, j, j.title, schemas, prefix) + let t = '' + if (level === 0) { + t += description(capitalize(info.name), json.description) + '\n' + t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, moduleProperty.type)) + } + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, '', info.type, info.json)) + shape += '\n' + t + } } - j = json.items[0] } else { - j = json.items + shape += '\n' + getSchemaType(module, json, name, schemas, prefix, {level: level, descriptions: descriptions}) } - - let info = getSchemaTypeInfo(module, j, j.name || name, schemas, prefix, {level : level, descriptions: descriptions, title: true}) - - if (info.type && info.type.length > 0) { - let type = getArrayElementSchema(json, module, schemas, info.name) - let arrayName = capitalize(info.name) + capitalize(type.type) - let objName = getTypeName(info.namespace, arrayName, prefix) - let tName = objName + 'Array' - let moduleName = info.namespace - info.json.namespace = info.namespace - let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) - let t = '' - if (level === 0) { - t += description(capitalize(info.name), json.description) + '\n' - t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, moduleProperty.type)) - } - t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + 'Handle'), getJsonNativeType(type), '', info.type, info.json)) - shape += '\n' + t - } - } - else { - shape += '\n' + getSchemaType(module, json, name, schemas, prefix, {level: level, descriptions: descriptions}) } return shape diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index 3437c98c..b2a260b5 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -51,5 +51,6 @@ function getJsonContainerDefinition (schema, name, props) { } export { - getJsonContainerDefinition + getJsonContainerDefinition, + getJsonDataStructName } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index eac20c16..489b3f52 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -211,20 +211,6 @@ const generateEnum = (schema, prefix)=> { } } -const getIncludeDefinitions = (json = {}, jsonData = false) => { - return getExternalSchemaPaths(json) - .map(ref => { - const mod = ref.split('#')[0].split('/').pop() - let i = `#include "Common/${capitalize(mod)}.h"` - if(jsonData === true) { - i += '\n' + `#include "JsonData_${capitalize(mod)}.h"` - } - return i - }) - .filter((item, index, arr) => arr.indexOf(item) === index) - .concat([`#include "Firebolt/Types.h"`]) -} - function getPropertyGetterSignature(method, module, paramType) { let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` @@ -251,7 +237,6 @@ export { getIncludeGuardClose, getNativeType, getModuleName, - getIncludeDefinitions, getPropertyGetterSignature, getPropertySetterSignature, getPropertyEventCallbackSignature, diff --git a/languages/c/templates/imports/default.cpp b/languages/c/templates/imports/default.cpp new file mode 100644 index 00000000..69e241f9 --- /dev/null +++ b/languages/c/templates/imports/default.cpp @@ -0,0 +1 @@ +#include "JsonData_${info.title}.h" diff --git a/languages/c/templates/imports/default.c b/languages/c/templates/imports/default.h similarity index 100% rename from languages/c/templates/imports/default.c rename to languages/c/templates/imports/default.h diff --git a/languages/c/templates/imports/default.jsondata b/languages/c/templates/imports/default.jsondata new file mode 100644 index 00000000..69e241f9 --- /dev/null +++ b/languages/c/templates/imports/default.jsondata @@ -0,0 +1 @@ +#include "JsonData_${info.title}.h" diff --git a/languages/c/templates/modules/include/Common/Module.h b/languages/c/templates/modules/include/Common/Module.h deleted file mode 100644 index 809418a2..00000000 --- a/languages/c/templates/modules/include/Common/Module.h +++ /dev/null @@ -1,40 +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 - */ - -#ifndef _COMMON_${info.TITLE}_H -#define _COMMON_${info.TITLE}_H - -#include "Firebolt.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// Enums - -/* ${ENUMS} */ - -// Schemas - -/* ${SCHEMAS} */ - -#ifdef __cplusplus -} -#endif - -#endif // Header Include Guard diff --git a/languages/c/templates/modules/src/JsonData_Module.h b/languages/c/templates/modules/src/JsonData_Module.h deleted file mode 100644 index 2c7ca8c8..00000000 --- a/languages/c/templates/modules/src/JsonData_Module.h +++ /dev/null @@ -1,29 +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 - */ - -#pragma once - -#include "Firebolt.h" - -namespace FireboltSDK { - namespace ${info.title} { - - /* ${SCHEMAS}} */ - - } -} diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 47a356d6..d34c1da5 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -16,11 +16,9 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "Firebolt.h" -#include "${info.title}.h" -#include "JsonData_${info.title}.h" - +#include "FireboltSDK.h" /* ${IMPORTS} */ +#include "${info.title}.h" namespace FireboltSDK { namespace ${info.title} { diff --git a/languages/c/templates/schemas/include/Common/Module.h b/languages/c/templates/schemas/include/Common/Module.h index 0326c220..ff037fba 100644 --- a/languages/c/templates/schemas/include/Common/Module.h +++ b/languages/c/templates/schemas/include/Common/Module.h @@ -20,6 +20,7 @@ #define _COMMON_${info.TITLE}_H #include "Firebolt.h" +/* ${IMPORTS} */ #ifdef __cplusplus extern "C" { diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/JsonData_Module.h index 7fa2b6f4..d0ecbbac 100644 --- a/languages/c/templates/schemas/src/JsonData_Module.h +++ b/languages/c/templates/schemas/src/JsonData_Module.h @@ -16,6 +16,11 @@ * SPDX-License-Identifier: Apache-2.0 */ +#pragma once + +/* ${IMPORTS} */ +#include "Common/${info.title}.h" + namespace FireboltSDK { namespace ${info.title} { // Types diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/Module_Common.cpp index 9dc2ee0a..e2389d50 100644 --- a/languages/c/templates/schemas/src/Module_Common.cpp +++ b/languages/c/templates/schemas/src/Module_Common.cpp @@ -16,9 +16,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "Firebolt.h" -#include "${info.title}.h" -#include "Common/${info.title}.h" +#include "FireboltSDK.h" +/* ${IMPORTS} */ #include "JsonData_${info.title}.h" /* ${ENUMS} */ diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 13ce46f4..a2c64ec0 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -46,6 +46,7 @@ const _inspector = obj => { // getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) // getSchemaType(schema, module, options = { destination: 'file.txt', title: true }) // getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getJsonType(schema, module, options = { name: 'Foo', prefix: '', descriptions: false, level: 0 }) let types = { getMethodSignature: ()=>null, @@ -133,6 +134,24 @@ const getLinkForSchema = (schema, json, { name = '' } = {}) => { return '#' } +const getComponentExternalSchema = (json) => { + let refSchemas = [] + if (json.components && json.components.schemas) { + Object.entries(json.components.schemas).forEach(([name, schema]) => { + let refs = getLinkedSchemaPaths(schema).map(path => getPathOr(null, path, schema)) + refs.map(ref => { + let title = '' + if (ref.includes('x-schemas')) { + if (ref.split('/')[2] !== json.info.title) { + title = ref.split('/')[2] + } + } + title && !refSchemas.includes(title) ? refSchemas.push(title) : null + }) + }) + } + return (refSchemas) +} // Maybe methods array of objects const getMethods = compose( @@ -319,7 +338,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { // grab the options so we don't have to pass them from method to method Object.assign(state, options) - const imports = generateImports(obj, templates) + const imports = generateImports(obj, templates, { destination : (options.destination ? options.destination : '') }) const initialization = generateInitialization(obj, templates) const enums = generateEnums(obj, templates, { destination : (options.destination ? options.destination : '') }) const eventsEnum = generateEvents(obj, templates) @@ -345,7 +364,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { const schemasArray = generateSchemas(obj, templates, { baseUrl: '', section: 'schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) const accessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).filter(body => body).join('\n')) : '' - const typesArray = schemasArray.filter(x => !x.enum) + const typesArray = schemasArray.length ? schemasArray.filter(x => !x.enum) : [] const types = (typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodTypes const accessors = (accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodAccessors @@ -632,7 +651,6 @@ function generateSchemas(json, templates, options) { if (['ListenResponse', 'ProviderRequest', 'ProviderResponse', 'FederatedResponse', 'FederatedRequest'].includes(name)) { return } - let content = getTemplate('/schemas/default', templates) if (!schema.examples || schema.examples.length === 0) { @@ -695,11 +713,11 @@ function generateSchemas(json, templates, options) { if (!isDeprecatedMethod(schema)) { schema.params.forEach(param => { if (param.schema && (param.schema.type === 'object')) { - list.push([param.name, param.schema, '', { prefix : schema.name}]) + list.push([param.name, param.schema, '', { prefix : schema.name }]) } }) if (schema.result.schema && (schema.result.schema.type === 'object')) { - list.push([schema.result.name, schema.result.schema, '', { prefix : schema.name}]) + list.push([schema.result.name, schema.result.schema, '', { prefix : schema.name }]) } } } @@ -741,8 +759,8 @@ function getRelatedSchemaLinks(schema = {}, json = {}, templates = {}, options = return links } -const generateImports = (json, templates) => { - let imports = getTemplate('/imports/default', templates) +const generateImports = (json, templates, options = { destination: '' }) => { + let imports = '' if (rpcMethodsOrEmptyArray(json).length) { imports += getTemplate('/imports/rpc', templates) @@ -771,11 +789,22 @@ const generateImports = (json, templates) => { 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() + + let template = prefix ? getTemplate(`/imports/default.${prefix}`, templates) : '' + if (!template) { + template = getTemplate(suffix ? `/imports/default.${suffix}` : '/imports/default', templates) + } - if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0) { - imports += Object.keys(json['x-schemas']).map(shared => getTemplate('/imports/default', templates).replace(/\$\{info.title\}/g, shared)).join('\n') + if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0 && !json.info['x-uri-titles']) { + imports += Object.keys(json['x-schemas']).map(shared => template.replace(/\$\{info.title\}/g, shared)).join('') } + let componentExternalSchema = getComponentExternalSchema(json) + if (componentExternalSchema.length && json.info['x-uri-titles']) { + imports += componentExternalSchema.map(shared => template.replace(/\$\{info.title\}/g, shared)).join('') + } return imports } @@ -1019,9 +1048,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' - + let seeAlso = '' - if (isPolymorphicPullMethod(methodObj) && pullsForType) { seeAlso = `See also: [${pullsForType}](#${pullsForType.toLowerCase()}-1)` // this assumes the schema will be after the method... } diff --git a/src/shared/typescript.mjs b/src/shared/typescript.mjs index e53747cd..79c3e022 100644 --- a/src/shared/typescript.mjs +++ b/src/shared/typescript.mjs @@ -327,7 +327,7 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { return '' } - + function getTypeScriptType(jsonType) { if (jsonType === 'integer') { return 'number' From 9d925c8a312b278e204a50403b95e45d36e179a9 Mon Sep 17 00:00:00 2001 From: sramani-metro <71630728+sramani-metro@users.noreply.github.com> Date: Tue, 20 Jun 2023 20:19:13 +0530 Subject: [PATCH 011/137] C-Language: Templates based property methods (#100) * feat: Add method templates for properties * feat: Property setters using templates * fix: Macro name correction --- languages/c/Types.mjs | 98 ++++++++++++++++--- languages/c/src/types/ImplHelpers.mjs | 63 +++++++++++- languages/c/src/types/NativeHelpers.mjs | 70 ++++++++++--- languages/c/templates/codeblocks/setter.c | 9 ++ languages/c/templates/declarations/default.c | 5 - languages/c/templates/declarations/property.c | 5 + languages/c/templates/defaults/default.c | 1 - languages/c/templates/defaults/property.c | 1 - .../c/templates/methods/{clear.js => clear.c} | 0 languages/c/templates/methods/property.c | 19 +++- languages/c/templates/methods/provide.c | 3 - languages/c/templates/methods/setter.c | 0 src/macrofier/engine.mjs | 12 ++- src/shared/typescript.mjs | 6 +- 14 files changed, 243 insertions(+), 49 deletions(-) create mode 100644 languages/c/templates/codeblocks/setter.c create mode 100644 languages/c/templates/declarations/property.c rename languages/c/templates/methods/{clear.js => clear.c} (100%) create mode 100644 languages/c/templates/methods/setter.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index bbd74eec..0886d3dc 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -18,8 +18,8 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' -import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema } from './src/types/NativeHelpers.mjs' -import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getPropertyAccessorsImpl } from './src/types/ImplHelpers.mjs' +import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature } from './src/types/NativeHelpers.mjs' +import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation } from './src/types/ImplHelpers.mjs' import { getJsonContainerDefinition, getJsonDataStructName } from './src/types/JSONHelpers.mjs' const getSdkNameSpace = () => 'FireboltSDK' @@ -166,33 +166,65 @@ const deepMergeAll = (module, name, schema, schemas, options) => { return union } +const hasTag = (method, tag) => { + return method.tags && method.tags.filter(t => t.name === tag).length > 0 +} function getMethodSignature(method, module, { destination, isInterface = false }) { - const extraParam = '${method.result.type}* ${method.result.name}' - const prefix = method.tags.find(t => t.name.split(":")[0] === "property") ? "Get" : "" + let signature = '' + let paramList = [] + if(hasTag(method, 'property') || hasTag(method, 'property:readonly') || hasTag(method, 'property:immutable')) { + + method.params.map(param => { + /* + paramList = [{name='', nativeType='', jsonType='', required=boolean}] + */ + paramList['nativeType'] = getSchemaType(param.schema, module, { title: true, name: param.name }) + paramList['jsonType'] = getJsonType(param.schema, module, {name: param.name}) + paramList['name'] = param.name + paramList['required'] = param.required + + }) - return 'uint32_t ${info.title}_' + prefix + '${method.Name}(' + extraParam + ')' + let resultType = method.result && getSchemaType(method.result.schema, module, { title: true, name: method.result.name, resultSchema: true}) || '' + + signature = getPropertyGetterSignature(method, module, resultType, paramList) + ';\n\n' + + if(hasTag(method, 'property') || hasTag(method, 'property:readonly')) { + signature += getPropertyEventCallbackSignature(method, module, resultType, paramList) + ';\n\n' + signature += getPropertyEventRegisterSignature(method, module, paramList) + ';\n\n' + signature += getPropertyEventUnregisterSignature(method, module) + ';\n\n' + } + + if(hasTag(method, 'property')) { + signature += getPropertySetterSignature(method, module, resultType, paramList) + ';\n\n' + } + } + return signature } + function getMethodSignatureParams(method, module, { destination }) { - return method.params.map(param => param.name + (!param.required ? '?' : '') + ': ' + getSchemaType(param.schema, module, { name: param.name, title: true, destination })).join(', ') + return method.params.map(param => getSchemaType(param.schema, module, { name: param.name, title: true, destination }) + (!param.required ? '* ' : ' ') + param.name ).join(', ') } const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop -function getSchemaType(schema, module, { name, prefix = '', destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - let info = getSchemaTypeInfo(module, schema, name, module['x-schemas'], prefix, { title: title }) +function getSchemaType(schema, module, { name, prefix = '', destination, resultSchema = false, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + let info = getSchemaTypeInfo(module, schema, name, module['x-schemas'], prefix, { title: title, resultSchema: resultSchema, event: event }) return info.type } -function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = {level: 0, descriptions: true, title: false}) { +function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = {level: 0, descriptions: true, title: false, resultSchema: false, event: false}) { if (json.schema) { json = json.schema } + let stringAsHandle = options.resultSchema || options.event + let structure = {} structure["type"] = '' structure["json"] = [] @@ -219,7 +251,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref } } else if (json.const) { - structure.type = getNativeType(json) + structure.type = getNativeType(json, stringAsHandle) structure.json = json return structure } @@ -240,7 +272,9 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref } else if (Array.isArray(json.type)) { let type = json.type.find(t => t !== 'null') - console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) + let sch = JSON.parse(JSON.stringify(json)) + sch.type = type + return getSchemaTypeInfo(module, sch, name, schemas, prefix, options) } else if (json.type === 'array' && json.items && (validJsonObjectProperties(json) === true)) { let res = '' @@ -300,7 +334,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref return structure } else if (json.type) { - structure.type = getNativeType(json) + structure.type = getNativeType(json, stringAsHandle) structure.json = json if (name || json.title) { structure.name = capitalize(name || json.title) @@ -534,6 +568,9 @@ const getJsonNativeType = json => { else if (jsonType === 'boolean') { type = 'WPEFramework::Core::JSON::Boolean' } + else if (jsonType === 'null') { + type = 'void' + } else { throw 'Unknown JSON Native Type !!!' } @@ -601,7 +638,9 @@ function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '' } else if (Array.isArray(json.type)) { let type = json.type.find(t => t !== 'null') - console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) + let sch = JSON.parse(JSON.stringify(json)) + sch.type = type + return getJsonTypeInfo(module, sch, name, schemas, prefix ) } else if (json.type === 'array' && json.items) { let res @@ -682,10 +721,41 @@ const enumReducer = (acc, val, i, arr) => { return acc } +function getSchemaInstantiation(schema, module, name, { instantiationType = '' } = {}) { + + if(instantiationType === 'params') { + if (schema.params.length > 0) { + let paramList = [] + schema.params.map(param => { + /* + paramList = [{name='', nativeType='', jsonType='', required=boolean}] + */ + const parameter = {} + parameter['nativeType'] = getSchemaType(param.schema, module, { title: true, name: param.name }) + parameter['jsonType'] = getJsonType(param.schema, module, {name: param.name}) + parameter['name'] = param.name + parameter['required'] = param.required + paramList.push(parameter) + + }) + return getParameterInstantiation(paramList) + } + } else if(instantiationType === 'result') { + let resultType = getSchemaType(schema, module, { title: true, name: name, resultSchema: true}) || '' + let resultJsonType = getJsonType(schema, module, {name: name}) || '' + + return getResultInstantiation(name, resultType, resultJsonType) + } + + return '' +} + + export default { getMethodSignature, getMethodSignatureParams, getSchemaShape, getSchemaType, - getJsonType + getJsonType, + getSchemaInstantiation } diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index 47852c9e..a39af0b6 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -1,3 +1,5 @@ +import { capitalize } from "./NativeHelpers.mjs" + const Indent = '\t' const getSdkNameSpace = () => 'FireboltSDK' @@ -288,9 +290,68 @@ const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPr return result } +/* +paramList = [{name='', nativeType='', jsonType='', required=boolean}] +*/ +function getParameterInstantiation(paramList, container = '') { + + let impl = ` ${container.length>0 ? container : 'JsonObject'} jsonParameters;\n` + paramList.forEach(param => { + impl += `\n` + const jsonType = param.jsonType + if (jsonType.length) { + if (param.required) { + if (param.nativeType.includes('FireboltTypes_StringHandle')) { + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = *(static_cast<${jsonType}*>(${param.name}));\n` + } + else { + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = ${param.name};\n` + } + impl += ` jsonParameters.Set(_T("${param.name}"), ${capitalize(param.name)});` + } + else { + impl += ` if (${param.name} != nullptr) {\n` + if (param.nativeType.includes('char*')) { + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = ${param.name};\n` + } else { + + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = *(${param.name});\n` + } + impl += ` jsonParameters.Set(_T("${param.name}"), ${capitalize(param.name)});\n` + impl += ` }` + } + } + }) + + return impl +} + +function getResultInstantiation (name, nativeType, container, indentLevel = 3) { + + let impl = '' + + if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + impl += `${' '.repeat(indentLevel)}${container}* strResult = new ${container}(jsonResult);` + '\n' + impl += `${' '.repeat(indentLevel)}*${name} = static_cast<${getFireboltStringType()}>(strResult);` + } else if (nativeType.includes('Handle')) { + impl += `${' '.repeat(indentLevel)}WPEFramework::Core::ProxyType<${container}>* resultPtr = new WPEFramework::Core::ProxyType<${container}>();\n` + impl += `${' '.repeat(indentLevel)}*resultPtr = WPEFramework::Core::ProxyType<${container}>::Create();\n` + impl += `${' '.repeat(indentLevel)}*(*resultPtr) = jsonResult;\n` + impl += `${' '.repeat(indentLevel)}*${name} = static_cast<${nativeType}>(resultPtr);` + } else { + impl += `${' '.repeat(indentLevel)}*${name} = jsonResult.Value();` + } + + return impl + +} + + export { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, - getPropertyAccessorsImpl + getPropertyAccessorsImpl, + getParameterInstantiation, + getResultInstantiation } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 489b3f52..65a78443 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -115,24 +115,32 @@ const getArrayElementSchema = (json, module, schemas = {}, name) => { return result } -const getNativeType = json => { - let type = '' +const getNativeType = (json, stringAsHandle = false) => { + let type let jsonType = json.const ? typeof json.const : json.type if (jsonType === 'string') { - type = 'char*' + type = 'char*' + if(stringAsHandle) { + type = getFireboltStringType() + } } else if (jsonType === 'number') { - type = 'float' + type = 'float' } else if (jsonType === 'integer') { - type = 'int32_t' + type = 'int32_t' + } else if (jsonType === 'boolean') { type = 'bool' } + else if (jsonType === 'null' ) { + type = 'void' + } return type } + const getObjectHandleManagement = varName => { let result = `typedef void* ${varName}Handle; @@ -211,24 +219,53 @@ const generateEnum = (schema, prefix)=> { } } -function getPropertyGetterSignature(method, module, paramType) { - let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` - return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` +/* +paramList = [{name='', nativeType='', jsonType='', required=boolean}] +*/ + +const getContextParams = (paramList) => paramList.map(param => param.nativeType + (!param.required ? '*' : '') + ' ' + param.name).join(', ') + +function getPropertyGetterSignature(property, module, propType, paramList = []) { + + let contextParams = '' + contextParams = getContextParams(paramList) + return `uint32_t ${capitalize(getModuleName(module))}_Get${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType}* ${property.result.name || property.name})` +} + +function getPropertySetterSignature(property, module, propType, paramList = []) { + let contextParams = '' + contextParams = getContextParams(paramList) + return `uint32_t ${capitalize(getModuleName(module))}_Set${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType} ${property.result.name || property.name})` +} + +function getPropertyEventCallbackSignature(property, module, propType, paramList = []) { + + let contextParams = '' + contextParams = getContextParams(paramList) + return `/*Callback to listen to updates on ${property.Name} property*/\n` + + `typedef void (*On${capitalize(getModuleName(module))}${capitalize(property.name)}Changed)( ${contextParams}${contextParams.length > 0 ? ', ':''}const void* userData, ${propType} ${property.result.name || property.name})` } -function getPropertySetterSignature(method, module, paramType) { - let m = `${capitalize(getModuleName(module))}_Set${capitalize(method.name)}` - return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType} ${method.result.name || method.name} )` +function getPropertyEventInnerCallbackSignature(method, module, schemas) { + let signature = `static void ${capitalize(getModuleName(module)) + capitalize(method.name)}` } -function getPropertyEventCallbackSignature(method, module, paramType) { - return `typedef void (*On${capitalize(method.name)}Changed)(${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType})` +function getPropertyEventRegisterSignature(property, module, paramList = []) { + let contextParams = '' + contextParams = getContextParams(paramList) + + return `/*Register to listen to updates on ${capitalize(property.name)} property*/\n` + + `uint32_t ${capitalize(getModuleName(module))}_Register_${capitalize(property.name)}Update( ${contextParams}${contextParams.length > 0 ? ', ':''}On${capitalize(getModuleName(module))}${capitalize(property.name)}Changed userCB, const void* userData )` + } -function getPropertyEventSignature(method, module) { - return `${description(method.name, 'Listen to updates')}\n` + `uint32_t ${capitalize(getModuleName(module))}_Listen${capitalize(method.name)}Update(On${capitalize(method.name)}Changed notification, uint16_t* listenerId)` +function getPropertyEventUnregisterSignature(property, module) { + return `/*Unregister to listen to updates on ${capitalize(property.name)} property*/\n` + + `uint32_t ${capitalize(getModuleName(module))}_Unregister_${capitalize(property.name)}Update( On${capitalize(getModuleName(module))}${capitalize(property.name)}Changed userCB )` + } + export { getHeaderText, getIncludeGuardOpen, @@ -240,7 +277,8 @@ export { getPropertyGetterSignature, getPropertySetterSignature, getPropertyEventCallbackSignature, - getPropertyEventSignature, + getPropertyEventRegisterSignature, + getPropertyEventUnregisterSignature, getMapAccessors, getArrayAccessors, capitalize, diff --git a/languages/c/templates/codeblocks/setter.c b/languages/c/templates/codeblocks/setter.c new file mode 100644 index 00000000..9f496543 --- /dev/null +++ b/languages/c/templates/codeblocks/setter.c @@ -0,0 +1,9 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.title}_${method.Name}( ${method.signature.params} ) +{ + const string method = _T("${info.title}.${method.name}"); + ${if.params} +${method.params.serialization} + ${end.if.params} + return FireboltSDK::Properties::Set(method, jsonParameters); +} diff --git a/languages/c/templates/declarations/default.c b/languages/c/templates/declarations/default.c index be0b1e14..e69de29b 100644 --- a/languages/c/templates/declarations/default.c +++ b/languages/c/templates/declarations/default.c @@ -1,5 +0,0 @@ -/* - * ${method.summary} - * ${method.params} - */ -${method.signature}; diff --git a/languages/c/templates/declarations/property.c b/languages/c/templates/declarations/property.c new file mode 100644 index 00000000..3550b45e --- /dev/null +++ b/languages/c/templates/declarations/property.c @@ -0,0 +1,5 @@ +/* + * ${method.summary} + * ${method.params} + */ +${method.signature} diff --git a/languages/c/templates/defaults/default.c b/languages/c/templates/defaults/default.c index e29085d1..e69de29b 100644 --- a/languages/c/templates/defaults/default.c +++ b/languages/c/templates/defaults/default.c @@ -1 +0,0 @@ - ${method.name}: ${method.example.value} \ No newline at end of file diff --git a/languages/c/templates/defaults/property.c b/languages/c/templates/defaults/property.c index 95ef20cf..e69de29b 100644 --- a/languages/c/templates/defaults/property.c +++ b/languages/c/templates/defaults/property.c @@ -1 +0,0 @@ - ${method.name}: function () { return MockProps.mock('${info.title}', '${method.name}', arguments, ${method.example.value}) } \ No newline at end of file diff --git a/languages/c/templates/methods/clear.js b/languages/c/templates/methods/clear.c similarity index 100% rename from languages/c/templates/methods/clear.js rename to languages/c/templates/methods/clear.c diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 1c70ba29..0b2843a8 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,12 +1,21 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_Get${method.Name}(${method.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { +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}"); - FireboltSDK::${info.title}::${method.result.type} jsonResult; + JsonObject jsonParameters; + ${if.params} +${method.params.serialization} + ${end.if.params} - uint32_t status = FireboltSDK::Properties::Get(method, jsonResult); + ${method.result.json} jsonResult; + + uint32_t status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { - WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); - *${method.result.name} = static_cast<${info.title}_${method.result.type}Handle>(resultPtr); + if (${method.result.name} != nullptr) { +${method.result.instantiation} + } } return status; } + +${method.setter} \ No newline at end of file diff --git a/languages/c/templates/methods/provide.c b/languages/c/templates/methods/provide.c index 8cb48885..e69de29b 100644 --- a/languages/c/templates/methods/provide.c +++ b/languages/c/templates/methods/provide.c @@ -1,3 +0,0 @@ -function provide(capability, provider) { - return ProvideManager.provide(capability, provider) -} diff --git a/languages/c/templates/methods/setter.c b/languages/c/templates/methods/setter.c new file mode 100644 index 00000000..e69de29b diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index a2c64ec0..50c10667 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -47,13 +47,15 @@ const _inspector = obj => { // getSchemaType(schema, module, options = { destination: 'file.txt', title: true }) // getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) // getJsonType(schema, module, options = { name: 'Foo', prefix: '', descriptions: false, level: 0 }) +// getSchemaInstantiation(schema, module, options = {type: 'params' | 'result' | 'event' | 'callback'}) let types = { getMethodSignature: ()=>null, getMethodSignatureParams: ()=>null, getSchemaShape: ()=>null, getSchemaType: ()=>null, - getJsonType: ()=>null + getJsonType: ()=>null, + getSchemaInstantiation: ()=>null } let config = { @@ -1048,6 +1050,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, {instantiationType: 'params'}) + const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' } ) let seeAlso = '' if (isPolymorphicPullMethod(methodObj) && pullsForType) { @@ -1080,6 +1084,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\.context\}(.*?)\$\{end\.if\.context\}/gms, event.params.length ? '$1' : '') + .replace(/\$\{method\.params\.serialization\}/g, serializedParams) // Typed signature stuff .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination, section: state.section })) @@ -1105,9 +1110,11 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .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, title: true, asPath: false, destination: state.destination })) //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result.schema, json, {name: result.name, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name : result.name })) + .replace(/\$\{method\.result\.instantiation\}/g, resultInst) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) .replace(/\$\{method\.alternative.link\}/g, '#'+(method.alternative || "").toLowerCase()) @@ -1121,6 +1128,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{method\.setter\}/g, setterTemplate) // must be last!! .replace(/\$\{method\.subscriber\}/g, subscriberTemplate) // must be last!! + if (method.deprecated) { template = template.replace(/\$\{if\.deprecated\}(.*?)\$\{end\.if\.deprecated\}/gms, '$1') } diff --git a/src/shared/typescript.mjs b/src/shared/typescript.mjs index 79c3e022..5982137e 100644 --- a/src/shared/typescript.mjs +++ b/src/shared/typescript.mjs @@ -346,10 +346,14 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, return acc } + function getSchemaInstantiation(schema, module, { instantiationType }) { + return '' + } export default { getMethodSignature, getMethodSignatureParams, getSchemaShape, getSchemaType, - getJsonType + getJsonType, + getSchemaInstantiation } \ No newline at end of file From 79f731be317adc4afec963c78582f6680f8d7168 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 22 Jun 2023 08:25:31 +0530 Subject: [PATCH 012/137] Add support to keep original file permissions of template/sdk files (#99) --- languages/c/language.config.json | 5 ++- src/macrofier/index.mjs | 22 +++++++++-- src/sdk/index.mjs | 3 +- src/shared/filesystem.mjs | 63 +++++++++++++++++++++----------- 4 files changed, 66 insertions(+), 27 deletions(-) diff --git a/languages/c/language.config.json b/languages/c/language.config.json index 185b0370..97e90519 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -10,5 +10,6 @@ "/include/Common/Module.h", "/src/Module_Common.cpp", "/src/JsonData_Module.h" - ] -} \ No newline at end of file + ], + "persistPermission": true +} diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index f8acada8..b1d61ee4 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -18,7 +18,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { emptyDir, readDir, readFiles, readJson, writeFiles, writeText } from '../shared/filesystem.mjs' +import { emptyDir, readDir, readFiles, readFilesPermissions, readJson, + writeFiles, writeFilesPermissions, writeText } from '../shared/filesystem.mjs' import { getTemplate, getTemplateForModule } from '../shared/template.mjs' import { getModule, hasPublicAPIs } from '../shared/modules.mjs' import { logHeader, logSuccess } from '../shared/io.mjs' @@ -42,6 +43,7 @@ const macrofy = async ( staticContent, templatesPerModule, templatesPerSchema, + persistPermission, createModuleDirectories, copySchemasIntoModules, aggregateFile, @@ -87,6 +89,12 @@ const macrofy = async ( const sharedTemplateList = await readDir(sharedTemplates, { recursive: true }) const templates = Object.assign(await readFiles(sharedTemplateList, sharedTemplates), await readFiles(sdkTemplateList, template)) // sdkTemplates are second so they win ties + let templatesPermission = {} + if (persistPermission) { + templatesPermission = Object.assign(await readFilesPermissions(sharedTemplateList, sharedTemplates), + await readFilesPermissions(sdkTemplateList, template)) + } + const exampleTemplates = {} for (var i=0; i chmodSync(ref, mode) + const readText = ref => readFile(ref) .then(resp => resp.toString()) @@ -39,6 +41,34 @@ const readDir = async (ref, options) => { return results.sort() } +const getIndex = (refs, base) => { + let index = base ? base.length : 0 + if (base && !refs[0].startsWith(base)) { + refs = refs.map(v => path.relative(base, v)) + index = 0 + } + else if (index === 0 && refs.length !== 1) { + // find the common prefix of all the files + while ((new Set(refs.map(r => r[index]))).size === 1) { + index++ + } + // back up one dirctory from the common prefix + index = path.join(path.join(refs[0].substring(0, index)), '..').length + } + return index +} + +const readFilesPermissions = (refs, base) => Promise.all(refs.map(ref => stat(ref))) + .then(permissions => { + if (!refs || refs.length === 0) { + return Promise.resolve({}) + } + const results = refs.map(v => [v.substring(getIndex(refs, base)), null]) + for (let i=0; i Promise.all(refs.map(ref => readFile(ref))) if (!refs || refs.length === 0) { return Promise.resolve({}) } - - let index = base ? base.length : 0 - if (base && !refs[0].startsWith(base)) { - refs = refs.map(v => path.relative(base, v)) - index = 0 - } - else if (index === 0 && refs.length !== 1) { - // find the common prefix of all the files - while ((new Set(refs.map(r => r[index]))).size === 1) { - index++ - } - - // back up one dirctory from the common prefix - index = path.join(path.join(refs[0].substring(0, index)), '..').length - } - - const results = refs.map(v => [v.substring(index), null]) + const results = refs.map(v => [v.substring(getIndex(refs, base)), null]) for (let i=0; i refs[i].endsWith(suffix))) { results[i][1] = contents[i] @@ -83,6 +97,11 @@ const writeFiles = (files) => { .map( ([file, contents]) => writeText(file, contents))) } +const writeFilesPermissions = (files) => { + return Promise.all(Object.entries(files) + .map( ([file, mode]) => setPermission(file, mode))) +} + export { readText, writeText, @@ -91,5 +110,7 @@ export { readDir, readFiles, writeFiles, - emptyDir -} \ No newline at end of file + emptyDir, + readFilesPermissions, + writeFilesPermissions +} From 450035ab9d293b9d143e601451f627f22f9a873c Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 22 Jun 2023 08:25:52 +0530 Subject: [PATCH 013/137] Event template implementation added (#101) --- languages/c/Types.mjs | 92 ++++++------ languages/c/src/types/ImplHelpers.mjs | 132 +++++++++++++++++- languages/c/src/types/NativeHelpers.mjs | 13 +- languages/c/templates/declarations/event.c | 4 + languages/c/templates/methods/default.c | 2 +- languages/c/templates/methods/event.c | 26 ++++ languages/c/templates/methods/property.c | 13 +- languages/c/templates/modules/src/Module.cpp | 1 + .../c/templates/schemas/src/Module_Common.cpp | 1 + src/macrofier/engine.mjs | 59 +++++--- 10 files changed, 260 insertions(+), 83 deletions(-) create mode 100644 languages/c/templates/declarations/event.c create mode 100644 languages/c/templates/methods/event.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 0886d3dc..72912930 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -18,8 +18,8 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' -import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature } from './src/types/NativeHelpers.mjs' -import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation } from './src/types/ImplHelpers.mjs' +import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' +import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation, getCallbackParametersInstantiation, getCallbackResultInstantiation, getCallbackResponseInstantiation } from './src/types/ImplHelpers.mjs' import { getJsonContainerDefinition, getJsonDataStructName } from './src/types/JSONHelpers.mjs' const getSdkNameSpace = () => 'FireboltSDK' @@ -170,44 +170,50 @@ const hasTag = (method, tag) => { return method.tags && method.tags.filter(t => t.name === tag).length > 0 } -function getMethodSignature(method, module, { destination, isInterface = false }) { - - let signature = '' +function getParamList(schema, module) { let paramList = [] - if(hasTag(method, 'property') || hasTag(method, 'property:readonly') || hasTag(method, 'property:immutable')) { - - method.params.map(param => { + if (schema.params.length > 0) { + schema.params.map(p => { /* - paramList = [{name='', nativeType='', jsonType='', required=boolean}] + param = {name='', nativeType='', jsonType='', required=boolean} */ - paramList['nativeType'] = getSchemaType(param.schema, module, { title: true, name: param.name }) - paramList['jsonType'] = getJsonType(param.schema, module, {name: param.name}) - paramList['name'] = param.name - paramList['required'] = param.required - + let param = {} + param['nativeType'] = getSchemaType(p.schema, module, { title: true, name: p.name }) + param['jsonType'] = getJsonType(p.schema, module, {name: p.name}) + param['name'] = p.name + param['required'] = p.required + paramList.push(param) }) + } + return paramList +} + +function getMethodSignature(method, module, { destination, isInterface = false }) { + + let signature = '' + if (hasTag(method, 'property') || hasTag(method, 'property:readonly') || hasTag(method, 'property:immutable')) { + let paramList = getParamList(method, module) let resultType = method.result && getSchemaType(method.result.schema, module, { title: true, name: method.result.name, resultSchema: true}) || '' signature = getPropertyGetterSignature(method, module, resultType, paramList) + ';\n\n' - if(hasTag(method, 'property') || hasTag(method, 'property:readonly')) { - signature += getPropertyEventCallbackSignature(method, module, resultType, paramList) + ';\n\n' - signature += getPropertyEventRegisterSignature(method, module, paramList) + ';\n\n' - signature += getPropertyEventUnregisterSignature(method, module) + ';\n\n' - } - - if(hasTag(method, 'property')) { + if (hasTag(method, 'property')) { signature += getPropertySetterSignature(method, module, resultType, paramList) + ';\n\n' } } return signature } +function getMethodSignatureParams(method, module, { destination, callback= false } = {}) { -function getMethodSignatureParams(method, module, { destination }) { - - return method.params.map(param => getSchemaType(param.schema, module, { name: param.name, title: true, destination }) + (!param.required ? '* ' : ' ') + param.name ).join(', ') + return method.params.map(param => { + let type = getSchemaType(param.schema, module, { name: param.name, title: true, destination }) + if ((callback === true) && (type === 'char*')) { + type = getFireboltStringType() + } + return type + (!param.required ? '* ' : ' ') + param.name + }).join(', ') } const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop @@ -723,34 +729,32 @@ const enumReducer = (acc, val, i, arr) => { function getSchemaInstantiation(schema, module, name, { instantiationType = '' } = {}) { - if(instantiationType === 'params') { - if (schema.params.length > 0) { - let paramList = [] - schema.params.map(param => { - /* - paramList = [{name='', nativeType='', jsonType='', required=boolean}] - */ - const parameter = {} - parameter['nativeType'] = getSchemaType(param.schema, module, { title: true, name: param.name }) - parameter['jsonType'] = getJsonType(param.schema, module, {name: param.name}) - parameter['name'] = param.name - parameter['required'] = param.required - paramList.push(parameter) - - }) - return getParameterInstantiation(paramList) - } - } else if(instantiationType === 'result') { + if (instantiationType === 'params') { + return getParameterInstantiation(getParamList(schema, module)) + } + else if (instantiationType === 'result') { let resultType = getSchemaType(schema, module, { title: true, name: name, resultSchema: true}) || '' let resultJsonType = getJsonType(schema, module, {name: name}) || '' - return getResultInstantiation(name, resultType, resultJsonType) } + else if (instantiationType === 'callback.params') { + let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + return getCallbackParametersInstantiation(getParamList(schema, module), resultJsonType) + } + else if (instantiationType === 'callback.result') { + let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + return getCallbackResultInstantiation(resultType, resultJsonType) + } + else if (instantiationType === 'callback.response') { + let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + return getCallbackResponseInstantiation(getParamList(schema, module), resultType, resultJsonType) + } return '' } - export default { getMethodSignature, getMethodSignatureParams, diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index a39af0b6..6509375a 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -1,10 +1,9 @@ -import { capitalize } from "./NativeHelpers.mjs" +import { capitalize, getFireboltStringType } from "./NativeHelpers.mjs" const Indent = '\t' const getSdkNameSpace = () => 'FireboltSDK' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' -const getFireboltStringType = () => 'FireboltTypes_StringHandle' const getObjectHandleManagementImpl = (varName, jsonDataName) => { @@ -320,12 +319,138 @@ function getParameterInstantiation(paramList, container = '') { impl += ` jsonParameters.Set(_T("${param.name}"), ${capitalize(param.name)});\n` impl += ` }` } + impl += '\n' } }) return impl } +const isNativeType = (type) => (type === 'float' || type === 'char*' || type === 'int32_t' || type === 'bool') + +function getCallbackParametersInstantiation(paramList, container = '') { + + let impl = '' + + if (paramList.length > 0) { + paramList.forEach(param => { + if (param.required !== undefined) { + if (param.nativeType !== 'char*') { + impl += ` ${param.nativeType} ${param.name};\n` + if (param.required === false) { + impl += ` ${param.nativeType}* ${param.name}Ptr = nullptr;\n` + } + } + else { + impl += ` ${getFireboltStringType()} ${param.name};\n` + } + } + }) + impl += `\n WPEFramework::Core::ProxyType<${container}>* jsonResponse;\n` + impl += ` WPEFramework::Core::ProxyType& var = *(static_cast*>(response)); + + ASSERT(var.IsValid() == true); + if (var.IsValid() == true) { + WPEFramework::Core::JSON::VariantContainer::Iterator elements = var->Variants(); + + while (elements.Next()) { + if (strcmp(elements.Label(), "value") == 0) { + + jsonResponse = new WPEFramework::Core::ProxyType<${container}>(); + string objectStr; + elements.Current().Object().ToString(objectStr); + (*jsonResponse)->FromString(objectStr); + } else if (strcmp(elements.Label(), "context") == 0) { + + WPEFramework::Core::JSON::VariantContainer::Iterator params = elements.Current().Object().Variants(); + while (params.Next()) {\n` + let contextParams = '' + + paramList.forEach(param => { + if (param.required !== undefined) { + if (isNativeType(param.nativeType) === true) { + if (contextParams.length > 0) { + contextParams += ` else if (strcmp(elements.Label(), "${param.name}") == 0) {\n` + } + else { + contextParams += ` if (strcmp(elements.Label(), "${param.name}") == 0) {\n` + } + if (param.nativeType === 'char*') { + contextParams += ` ${getSdkNameSpace()}::JSON::String* ${param.name}Value = new ${getSdkNameSpace()}::JSON::String(); + *${param.name}Value = elements.Current().Value().c_str(); + ${param.name} = ${param.name}Value;\n` + } + else if (param.nativeType === 'bool') { + contextParams += ` ${param.name} = elements.Current().Boolean();\n` + } + else if ((param.nativeType === 'float') || (param.nativeType === 'int32_t')) { + contextParams += ` ${param.name} = elements.Current().Number();\n` + } + if ((param.nativeType !== 'char*') && (param.required === false)) { + contextParams += ` ${param.name}Ptr = &${param.name};\n` + } + contextParams += ` }\n` + } + } + }) + impl += contextParams + impl += ` } + } else { + ASSERT(false); + } + } + }\n` + } else { + + impl +=` WPEFramework::Core::ProxyType<${container}>* jsonResponse = static_cast*>(response);\n` + } + + return impl +} + +function getCallbackResultInstantiation(nativeType, container = '') { + let impl = '' + if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + impl +=` + ${container}* jsonStrResponse = new ${container}(); + *jsonStrResponse = *(*jsonResponse); + jsonResponse->Release();` + '\n' + } + return impl +} + +function getCallbackResponseInstantiation(paramList, nativeType, container = '') { + let impl = '' + + if (paramList.length > 0) { + paramList.forEach(param => { + if (param.required !== undefined) { + if (param.nativeType === 'char*') { + impl += `static_cast<${getFireboltStringType()}>(${param.name}), ` + } + else if (param.required === true) { + impl += `${param.name}, ` + } + else if (param.required === false) { + impl += `${param.name}Ptr, ` + } + } + }) + } + + if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + impl += `static_cast<${nativeType}>(jsonStrResponse)` + } + else if (nativeType.includes('Handle')) { + impl += `static_cast<${nativeType}>(jsonResponse)` + } + else { + impl += `static_cast<${nativeType}>((*jsonResponse)->Value())` + } + + return impl +} + function getResultInstantiation (name, nativeType, container, indentLevel = 3) { let impl = '' @@ -353,5 +478,8 @@ export { getObjectHandleManagementImpl, getPropertyAccessorsImpl, getParameterInstantiation, + getCallbackParametersInstantiation, + getCallbackResultInstantiation, + getCallbackResponseInstantiation, getResultInstantiation } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 65a78443..022437e8 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -120,7 +120,7 @@ const getNativeType = (json, stringAsHandle = false) => { let jsonType = json.const ? typeof json.const : json.type if (jsonType === 'string') { type = 'char*' - if(stringAsHandle) { + if (stringAsHandle) { type = getFireboltStringType() } } @@ -140,7 +140,6 @@ const getNativeType = (json, stringAsHandle = false) => { return type } - const getObjectHandleManagement = varName => { let result = `typedef void* ${varName}Handle; @@ -229,13 +228,16 @@ function getPropertyGetterSignature(property, module, propType, paramList = []) let contextParams = '' contextParams = getContextParams(paramList) - return `uint32_t ${capitalize(getModuleName(module))}_Get${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType}* ${property.result.name || property.name})` + return `uint32_t ${capitalize(getModuleName(module))}_Get${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType}* ${property.result.name || property.name} )` } function getPropertySetterSignature(property, module, propType, paramList = []) { let contextParams = '' contextParams = getContextParams(paramList) - return `uint32_t ${capitalize(getModuleName(module))}_Set${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType} ${property.result.name || property.name})` + if (propType === getFireboltStringType()) { + propType = 'char*' + } + return `uint32_t ${capitalize(getModuleName(module))}_Set${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType} ${property.result.name || property.name} )` } function getPropertyEventCallbackSignature(property, module, propType, paramList = []) { @@ -288,5 +290,6 @@ export { getPropertyAccessors, isOptional, generateEnum, - getArrayElementSchema + getArrayElementSchema, + getFireboltStringType } diff --git a/languages/c/templates/declarations/event.c b/languages/c/templates/declarations/event.c new file mode 100644 index 00000000..45e4b608 --- /dev/null +++ b/languages/c/templates/declarations/event.c @@ -0,0 +1,4 @@ +/* ${method.name} - ${method.description} */ +typedef void (*${info.Title}${method.Name}Callback)( const void* userData, ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${event.result.type} ); +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 ); +uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 49f76ce1..6a023534 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -21,4 +21,4 @@ uint32_t ${info.title}_${method.Name}(${method.params.list}${if.params}, ${end.i } return status; -} \ No newline at end of file +} diff --git a/languages/c/templates/methods/event.c b/languages/c/templates/methods/event.c new file mode 100644 index 00000000..ec868cd5 --- /dev/null +++ b/languages/c/templates/methods/event.c @@ -0,0 +1,26 @@ +/* ${method.name} - ${method.description} */ +static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) +{ +${event.callback.params.serialization} + ASSERT(jsonResponse->IsValid() == true); + if (jsonResponse->IsValid() == true) { +${event.callback.result.instantiation} + ${info.Title}${method.Name}Callback callback = reinterpret_cast<${info.Title}${method.Name}Callback>(userCB); + callback(userData, ${event.callback.response.instantiation}); + } +} +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}"); + uint32_t status = FireboltSDKErrorNone; + + if (userCB != nullptr) { + ${event.params.serialization} + status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${info.Title}${method.Name}InnerCallback, reinterpret_cast(userCB), userData); + } + return status; +} +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(userCB)); +} diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 0b2843a8..c7510da9 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -2,14 +2,10 @@ 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}"); - JsonObject jsonParameters; - ${if.params} -${method.params.serialization} - ${end.if.params} - +${if.params}${method.params.serialization}${end.if.params} ${method.result.json} jsonResult; - - uint32_t status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult); + ${if.params}uint32_t status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult);${end.if.params} + ${if.params.empty}uint32_t status = FireboltSDK::Properties::Get(method, jsonResult);${end.if.params.empty} if (status == FireboltSDKErrorNone) { if (${method.result.name} != nullptr) { ${method.result.instantiation} @@ -17,5 +13,4 @@ uint32_t ${info.title}_Get${method.Name}( ${method.signature.params}${if.params} } return status; } - -${method.setter} \ No newline at end of file +${method.setter} diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index d34c1da5..65721f1e 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -35,6 +35,7 @@ extern "C" { /* ${ACCESSORS} */ /* ${METHODS} */ +/* ${EVENTS} */ #ifdef __cplusplus } diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/Module_Common.cpp index e2389d50..0ccdfc28 100644 --- a/languages/c/templates/schemas/src/Module_Common.cpp +++ b/languages/c/templates/schemas/src/Module_Common.cpp @@ -28,6 +28,7 @@ extern "C" { /* ${ACCESSORS} */ /* ${METHODS} */ + /* ${EVENTS} */ #ifdef __cplusplus } diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 50c10667..85cb67e2 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -47,7 +47,7 @@ const _inspector = obj => { // getSchemaType(schema, module, options = { destination: 'file.txt', title: true }) // getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) // getJsonType(schema, module, options = { name: 'Foo', prefix: '', descriptions: false, level: 0 }) -// getSchemaInstantiation(schema, module, options = {type: 'params' | 'result' | 'event' | 'callback'}) +// getSchemaInstantiation(schema, module, options = {type: 'params' | 'result' | 'callback.params'| 'callback.result' | 'callback.response'}) let types = { getMethodSignature: ()=>null, @@ -70,6 +70,19 @@ const state = { const capitalize = str => str[0].toUpperCase() + str.substr(1) const hasMethodsSchema = (json, options) => json.methods && json.methods.length +const indent = (str, padding) => { + let first = true + return str.split('\n').map(line => { + if (first) { + first = false + return line + } + else { + return padding + line + } + }).join('\n') +} + const setTyper = (t) => { types = t } @@ -1022,9 +1035,9 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const capabilities = getTemplate('/sections/capabilities', templates) + insertCapabilityMacros(getTemplate('/capabilities/default', templates), methodObj.tags.find(t => t.name === "capabilities"), methodObj, json) const result = JSON.parse(JSON.stringify(methodObj.result)) - const event = JSON.parse(JSON.stringify(methodObj)) + const event = isEventMethod(methodObj) ? JSON.parse(JSON.stringify(methodObj)) : '' - if (isEventMethod(methodObj)) { + if (event) { result.schema = JSON.parse(JSON.stringify(getPayloadFromEvent(methodObj))) event.result.schema = getPayloadFromEvent(event) event.params = event.params.filter(p => p.name !== 'listen') @@ -1052,6 +1065,12 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, {instantiationType: 'params'}) const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' } ) + const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'params'}), ' ') : '' + const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.params'}) : '' + const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.result'}) : '' + const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.response'}) : '' + const resultType = result.schema ? types.getSchemaType(result.schema, json, { name: result.name }) : '' + const resultJsonType = result.schema ? types.getJsonType(result.schema, json, { name: result.name }) : '' let seeAlso = '' if (isPolymorphicPullMethod(methodObj) && pullsForType) { @@ -1083,8 +1102,9 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{method\.params\.array\}/g, JSON.stringify(methodObj.params.map(p => p.name))) .replace(/\$\{method\.params\.count}/g, methodObj.params ? methodObj.params.length : 0) .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/gms, method.params.length ? '$1' : '') - .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event.params.length ? '$1' : '') - .replace(/\$\{method\.params\.serialization\}/g, serializedParams) + .replace(/\$\{if\.params.empty\}(.*?)\$\{end\.if\.params.empty\}/gms, method.params.length === 0 ? '$1' : '') + .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event && event.params.length ? '$1' : '') + .replace(/\$\{method\.params\.serialization\}/g, serializedParams) // Typed signature stuff .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination, section: state.section })) @@ -1095,8 +1115,15 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{event\.name\}/g, method.name.toLowerCase()[2] + method.name.substr(3)) .replace(/\$\{event\.params\}/g, eventParams) .replace(/\$\{event\.params\.table\.rows\}/g, eventParamsRows) - .replace(/\$\{event\.signature\.params\}/g, types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section })) + .replace(/\$\{if\.event\.params\}(.*?)\$\{end\.if\.event\.params\}/gms, event && event.params.length ? '$1' : '') + .replace(/\$\{event\.signature\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section }) : '') + .replace(/\$\{event\.signature\.callback\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section, callback: true }) : '') + .replace(/\$\{event\.params\.serialization\}/g, serializedEventParams) + .replace(/\$\{event\.callback\.params\.serialization\}/g, callbackSerializedParams) + .replace(/\$\{event\.callback\.result\.instantiation\}/g, callbackResultInst) + .replace(/\$\{event\.callback\.response\.instantiation\}/g, callbackResponseInst) .replace(/\$\{info\.title\}/g, info.title) + .replace(/\$\{info\.Title\}/g, capitalize(info.title)) .replace(/\$\{info\.TITLE\}/g, info.title.toUpperCase()) .replace(/\$\{method\.property\.immutable\}/g, hasTag(methodObj, 'property:immutable')) .replace(/\$\{method\.property\.readonly\}/g, !getSetterFor(methodObj.name, json)) @@ -1112,9 +1139,10 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .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, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, baseUrl: options.baseUrl .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') + .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name : result.name })) - .replace(/\$\{method\.result\.instantiation\}/g, resultInst) + .replace(/\$\{method\.result\.instantiation\}/g, resultInst) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) .replace(/\$\{method\.alternative.link\}/g, '#'+(method.alternative || "").toLowerCase()) @@ -1408,19 +1436,6 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te while (match = template.match(regex)) { let methodsBlock = '' - const indent = (str, padding) => { - let first = true - return str.split('\n').map(line => { - if (first) { - first = false - return line - } - else { - return padding + line - } - }).join('\n') - } - let i = 1 iface.forEach(method => { @@ -1489,7 +1504,7 @@ export { generateMacros, insertMacros, generateAggregateMacros, - insertAggregateMacros, + insertAggregateMacros } export default { From 229cae65fdcec1856ef7393df28feea116d8df8b Mon Sep 17 00:00:00 2001 From: sramani-metro <71630728+sramani-metro@users.noreply.github.com> Date: Thu, 22 Jun 2023 12:19:00 +0530 Subject: [PATCH 014/137] Template for Polymorphic pull method (#102) * feat: Add method templates for properties * feat: Property setters using templates * fix: Macro name correction * feat: Add template for polymorphic-pull --- .../methods/polymorphic-pull-event.c | 0 .../c/templates/methods/polymorphic-pull.c | 21 +++++++++++++++++++ .../c/templates/methods/polymorphic-reducer.c | 11 ---------- 3 files changed, 21 insertions(+), 11 deletions(-) create mode 100644 languages/c/templates/methods/polymorphic-pull-event.c create mode 100644 languages/c/templates/methods/polymorphic-pull.c diff --git a/languages/c/templates/methods/polymorphic-pull-event.c b/languages/c/templates/methods/polymorphic-pull-event.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/methods/polymorphic-pull.c b/languages/c/templates/methods/polymorphic-pull.c new file mode 100644 index 00000000..553b2946 --- /dev/null +++ b/languages/c/templates/methods/polymorphic-pull.c @@ -0,0 +1,21 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.title}_Push${method.Name}(${method.signature.params}) +{ + uint32_t status = FireboltSDKErrorUnavailable; + ${if.params} +${method.params.serialization} + ${end.if.params} + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + WPEFramework::Core::JSON::Boolean jsonResult; + status = transport->Invoke(_T("${info.title}.${method.name}"), jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; + } + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; +} diff --git a/languages/c/templates/methods/polymorphic-reducer.c b/languages/c/templates/methods/polymorphic-reducer.c index db07747f..e69de29b 100644 --- a/languages/c/templates/methods/polymorphic-reducer.c +++ b/languages/c/templates/methods/polymorphic-reducer.c @@ -1,11 +0,0 @@ - -function ${method.name}(${method.params.list}) { - const transforms = ${method.transforms} - - if (arguments.length === 1 && Array.isArray(arguments[0])) { - return Transport.send('${info.title}', '${method.name}', arguments[0], transforms) - } - else { - return Transport.send('${info.title}', '${method.name}', { ${method.params.list} }, transforms) - } -} \ No newline at end of file From 1613f3ea66c90b04602874b207fd9a29a2cb4aae Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 5 Jul 2023 12:09:18 -0400 Subject: [PATCH 015/137] fix: In progress commit --- languages/c/Types.mjs | 186 +++++++++++++++++- languages/c/src/types/NativeHelpers.mjs | 2 +- languages/c/templates/declarations/default.c | 5 + languages/c/templates/declarations/event.c | 6 +- languages/c/templates/declarations/property.c | 2 +- languages/c/templates/language/enum-item.c | 1 + languages/c/templates/language/enum.c | 3 + languages/c/templates/language/parameter.c | 1 + languages/c/templates/language/schema-item.c | 1 + languages/c/templates/language/schema.c | 3 + languages/c/templates/methods/default.c | 4 +- languages/c/templates/methods/event.c | 6 +- languages/c/templates/methods/property.c | 7 +- languages/c/templates/types/enum.cpp | 2 +- languages/c/templates/types/enum.h | 2 +- src/macrofier/engine.mjs | 27 ++- src/macrofier/index.mjs | 2 +- 17 files changed, 231 insertions(+), 29 deletions(-) create mode 100644 languages/c/templates/language/enum-item.c create mode 100644 languages/c/templates/language/enum.c create mode 100644 languages/c/templates/language/parameter.c create mode 100644 languages/c/templates/language/schema-item.c create mode 100644 languages/c/templates/language/schema.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 72912930..9b871aa2 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -21,6 +21,7 @@ import { getPath } from '../../src/shared/json-schema.mjs' import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation, getCallbackParametersInstantiation, getCallbackResultInstantiation, getCallbackResponseInstantiation } from './src/types/ImplHelpers.mjs' import { getJsonContainerDefinition, getJsonDataStructName } from './src/types/JSONHelpers.mjs' +import { localizeDependencies } from '../../src/shared/json-schema.mjs' const getSdkNameSpace = () => 'FireboltSDK' const getJsonNativeTypeForOpaqueString = () => getSdkNameSpace() + '::JSON::String' @@ -270,7 +271,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref //Enum structure.name = name || json.title let typeName = getTypeName(getModuleName(module), name || json.title, prefix, false, false) - let res = description(capitalize(name || json.title), json.description) + '\n' + generateEnum(json, typeName) +// let res = description(capitalize(name || json.title), json.description) + '\n' + generateEnum(json, typeName) structure.json = json structure.type = typeName structure.namespace = getModuleName(module) @@ -297,10 +298,10 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref res = getSchemaTypeInfo(module, json.items, json.items.name || name, schemas, prefix) } - let arrayName = capitalize(res.name) + capitalize(res.json.type) + let arrayName = capitalize(res.name)// + capitalize(res.json.type) let n = getTypeName(getModuleName(module), arrayName, prefix) structure.name = res.name || name && (capitalize(name)) - structure.type = n + 'ArrayHandle' + structure.type = n structure.json = json structure.namespace = getModuleName(module) return structure @@ -326,7 +327,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref else if (json.type === 'object') { structure.json = json if (hasProperties(json)) { - structure.type = getTypeName(getModuleName(module), json.title || name, prefix) + 'Handle' + structure.type = getTypeName(getModuleName(module), json.title || name, prefix) structure.name = (json.name ? json.name : (json.title ? json.title : name)) structure.namespace = (json.namespace ? json.namespace : getModuleName(module)) } @@ -352,11 +353,178 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref return structure } -function getSchemaShape(json, module, { name = '', prefix = '', level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { +// function getSchemaShape(json, module, { name = '', prefix = '', level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { +// let shape = getSchemaShapeInfo(json, module, module['x-schemas'], { name, prefix, merged: false, level, title, summary, descriptions, destination, section, enums }) +// return shape +// } - let shape = getSchemaShapeInfo(json, module, module['x-schemas'], { name, prefix, merged: false, level, title, summary, descriptions, destination, section, enums }) - return shape +function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, summary, descriptions = true, destination, enums = true } = {}) { + schema = JSON.parse(JSON.stringify(schema)) + let structure = [] + + let prefix = (level === 0 ? 'typedef ' : '') + let operator = '' + let theTitle = schema.title || name + + theTitle = `F${module.info.title}_${theTitle}` + + if (enums && level === 0 && schema.type === "string" && Array.isArray(schema.enum)) { + return `typedef enum {\n\t` + schema.enum.map(value => value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase()).join(',\n\t') + `\n} ${schema.title || name};\n` + } + + if (!theTitle) { + prefix = operator = theTitle = '' + } + + if (schema['$ref']) { + if (level === 0) { + return `${prefix}${theTitle};` + } + else { + const someJson = getPath(schema['$ref'], module) + if (someJson) { + return getSchemaShape(someJson, module, { name, level, title, summary, descriptions, destination, enums: false }) + } + else { + ' '.repeat(level) + `${prefix}${theTitle}${operator}` + } + } + } + else if (schema.hasOwnProperty('const')) { + // TODO... + return ' '.repeat(level) + `${prefix}${theTitle}${operator} ` + JSON.stringify(schema.const) + } + else if (title && schema.title) { + let summary = '' + if (level > 0 && (summary || schema.description)) { + summary = `\t// ${(summary || schema.description).split('\n')[0]}` + } + return ' '.repeat(level) + `${prefix}${theTitle}${operator} ${name}; ` + summary + } + else if (schema.type === 'object') { + let suffix = '{' + + structure.push(' '.repeat(level) + `${prefix}struct${operator} ${suffix}`) + + if (schema.properties) { + Object.entries(schema.properties).forEach(([name, prop]) => { + if (!schema.required || !schema.required.includes(name)) { +// name = name + '?' + } + const schemaShape = getSchemaShape(prop, module, {name: name, summary: prop.description, descriptions: descriptions, level: level+1, title: true}) + structure.push(schemaShape) + }) + } + else if (schema.propertyNames) { + const { propertyNames } = localizeDependencies(schema, module) + if (propertyNames.enum) { + propertyNames.enum.forEach(prop => { + let type = 'any' + + if (schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { + type = getSchemaType(schema.additionalProperties, module) + } + + if (schema.patternProperties) { + Object.entries(schema.patternProperties).forEach(([pattern, schema]) => { + let regex = new RegExp(pattern) + if (prop.match(regex)) { + type = getSchemaType(schema, module) + } + }) + } + + return getSchemaShape(schema.propertyNames, module, { name: schema.title }) + +// structure.push(getSchemaShape({type: type}, module, {name: safeName(prop), descriptions: descriptions, level: level+1})) + }) + } + } + else if (schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { + let type = getSchemaType(schema.additionalProperties, module, { destination }) + structure.push(getSchemaShape({type: type}, module, {name: '[property: string]', descriptions: descriptions, level: level+1})) + } + + structure.push(' '.repeat(level) + `} ${theTitle};`) + } + else if (schema.anyOf) { + return ' '.repeat(level) + `${prefix}${theTitle}${operator} ` + schema.anyOf.map(s => getSchemaType(s, module, { name, level, title, summary, descriptions, destination })).join(' | ') + } + else if (schema.oneOf) { + return ' '.repeat(level) + `${prefix}${theTitle}${operator} ` + schema.oneOf.map(s => getSchemaType(s, module, { name, level, title, summary, descriptions, destination })).join(' | ') + } + else if (schema.allOf) { + const merger = (key) => function(a, b) { + if (a.const) { + return JSON.parse(JSON.stringify(a)) + } + else if (b.const) { + return JSON.parse(JSON.stringify(b)) + } + else { + return deepmerge(a, b, {customMerge: merger}) + } + } + + let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x).reverse()], { + customMerge: merger + }) + + if (schema.title) { + union.title = schema.title + } + delete union['$ref'] + + return getSchemaShape(union, module, { name, level, title, summary, descriptions, destination }) + } + else if (schema.type || schema.const) { + const isArrayWithSchemaForItems = schema.type === 'array' && schema.items && !Array.isArray(schema.items) + const isArrayWithSpecificItems = schema.type === 'array' && schema.items && Array.isArray(schema.items) + + // TODO: deal with fixed sized arrays vs arbitrary arrays + let suffix + let summary = '' + + if (schema.const) { + suffix = JSON.stringify(schema.const) + } + else if (isArrayWithSchemaForItems) { + suffix = getSchemaType(schema.items, module, { title: level ? true : false }) + '[]' // prefer schema title over robust descriptor + } + else if (isArrayWithSpecificItems) { + suffix = '[' + schema.items.map(i => getSchemaType(i, module, {title: level ? true : false })).join(', ') + ']' + } + else { + suffix = getSchemaType(schema, module, { title: level ? true : false }) // prefer schema title over robust descriptor + } + + // if there's a summary or description, append it as a comment (description only gets first line) + if (level > 0 && (summary || schema.description)) { + summary = `\t// ${summary || schema.description.split('\n')[0]}` + } + + if (suffix === 'array') { + suffix = '[]' + } + + if (theTitle === suffix) { + return ' '.repeat(level) + `${prefix}${name}` + } + else { + return ' '.repeat(level) + `${prefix}${suffix} ${name}${operator}; ${summary}` + } + } + + structure = structure.join('\n').split('\n') + + if (level === 0) { + const length = str => str.length + let max = Math.max(...structure.map(l => l.split('\t//')[0]).map(length)) + 2 + structure = structure.map( l => l.split('\t//').join(' '.repeat(max - l.split('\t//')[0].length) + '//')) + } + return structure.join('\n') } + function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '', merged = false, level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { let shape = '' @@ -430,7 +598,7 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, schemas, prefix) let t = description(capitalize(info.name), json.description) + '\n' - t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) c_shape += '\n' + t props.push({name: `${pname}`, type: `WPEFramework::Core::JSON::ArrayType<${subModuleProperty.type}>`}) } @@ -545,7 +713,7 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' t += description(capitalize(info.name), json.description) + '\n' t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, moduleProperty.type)) } - t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, '', info.type, info.json)) + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName), subModuleProperty.type, '', info.type, info.json)) shape += '\n' + t } } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 022437e8..927cbd53 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -27,7 +27,7 @@ import deepmerge from 'deepmerge' const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = predicates -const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' +const getModuleName = json => 'F' + getPathOr(null, ['info', 'title'], json) || json.title || 'missing' const getFireboltStringType = () => 'FireboltTypes_StringHandle' const getHeaderText = () => { diff --git a/languages/c/templates/declarations/default.c b/languages/c/templates/declarations/default.c index e69de29b..c1d5bc15 100644 --- a/languages/c/templates/declarations/default.c +++ b/languages/c/templates/declarations/default.c @@ -0,0 +1,5 @@ +/* + * ${method.summary} + * ${method.params} + */ +int F${info.title}_${method.Name}(${method.signature.params}${if.result.params}${if.params}, ${end.if.params}${end.if.result.params}${method.result.params}); diff --git a/languages/c/templates/declarations/event.c b/languages/c/templates/declarations/event.c index 45e4b608..42a8b136 100644 --- a/languages/c/templates/declarations/event.c +++ b/languages/c/templates/declarations/event.c @@ -1,4 +1,4 @@ /* ${method.name} - ${method.description} */ -typedef void (*${info.Title}${method.Name}Callback)( const void* userData, ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${event.result.type} ); -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 ); -uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); +typedef void (*${info.Title}${method.Name}Callback)( const void* userData, ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${event.result.type} ${method.result.name} ); +int ${info.title}_Register_${method.Name}( ${event.signature.params}${if.event.params}, ${end.if.event.params}${info.Title}${method.Name}Callback userCB, const void* userData ); +int ${info.title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); diff --git a/languages/c/templates/declarations/property.c b/languages/c/templates/declarations/property.c index 3550b45e..7ed669d8 100644 --- a/languages/c/templates/declarations/property.c +++ b/languages/c/templates/declarations/property.c @@ -2,4 +2,4 @@ * ${method.summary} * ${method.params} */ -${method.signature} +int F${info.title}_Get${method.Name}(${method.signature.params}${if.params}, ${end.if.params}${method.result.params}); diff --git a/languages/c/templates/language/enum-item.c b/languages/c/templates/language/enum-item.c new file mode 100644 index 00000000..79aabbeb --- /dev/null +++ b/languages/c/templates/language/enum-item.c @@ -0,0 +1 @@ + ${key} diff --git a/languages/c/templates/language/enum.c b/languages/c/templates/language/enum.c new file mode 100644 index 00000000..0551b99c --- /dev/null +++ b/languages/c/templates/language/enum.c @@ -0,0 +1,3 @@ +typedef enum { + ${items} +} F${info.title}_${title}; diff --git a/languages/c/templates/language/parameter.c b/languages/c/templates/language/parameter.c new file mode 100644 index 00000000..2ff7a678 --- /dev/null +++ b/languages/c/templates/language/parameter.c @@ -0,0 +1 @@ +${type} ${name} \ No newline at end of file diff --git a/languages/c/templates/language/schema-item.c b/languages/c/templates/language/schema-item.c new file mode 100644 index 00000000..ecded7d5 --- /dev/null +++ b/languages/c/templates/language/schema-item.c @@ -0,0 +1 @@ + ${type} ${property}; diff --git a/languages/c/templates/language/schema.c b/languages/c/templates/language/schema.c new file mode 100644 index 00000000..22760540 --- /dev/null +++ b/languages/c/templates/language/schema.c @@ -0,0 +1,3 @@ +typedef struct { + ${properties} +} F${info.title}_${title}; diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 6a023534..b69bab1f 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -1,6 +1,6 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_${method.Name}(${method.params.list}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { - uint32_t status = FireboltSDKErrorUnavailable; +int F${info.title}_${method.Name}(${method.signature.params}${if.result.params}${if.params}, ${end.if.params}${end.if.result.params}${method.result.params}) { + int status = FireboltSDKErrorUnavailable; FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { diff --git a/languages/c/templates/methods/event.c b/languages/c/templates/methods/event.c index ec868cd5..766a78b3 100644 --- a/languages/c/templates/methods/event.c +++ b/languages/c/templates/methods/event.c @@ -9,10 +9,10 @@ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* callback(userData, ${event.callback.response.instantiation}); } } -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 ) +int ${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}"); - uint32_t status = FireboltSDKErrorNone; + int status = FireboltSDKErrorNone; if (userCB != nullptr) { ${event.params.serialization} @@ -20,7 +20,7 @@ uint32_t ${info.Title}_Register_${method.Name}( ${event.signature.params}${if.ev } return status; } -uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB) +int ${info.title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB) { return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title}.${method.name}"), reinterpret_cast(userCB)); } diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index c7510da9..2d461f98 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,11 +1,10 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_Get${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name} ) -{ +int F${info.title}_Get${method.Name}(${method.signature.params}${if.params}, ${end.if.params}${method.result.params}) { const string method = _T("${info.title}.${method.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} - ${if.params.empty}uint32_t status = FireboltSDK::Properties::Get(method, jsonResult);${end.if.params.empty} + ${if.params}int status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult);${end.if.params} + ${if.params.empty}int status = FireboltSDK::Properties::Get(method, jsonResult);${end.if.params.empty} if (status == FireboltSDKErrorNone) { if (${method.result.name} != nullptr) { ${method.result.instantiation} diff --git a/languages/c/templates/types/enum.cpp b/languages/c/templates/types/enum.cpp index ddda2ae9..d18d882d 100644 --- a/languages/c/templates/types/enum.cpp +++ b/languages/c/templates/types/enum.cpp @@ -1,4 +1,4 @@ /* ${title} ${description} */ ENUM_CONVERSION_BEGIN(${info.title}_${name}) { ${info.TITLE}_${NAME}_${key}, _T("${value}") }, - ENUM_CONVERSION_END(${info.title}_${name}) + ENUM_CONVERSION_END(F${info.title}_${name}) diff --git a/languages/c/templates/types/enum.h b/languages/c/templates/types/enum.h index 6926fa77..9fa3c0a9 100644 --- a/languages/c/templates/types/enum.h +++ b/languages/c/templates/types/enum.h @@ -1,4 +1,4 @@ /* ${title} ${description} */ typedef enum { ${info.TITLE}_${NAME}_${key}, -} ${info.title}_${name}; +} F${info.title}_${name}; diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 85cb67e2..3f98b343 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -31,7 +31,7 @@ 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 isEmpty from 'crocks/core/isEmpty.js' -import { getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies, isDefinitionReferencedBySchema } from '../shared/json-schema.mjs' +import { getPath as getJsonPath, getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies, isDefinitionReferencedBySchema } from '../shared/json-schema.mjs' // util for visually debugging crocks ADTs const _inspector = obj => { @@ -548,12 +548,12 @@ const getEnumProperties = schema => compose( let enm = v if (isEnumType(v) == true) { enm = Object.assign({}, v) - enm.title = k + enm.title = schema.title + k[0].toUpperCase() + k.substring(1) } else if (v.type === 'object') { enm = getEnumProperties(v) } else if (v.type === 'array') { enm = Object.assign({}, (v.items[0] ? v.items[0] : v.items)) - enm.title = k + enm.title = schema.title + k[0].toUpperCase() + k.substring(1) } return enm })), @@ -562,6 +562,7 @@ const getEnumProperties = schema => compose( )(schema) const convertEnumTemplate = (sch, templateName, templates) => { + console.log(sch.title) const template = getTemplate(templateName, templates).split('\n') let schema = isEnumType(sch) ? sch : getEnumProperties(sch) for (var i = 0; i < template.length; i++) { @@ -1071,6 +1072,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.response'}) : '' const resultType = result.schema ? types.getSchemaType(result.schema, json, { name: result.name }) : '' const resultJsonType = result.schema ? types.getJsonType(result.schema, json, { name: result.name }) : '' + const resultParams = generateResultParams(result.schema, json, templates, { name: result.name }) let seeAlso = '' if (isPolymorphicPullMethod(methodObj) && pullsForType) { @@ -1102,6 +1104,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{method\.params\.array\}/g, JSON.stringify(methodObj.params.map(p => p.name))) .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\.params\}(.*?)\$\{end\.if\.result\.params\}/gms, resultParams ? '$1' : '') .replace(/\$\{if\.params.empty\}(.*?)\$\{end\.if\.params.empty\}/gms, method.params.length === 0 ? '$1' : '') .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event && event.params.length ? '$1' : '') .replace(/\$\{method\.params\.serialization\}/g, serializedParams) @@ -1143,6 +1146,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name : result.name })) .replace(/\$\{method\.result\.instantiation\}/g, resultInst) + .replace(/\$\{method\.result\.params\}/g, resultParams) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) .replace(/\$\{method\.alternative.link\}/g, '#'+(method.alternative || "").toLowerCase()) @@ -1308,6 +1312,23 @@ function generateResult(result, json, templates, { name = '' } = {}) { } } +// TODO: this is hard coded to C +function generateResultParams(result, json, templates, {name = ''}={}) { + while (result.$ref) { + result = getJsonPath(result.$ref, json) + } + + if (result.hasOwnProperty('const')) { + return '' + } + else if (result.type && result.type === 'object' && result.properties) { + return Object.entries(result.properties).map( ([name, type]) => `${types.getSchemaType(type, json, {name: name})} ${name}`).join(', ') + } + else { + return `${types.getSchemaType(result, json, { name: name})} *${name}` + } +} + function insertSchemaMacros(template, title, schema, module) { return template.replace(/\$\{property\}/g, title) .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { name: title, destination: state.destination, section: state.section, code: false })) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index b1d61ee4..5c83b795 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -277,7 +277,7 @@ const macrofy = async ( await writeFiles(outputFiles) if (persistPermission) { - await writeFilesPermissions(templatesPermission) +// await writeFilesPermissions(templatesPermission) } logSuccess(`Wrote ${Object.keys(outputFiles).length} files.`) From f3970c319dbb64bb512df9534aeb0462e42cd816 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 5 Jul 2023 14:54:52 -0400 Subject: [PATCH 016/137] fix: Promote and name sub-schemas in one place --- src/macrofier/engine.mjs | 549 ++++++++++++++++++++------------------- src/macrofier/index.mjs | 6 +- 2 files changed, 281 insertions(+), 274 deletions(-) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 85cb67e2..b167f4d4 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -50,16 +50,17 @@ const _inspector = obj => { // getSchemaInstantiation(schema, module, options = {type: 'params' | 'result' | 'callback.params'| 'callback.result' | 'callback.response'}) let types = { - getMethodSignature: ()=>null, - getMethodSignatureParams: ()=>null, - getSchemaShape: ()=>null, - getSchemaType: ()=>null, - getJsonType: ()=>null, - getSchemaInstantiation: ()=>null + getMethodSignature: () => null, + getMethodSignatureParams: () => null, + getSchemaShape: () => null, + getSchemaType: () => null, + getJsonType: () => null, + getSchemaInstantiation: () => null } let config = { - copySchemasIntoModules: false + copySchemasIntoModules: false, + extractSubSchemas: false } const state = { @@ -68,7 +69,6 @@ const state = { } const capitalize = str => str[0].toUpperCase() + str.substr(1) -const hasMethodsSchema = (json, options) => json.methods && json.methods.length const indent = (str, padding) => { let first = true @@ -129,21 +129,21 @@ const getLinkForSchema = (schema, json, { name = '' } = {}) => { return `#\$\{LINK:schema:${type}\}` } else { - const [group, schema] = Object.entries(json['x-schemas']).find( ([key, value]) => json['x-schemas'][key] && json['x-schemas'][key][type]) || [null, null] - if (group && schema) { - if (copySchemasIntoModules) { - return `#\$\{LINK:schema:${type}\}` + const [group, schema] = Object.entries(json['x-schemas']).find(([key, value]) => json['x-schemas'][key] && json['x-schemas'][key][type]) || [null, null] + if (group && schema) { + if (copySchemasIntoModules) { + return `#\$\{LINK:schema:${type}\}` + } + else { + const base = dirs ? '..' : '.' + if (dirs) { + return `${base}/${group}/schemas/#${type}` } else { - const base = dirs ? '..' : '.' - if (dirs) { - return `${base}/${group}/schemas/#${type}` - } - else { - return `${base}/schemas/${group}.md#${type}` - } + return `${base}/schemas/${group}.md#${type}` } } + } } return '#' @@ -348,14 +348,74 @@ const generateAggregateMacros = (openrpc, modules, templates, library) => Object library: library }) +const addContentDescriptorSubSchema = (descriptor, prefix, obj) => { + const title = prefix.charAt(0).toUpperCase() + prefix.substring(1) + descriptor.name.charAt(0).toUpperCase() + descriptor.name.substring(1) + if (obj.components.schemas[title]) { + throw 'Generated name `' + title + '` already exists...' + } + obj.components.schemas[title] = descriptor.schema + obj.components.schemas[title].title = title + descriptor.schema = { + $ref: "#/components/schemas/" + title + } +} + +// only consider sub-objects and sub enums to be sub-schemas +const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) + +const promoteAndNameSubSchemas = (obj) => { + // make a copy so we don't polute our inputs + obj = JSON.parse(JSON.stringify(obj)) + // find anonymous method param or result schemas and name/promote them + obj.methods && obj.methods.forEach(method => { + method.params && method.params.forEach(param => { + if (isSubSchema(param.schema)) { + addContentDescriptorSubSchema(param, method.name, obj) + } + }) + if (isSubSchema(method.result.schema)) { + addContentDescriptorSubSchema(method.result, method.name, obj) + } + }) + + // find non-primative sub-schemas of components.schemas and name/promote them + if (obj.components && obj.components.schemas) { + let more = true + while (more) { + more = false + Object.entries(obj.components.schemas).forEach(([key, schema]) => { + if (schema.type === "object" && schema.properties) { + Object.entries(schema.properties).forEach(([name, propSchema]) => { + if (isSubSchema(propSchema)) { + more = true + const descriptor = { + name: name, + schema: propSchema + } + addContentDescriptorSubSchema(descriptor, key, obj) + schema.properties[name] = descriptor.schema + } + }) + } + }) + } + } + + return obj +} + const generateMacros = (obj, templates, languages, options = {}) => { + // for languages that don't support nested schemas, let's promote them to first-class schemas w/ titles + if (config.extractSubSchemas) { + obj = promoteAndNameSubSchemas(obj) + } // grab the options so we don't have to pass them from method to method Object.assign(state, options) - const imports = generateImports(obj, templates, { destination : (options.destination ? options.destination : '') }) + const imports = generateImports(obj, templates, { destination: (options.destination ? options.destination : '') }) const initialization = generateInitialization(obj, templates) - const enums = generateEnums(obj, templates, { destination : (options.destination ? options.destination : '') }) + const enums = generateEnums(obj, templates, { destination: (options.destination ? options.destination : '') }) const eventsEnum = generateEvents(obj, templates) const examples = generateExamples(obj, templates, languages) @@ -367,10 +427,6 @@ const generateMacros = (obj, templates, languages, options = {}) => { const declarations = declarationsArray.length ? getTemplate('/sections/declarations', templates).replace(/\$\{declaration\.list\}/g, declarationsArray.map(m => m.declaration).join('\n')) : '' 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 methodTypesArray = generateSchemas(obj, templates, { baseUrl: '', section: 'methods_schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) - const methodTypes = methodTypesArray.length ? getTemplate('/sections/methods_types', templates).replace(/\$\{schema.list\}/g, methodTypesArray.map(s => s.body).filter(body => body).join('\n')) : '' - const methodAccessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'methods_accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) - const methodAccessors = methodAccessorsArray.length ? getTemplate('/sections/methods_accessors', templates).replace(/\$\{schema.list\}/g, methodAccessorsArray.map(s => s.body).filter(body => body).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')) : '' @@ -380,9 +436,9 @@ const generateMacros = (obj, templates, languages, options = {}) => { const accessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).filter(body => body).join('\n')) : '' const typesArray = schemasArray.length ? schemasArray.filter(x => !x.enum) : [] - const types = (typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodTypes + const types = (typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).filter(body => body).join('\n')) : '') - const accessors = (accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodAccessors + const accessors = (accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).filter(body => body).join('\n')) : '') const module = getTemplate('/codeblocks/module', templates) const macros = { @@ -425,7 +481,7 @@ const insertMacros = (fContents = '', macros = {}) => { if (macros.append) { fContents += '\n' + macros.module } - + const quote = config.operators ? config.operators.stringQuotation : '"' const or = config.operators ? config.operators.or : ' | ' @@ -453,7 +509,7 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{info\.TITLE\}/g, macros.title.toUpperCase()) fContents = fContents.replace(/\$\{info\.description\}/g, macros.description) fContents = fContents.replace(/\$\{info\.version\}/g, macros.version.readable) - + if (macros.public) { fContents = fContents.replace(/\$\{if\.public\}(.*?)\$\{end\.if\.public\}/gms, '$1') } @@ -498,7 +554,7 @@ function insertTableofContents(content) { count[slug] = 0 } const link = '#' + slug + (count[slug] ? `-${count[slug]}` : '') - toc += ' ' + ' '.repeat(level-1) + `- [${title}](${link})\n` + toc += ' ' + ' '.repeat(level - 1) + `- [${title}](${link})\n` } } }).join('\n') @@ -511,7 +567,7 @@ function insertTableofContents(content) { const index = candidates.findIndex(line => line.indexOf(`- [${match[2]}](`) >= 0) let extra = '' - + // add '-1' to schemas when there's more than once match if (index > 0 && match[1] === 'schema') { extra = '-1' @@ -525,51 +581,14 @@ function insertTableofContents(content) { return content } -const isEnumType = x => x.type !== 'undefined' && x.type === 'string' && Array.isArray(x.enum) - -const getProperties = x => { - return Array.isArray(x.properties) ? x.properties[0] : x.properties -} - -const isEnumProperties = schema => compose( - getProperties, - filter(enm => enm), - map(filter(enm => enm)), - map(props => props.map(([k, v]) => ((v.type === 'object') ? isEnumProperties(v) : ((v.type === 'array') ? isEnumType(v.items[0] ? v.items[0] : v.items): isEnumType(v))))), - map(Object.entries), - filter(schema => isObject(schema)) -)(schema) - -const getEnumProperties = schema => compose( - getProperties, - filter(enm => enm), - map(filter(isEnumType)), - map(props => props.map(([k, v]) => { - let enm = v - if (isEnumType(v) == true) { - enm = Object.assign({}, v) - enm.title = k - } else if (v.type === 'object') { - enm = getEnumProperties(v) - } else if (v.type === 'array') { - enm = Object.assign({}, (v.items[0] ? v.items[0] : v.items)) - enm.title = k - } - return enm - })), - map(Object.entries), - filter(schema => isObject(schema)) -)(schema) - -const convertEnumTemplate = (sch, templateName, templates) => { +const convertEnumTemplate = (schema, templateName, templates) => { const template = getTemplate(templateName, templates).split('\n') - let schema = isEnumType(sch) ? sch : getEnumProperties(sch) for (var i = 0; i < template.length; i++) { if (template[i].indexOf('${key}') >= 0) { template[i] = schema.enum.map(value => { const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() return template[i].replace(/\$\{key\}/g, safeName) - .replace(/\$\{value\}/g, value) + .replace(/\$\{value\}/g, value) }).join('\n') if (!templateName.includes(".cpp")) { template[i] = template[i].replace(/,*$/, ''); @@ -577,14 +596,14 @@ const convertEnumTemplate = (sch, templateName, templates) => { } } return template.join('\n') - .replace(/\$\{title\}/g, capitalize(schema.title)) - .replace(/\$\{description\}/g, schema.description ? ('- ' + schema.description) : '') - .replace(/\$\{name\}/g, schema.title) - .replace(/\$\{NAME\}/g, schema.title.toUpperCase()) + .replace(/\$\{title\}/g, capitalize(schema.title)) + .replace(/\$\{description\}/g, schema.description ? ('- ' + schema.description) : '') + .replace(/\$\{name\}/g, schema.title) + .replace(/\$\{NAME\}/g, schema.title.toUpperCase()) } const enumFinder = compose( - filter(x => ((isEnumType(x) && x.title) || isEnumProperties(x))), + filter(x => isEnum(x)), map(([_, val]) => val), filter(([_key, val]) => isObject(val)) ) @@ -659,24 +678,24 @@ const isEnum = x => x.type && x.type === 'string' && Array.isArray(x.enum) && x. function generateSchemas(json, templates, options) { let results = [] - const schemas = (options.section.includes('methods') ? (hasMethodsSchema(json) ? json.methods : '') : (json.definitions || (json.components && json.components.schemas) || {})) + const schemas = JSON.parse(JSON.stringify(json.definitions || (json.components && json.components.schemas) || {})) const generate = (name, schema, uri, { prefix = '' } = {}) => { // these are internal schemas used by the firebolt-openrpc tooling, and not meant to be used in code/doc generation if (['ListenResponse', 'ProviderRequest', 'ProviderResponse', 'FederatedResponse', 'FederatedRequest'].includes(name)) { return - } + } let content = getTemplate('/schemas/default', templates) if (!schema.examples || schema.examples.length === 0) { - content = content.replace(/\$\{if\.examples\}.*?\{end\.if\.examples\}/gms, '') + content = content.replace(/\$\{if\.examples\}.*?\{end\.if\.examples\}/gms, '') } else { content = content.replace(/\$\{if\.examples\}(.*?)\{end\.if\.examples\}/gms, '$1') } if (!schema.description) { - content = content.replace(/\$\{if\.description\}.*?\{end\.if\.description\}/gms, '') + content = content.replace(/\$\{if\.description\}.*?\{end\.if\.description\}/gms, '') } else { content = content.replace(/\$\{if\.description\}(.*?)\{end\.if\.description\}/gms, '$1') @@ -684,20 +703,20 @@ function generateSchemas(json, templates, options) { const schemaShape = types.getSchemaShape(schema, json, { name, prefix, destination: state.destination, section: options.section }) content = content - .replace(/\$\{schema.title\}/, (schema.title || name)) - .replace(/\$\{schema.description\}/, schema.description || '') - .replace(/\$\{schema.shape\}/, schemaShape) + .replace(/\$\{schema.title\}/, (schema.title || name)) + .replace(/\$\{schema.description\}/, schema.description || '') + .replace(/\$\{schema.shape\}/, schemaShape) if (schema.examples) { - content = content.replace(/\$\{schema.example\}/, schema.examples.map(ex => JSON.stringify(ex, null, ' ')).join('\n\n')) + content = content.replace(/\$\{schema.example\}/, schema.examples.map(ex => JSON.stringify(ex, null, ' ')).join('\n\n')) } let seeAlso = getRelatedSchemaLinks(schema, json, templates, options) if (seeAlso) { - content = content.replace(/\$\{schema.seeAlso\}/, '\n\n' + seeAlso) + content = content.replace(/\$\{schema.seeAlso\}/, '\n\n' + seeAlso) } else { - content = content.replace(/.*\$\{schema.seeAlso\}/, '') + content = content.replace(/.*\$\{schema.seeAlso\}/, '') } content = content.trim().length ? content.trimEnd() : content.trim() @@ -720,30 +739,18 @@ function generateSchemas(json, templates, options) { const list = [] // schemas may be 1 or 2 levels deeps - Object.entries(schemas).forEach( ([name, schema]) => { + Object.entries(schemas).forEach(([name, schema]) => { if (isSchema(schema)) { list.push([name, schema]) } - else if (schema.tags) { - if (!isDeprecatedMethod(schema)) { - schema.params.forEach(param => { - if (param.schema && (param.schema.type === 'object')) { - list.push([param.name, param.schema, '', { prefix : schema.name }]) - } - }) - if (schema.result.schema && (schema.result.schema.type === 'object')) { - list.push([schema.result.name, schema.result.schema, '', { prefix : schema.name }]) - } - } - } }) list.sort((a, b) => { const aInB = isDefinitionReferencedBySchema('#/components/schemas/' + a[0], b[1]) const bInA = isDefinitionReferencedBySchema('#/components/schemas/' + b[0], a[1]) - if(isEnum(a[1]) || (aInB && !bInA)) { + if (isEnum(a[1]) || (aInB && !bInA)) { return -1 - } else if(isEnum(b[1]) || (!aInB && bInA)) { + } else if (isEnum(b[1]) || (!aInB && bInA)) { return 1 } return 0; @@ -762,14 +769,14 @@ function getRelatedSchemaLinks(schema = {}, json = {}, templates = {}, options = // - convert them to the $ref value (which are paths to other schema files), instead of the path to the ref node itself // - convert those into markdown links of the form [Schema](Schema#/link/to/element) let links = getLinkedSchemaPaths(schema) - .map(path => getPathOr(null, path, schema)) - .filter(path => seen.hasOwnProperty(path) ? false : (seen[path] = true)) - .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, 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') + .map(path => getPathOr(null, path, schema)) + .filter(path => seen.hasOwnProperty(path) ? false : (seen[path] = true)) + .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, 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') return links } @@ -882,13 +889,13 @@ function generateExamples(json = {}, mainTemplates = {}, languages = {}) { examples[method.name] = method.examples.map(example => ({ json: example, value: example.result.value, - languages: Object.fromEntries(Object.entries(languages).map( ([lang, templates]) => ([lang, { + languages: Object.fromEntries(Object.entries(languages).map(([lang, templates]) => ([lang, { langcode: templates['__config'].langcode, code: getTemplateForExample(method, templates) - .replace(/\$\{rpc\.example\.params\}/g, JSON.stringify(Object.fromEntries(example.params.map(param => [param.name, param.value])))), + .replace(/\$\{rpc\.example\.params\}/g, JSON.stringify(Object.fromEntries(example.params.map(param => [param.name, param.value])))), result: getTemplateForExampleResult(method, templates) - .replace(/\$\{example\.result\}/g, JSON.stringify(example.result.value, null, '\t')) - .replace(/\$\{example\.result\.item\}/g, Array.isArray(example.result.value) ? JSON.stringify(example.result.value[0], null, '\t') : ''), + .replace(/\$\{example\.result\}/g, JSON.stringify(example.result.value, null, '\t')) + .replace(/\$\{example\.result\.item\}/g, Array.isArray(example.result.value) ? JSON.stringify(example.result.value[0], null, '\t') : ''), template: lang === 'JSON-RPC' ? getTemplate('/examples/jsonrpc', mainTemplates) : getTemplateForExample(method, mainTemplates) // getTemplate('/examples/default', mainTemplates) }]))) })) @@ -898,7 +905,7 @@ function generateExamples(json = {}, mainTemplates = {}, languages = {}) { examples[method.name] = examples[method.name].map(example => ({ json: example.json, value: example.value, - languages: Object.fromEntries(Object.entries(example.languages).filter( ([k, v]) => k === 'JSON-RPC')) + languages: Object.fromEntries(Object.entries(example.languages).filter(([k, v]) => k === 'JSON-RPC')) })) } @@ -909,7 +916,7 @@ function generateExamples(json = {}, mainTemplates = {}, languages = {}) { example.languages['JSON-RPC'].code = JSON.stringify(JSON.parse(example.languages['JSON-RPC'].code), null, '\t') example.languages['JSON-RPC'].result = JSON.stringify(JSON.parse(example.languages['JSON-RPC'].result), null, '\t') } - catch (error) {} + catch (error) { } } }) }) @@ -974,12 +981,12 @@ function generateMethods(json = {}, examples = {}, templates = {}) { body: getTemplate('/methods/once', templates), declaration: getTemplate('/declarations/once', templates) }) - + results.push({ name: "clear", body: getTemplate('/methods/clear', templates), declaration: getTemplate('/declarations/clear', templates) - }) + }) } results.sort((a, b) => a.name.localeCompare(b.name)) @@ -988,7 +995,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, examples = {}) { const moduleName = getModuleName(json) const info = { @@ -1036,12 +1043,12 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const result = JSON.parse(JSON.stringify(methodObj.result)) const event = isEventMethod(methodObj) ? JSON.parse(JSON.stringify(methodObj)) : '' - + if (event) { result.schema = JSON.parse(JSON.stringify(getPayloadFromEvent(methodObj))) event.result.schema = getPayloadFromEvent(event) event.params = event.params.filter(p => p.name !== 'listen') - } + } const eventParams = event.params && event.params.length ? getTemplate('/sections/parameters', templates) + event.params.map(p => insertParameterMacros(getTemplate('/parameters/default', templates), p, event, json)).join('') : '' const eventParamsRows = event.params && event.params.length ? event.params.map(p => insertParameterMacros(getTemplate('/parameters/default', templates), p, event, json)).join('') : '' @@ -1059,16 +1066,16 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const subscriberTemplate = (subscriber ? insertMethodMacros(getTemplate('/codeblocks/subscriber', templates), subscriber, json, templates, 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 + const pullsParams = (puller || pullsFor) ? localizeDependencies(getPayloadFromEvent(puller || methodObj), json, null, { mergeAllOfs: true }).properties.parameters : null const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) - const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) - const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' - const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, {instantiationType: 'params'}) - const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' } ) - const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'params'}), ' ') : '' - const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.params'}) : '' - const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.result'}) : '' - const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.response'}) : '' + const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) + const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, { instantiationType: 'params' }) + const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' }) + const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'params' }), ' ') : '' + const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.params' }) : '' + const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.result' }) : '' + const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.response' }) : '' const resultType = result.schema ? types.getSchemaType(result.schema, json, { name: result.name }) : '' const resultJsonType = result.schema ? types.getJsonType(result.schema, json, { name: result.name }) : '' @@ -1082,9 +1089,9 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { } if (isTemporalSetMethod(methodObj)) { - itemName = result.schema.items.title || 'item' - itemName = itemName.charAt(0).toLowerCase() + itemName.substring(1) - itemType = types.getSchemaType(result.schema.items, json, { destination: state.destination, section: state.section }) + itemName = result.schema.items.title || 'item' + itemName = itemName.charAt(0).toLowerCase() + itemName.substring(1) + itemType = types.getSchemaType(result.schema.items, json, { destination: state.destination, section: state.section }) } template = insertExampleMacros(template, examples[methodObj.name] || [], methodObj, json, templates) @@ -1092,7 +1099,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { template = template.replace(/\$\{method\.name\}/g, method.name) .replace(/\$\{method\.summary\}/g, methodObj.summary) .replace(/\$\{method\.description\}/g, methodObj.description - || methodObj.summary) + || methodObj.summary) // Parameter stuff .replace(/\$\{method\.params\}/g, params) .replace(/\$\{method\.params\.table\.rows\}/g, paramsRows) @@ -1106,8 +1113,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event && event.params.length ? '$1' : '') .replace(/\$\{method\.params\.serialization\}/g, serializedParams) // Typed signature stuff - .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) - .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination, section: state.section })) + .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) + .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(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\.deprecation\}/g, deprecation) @@ -1116,7 +1123,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{event\.params\}/g, eventParams) .replace(/\$\{event\.params\.table\.rows\}/g, eventParamsRows) .replace(/\$\{if\.event\.params\}(.*?)\$\{end\.if\.event\.params\}/gms, event && event.params.length ? '$1' : '') - .replace(/\$\{event\.signature\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section }) : '') + .replace(/\$\{event\.signature\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section }) : '') .replace(/\$\{event\.signature\.callback\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section, callback: true }) : '') .replace(/\$\{event\.params\.serialization\}/g, serializedEventParams) .replace(/\$\{event\.callback\.params\.serialization\}/g, callbackSerializedParams) @@ -1136,22 +1143,22 @@ 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, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') + .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, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) - .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name : result.name })) + .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) .replace(/\$\{method\.result\.instantiation\}/g, resultInst) - .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) + .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) - .replace(/\$\{method\.alternative.link\}/g, '#'+(method.alternative || "").toLowerCase()) - .replace(/\$\{method\.pulls\.for\}/g, pullsFor ? pullsFor.name : '' ) + .replace(/\$\{method\.alternative.link\}/g, '#' + (method.alternative || "").toLowerCase()) + .replace(/\$\{method\.pulls\.for\}/g, pullsFor ? pullsFor.name : '') .replace(/\$\{method\.pulls\.type\}/g, pullsForType) .replace(/\$\{method\.pulls\.result\}/g, pullsResultType) .replace(/\$\{method\.pulls\.params.type\}/g, pullsParams ? pullsParams.title : '') .replace(/\$\{method\.pulls\.params\}/g, pullsParamsType) - .replace(/\$\{method\.setter\.for\}/g, setterFor ) + .replace(/\$\{method\.setter\.for\}/g, setterFor) .replace(/\$\{method\.puller\}/g, pullerTemplate) // must be last!! .replace(/\$\{method\.setter\}/g, setterTemplate) // must be last!! .replace(/\$\{method\.subscriber\}/g, subscriberTemplate) // must be last!! @@ -1171,7 +1178,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { template = template.replace(/\$\{method\.params\[([0-9]+)\]\.type\}/g, types.getSchemaType(methodObj.params[index].schema, json, { destination: state.destination })) template = template.replace(/\$\{method\.params\[([0-9]+)\]\.name\}/g, methodObj.params[index].name) }) - + // Note that we do this twice to ensure all recursive macros are resolved template = insertExampleMacros(template, examples[methodObj.name] || [], methodObj, json, templates) @@ -1209,38 +1216,38 @@ function insertExampleMacros(template, examples, method, json, templates) { let indent = ' '.repeat(json.info.title.length + method.name.length + 2) let params = formatParams(method.params, ', ') if (params.length + indent > 80) { - params = formatParams(method.params, ',\n', true) - params = params.split('\n') - let first = params.shift() - params = params.map(p => indent + p) - params.unshift(first) - params = params.join('\n') + params = formatParams(method.params, ',\n', true) + params = params.split('\n') + let first = params.shift() + params = params.map(p => indent + p) + params.unshift(first) + params = params.join('\n') } languageContent = languageContent - .replace(/\$\{example\.code\}/g, language.code) - .replace(/\$\{example\.name\}/g, example.json.name) - .replace(/\$\{example\.language\}/g, name) - .replace(/\$\{example\.langcode\}/g, language.langcode) - - .replace(/\$\{method\.result\.name\}/g, method.result.name) - .replace(/\$\{method\.name\}/g, method.name) - .replace(/\$\{example\.params\}/g, params) - .replace(/\$\{example\.result\}/g, language.result) - .replace(/\$\{example\.result\.item\}/g, Array.isArray(example.json.result.value) ? JSON.stringify(example.json.result.value[0], null, '\t') : '') - .replace(/\$\{module\}/g, json.info.title) + .replace(/\$\{example\.code\}/g, language.code) + .replace(/\$\{example\.name\}/g, example.json.name) + .replace(/\$\{example\.language\}/g, name) + .replace(/\$\{example\.langcode\}/g, language.langcode) + + .replace(/\$\{method\.result\.name\}/g, method.result.name) + .replace(/\$\{method\.name\}/g, method.name) + .replace(/\$\{example\.params\}/g, params) + .replace(/\$\{example\.result\}/g, language.result) + .replace(/\$\{example\.result\.item\}/g, Array.isArray(example.json.result.value) ? JSON.stringify(example.json.result.value[0], null, '\t') : '') + .replace(/\$\{module\}/g, json.info.title) const matches = [...languageContent.matchAll(/\$\{method\.params\[([0-9]+)\]\.example\.value\}/g)] matches.forEach(match => { const paramIndex = parseInt(match[1]) let indent = 0 - while (match.index-indent >= 0 && match.input[match.index-indent] !== '\n') { + while (match.index - indent >= 0 && match.input[match.index - indent] !== '\n') { indent++ } - const value = JSON.stringify(method.examples[index].params[paramIndex].value, null, '\t').split('\n').map( (line, i) => i > 0 ? ' '.repeat(indent) + line : line).join('\n') + const value = JSON.stringify(method.examples[index].params[paramIndex].value, null, '\t').split('\n').map((line, i) => i > 0 ? ' '.repeat(indent) + line : line).join('\n') languageContent = languageContent.replace(/\$\{method\.params\[([0-9]+)\]\.example\.value\}/g, value) }) - + if (originator) { const originalExample = originator.examples.length > index ? originator.examples[index] : originator.examples[0] @@ -1248,10 +1255,10 @@ function insertExampleMacros(template, examples, method, json, templates) { matches.forEach(match => { const paramIndex = parseInt(match[1]) let indent = 0 - while (match.index-indent >= 0 && match.input[match.index-indent] !== '\n') { + while (match.index - indent >= 0 && match.input[match.index - indent] !== '\n') { indent++ } - const value = JSON.stringify(originalExample.params[paramIndex].value, null, '\t').split('\n').map( (line, i) => i > 0 ? ' '.repeat(indent) + line : line).join('\n') + const value = JSON.stringify(originalExample.params[paramIndex].value, null, '\t').split('\n').map((line, i) => i > 0 ? ' '.repeat(indent) + line : line).join('\n') languageContent = languageContent.replace(/\$\{originator\.params\[([0-9]+)\]\.example\.value\}/g, value) }) } @@ -1273,12 +1280,12 @@ function insertExampleMacros(template, examples, method, json, templates) { function generateResult(result, json, templates, { name = '' } = {}) { - const type = types.getSchemaType(result, json, { name: name, destination: state.destination, section: state.section }) + const type = types.getSchemaType(result, json, { name: name, destination: state.destination, section: state.section }) if (result.type === 'object' && result.properties) { let content = getTemplate('/types/object', templates).split('\n') - for (var i=0; i= 0) { content[i] = Object.entries(result.properties).map(([title, property]) => insertSchemaMacros(content[i], title, property, json)).join('\n') } @@ -1290,17 +1297,17 @@ 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, { name: name }) // if we get a real link use it if (link !== '#') { - return `[${types.getSchemaType(result, json, { destination: state.destination, section: state.section })}](${link})` + return `[${types.getSchemaType(result, json, { destination: state.destination, section: state.section })}](${link})` } // otherwise this was a schema with no title, and we'll just copy it here else { const schema = localizeDependencies(result, json) return getTemplate('/types/default', templates) - .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { name: result.$ref.split("/").pop() })) + .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { name: result.$ref.split("/").pop() })) } } else { @@ -1310,15 +1317,15 @@ function generateResult(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, destination: state.destination, section: state.section, code: false })) - .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module, { name: title })) - .replace(/\$\{description\}/g, schema.description || '') - .replace(/\$\{name\}/g, title || '') + .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { name: title, destination: state.destination, section: state.section, code: false })) + .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module, { name: title })) + .replace(/\$\{description\}/g, schema.description || '') + .replace(/\$\{name\}/g, title || '') } function insertParameterMacros(template, param, method, module) { -//| `${method.param.name}` | ${method.param.type} | ${method.param.required} | ${method.param.summary} ${method.param.constraints} | + //| `${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, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl @@ -1326,18 +1333,18 @@ function insertParameterMacros(template, param, method, module) { let jsonType = types.getJsonType(param.schema, module, { name: param.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) if (constraints && type) { - constraints = '
' + constraints + constraints = '
' + constraints } return template - .replace(/\$\{method.param.name\}/g, param.name) - .replace(/\$\{method.param.Name\}/g, param.name[0].toUpperCase() + param.name.substring(1)) - .replace(/\$\{method.param.summary\}/g, param.summary || '') - .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.constraints\}/g, constraints) //getType(param)) + .replace(/\$\{method.param.name\}/g, param.name) + .replace(/\$\{method.param.Name\}/g, param.name[0].toUpperCase() + param.name.substring(1)) + .replace(/\$\{method.param.summary\}/g, param.summary || '') + .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.constraints\}/g, constraints) //getType(param)) } function insertCapabilityMacros(template, capabilities, method, module) { @@ -1347,18 +1354,18 @@ function insertCapabilityMacros(template, capabilities, method, module) { roles.forEach(role => { if (capabilities[role] && capabilities[role].length) { content.push(template.replace(/\$\{role\}/g, role.split('-').pop()) - .replace(/\$\{capability\}/g, capabilities[role].join('
'))) // Warning, hack! + .replace(/\$\{capability\}/g, capabilities[role].join('
'))) // Warning, hack! } }) if (capabilities['x-provides']) { content.push(template.replace(/\$\{role\}/g, 'provides') - .replace(/\$\{capability\}/g, capabilities['x-provides'])) -} + .replace(/\$\{capability\}/g, capabilities['x-provides'])) + } return content.join() } - + function generateProviderInterfaces(json, templates) { const interfaces = getProvidedCapabilities(json) let template = getTemplate('/sections/provider-interfaces', templates) @@ -1384,83 +1391,83 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te let interfaceShape = getTemplate('/codeblocks/interface', templates) interfaceShape = interfaceShape.replace(/\$\{name\}/g, name) - .replace(/\$\{capability\}/g, capability) - .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => `\t${types.getMethodSignature(method, moduleJson, { destination: state.destination, section: state.section, isInterface: true })}`).join('\n') + '\n') + .replace(/\$\{capability\}/g, capability) + .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => `\t${types.getMethodSignature(method, moduleJson, { destination: state.destination, section: state.section, isInterface: true })}`).join('\n') + '\n') if (iface.length === 0) { - template = template.replace(/\$\{provider\.methods\}/gms, '') + template = template.replace(/\$\{provider\.methods\}/gms, '') } else { - let regex = /\$\{provider\.methods\}/gms - let match = template.match(regex) + let regex = /\$\{provider\.methods\}/gms + let match = template.match(regex) + + let methodsBlock = '' + + // insert the standard method templates for each provider + if (match) { + iface.forEach(method => { + // add a tag to pick the correct template + method.tags.unshift({ + name: 'provider' + }) + const parametersSchema = method.params[0].schema + const parametersShape = types.getSchemaShape(parametersSchema, moduleJson, { destination: state.destination, section: state.section }) + let methodBlock = insertMethodMacros(getTemplateForMethod(method, templates), method, moduleJson, templates) + methodBlock = methodBlock.replace(/\${parameters\.shape\}/g, parametersShape) + const hasProviderParameters = parametersSchema && parametersSchema.properties && Object.keys(parametersSchema.properties).length > 0 + if (hasProviderParameters) { + const lines = methodBlock.split('\n') + for (let i = lines.length - 1; i >= 0; i--) { + if (lines[i].match(/\$\{provider\.param\.[a-zA-Z]+\}/)) { + let line = lines[i] + lines.splice(i, 1) + line = insertProviderParameterMacros(line, method.params[0].schema, moduleJson) + lines.splice(i++, 0, line) + } + } + methodBlock = lines.join('\n') + } + else { + methodBlock = methodBlock.replace(/\$\{if\.provider\.params\}.*?\$\{end\.if\.provider\.params\}/gms, '') + } + methodsBlock += methodBlock + }) + + match = template.match(regex) + template = template.replace(regex, methodsBlock) + } + regex = /\$\{provider\.interface\.start\}.*?\$\{provider\.interface\.end\}/s + + // insert the granular method details for any ${provider.method.start} loops + while (match = template.match(regex)) { let methodsBlock = '' - - // insert the standard method templates for each provider - if (match) { - iface.forEach(method => { - // add a tag to pick the correct template - method.tags.unshift({ - name: 'provider' - }) - const parametersSchema = method.params[0].schema - const parametersShape = types.getSchemaShape(parametersSchema, moduleJson, { destination: state.destination, section: state.section }) - let methodBlock = insertMethodMacros(getTemplateForMethod(method, templates), method, moduleJson, templates) - methodBlock = methodBlock.replace(/\${parameters\.shape\}/g, parametersShape) - const hasProviderParameters = parametersSchema && parametersSchema.properties && Object.keys(parametersSchema.properties).length > 0 - if (hasProviderParameters) { - const lines = methodBlock.split('\n') - for (let i = lines.length - 1; i >= 0; i--) { - if (lines[i].match(/\$\{provider\.param\.[a-zA-Z]+\}/)) { - let line = lines[i] - lines.splice(i, 1) - line = insertProviderParameterMacros(line, method.params[0].schema, moduleJson) - lines.splice(i++, 0, line) - } - } - methodBlock = lines.join('\n') - } - else { - methodBlock = methodBlock.replace(/\$\{if\.provider\.params\}.*?\$\{end\.if\.provider\.params\}/gms, '') - } - methodsBlock += methodBlock - }) - match = template.match(regex) - template = template.replace(regex, methodsBlock) - } + let i = 1 + iface.forEach(method => { - regex = /\$\{provider\.interface\.start\}.*?\$\{provider\.interface\.end\}/s - - // insert the granular method details for any ${provider.method.start} loops - while (match = template.match(regex)) { - let methodsBlock = '' - - let i = 1 - iface.forEach(method => { - - methodsBlock += match[0].replace(/\$\{provider\.interface\.name\}/g, method.name) - .replace(/\$\{provider\.interface\.Name\}/g, method.name.charAt(0).toUpperCase() + method.name.substr(1)) - - // first check for indented lines, and do the fancy indented replacement - .replace(/^([ \t]+)(.*?)\$\{provider\.interface\.example\.result\}/gm, '$1$2' + indent(JSON.stringify(method.examples[0].result.value, null, ' '), '$1')) - .replace(/^([ \t]+)(.*?)\$\{provider\.interface\.example\.parameters\}/gm, '$1$2' + indent(JSON.stringify(method.examples[0].params[0].value, null, ' '), '$1')) - // okay now just do the basic replacement (a single regex for both was not fun) - .replace(/\$\{provider\.interface\.example\.result\}/g, JSON.stringify(method.examples[0].result.value)) - .replace(/\$\{provider\.interface\.example\.parameters\}/g, JSON.stringify(method.examples[0].params[0].value)) - - .replace(/\$\{provider\.interface\.example\.correlationId\}/g, JSON.stringify(method.examples[0].params[1].value.correlationId)) - - // a set of up to three RPC "id" values for generating intersting examples with matching ids - .replace(/\$\{provider\.interface\.i\}/g, i) - .replace(/\$\{provider\.interface\.j\}/g, (i+iface.length)) - .replace(/\$\{provider\.interface\.k\}/g, (i+2*iface.length)) - - i++ - }) - methodsBlock = methodsBlock.replace(/\$\{provider\.interface\.[a-zA-Z]+\}/g, '') - template = template.replace(regex, methodsBlock) - } + methodsBlock += match[0].replace(/\$\{provider\.interface\.name\}/g, method.name) + .replace(/\$\{provider\.interface\.Name\}/g, method.name.charAt(0).toUpperCase() + method.name.substr(1)) + + // first check for indented lines, and do the fancy indented replacement + .replace(/^([ \t]+)(.*?)\$\{provider\.interface\.example\.result\}/gm, '$1$2' + indent(JSON.stringify(method.examples[0].result.value, null, ' '), '$1')) + .replace(/^([ \t]+)(.*?)\$\{provider\.interface\.example\.parameters\}/gm, '$1$2' + indent(JSON.stringify(method.examples[0].params[0].value, null, ' '), '$1')) + // okay now just do the basic replacement (a single regex for both was not fun) + .replace(/\$\{provider\.interface\.example\.result\}/g, JSON.stringify(method.examples[0].result.value)) + .replace(/\$\{provider\.interface\.example\.parameters\}/g, JSON.stringify(method.examples[0].params[0].value)) + + .replace(/\$\{provider\.interface\.example\.correlationId\}/g, JSON.stringify(method.examples[0].params[1].value.correlationId)) + + // a set of up to three RPC "id" values for generating intersting examples with matching ids + .replace(/\$\{provider\.interface\.i\}/g, i) + .replace(/\$\{provider\.interface\.j\}/g, (i + iface.length)) + .replace(/\$\{provider\.interface\.k\}/g, (i + 2 * iface.length)) + + i++ + }) + methodsBlock = methodsBlock.replace(/\$\{provider\.interface\.[a-zA-Z]+\}/g, '') + template = template.replace(regex, methodsBlock) + } } // TODO: JSON-RPC examples need to use ${provider.interface} macros, but we're replacing them globally instead of each block @@ -1476,25 +1483,25 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te function insertProviderParameterMacros(data = '', parameters, module = {}, options = {}) { if (!parameters || !parameters.properties) { - return '' + return '' } let result = '' Object.entries(parameters.properties).forEach(([name, param]) => { - let constraints = getSchemaConstraints(param, module) - let type = types.getSchemaType(param, module, { destination: state.destination, section: state.section, code: true, link: true, title: true, asPath: options.asPath, baseUrl: options.baseUrl }) + let constraints = getSchemaConstraints(param, module) + let type = types.getSchemaType(param, module, { destination: state.destination, section: state.section, code: true, link: true, title: true, asPath: options.asPath, baseUrl: options.baseUrl }) - if (constraints && type) { - constraints = '
' + constraints - } + if (constraints && type) { + constraints = '
' + constraints + } - result += data - .replace(/\$\{provider.param.name\}/, name) - .replace(/\$\{provider.param.summary\}/, param.description || '') - .replace(/\$\{provider.param.required\}/, (parameters.required && parameters.required.includes(name)) || 'false') - .replace(/\$\{provider.param.type\}/, type) - .replace(/\$\{provider.param.constraints\}/, constraints) + '\n' + result += data + .replace(/\$\{provider.param.name\}/, name) + .replace(/\$\{provider.param.summary\}/, param.description || '') + .replace(/\$\{provider.param.required\}/, (parameters.required && parameters.required.includes(name)) || 'false') + .replace(/\$\{provider.param.type\}/, type) + .replace(/\$\{provider.param.constraints\}/, constraints) + '\n' }) return result diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index b1d61ee4..58a9e7e2 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -46,6 +46,7 @@ const macrofy = async ( persistPermission, createModuleDirectories, copySchemasIntoModules, + extractSubSchemas = true, aggregateFile, operators, hidePrivate = true, @@ -63,8 +64,6 @@ const macrofy = async ( return new Promise( async (resolve, reject) => { const openrpc = await readJson(input) - - logHeader(`Generating ${headline} for version ${openrpc.info.title} ${openrpc.info.version}`) let typer @@ -81,6 +80,7 @@ const macrofy = async ( engine.setConfig({ copySchemasIntoModules, createModuleDirectories, + extractSubSchemas, operators }) @@ -277,7 +277,7 @@ const macrofy = async ( await writeFiles(outputFiles) if (persistPermission) { - await writeFilesPermissions(templatesPermission) + //await writeFilesPermissions(templatesPermission) } logSuccess(`Wrote ${Object.keys(outputFiles).length} files.`) From 2a39d442fcb8a48e5131db3b6a60cad956177acc Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 5 Jul 2023 15:32:58 -0400 Subject: [PATCH 017/137] fix: Add extractSubSchemas flag to C language --- languages/c/language.config.json | 1 + src/macrofier/index.mjs | 2 +- src/sdk/index.mjs | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/languages/c/language.config.json b/languages/c/language.config.json index 97e90519..77cde389 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -2,6 +2,7 @@ "name": "C", "langcode": "c", "createModuleDirectories": false, + "extractSubSchemas": true, "templatesPerModule": [ "/include/Module.h", "/src/Module.cpp" diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 58a9e7e2..0012d86a 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -46,7 +46,7 @@ const macrofy = async ( persistPermission, createModuleDirectories, copySchemasIntoModules, - extractSubSchemas = true, + extractSubSchemas, aggregateFile, operators, hidePrivate = true, diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index c5727cfc..7e85fab9 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -61,6 +61,7 @@ const run = async ({ operators: config.operators, createModuleDirectories: config.createModuleDirectories, copySchemasIntoModules: config.copySchemasIntoModules, + extractSubSchemas: config.extractSubSchemas, staticModuleNames: staticModuleNames, hideExcluded: true, aggregateFile: config.aggregateFile, From b3eb478f73a4eb251860b5da0353e401939b70ec Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 5 Jul 2023 15:39:25 -0400 Subject: [PATCH 018/137] fix: Uncomment writeFilePermissions --- src/macrofier/index.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 0012d86a..3db5d17a 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -277,7 +277,7 @@ const macrofy = async ( await writeFiles(outputFiles) if (persistPermission) { - //await writeFilesPermissions(templatesPermission) + await writeFilesPermissions(templatesPermission) } logSuccess(`Wrote ${Object.keys(outputFiles).length} files.`) From ad4fb21b2a28c5938ef090b6c49d3fb49abe7a10 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 10 Jul 2023 10:12:50 +0530 Subject: [PATCH 019/137] polymorphic-pull: method and event implementation added (#107) --- languages/c/Types.mjs | 26 ++++++--- .../declarations/polymorphic-pull-event.c | 4 ++ .../templates/declarations/polymorphic-pull.c | 2 + .../methods/polymorphic-pull-event.c | 54 +++++++++++++++++++ .../c/templates/methods/polymorphic-pull.c | 12 ++--- src/macrofier/engine.mjs | 16 ++++-- 6 files changed, 97 insertions(+), 17 deletions(-) create mode 100644 languages/c/templates/declarations/polymorphic-pull-event.c create mode 100644 languages/c/templates/declarations/polymorphic-pull.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 72912930..edf817c9 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -205,15 +205,21 @@ function getMethodSignature(method, module, { destination, isInterface = false } return signature } -function getMethodSignatureParams(method, module, { destination, callback= false } = {}) { - - return method.params.map(param => { +function getMethodSignatureParams(method, module, { destination, callback = false } = {}) { + let signatureParams = '' + let polymorphicPull = method.tags.find(t => t.name === 'polymorphic-pull') + method.params.map(param => { + if (polymorphicPull && (param.name === 'correlationId')) { + return + } + signatureParams += (signatureParams.length > 0) ? ', ' : '' let type = getSchemaType(param.schema, module, { name: param.name, title: true, destination }) if ((callback === true) && (type === 'char*')) { type = getFireboltStringType() } - return type + (!param.required ? '* ' : ' ') + param.name - }).join(', ') + signatureParams += type + (!param.required ? '* ' : ' ') + param.name + }) + return signatureParams } const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop @@ -738,19 +744,23 @@ function getSchemaInstantiation(schema, module, name, { instantiationType = '' } return getResultInstantiation(name, resultType, resultJsonType) } else if (instantiationType === 'callback.params') { - let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' return getCallbackParametersInstantiation(getParamList(schema, module), resultJsonType) } else if (instantiationType === 'callback.result') { let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' - let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' return getCallbackResultInstantiation(resultType, resultJsonType) } else if (instantiationType === 'callback.response') { let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' - let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' return getCallbackResponseInstantiation(getParamList(schema, module), resultType, resultJsonType) } + else if (instantiationType === 'pull.param.name') { + let resultJsonType = getJsonType(schema, module, { name: name }) || '' + return resultJsonType && resultJsonType[0].split('_')[1] || '' + } return '' } diff --git a/languages/c/templates/declarations/polymorphic-pull-event.c b/languages/c/templates/declarations/polymorphic-pull-event.c new file mode 100644 index 00000000..26f1f1c4 --- /dev/null +++ b/languages/c/templates/declarations/polymorphic-pull-event.c @@ -0,0 +1,4 @@ +/* ${method.name} - ${method.description} */ +typedef void* (*${info.Title}${method.Name}Callback)( const void* userData, ${method.pulls.param.type} ); +uint32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callback userCB, const void* userData ); +uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); diff --git a/languages/c/templates/declarations/polymorphic-pull.c b/languages/c/templates/declarations/polymorphic-pull.c new file mode 100644 index 00000000..fbf74697 --- /dev/null +++ b/languages/c/templates/declarations/polymorphic-pull.c @@ -0,0 +1,2 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ); diff --git a/languages/c/templates/methods/polymorphic-pull-event.c b/languages/c/templates/methods/polymorphic-pull-event.c index e69de29b..d2f5ef4c 100644 --- a/languages/c/templates/methods/polymorphic-pull-event.c +++ b/languages/c/templates/methods/polymorphic-pull-event.c @@ -0,0 +1,54 @@ +/* ${method.name} - ${method.description} */ +static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) +{ +${event.callback.params.serialization} + ASSERT(jsonResponse->IsValid() == true); + if (jsonResponse->IsValid() == true) { + + ${info.Title}${method.Name}Callback callback = reinterpret_cast<${info.Title}${method.Name}Callback>(userCB); + + WPEFramework::Core::ProxyType<${method.pulls.param.json.type}>* requestParam = new WPEFramework::Core::ProxyType<${method.pulls.param.json.type}>(); + *requestParam = WPEFramework::Core::ProxyType<${method.pulls.param.json.type}>::Create(); + *(*requestParam) = (*jsonResponse)->${event.pulls.param.name}Parameters; + + ${method.pulls.type} result = reinterpret_cast<${method.pulls.type}>(callback(userData, reinterpret_cast<${method.pulls.param.type}>(requestParam))); + + JsonObject jsonParameters; + WPEFramework::Core::JSON::Variant CorrelationId = (*jsonResponse)->CorrelationId.Value(); + jsonParameters.Set(_T("correlationId"), CorrelationId); + + ${method.pulls.json.type}& resultObj = *(*(reinterpret_cast*>(result))); + string resultStr; + resultObj.ToString(resultStr); + WPEFramework::Core::JSON::VariantContainer resultContainer(resultStr); + WPEFramework::Core::JSON::Variant Result = resultContainer; + jsonParameters.Set(_T("result"), Result); + + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + 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(), "${info.Title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; + } + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport"); + } + } +} +uint32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callback userCB, const void* userData ) +{ + const string eventName = _T("${info.title}.${method.name}"); + uint32_t status = FireboltSDKErrorNone; + + if (userCB != nullptr) { + ${event.params.serialization} + status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${info.Title}${method.Name}InnerCallback, reinterpret_cast(userCB), userData); + } + return status; +} +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(userCB)); +} diff --git a/languages/c/templates/methods/polymorphic-pull.c b/languages/c/templates/methods/polymorphic-pull.c index 553b2946..ec052e64 100644 --- a/languages/c/templates/methods/polymorphic-pull.c +++ b/languages/c/templates/methods/polymorphic-pull.c @@ -1,20 +1,20 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_Push${method.Name}(${method.signature.params}) +uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ) { uint32_t status = FireboltSDKErrorUnavailable; - ${if.params} + + string correlationId = ""; ${method.params.serialization} - ${end.if.params} FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); - if (transport != nullptr) { + if (transport != nullptr) { WPEFramework::Core::JSON::Boolean jsonResult; status = transport->Invoke(_T("${info.title}.${method.name}"), jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; } } else { - FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport"); } return status; diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index b167f4d4..770d890e 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -1068,10 +1068,16 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) 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 const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) - const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) - const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) + + const pullsForJsonType = pullsResult ? types.getJsonType(pullsResult, json, { name: pullsResult.name }) : '' + const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const pullsForParamType = pullsParams ? types.getSchemaType(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const pullsForParamJsonType = pullsParams ? types.getJsonType(pullsParams, json, { name: pullsParams.title }) : '' + const pullsEventParamName = event ? types.getSchemaInstantiation(event.result, json, event.name, { instantiationType: 'pull.param.name' }) : '' + const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, { instantiationType: 'params' }) - const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' }) + const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' } ) const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'params' }), ' ') : '' const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.params' }) : '' const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.result' }) : '' @@ -1148,6 +1154,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) + .replace(/\$\{event\.pulls\.param\.name\}/g, pullsEventParamName) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) .replace(/\$\{method\.result\.instantiation\}/g, resultInst) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) @@ -1155,9 +1162,12 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.alternative.link\}/g, '#' + (method.alternative || "").toLowerCase()) .replace(/\$\{method\.pulls\.for\}/g, pullsFor ? pullsFor.name : '') .replace(/\$\{method\.pulls\.type\}/g, pullsForType) + .replace(/\$\{method\.pulls\.json\.type\}/g, pullsForJsonType) .replace(/\$\{method\.pulls\.result\}/g, pullsResultType) .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\.setter\.for\}/g, setterFor) .replace(/\$\{method\.puller\}/g, pullerTemplate) // must be last!! .replace(/\$\{method\.setter\}/g, setterTemplate) // must be last!! From e44476c5db5ecd52961326b40a5cbd51403062bb Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 10 Jul 2023 10:13:28 +0530 Subject: [PATCH 020/137] SchemaSorting: logic updated to consider all schemas (#106) --- src/macrofier/engine.mjs | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 770d890e..18091b7e 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -673,6 +673,24 @@ function generateDefaults(json = {}, templates) { return reducer(json) } +function sortSchemasByReference(schemas = []) { + let indexA = 0; + while (indexA < schemas.length) { + + let swapped = false + for (let indexB = indexA + 1; indexB < schemas.length; ++indexB) { + const bInA = isDefinitionReferencedBySchema('#/components/schemas/' + schemas[indexB][0], schemas[indexA][1]) + if ((isEnum(schemas[indexB][1]) && !isEnum(schemas[indexA][1])) || (bInA === true)) { + [schemas[indexA], schemas[indexB]] = [schemas[indexB], schemas[indexA]] + swapped = true + break + } + } + indexA = swapped ? indexA : ++indexA + } + return schemas +} + const isEnum = x => x.type && x.type === 'string' && Array.isArray(x.enum) && x.title function generateSchemas(json, templates, options) { @@ -736,7 +754,7 @@ function generateSchemas(json, templates, options) { results.push(result) } - const list = [] + let list = [] // schemas may be 1 or 2 levels deeps Object.entries(schemas).forEach(([name, schema]) => { @@ -745,17 +763,7 @@ function generateSchemas(json, templates, options) { } }) - list.sort((a, b) => { - const aInB = isDefinitionReferencedBySchema('#/components/schemas/' + a[0], b[1]) - const bInA = isDefinitionReferencedBySchema('#/components/schemas/' + b[0], a[1]) - if (isEnum(a[1]) || (aInB && !bInA)) { - return -1 - } else if (isEnum(b[1]) || (!aInB && bInA)) { - return 1 - } - return 0; - }) - + list = sortSchemasByReference(list) list.forEach(item => generate(...item)) return results From 0def42422565edf68201d740ee4834741470a7a0 Mon Sep 17 00:00:00 2001 From: sramani-metro <71630728+sramani-metro@users.noreply.github.com> Date: Tue, 11 Jul 2023 13:23:11 +0530 Subject: [PATCH 021/137] fix: Fix the reentrancy of methods from callback (#105) --- languages/c/templates/sdk/src/Transport/Transport.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/languages/c/templates/sdk/src/Transport/Transport.h b/languages/c/templates/sdk/src/Transport/Transport.h index 2aff350d..d12312a5 100644 --- a/languages/c/templates/sdk/src/Transport/Transport.h +++ b/languages/c/templates/sdk/src/Transport/Transport.h @@ -668,15 +668,15 @@ namespace FireboltSDK { } result = WPEFramework::Core::ERROR_NONE; + _adminLock.Unlock(); } else { - + _adminLock.Unlock(); string eventName; if (IsEvent(inbound->Id.Value(), eventName)) { _eventHandler->Dispatch(eventName, inbound); } } - _adminLock.Unlock(); } return (result); From 65090660165ab0d57f180177c56299f54481ecc1 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Tue, 11 Jul 2023 21:58:32 +0530 Subject: [PATCH 022/137] Default template implementation added (#103) Default template implementation added --- languages/c/Types.mjs | 62 ++++++++++++-------- languages/c/src/types/ImplHelpers.mjs | 26 ++++---- languages/c/src/types/NativeHelpers.mjs | 4 +- languages/c/templates/codeblocks/setter.c | 6 +- languages/c/templates/declarations/default.c | 3 + languages/c/templates/methods/default.c | 33 +++++------ languages/c/templates/methods/property.c | 2 +- src/macrofier/engine.mjs | 6 +- 8 files changed, 83 insertions(+), 59 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index edf817c9..2a8f5aa0 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -170,6 +170,9 @@ const hasTag = (method, tag) => { return method.tags && method.tags.filter(t => t.name === tag).length > 0 } +const IsResultConstNullSuccess = (schema, name) => (name === 'success' && !schema.const && !schema.type) +const IsResultBooleanSuccess = (schema, name) => (name === 'success' && schema.type === 'boolean') + function getParamList(schema, module) { let paramList = [] if (schema.params.length > 0) { @@ -229,13 +232,13 @@ function getSchemaType(schema, module, { name, prefix = '', destination, resultS return info.type } -function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = {level: 0, descriptions: true, title: false, resultSchema: false, event: false}) { +function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = { level: 0, descriptions: true, title: false, resultSchema: false, event: false}) { if (json.schema) { json = json.schema } - let stringAsHandle = options.resultSchema || options.event + let fireboltString = options.resultSchema || options.event let structure = {} structure["type"] = '' @@ -263,7 +266,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref } } else if (json.const) { - structure.type = getNativeType(json, stringAsHandle) + structure.type = getNativeType(json, fireboltString) structure.json = json return structure } @@ -320,7 +323,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref return getSchemaTypeInfo(module, union, '', schemas, '', options) } else if (json.oneOf) { - structure.type = 'char*' + structure.type = fireboltString ? getFireboltStringType() : 'char*' structure.json.type = 'string' return structure } @@ -337,7 +340,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref structure.namespace = (json.namespace ? json.namespace : getModuleName(module)) } else { - structure.type = 'char*' + structure.type = fireboltString ? getFireboltStringType() : 'char*' } if (name) { structure.name = capitalize(name) @@ -346,14 +349,14 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref return structure } else if (json.type) { - structure.type = getNativeType(json, stringAsHandle) - structure.json = json - if (name || json.title) { - structure.name = capitalize(name || json.title) + if (!IsResultBooleanSuccess(json, name) && !IsResultConstNullSuccess(json, name)) { + structure.type = getNativeType(json, fireboltString) + structure.json = json + if (name || json.title) { + structure.name = capitalize(name || json.title) + } + structure.namespace = getModuleName(module) } - structure.namespace = getModuleName(module) - - return structure } return structure } @@ -377,13 +380,12 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' if (json['$ref'][0] === '#') { //Ref points to local schema //Get Path to ref in this module and getSchemaType - const schema = getPath(json['$ref'], module, schemas) - const tname = schema.title || json['$ref'].split('/').pop() + let schema = getPath(json['$ref'], module, schemas) + const tName = schema.title || json['$ref'].split('/').pop() if (json['$ref'].includes('x-schemas')) { schema = (getRefModule(json['$ref'].split('/')[2])) } - - shape = getSchemaShapeInfo(schema, module, schemas, { name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) + shape = getSchemaShapeInfo(schema, module, schemas, { name: tName, prefix, merged, level, title, summary, descriptions, destination, section, enums }) } } //If the schema is a const, @@ -429,7 +431,6 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' let info = getSchemaTypeInfo(module, items, items.name || pname, schemas, prefix, {level : level, descriptions: descriptions, title: true}) if (info.type && info.type.length > 0) { let objName = tName + '_' + capitalize(prop.title || pname) - let moduleName = info.namespace info.json.namespace = info.namespace let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) let prefixName = ((prefix.length > 0) && items['$ref']) ? '' : prefix @@ -539,10 +540,14 @@ 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(name) + capitalize(type.type) - let objName = getTypeName(info.namespace, arrayName, prefix) + let arrayName = capitalize(info.name) + capitalize(type.type) + let namespace = info.namespace + if (type && type.type === 'object') { + namespace = getModuleName(module) + } + let objName = getTypeName(namespace, arrayName, prefix) let tName = objName + 'Array' - let moduleName = info.namespace + info.json.namespace = info.namespace let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) let subModuleProperty = getJsonTypeInfo(module, j, j.title, schemas, prefix) @@ -712,6 +717,9 @@ function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '' structure.type = getJsonNativeType(json) return structure } + else { + structure.type = 'JsonObject' + } return structure } @@ -739,9 +747,17 @@ function getSchemaInstantiation(schema, module, name, { instantiationType = '' } return getParameterInstantiation(getParamList(schema, module)) } else if (instantiationType === 'result') { - let resultType = getSchemaType(schema, module, { title: true, name: name, resultSchema: true}) || '' - let resultJsonType = getJsonType(schema, module, {name: name}) || '' - return getResultInstantiation(name, resultType, resultJsonType) + let result = '' + + if (!IsResultConstNullSuccess(schema, name)) { + let resultJsonType = getJsonType(schema, module, {name: name}) || '' + let resultType = '' + if (!IsResultBooleanSuccess(schema, name)) { + resultType = getSchemaType(schema, module, { title: true, name: name, resultSchema: true}) || '' + } + result = getResultInstantiation(name, resultType, resultJsonType) + } + return result } else if (instantiationType === 'callback.params') { let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index 6509375a..3d5403d4 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -455,16 +455,22 @@ function getResultInstantiation (name, nativeType, container, indentLevel = 3) { let impl = '' - if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { - impl += `${' '.repeat(indentLevel)}${container}* strResult = new ${container}(jsonResult);` + '\n' - impl += `${' '.repeat(indentLevel)}*${name} = static_cast<${getFireboltStringType()}>(strResult);` - } else if (nativeType.includes('Handle')) { - impl += `${' '.repeat(indentLevel)}WPEFramework::Core::ProxyType<${container}>* resultPtr = new WPEFramework::Core::ProxyType<${container}>();\n` - impl += `${' '.repeat(indentLevel)}*resultPtr = WPEFramework::Core::ProxyType<${container}>::Create();\n` - impl += `${' '.repeat(indentLevel)}*(*resultPtr) = jsonResult;\n` - impl += `${' '.repeat(indentLevel)}*${name} = static_cast<${nativeType}>(resultPtr);` - } else { - impl += `${' '.repeat(indentLevel)}*${name} = jsonResult.Value();` + if (nativeType) { + impl += `${' '.repeat(indentLevel)}if (${name} != nullptr) {` + '\n' + if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + impl += `${' '.repeat(indentLevel + 1)}${container}* strResult = new ${container}(jsonResult);` + '\n' + impl += `${' '.repeat(indentLevel + 1)}*${name} = static_cast<${getFireboltStringType()}>(strResult);` + } else if (nativeType.includes('Handle')) { + impl += `${' '.repeat(indentLevel + 1)}WPEFramework::Core::ProxyType<${container}>* resultPtr = new WPEFramework::Core::ProxyType<${container}>();\n` + impl += `${' '.repeat(indentLevel + 1)}*resultPtr = WPEFramework::Core::ProxyType<${container}>::Create();\n` + impl += `${' '.repeat(indentLevel + 1)}*(*resultPtr) = jsonResult;\n` + impl += `${' '.repeat(indentLevel + 1)}*${name} = static_cast<${nativeType}>(resultPtr);` + } else { + impl += `${' '.repeat(indentLevel + 1)}*${name} = jsonResult.Value();` + } + impl += `${' '.repeat(indentLevel)}}` + '\n' + } else if (name === 'success') { + impl += `${' '.repeat(indentLevel)}status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported;` } return impl diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 022437e8..1460e22e 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -115,12 +115,12 @@ const getArrayElementSchema = (json, module, schemas = {}, name) => { return result } -const getNativeType = (json, stringAsHandle = false) => { +const getNativeType = (json, fireboltString = false) => { let type let jsonType = json.const ? typeof json.const : json.type if (jsonType === 'string') { type = 'char*' - if (stringAsHandle) { + if (fireboltString) { type = getFireboltStringType() } } diff --git a/languages/c/templates/codeblocks/setter.c b/languages/c/templates/codeblocks/setter.c index 9f496543..342a98d6 100644 --- a/languages/c/templates/codeblocks/setter.c +++ b/languages/c/templates/codeblocks/setter.c @@ -1,9 +1,7 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_${method.Name}( ${method.signature.params} ) +uint32_t ${info.Title}_${method.Name}( ${method.signature.params} ) { const string method = _T("${info.title}.${method.name}"); - ${if.params} -${method.params.serialization} - ${end.if.params} +${if.params}${method.params.serialization}${end.if.params} return FireboltSDK::Properties::Set(method, jsonParameters); } diff --git a/languages/c/templates/declarations/default.c b/languages/c/templates/declarations/default.c index e69de29b..ac4e7f78 100644 --- a/languages/c/templates/declarations/default.c +++ b/languages/c/templates/declarations/default.c @@ -0,0 +1,3 @@ +/* ${method.name} - ${method.description} +${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation}${end.if.deprecated} */ +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} ); diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 6a023534..6fbca47e 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -1,24 +1,21 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_${method.Name}(${method.params.list}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { - uint32_t status = FireboltSDKErrorUnavailable; - FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); - if (transport != nullptr) { - - JsonObject jsonParameters; +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} ) { - ${if.params} -${method.params.json} - ${end.if.params} + uint32_t status = FireboltSDKErrorUnavailable; + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { - WPEFramework::Core::JSON::Boolean jsonResult; - status = transport->Invoke("${info.title}.${method.name}", jsonParameters, jsonResult); - if (status == FireboltSDKErrorNone) { - *success = jsonResult.Value(); - } + ${method.params.serialization.with.indent} + ${method.result.json.type} jsonResult; + status = transport->Invoke("${info.title}.${method.name}", jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully invoked"); +${method.result.instantiation} + } - } else { - FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); - } + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } - return status; + return status; } diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index c7510da9..9a92dce4 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,5 +1,5 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_Get${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name} ) +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}"); ${if.params}${method.params.serialization}${end.if.params} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 18091b7e..b4f4f9c8 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -1123,9 +1123,12 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.params\.array\}/g, JSON.stringify(methodObj.params.map(p => p.name))) .replace(/\$\{method\.params\.count}/g, methodObj.params ? methodObj.params.length : 0) .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/gms, method.params.length ? '$1' : '') - .replace(/\$\{if\.params.empty\}(.*?)\$\{end\.if\.params.empty\}/gms, method.params.length === 0 ? '$1' : '') + .replace(/\$\{if\.result\}(.*?)\$\{end\.if\.result\}/gms, resultType ? '$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' : '') .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event && event.params.length ? '$1' : '') .replace(/\$\{method\.params\.serialization\}/g, serializedParams) + .replace(/\$\{method\.params\.serialization\.with\.indent\}/g, indent(serializedParams, ' ')) // Typed signature stuff .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination, section: state.section })) @@ -1164,6 +1167,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{event\.pulls\.param\.name\}/g, pullsEventParamName) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) + .replace(/\$\{method\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{method\.result\.instantiation\}/g, resultInst) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) From e6c6bed75fafb28c00feec96ffd6ed1aa1768fc7 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Tue, 11 Jul 2023 15:08:01 -0400 Subject: [PATCH 023/137] feat(macrofier): Add dynamic schema template output --- languages/c/Types.mjs | 113 ++-- languages/c/language.config.json | 13 +- languages/c/src/types/NativeHelpers.mjs | 6 +- languages/c/templates/accessors/anyOf.c | 1 + languages/c/templates/accessors/array.c | 4 + languages/c/templates/accessors/const.c | 0 languages/c/templates/accessors/default.c | 4 + languages/c/templates/accessors/enum.cpp | 4 + languages/c/templates/accessors/enum.h | 4 + languages/c/templates/accessors/object.c | 7 + languages/c/templates/accessors/primitive.c | 1 + languages/c/templates/accessors/ref.c | 1 + languages/c/templates/accessors/title.c | 1 + languages/c/templates/accessors/tuple.c | 2 + languages/c/templates/declarations/default.c | 2 +- languages/c/templates/declarations/event.c | 2 +- .../declarations/polymorphic-reducer.c | 4 +- languages/c/templates/declarations/property.c | 2 +- languages/c/templates/methods/default.c | 2 +- languages/c/templates/methods/property.c | 2 +- .../c/templates/modules/include/Module.h | 2 +- .../modules/include/Module_Accessors.h | 41 ++ languages/c/templates/parameters/optional.c | 1 + languages/c/templates/parameters/result.c | 1 + .../schemas/include/Common/Module_Accessors.h | 39 ++ languages/c/templates/sections/enum.cpp | 5 - languages/c/templates/sections/enums.c | 1 + languages/c/templates/types/anyOf.c | 1 + languages/c/templates/types/array.c | 1 + languages/c/templates/types/const.c | 0 languages/c/templates/types/default.c | 4 + languages/c/templates/types/enum.cpp | 6 +- languages/c/templates/types/enum.h | 4 +- languages/c/templates/types/object.c | 3 + languages/c/templates/types/primitive.c | 1 + languages/c/templates/types/ref.c | 1 + languages/c/templates/types/title.c | 1 + languages/c/templates/types/tuple.c | 3 + languages/javascript/language.config.json | 6 + .../templates/declarations/default.js | 2 +- .../templates/declarations/interface.js | 1 + .../declarations/polymorphic-reducer.js | 4 +- .../templates/declarations/synchronous.js | 6 + .../templates/parameters/default.js | 2 +- .../templates/parameters/optional.js | 1 + .../javascript/templates/sections/enums.js | 1 + .../javascript/templates/types/anyOf.mjs | 1 + .../javascript/templates/types/array.mjs | 1 + .../javascript/templates/types/const.mjs | 1 + .../javascript/templates/types/default.mjs | 4 + languages/javascript/templates/types/enum.mjs | 5 +- languages/javascript/templates/types/enum.ts | 6 + .../javascript/templates/types/object.mjs | 3 + .../javascript/templates/types/primitive.mjs | 1 + languages/javascript/templates/types/ref.mjs | 1 + .../javascript/templates/types/title.mjs | 1 + .../javascript/templates/types/tuple.mjs | 3 + src/macrofier/engine.mjs | 155 ++++-- src/macrofier/index.mjs | 18 +- src/macrofier/types.mjs | 499 ++++++++++++++++++ src/sdk/index.mjs | 2 + src/shared/typescript.mjs | 2 + src/validate/index.mjs | 2 +- 63 files changed, 887 insertions(+), 131 deletions(-) create mode 100644 languages/c/templates/accessors/anyOf.c create mode 100644 languages/c/templates/accessors/array.c create mode 100644 languages/c/templates/accessors/const.c create mode 100644 languages/c/templates/accessors/default.c create mode 100644 languages/c/templates/accessors/enum.cpp create mode 100644 languages/c/templates/accessors/enum.h create mode 100644 languages/c/templates/accessors/object.c create mode 100644 languages/c/templates/accessors/primitive.c create mode 100644 languages/c/templates/accessors/ref.c create mode 100644 languages/c/templates/accessors/title.c create mode 100644 languages/c/templates/accessors/tuple.c create mode 100644 languages/c/templates/modules/include/Module_Accessors.h create mode 100644 languages/c/templates/parameters/optional.c create mode 100644 languages/c/templates/parameters/result.c create mode 100644 languages/c/templates/schemas/include/Common/Module_Accessors.h delete mode 100644 languages/c/templates/sections/enum.cpp create mode 100644 languages/c/templates/sections/enums.c create mode 100644 languages/c/templates/types/anyOf.c create mode 100644 languages/c/templates/types/array.c create mode 100644 languages/c/templates/types/const.c create mode 100644 languages/c/templates/types/default.c create mode 100644 languages/c/templates/types/object.c create mode 100644 languages/c/templates/types/primitive.c create mode 100644 languages/c/templates/types/ref.c create mode 100644 languages/c/templates/types/title.c create mode 100644 languages/c/templates/types/tuple.c create mode 100644 languages/javascript/templates/declarations/interface.js create mode 100644 languages/javascript/templates/declarations/synchronous.js create mode 100644 languages/javascript/templates/parameters/optional.js create mode 100644 languages/javascript/templates/sections/enums.js create mode 100644 languages/javascript/templates/types/anyOf.mjs create mode 100644 languages/javascript/templates/types/array.mjs create mode 100644 languages/javascript/templates/types/const.mjs create mode 100644 languages/javascript/templates/types/default.mjs create mode 100644 languages/javascript/templates/types/enum.ts create mode 100644 languages/javascript/templates/types/object.mjs create mode 100644 languages/javascript/templates/types/primitive.mjs create mode 100644 languages/javascript/templates/types/ref.mjs create mode 100644 languages/javascript/templates/types/title.mjs create mode 100644 languages/javascript/templates/types/tuple.mjs create mode 100644 src/macrofier/types.mjs diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 9b871aa2..f0c70a45 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -208,23 +208,26 @@ function getMethodSignature(method, module, { destination, isInterface = false } function getMethodSignatureParams(method, module, { destination, callback= false } = {}) { - return method.params.map(param => { + const result = method.params.map(param => { let type = getSchemaType(param.schema, module, { name: param.name, title: true, destination }) if ((callback === true) && (type === 'char*')) { type = getFireboltStringType() } return type + (!param.required ? '* ' : ' ') + param.name }).join(', ') + + return result } -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop +const safeName = val => val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + +function getSchemaType(schema, module, { name, moduleTitle, prefix = '', destination, resultSchema = false, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + let info = getSchemaTypeInfo(module, schema, name, module['x-schemas'], prefix, { title: title, moduleTitle: moduleTitle, resultSchema: resultSchema, event: event }) -function getSchemaType(schema, module, { name, prefix = '', destination, resultSchema = false, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - let info = getSchemaTypeInfo(module, schema, name, module['x-schemas'], prefix, { title: title, resultSchema: resultSchema, event: event }) return info.type } -function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = {level: 0, descriptions: true, title: false, resultSchema: false, event: false}) { +function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = {moduleTitle: '', level: 0, descriptions: true, title: false, resultSchema: false, event: false}) { if (json.schema) { json = json.schema @@ -246,7 +249,8 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref let tName = definition.title || json['$ref'].split('/').pop() let schema = module if (json['$ref'].includes('x-schemas')) { - schema = (getRefModule(json['$ref'].split('/')[2])) + options.moduleTitle = json['$ref'].split('/')[2] + schema = getRefModule(options.moduleTitle) } const res = getSchemaTypeInfo(schema, definition, tName, schemas, '', options) @@ -270,7 +274,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref else if (json.type === 'string' && json.enum) { //Enum structure.name = name || json.title - let typeName = getTypeName(getModuleName(module), name || json.title, prefix, false, false) + let typeName = getTypeName(getModuleName(module), json.title || name, prefix, false, false) // let res = description(capitalize(name || json.title), json.description) + '\n' + generateEnum(json, typeName) structure.json = json structure.type = typeName @@ -299,9 +303,14 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref } let arrayName = capitalize(res.name)// + capitalize(res.json.type) - let n = getTypeName(getModuleName(module), arrayName, prefix) - structure.name = res.name || name && (capitalize(name)) - structure.type = n + try { + let n = getTypeName(getModuleName(module), json.title || name, prefix) + structure.name = res.name || name && (capitalize(name)) + structure.type = n + } + catch (e) { + console.dir(json) + } structure.json = json structure.namespace = getModuleName(module) return structure @@ -327,9 +336,12 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref else if (json.type === 'object') { structure.json = json if (hasProperties(json)) { - structure.type = getTypeName(getModuleName(module), json.title || name, prefix) + if (!json.title) { + console.dir(json) + } + structure.type = getTypeName(options.moduleTitle || getModuleName(module), json.title || name, prefix) structure.name = (json.name ? json.name : (json.title ? json.title : name)) - structure.namespace = (json.namespace ? json.namespace : getModuleName(module)) + structure.namespace = (json.namespace ? json.namespace : options.moduleTitle || getModuleName(module)) } else { structure.type = 'char*' @@ -344,7 +356,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref structure.type = getNativeType(json, stringAsHandle) structure.json = json if (name || json.title) { - structure.name = capitalize(name || json.title) + structure.name = capitalize(json.title || name) } structure.namespace = getModuleName(module) @@ -358,7 +370,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref // return shape // } -function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, summary, descriptions = true, destination, enums = true } = {}) { +function getSchemaShape(schema = {}, module = {}, { name = '', property = '', moduleTitle = '', level = 0, title, summary, descriptions = true, destination, enums = true } = {}) { schema = JSON.parse(JSON.stringify(schema)) let structure = [] @@ -366,10 +378,10 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, let operator = '' let theTitle = schema.title || name - theTitle = `F${module.info.title}_${theTitle}` + theTitle = theTitle ? getTypeName(moduleTitle || module.info.title, theTitle) : 'Unknown' //`${moduleTitle || module.info.title}_${theTitle}` if (enums && level === 0 && schema.type === "string" && Array.isArray(schema.enum)) { - return `typedef enum {\n\t` + schema.enum.map(value => value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase()).join(',\n\t') + `\n} ${schema.title || name};\n` + return `typedef enum {\n\t` + schema.enum.map(value => theTitle.toUpperCase() + '_' + value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase()).join(',\n\t') + `\n} ${theTitle};\n` } if (!theTitle) { @@ -382,8 +394,12 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, } else { const someJson = getPath(schema['$ref'], module) + let moduleTitle = module.info.title + if (schema['$ref'].indexOf("/x-schemas/") >= 0) { + moduleTitle = schema['$ref'].split('/')[2] + } if (someJson) { - return getSchemaShape(someJson, module, { name, level, title, summary, descriptions, destination, enums: false }) + return getSchemaShape(someJson, module, { name, property, moduleTitle, level, title, summary, descriptions, destination, enums: false }) } else { ' '.repeat(level) + `${prefix}${theTitle}${operator}` @@ -399,7 +415,19 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, if (level > 0 && (summary || schema.description)) { summary = `\t// ${(summary || schema.description).split('\n')[0]}` } - return ' '.repeat(level) + `${prefix}${theTitle}${operator} ${name}; ` + summary + return ' '.repeat(level) + `${prefix}${theTitle}${operator} ${property}; ` + summary + } + else if (schema.type === 'array' && schema.items && Array.isArray(schema.items)) { + if (schema.items.length === schema.items.filter(item => item['x-property']).length) { + const object = JSON.parse(JSON.stringify(schema)) + object.type = 'object' + object.properties = {} + object.items.forEach(item => { + object.properties[item['x-property']] = item + delete item['x-property'] + }) + return getSchemaShape(object, module, { name, moduleTitle, level, title, summary, descriptions, destination, enums}) + } } else if (schema.type === 'object') { let suffix = '{' @@ -411,46 +439,49 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, if (!schema.required || !schema.required.includes(name)) { // name = name + '?' } - const schemaShape = getSchemaShape(prop, module, {name: name, summary: prop.description, descriptions: descriptions, level: level+1, title: true}) + const schemaShape = getSchemaShape(prop, module, {property: name, summary: prop.description, descriptions: descriptions, level: level+1, title: true}) structure.push(schemaShape) }) } else if (schema.propertyNames) { - const { propertyNames } = localizeDependencies(schema, module) - if (propertyNames.enum) { - propertyNames.enum.forEach(prop => { + const localizedSchema = localizeDependencies(schema, module) + if (localizedSchema.propertyNames.enum) { + localizedSchema.propertyNames.enum.forEach(prop => { let type = 'any' - if (schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { - type = getSchemaType(schema.additionalProperties, module) + if (localizedSchema.additionalProperties && (typeof localizedSchema.additionalProperties === 'object')) { + type = localizedSchema.additionalProperties } - if (schema.patternProperties) { - Object.entries(schema.patternProperties).forEach(([pattern, schema]) => { + if (localizedSchema.patternProperties) { + Object.entries(localizedSchema.patternProperties).forEach(([pattern, schema]) => { let regex = new RegExp(pattern) if (prop.match(regex)) { - type = getSchemaType(schema, module) + type = schema } }) } - return getSchemaShape(schema.propertyNames, module, { name: schema.title }) +// return getSchemaShape(schema.propertyNames, module, { name: schema.title }) -// structure.push(getSchemaShape({type: type}, module, {name: safeName(prop), descriptions: descriptions, level: level+1})) + structure.push(getSchemaShape(type, module, {property: safeName(prop), descriptions: descriptions, level: level+1})) }) } } else if (schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { let type = getSchemaType(schema.additionalProperties, module, { destination }) - structure.push(getSchemaShape({type: type}, module, {name: '[property: string]', descriptions: descriptions, level: level+1})) + // TODO: C doesn't support this... + // structure.push(getSchemaShape({type: type}, module, {name: '[property: string]', descriptions: descriptions, level: level+1})) } structure.push(' '.repeat(level) + `} ${theTitle};`) } else if (schema.anyOf) { + return '' return ' '.repeat(level) + `${prefix}${theTitle}${operator} ` + schema.anyOf.map(s => getSchemaType(s, module, { name, level, title, summary, descriptions, destination })).join(' | ') } else if (schema.oneOf) { + return '' return ' '.repeat(level) + `${prefix}${theTitle}${operator} ` + schema.oneOf.map(s => getSchemaType(s, module, { name, level, title, summary, descriptions, destination })).join(' | ') } else if (schema.allOf) { @@ -489,15 +520,19 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, suffix = JSON.stringify(schema.const) } else if (isArrayWithSchemaForItems) { - suffix = getSchemaType(schema.items, module, { title: level ? true : false }) + '[]' // prefer schema title over robust descriptor + suffix = getSchemaType(schema.items, module, { title: level ? true : false, name: name }) + '[]' // prefer schema title over robust descriptor } else if (isArrayWithSpecificItems) { - suffix = '[' + schema.items.map(i => getSchemaType(i, module, {title: level ? true : false })).join(', ') + ']' + suffix = '[' + schema.items.map(i => getSchemaType(i, module, {title: level ? true : false, name: name })).join(', ') + ']' } else { - suffix = getSchemaType(schema, module, { title: level ? true : false }) // prefer schema title over robust descriptor + suffix = getSchemaType(schema, module, { title: level ? true : false, name: name }) // prefer schema title over robust descriptor } + if (level === 0) { + property = theTitle + } + // if there's a summary or description, append it as a comment (description only gets first line) if (level > 0 && (summary || schema.description)) { summary = `\t// ${summary || schema.description.split('\n')[0]}` @@ -507,11 +542,11 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, suffix = '[]' } - if (theTitle === suffix) { - return ' '.repeat(level) + `${prefix}${name}` + if (summary) { + return ' '.repeat(level) + `${prefix}${suffix} ${property}; ${summary}` } else { - return ' '.repeat(level) + `${prefix}${suffix} ${name}${operator}; ${summary}` + return ' '.repeat(level) + `${prefix}${suffix} ${property};` } } @@ -567,7 +602,7 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' else if (json.properties && (validJsonObjectProperties(json) === true)) { let c_shape = description(capitalize(name), json.description) let cpp_shape = '' - let tName = getTypeName(getModuleName(module), name, prefix) + let tName = getTypeName(getModuleName(module), json.title || name, prefix) c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(json, module, { name }))) let props = [] let containerName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? (prefix + '_' + capitalize(name)) : capitalize(name) @@ -645,7 +680,7 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' info.json.type = 'string' } - let tName = getTypeName(getModuleName(module), name, prefix) + let tName = getTypeName(getModuleName(module), json.title || name, prefix) let t = description(capitalize(name), json.description) + '\n' let containerType = 'WPEFramework::Core::JSON::VariantContainer' @@ -769,7 +804,7 @@ function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '' if (json['$ref']) { if (json['$ref'][0] === '#') { //Ref points to local schema - //Get Path to ref in this module and getSchemaType + //Get Path to ref in this module and getSchemaTypef let definition = getPath(json['$ref'], module, schemas) let tName = definition.title || json['$ref'].split('/').pop() diff --git a/languages/c/language.config.json b/languages/c/language.config.json index 77cde389..c13b1cce 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -5,12 +5,23 @@ "extractSubSchemas": true, "templatesPerModule": [ "/include/Module.h", + "/include/Module_Accessors.h", "/src/Module.cpp" ], "templatesPerSchema": [ "/include/Common/Module.h", + "/include/Common/Module_Accessors.h", "/src/Module_Common.cpp", "/src/JsonData_Module.h" ], - "persistPermission": true + "persistPermission": true, + "primitives": { + "boolean": "bool", + "integer": "int", + "number": "float", + "string": "char*" + }, + "additionalSchemaTemplates": [ + "accessors" + ] } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 927cbd53..491fabb3 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -27,7 +27,7 @@ import deepmerge from 'deepmerge' const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = predicates -const getModuleName = json => 'F' + getPathOr(null, ['info', 'title'], json) || json.title || 'missing' +const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' const getFireboltStringType = () => 'FireboltTypes_StringHandle' const getHeaderText = () => { @@ -128,7 +128,7 @@ const getNativeType = (json, stringAsHandle = false) => { type = 'float' } else if (jsonType === 'integer') { - type = 'int32_t' + type = 'int' } else if (jsonType === 'boolean') { @@ -188,7 +188,7 @@ const getTypeName = (moduleName, varName, prefix = '', upperCase = false, capita } prefix = (prefix.length > 0) ?(upperCase ? prefix.toUpperCase() : capitalize(prefix)) : prefix let name = (prefix.length > 0) ? `${mName}_${prefix}_${vName}` : `${mName}_${vName}` - return name + return 'F' + name } const getArrayAccessors = (arrayName, propertyType, valueType) => { diff --git a/languages/c/templates/accessors/anyOf.c b/languages/c/templates/accessors/anyOf.c new file mode 100644 index 00000000..a2682179 --- /dev/null +++ b/languages/c/templates/accessors/anyOf.c @@ -0,0 +1 @@ +/* AnyOf is not supported in C: ${title} */ \ No newline at end of file diff --git a/languages/c/templates/accessors/array.c b/languages/c/templates/accessors/array.c new file mode 100644 index 00000000..3ebf9f53 --- /dev/null +++ b/languages/c/templates/accessors/array.c @@ -0,0 +1,4 @@ +uint32_t ${info.Title}_${Title}Array_Size(${type} handle); +${type} ${title}Array_Get(${type} handle, uint32_t index); +void ${info.Title}_${Title}Array_Add(${propertyType}Handle handle, ${valueType} value); +void ${info.Title}_${Title}Array_Clear(${propertyType}Handle handle); diff --git a/languages/c/templates/accessors/const.c b/languages/c/templates/accessors/const.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/accessors/default.c b/languages/c/templates/accessors/default.c new file mode 100644 index 00000000..1f1fe89d --- /dev/null +++ b/languages/c/templates/accessors/default.c @@ -0,0 +1,4 @@ +/* + * ${title} - ${description} + */ +${shape} diff --git a/languages/c/templates/accessors/enum.cpp b/languages/c/templates/accessors/enum.cpp new file mode 100644 index 00000000..6776b41a --- /dev/null +++ b/languages/c/templates/accessors/enum.cpp @@ -0,0 +1,4 @@ + /* ${title} ${description} */ + ENUM_CONVERSION_BEGIN(${name}) + { ${NAME}_${key}, _T("${value}") }, + ENUM_CONVERSION_END(${name}) diff --git a/languages/c/templates/accessors/enum.h b/languages/c/templates/accessors/enum.h new file mode 100644 index 00000000..92108c75 --- /dev/null +++ b/languages/c/templates/accessors/enum.h @@ -0,0 +1,4 @@ +/* ${title} ${description} */ +typedef enum { + ${NAME}_${key}, +} ${name}; diff --git a/languages/c/templates/accessors/object.c b/languages/c/templates/accessors/object.c new file mode 100644 index 00000000..9aa56c57 --- /dev/null +++ b/languages/c/templates/accessors/object.c @@ -0,0 +1,7 @@ +typedef void* ${varName}Handle; +${varName}Handle ${varName}Handle_Create(void); +void ${varName}Handle_Addref(${varName}Handle handle); +void ${varName}Handle_Release(${varName}Handle handle); +bool ${varName}Handle_IsValid(${varName}Handle handle); + +${property}${shape} diff --git a/languages/c/templates/accessors/primitive.c b/languages/c/templates/accessors/primitive.c new file mode 100644 index 00000000..2f470670 --- /dev/null +++ b/languages/c/templates/accessors/primitive.c @@ -0,0 +1 @@ +int F${info.Title}_GetProperty${type}(); \ No newline at end of file diff --git a/languages/c/templates/accessors/ref.c b/languages/c/templates/accessors/ref.c new file mode 100644 index 00000000..41d15c96 --- /dev/null +++ b/languages/c/templates/accessors/ref.c @@ -0,0 +1 @@ +${title} \ No newline at end of file diff --git a/languages/c/templates/accessors/title.c b/languages/c/templates/accessors/title.c new file mode 100644 index 00000000..ca6b6897 --- /dev/null +++ b/languages/c/templates/accessors/title.c @@ -0,0 +1 @@ +F${info.Title}_${Title} \ No newline at end of file diff --git a/languages/c/templates/accessors/tuple.c b/languages/c/templates/accessors/tuple.c new file mode 100644 index 00000000..f7e6d4fd --- /dev/null +++ b/languages/c/templates/accessors/tuple.c @@ -0,0 +1,2 @@ + int Tubple_GET${property}(${shape}handle); + \ No newline at end of file diff --git a/languages/c/templates/declarations/default.c b/languages/c/templates/declarations/default.c index c1d5bc15..5d972e4a 100644 --- a/languages/c/templates/declarations/default.c +++ b/languages/c/templates/declarations/default.c @@ -2,4 +2,4 @@ * ${method.summary} * ${method.params} */ -int F${info.title}_${method.Name}(${method.signature.params}${if.result.params}${if.params}, ${end.if.params}${end.if.result.params}${method.result.params}); +int F${info.title}_${method.Name}(${method.signature.params}${if.result.properties}${if.params}, ${end.if.params}${end.if.result.properties}${method.result.properties}); diff --git a/languages/c/templates/declarations/event.c b/languages/c/templates/declarations/event.c index 42a8b136..f91c6a39 100644 --- a/languages/c/templates/declarations/event.c +++ b/languages/c/templates/declarations/event.c @@ -1,4 +1,4 @@ /* ${method.name} - ${method.description} */ -typedef void (*${info.Title}${method.Name}Callback)( const void* userData, ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${event.result.type} ${method.result.name} ); +typedef void (*${info.Title}${method.Name}Callback)( const void* userData, ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${method.result.properties} ); int ${info.title}_Register_${method.Name}( ${event.signature.params}${if.event.params}, ${end.if.event.params}${info.Title}${method.Name}Callback userCB, const void* userData ); int ${info.title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); diff --git a/languages/c/templates/declarations/polymorphic-reducer.c b/languages/c/templates/declarations/polymorphic-reducer.c index cf974e1a..5d972e4a 100644 --- a/languages/c/templates/declarations/polymorphic-reducer.c +++ b/languages/c/templates/declarations/polymorphic-reducer.c @@ -2,6 +2,4 @@ * ${method.summary} * ${method.params} */ -${method.signature} - -// TODO: generate reducer signature +int F${info.title}_${method.Name}(${method.signature.params}${if.result.properties}${if.params}, ${end.if.params}${end.if.result.properties}${method.result.properties}); diff --git a/languages/c/templates/declarations/property.c b/languages/c/templates/declarations/property.c index 7ed669d8..77aac221 100644 --- a/languages/c/templates/declarations/property.c +++ b/languages/c/templates/declarations/property.c @@ -2,4 +2,4 @@ * ${method.summary} * ${method.params} */ -int F${info.title}_Get${method.Name}(${method.signature.params}${if.params}, ${end.if.params}${method.result.params}); +int F${info.title}_Get${method.Name}(${method.signature.params}${if.params}, ${end.if.params}${method.result.properties}); diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index b69bab1f..3707e68b 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -1,5 +1,5 @@ /* ${method.name} - ${method.description} */ -int F${info.title}_${method.Name}(${method.signature.params}${if.result.params}${if.params}, ${end.if.params}${end.if.result.params}${method.result.params}) { +int F${info.title}_${method.Name}(${method.signature.params}${if.result.properties}${if.params}, ${end.if.params}${end.if.result.properties}${method.result.properties}) { int status = FireboltSDKErrorUnavailable; FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 2d461f98..7c46f7c1 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,5 +1,5 @@ /* ${method.name} - ${method.description} */ -int F${info.title}_Get${method.Name}(${method.signature.params}${if.params}, ${end.if.params}${method.result.params}) { +int F${info.title}_Get${method.Name}(${method.signature.params}${if.result.properties}${if.params}, ${end.if.params}${end.if.result.properties}${method.result.properties}) { const string method = _T("${info.title}.${method.name}"); ${if.params}${method.params.serialization}${end.if.params} ${method.result.json} jsonResult; diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h index a202f643..7a192768 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/Module.h @@ -30,7 +30,7 @@ extern "C" { /* ${ENUMS} */ -/* ${ACCESSORS} */ +/* ${TYPES} */ /* ${DECLARATIONS} */ diff --git a/languages/c/templates/modules/include/Module_Accessors.h b/languages/c/templates/modules/include/Module_Accessors.h new file mode 100644 index 00000000..fbcd5cfb --- /dev/null +++ b/languages/c/templates/modules/include/Module_Accessors.h @@ -0,0 +1,41 @@ +/* + * 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 + */ + +#ifndef _${info.TITLE}_H +#define _${info.TITLE}_H + +#include "Firebolt.h" +/* ${IMPORTS} */ + +#ifdef __cplusplus +extern "C" { +#endif + +// Enums + +/* ${ENUMS} */ + +/* ${TYPES:accessors} */ + +/* ${DECLARATIONS} */ + +#ifdef __cplusplus +} +#endif + +#endif // Header Include Guard diff --git a/languages/c/templates/parameters/optional.c b/languages/c/templates/parameters/optional.c new file mode 100644 index 00000000..e6e3b8ba --- /dev/null +++ b/languages/c/templates/parameters/optional.c @@ -0,0 +1 @@ +${method.param.type} ${method.param.name} \ No newline at end of file diff --git a/languages/c/templates/parameters/result.c b/languages/c/templates/parameters/result.c new file mode 100644 index 00000000..699c8b5b --- /dev/null +++ b/languages/c/templates/parameters/result.c @@ -0,0 +1 @@ +${method.param.type} *${method.param.name} \ No newline at end of file diff --git a/languages/c/templates/schemas/include/Common/Module_Accessors.h b/languages/c/templates/schemas/include/Common/Module_Accessors.h new file mode 100644 index 00000000..e93a77a2 --- /dev/null +++ b/languages/c/templates/schemas/include/Common/Module_Accessors.h @@ -0,0 +1,39 @@ +/* + * 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 + */ + +#ifndef _COMMON_${info.TITLE}_H +#define _COMMON_${info.TITLE}_H + +#include "Firebolt.h" +/* ${IMPORTS} */ + +#ifdef __cplusplus +extern "C" { +#endif + +// Enums + +/* ${ENUMS} */ + +/* ${TYPES:accessors} */ + +#ifdef __cplusplus +} +#endif + +#endif // Header Include Guard diff --git a/languages/c/templates/sections/enum.cpp b/languages/c/templates/sections/enum.cpp deleted file mode 100644 index e5165c61..00000000 --- a/languages/c/templates/sections/enum.cpp +++ /dev/null @@ -1,5 +0,0 @@ -namespace WPEFramework { - -${schema.list} - -} diff --git a/languages/c/templates/sections/enums.c b/languages/c/templates/sections/enums.c new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/c/templates/sections/enums.c @@ -0,0 +1 @@ +${schema.list} diff --git a/languages/c/templates/types/anyOf.c b/languages/c/templates/types/anyOf.c new file mode 100644 index 00000000..9cc8aaef --- /dev/null +++ b/languages/c/templates/types/anyOf.c @@ -0,0 +1 @@ +/* AnyOf is not supported in C */ \ No newline at end of file diff --git a/languages/c/templates/types/array.c b/languages/c/templates/types/array.c new file mode 100644 index 00000000..6f532328 --- /dev/null +++ b/languages/c/templates/types/array.c @@ -0,0 +1 @@ +${title} * \ No newline at end of file diff --git a/languages/c/templates/types/const.c b/languages/c/templates/types/const.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/types/default.c b/languages/c/templates/types/default.c new file mode 100644 index 00000000..38b05042 --- /dev/null +++ b/languages/c/templates/types/default.c @@ -0,0 +1,4 @@ +/* + * ${title} - ${description} + */ +typedef ${shape} ${title}; diff --git a/languages/c/templates/types/enum.cpp b/languages/c/templates/types/enum.cpp index d18d882d..6776b41a 100644 --- a/languages/c/templates/types/enum.cpp +++ b/languages/c/templates/types/enum.cpp @@ -1,4 +1,4 @@ /* ${title} ${description} */ - ENUM_CONVERSION_BEGIN(${info.title}_${name}) - { ${info.TITLE}_${NAME}_${key}, _T("${value}") }, - ENUM_CONVERSION_END(F${info.title}_${name}) + ENUM_CONVERSION_BEGIN(${name}) + { ${NAME}_${key}, _T("${value}") }, + ENUM_CONVERSION_END(${name}) diff --git a/languages/c/templates/types/enum.h b/languages/c/templates/types/enum.h index 9fa3c0a9..92108c75 100644 --- a/languages/c/templates/types/enum.h +++ b/languages/c/templates/types/enum.h @@ -1,4 +1,4 @@ /* ${title} ${description} */ typedef enum { - ${info.TITLE}_${NAME}_${key}, -} F${info.title}_${name}; + ${NAME}_${key}, +} ${name}; diff --git a/languages/c/templates/types/object.c b/languages/c/templates/types/object.c new file mode 100644 index 00000000..73cef62f --- /dev/null +++ b/languages/c/templates/types/object.c @@ -0,0 +1,3 @@ +struct { + ${shape}${property}; // ${summary} +} \ No newline at end of file diff --git a/languages/c/templates/types/primitive.c b/languages/c/templates/types/primitive.c new file mode 100644 index 00000000..21ae259c --- /dev/null +++ b/languages/c/templates/types/primitive.c @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/c/templates/types/ref.c b/languages/c/templates/types/ref.c new file mode 100644 index 00000000..41d15c96 --- /dev/null +++ b/languages/c/templates/types/ref.c @@ -0,0 +1 @@ +${title} \ No newline at end of file diff --git a/languages/c/templates/types/title.c b/languages/c/templates/types/title.c new file mode 100644 index 00000000..ca6b6897 --- /dev/null +++ b/languages/c/templates/types/title.c @@ -0,0 +1 @@ +F${info.Title}_${Title} \ No newline at end of file diff --git a/languages/c/templates/types/tuple.c b/languages/c/templates/types/tuple.c new file mode 100644 index 00000000..73cef62f --- /dev/null +++ b/languages/c/templates/types/tuple.c @@ -0,0 +1,3 @@ +struct { + ${shape}${property}; // ${summary} +} \ No newline at end of file diff --git a/languages/javascript/language.config.json b/languages/javascript/language.config.json index a2eff1ed..eee8f599 100644 --- a/languages/javascript/language.config.json +++ b/languages/javascript/language.config.json @@ -13,5 +13,11 @@ "operators": { "or": " | ", "stringQuotation": "'" + }, + "primitives": { + "boolean": "boolean", + "integer": "number", + "number": "number", + "string": "string" } } \ No newline at end of file diff --git a/languages/javascript/templates/declarations/default.js b/languages/javascript/templates/declarations/default.js index a9690ece..6eb4d88d 100644 --- a/languages/javascript/templates/declarations/default.js +++ b/languages/javascript/templates/declarations/default.js @@ -3,4 +3,4 @@ * ${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation} ${end.if.deprecated} */ - ${method.signature} +function ${method.name}(${method.signature.params}): Promise<${method.result.type}> diff --git a/languages/javascript/templates/declarations/interface.js b/languages/javascript/templates/declarations/interface.js new file mode 100644 index 00000000..fb48facb --- /dev/null +++ b/languages/javascript/templates/declarations/interface.js @@ -0,0 +1 @@ +${method.name}(${method.signature.params}): Promise<${method.result.type}> \ No newline at end of file diff --git a/languages/javascript/templates/declarations/polymorphic-reducer.js b/languages/javascript/templates/declarations/polymorphic-reducer.js index 24fff57d..6eb4d88d 100644 --- a/languages/javascript/templates/declarations/polymorphic-reducer.js +++ b/languages/javascript/templates/declarations/polymorphic-reducer.js @@ -3,6 +3,4 @@ * ${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation} ${end.if.deprecated} */ -${method.signature} - -// TODO: generate reducer signature \ No newline at end of file +function ${method.name}(${method.signature.params}): Promise<${method.result.type}> diff --git a/languages/javascript/templates/declarations/synchronous.js b/languages/javascript/templates/declarations/synchronous.js new file mode 100644 index 00000000..ca039b32 --- /dev/null +++ b/languages/javascript/templates/declarations/synchronous.js @@ -0,0 +1,6 @@ + /** + * ${method.summary} + * +${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation} +${end.if.deprecated} */ +function ${method.name}(${method.signature.params}): ${method.result.type} diff --git a/languages/javascript/templates/parameters/default.js b/languages/javascript/templates/parameters/default.js index 916a8adf..ab44d4b5 100644 --- a/languages/javascript/templates/parameters/default.js +++ b/languages/javascript/templates/parameters/default.js @@ -1 +1 @@ -${method.params.list} \ No newline at end of file +${method.param.name}: ${method.param.type} \ No newline at end of file diff --git a/languages/javascript/templates/parameters/optional.js b/languages/javascript/templates/parameters/optional.js new file mode 100644 index 00000000..20cf5889 --- /dev/null +++ b/languages/javascript/templates/parameters/optional.js @@ -0,0 +1 @@ +${method.param.name}?: ${method.param.type} \ No newline at end of file diff --git a/languages/javascript/templates/sections/enums.js b/languages/javascript/templates/sections/enums.js new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/javascript/templates/sections/enums.js @@ -0,0 +1 @@ +${schema.list} diff --git a/languages/javascript/templates/types/anyOf.mjs b/languages/javascript/templates/types/anyOf.mjs new file mode 100644 index 00000000..0ffe8e7a --- /dev/null +++ b/languages/javascript/templates/types/anyOf.mjs @@ -0,0 +1 @@ +${type} ${delimiter} | ${end.delimiter} \ No newline at end of file diff --git a/languages/javascript/templates/types/array.mjs b/languages/javascript/templates/types/array.mjs new file mode 100644 index 00000000..f6dc0dcf --- /dev/null +++ b/languages/javascript/templates/types/array.mjs @@ -0,0 +1 @@ +${title}[] \ No newline at end of file diff --git a/languages/javascript/templates/types/const.mjs b/languages/javascript/templates/types/const.mjs new file mode 100644 index 00000000..b711be8b --- /dev/null +++ b/languages/javascript/templates/types/const.mjs @@ -0,0 +1 @@ +${value} \ No newline at end of file diff --git a/languages/javascript/templates/types/default.mjs b/languages/javascript/templates/types/default.mjs new file mode 100644 index 00000000..8723ec3a --- /dev/null +++ b/languages/javascript/templates/types/default.mjs @@ -0,0 +1,4 @@ +/* + * ${title} - ${description} + */ +type ${title} = ${shape} diff --git a/languages/javascript/templates/types/enum.mjs b/languages/javascript/templates/types/enum.mjs index 907fb37d..35529071 100644 --- a/languages/javascript/templates/types/enum.mjs +++ b/languages/javascript/templates/types/enum.mjs @@ -1,3 +1,6 @@ -${name}: { +/* + * ${title} - ${description} + */ +${title}: { ${key}: '${value}', }, diff --git a/languages/javascript/templates/types/enum.ts b/languages/javascript/templates/types/enum.ts new file mode 100644 index 00000000..16c14463 --- /dev/null +++ b/languages/javascript/templates/types/enum.ts @@ -0,0 +1,6 @@ +/* + * ${title} - ${description} + */ +enum ${title} { + ${key} = '${value}', +} diff --git a/languages/javascript/templates/types/object.mjs b/languages/javascript/templates/types/object.mjs new file mode 100644 index 00000000..1110ba5f --- /dev/null +++ b/languages/javascript/templates/types/object.mjs @@ -0,0 +1,3 @@ +{ + ${property}${if.optional}?${end.optional}: ${shape} // ${summary} +} diff --git a/languages/javascript/templates/types/primitive.mjs b/languages/javascript/templates/types/primitive.mjs new file mode 100644 index 00000000..23bbace7 --- /dev/null +++ b/languages/javascript/templates/types/primitive.mjs @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/javascript/templates/types/ref.mjs b/languages/javascript/templates/types/ref.mjs new file mode 100644 index 00000000..a60cb41f --- /dev/null +++ b/languages/javascript/templates/types/ref.mjs @@ -0,0 +1 @@ +${title} \ No newline at end of file diff --git a/languages/javascript/templates/types/title.mjs b/languages/javascript/templates/types/title.mjs new file mode 100644 index 00000000..a60cb41f --- /dev/null +++ b/languages/javascript/templates/types/title.mjs @@ -0,0 +1 @@ +${title} \ No newline at end of file diff --git a/languages/javascript/templates/types/tuple.mjs b/languages/javascript/templates/types/tuple.mjs new file mode 100644 index 00000000..2fb19c56 --- /dev/null +++ b/languages/javascript/templates/types/tuple.mjs @@ -0,0 +1,3 @@ +[ + ${shape}${delimiter},${end.delimiter} // ${property} ${summary} +] \ No newline at end of file diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 0c8e641f..e1b13ca8 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -42,7 +42,6 @@ const _inspector = obj => { } } -// getMethodSignature(method, module, options = { destination: 'file.txt' }) // getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) // getSchemaType(schema, module, options = { destination: 'file.txt', title: true }) // getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) @@ -50,7 +49,6 @@ const _inspector = obj => { // getSchemaInstantiation(schema, module, options = {type: 'params' | 'result' | 'callback.params'| 'callback.result' | 'callback.response'}) let types = { - getMethodSignature: () => null, getMethodSignatureParams: () => null, getSchemaShape: () => null, getSchemaType: () => null, @@ -65,7 +63,8 @@ let config = { const state = { destination: undefined, - section: undefined + section: undefined, + typeTemplateDir: 'types' } const capitalize = str => str[0].toUpperCase() + str.substr(1) @@ -122,7 +121,7 @@ const getLinkForSchema = (schema, json, { name = '' } = {}) => { const dirs = config.createModuleDirectories const copySchemasIntoModules = config.copySchemasIntoModules - const type = types.getSchemaType(schema, json, { name: name, destination: state.destination, section: state.section }) + const type = types.getSchemaType(schema, json, { name: name, 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]) { @@ -373,7 +372,7 @@ const promoteAndNameSubSchemas = (obj) => { addContentDescriptorSubSchema(param, method.name, obj) } }) - if (isSubSchema(method.result.schema)) { + if (isSubSchema(method.result.schema) && method.result.schema.title) { addContentDescriptorSubSchema(method.result, method.name, obj) } }) @@ -413,56 +412,61 @@ const generateMacros = (obj, templates, languages, options = {}) => { // grab the options so we don't have to pass them from method to method Object.assign(state, options) - const imports = generateImports(obj, templates, { destination: (options.destination ? options.destination : '') }) - const initialization = generateInitialization(obj, templates) - const enums = generateEnums(obj, templates, { destination: (options.destination ? options.destination : '') }) - const eventsEnum = generateEvents(obj, templates) - const examples = generateExamples(obj, templates, languages) + const macros = { + schemas: {}, + types: {}, + enums: {} + } + + Array.from(new Set(['types'].concat(config.additionalSchemaTemplates))).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')) + 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')) + const cr = schemasArray.find(s => s.name === 'CloseReason') + cr && console.dir(cr) + }) + + const examples = generateExamples(obj, templates, languages) const allMethodsArray = generateMethods(obj, examples, templates) 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) - const declarations = declarationsArray.length ? getTemplate('/sections/declarations', templates).replace(/\$\{declaration\.list\}/g, declarationsArray.map(m => m.declaration).join('\n')) : '' + 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 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 schemasArray = generateSchemas(obj, templates, { baseUrl: '', section: 'schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) - const accessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) - const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).filter(body => body).join('\n')) : '' - const typesArray = schemasArray.length ? schemasArray.filter(x => !x.enum) : [] - const types = (typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).filter(body => body).join('\n')) : '') - - const accessors = (accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).filter(body => body).join('\n')) : '') const module = getTemplate('/codeblocks/module', templates) - const macros = { + Object.assign(macros, { imports, initialization, - enums, events, eventList, eventsEnum, methods, methodList, - accessors, declarations, defaults, examples, - schemas, - types, providerInterfaces, version: getSemanticVersion(obj), title: obj.info.title, description: obj.info.description, module: module, public: hasPublicAPIs(obj) - } + }) return macros } @@ -493,10 +497,22 @@ const insertMacros = (fContents = '', macros = {}) => { 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) - fContents = fContents.replace(/[ \t]*\/\* \$\{SCHEMAS\} \*\/[ \t]*\n/, macros.schemas) - fContents = fContents.replace(/[ \t]*\/\* \$\{TYPES\} \*\/[ \t]*\n/, macros.types) + + + // 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 => { + ['SCHEMAS', 'TYPES', 'ENUMS'].forEach(type => { + 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]*\/\* \$\{ENUMS\} \*\/[ \t]*\n/, macros.enums) fContents = fContents.replace(/[ \t]*\/\* \$\{IMPORTS\} \*\/[ \t]*\n/, macros.imports) fContents = fContents.replace(/[ \t]*\/\* \$\{INITIALIZATION\} \*\/[ \t]*\n/, macros.initialization) fContents = fContents.replace(/[ \t]*\/\* \$\{DEFAULTS\} \*\/[ \t]*\n/, macros.defaults) @@ -608,13 +624,13 @@ const enumFinder = compose( filter(([_key, val]) => isObject(val)) ) -const generateEnums = (json, templates, options = { destination: '' }) => { +const generateEventEnums = (json, templates, options = { destination: '' }) => { const suffix = options.destination.split('.').pop() return compose( option(''), map(val => { let template = getTemplate(`/sections/enum.${suffix}`, templates) - return template ? template.replace(/\$\{schema.list\}/g, val.trimEnd()) : val + return template ? template.replace(/\$\{schema.list\}/g, val) : val }), map(reduce((acc, val) => acc.concat(val).concat('\n'), '')), map(map((schema) => convertEnumTemplate(schema, suffix ? `/types/enum.${suffix}` : '/types/enum', templates))), @@ -645,7 +661,7 @@ const generateEvents = (json, templates) => { return acc }, null) - return generateEnums(obj, templates) + return generateEventEnums(obj, templates) } function generateDefaults(json = {}, templates) { @@ -700,7 +716,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, destination: state.destination, section: options.section }) + const schemaShape = types.getSchemaShape(schema, json, { name, prefix, templateDir: state.typeTemplateDir, destination: state.destination, section: options.section }) content = content .replace(/\$\{schema.title\}/, (schema.title || name)) @@ -718,7 +734,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.trimEnd() : content.trim() const isEnum = x => x.type === 'string' && Array.isArray(x.enum) && x.title @@ -774,7 +790,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, 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, { 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 .filter(link => link) .join('\n') @@ -1067,18 +1083,18 @@ function insertMethodMacros(template, methodObj, json, templates, 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 - const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) - const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) - const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) + const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) + const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) : '' const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, { instantiationType: 'params' }) const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' }) const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'params' }), ' ') : '' const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.params' }) : '' const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.result' }) : '' const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.response' }) : '' - const resultType = result.schema ? types.getSchemaType(result.schema, json, { name: result.name }) : '' - const resultJsonType = result.schema ? types.getJsonType(result.schema, json, { name: result.name }) : '' - const resultParams = generateResultParams(result.schema, json, templates, { name: result.name }) + const resultType = result.schema ? types.getSchemaType(result.schema, json, { name: result.name, templateDir: state.typeTemplateDir }) : '' + const resultJsonType = result.schema ? types.getJsonType(result.schema, json, { name: result.name}) : '' + const resultParams = generateResultParams(result.schema, json, templates, { name: result.name}) let seeAlso = '' if (isPolymorphicPullMethod(methodObj) && pullsForType) { @@ -1092,7 +1108,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) if (isTemporalSetMethod(methodObj)) { itemName = result.schema.items.title || 'item' itemName = itemName.charAt(0).toLowerCase() + itemName.substring(1) - itemType = types.getSchemaType(result.schema.items, json, { destination: state.destination, section: state.section }) + itemType = types.getSchemaType(result.schema.items, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) } template = insertExampleMacros(template, examples[methodObj.name] || [], methodObj, json, templates) @@ -1110,12 +1126,11 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.params\.array\}/g, JSON.stringify(methodObj.params.map(p => p.name))) .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\.params\}(.*?)\$\{end\.if\.result\.params\}/gms, resultParams ? '$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\.context\}(.*?)\$\{end\.if\.context\}/gms, event && event.params.length ? '$1' : '') .replace(/\$\{method\.params\.serialization\}/g, serializedParams) // Typed signature stuff - .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination, section: state.section })) .replace(/\$\{method\.context\}/g, method.context.join(', ')) .replace(/\$\{method\.context\.array\}/g, JSON.stringify(method.context)) @@ -1146,13 +1161,13 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .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, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, 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, resultSchema: true })) //, baseUrl: options.baseUrl .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, templateDir: state.typeTemplateDir, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) .replace(/\$\{method\.result\.instantiation\}/g, resultInst) - .replace(/\$\{method\.result\.params\}/g, resultParams) + .replace(/\$\{method\.result\.properties\}/g, resultParams) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) .replace(/\$\{method\.alternative.link\}/g, '#' + (method.alternative || "").toLowerCase()) @@ -1178,7 +1193,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) const matches = [...template.matchAll(/\$\{method\.params\[([0-9]+)\]\.type\}/g)] matches.forEach(match => { const index = parseInt(match[1]) - template = template.replace(/\$\{method\.params\[([0-9]+)\]\.type\}/g, types.getSchemaType(methodObj.params[index].schema, json, { destination: state.destination })) + template = template.replace(/\$\{method\.params\[([0-9]+)\]\.type\}/g, types.getSchemaType(methodObj.params[index].schema, json, { destination: state.destination, templateDir: state.typeTemplateDir })) template = template.replace(/\$\{method\.params\[([0-9]+)\]\.name\}/g, methodObj.params[index].name) }) @@ -1283,7 +1298,7 @@ function insertExampleMacros(template, examples, method, json, templates) { function generateResult(result, json, templates, { name = '' } = {}) { - const type = types.getSchemaType(result, json, { name: name, destination: state.destination, section: state.section }) + const type = types.getSchemaType(result, json, { name: name, templateDir: state.typeTemplateDir, destination: state.destination, section: state.section }) if (result.type === 'object' && result.properties) { let content = getTemplate('/types/object', templates).split('\n') @@ -1304,13 +1319,13 @@ function generateResult(result, json, templates, { name = '' } = {}) { // if we get a real link use it if (link !== '#') { - return `[${types.getSchemaType(result, json, { destination: state.destination, section: state.section })}](${link})` + return `[${types.getSchemaType(result, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section })}](${link})` } // otherwise this was a schema with no title, and we'll just copy it here else { const schema = localizeDependencies(result, json) return getTemplate('/types/default', templates) - .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { name: result.$ref.split("/").pop() })) + .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { name: result.$ref.split("/").pop(), templateDir: state.typeTemplateDir })) } } else { @@ -1318,26 +1333,49 @@ function generateResult(result, json, templates, { name = '' } = {}) { } } -// TODO: this is hard coded to C function generateResultParams(result, json, templates, {name = ''}={}) { + let moduleTitle = json.info.title + while (result.$ref) { + if (result.$ref.includes("/x-schemas/")) { + moduleTitle = result.$ref.split("/")[2] + } result = getJsonPath(result.$ref, json) } + // const results are almost certainly `"const": "null"` so there's no need to include it in the method signature if (result.hasOwnProperty('const')) { return '' } - else if (result.type && result.type === 'object' && result.properties) { - return Object.entries(result.properties).map( ([name, type]) => `${types.getSchemaType(type, json, {name: name})} ${name}`).join(', ') + // Objects with no titles get unwrapped + else if (result.type && !result.title && result.type === 'object' && result.properties) { + 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, templateDir: state.typeTemplateDir, moduleTitle: moduleTitle})) + ).join(', ') // most languages separate params w/ a comma, so leaving this here for now + } + // tuples get unwrapped + else if (result.type && result.type === 'array' && Array.isArray(result.items)) { + // TODO: this is hard coded to C + 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, templateDir: state.typeTemplateDir, moduleTitle: moduleTitle})) + ).join(', ') } + // everything else is just output as-is else { - return `${types.getSchemaType(result, json, { name: name})} *${name}` + const template = getTemplate('/parameters/result', templates) + return template + .replace(/\$\{method\.param\.name\}/g, `name`) + .replace(/\$\{method\.param\.type\}/g, types.getSchemaType(result, json, {name: name, templateDir: state.typeTemplateDir, moduleTitle: moduleTitle})) } } function insertSchemaMacros(template, title, schema, module) { return template.replace(/\$\{property\}/g, title) - .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { name: title, destination: state.destination, section: state.section, code: false })) + .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(/\$\{description\}/g, schema.description || '') .replace(/\$\{name\}/g, title || '') @@ -1348,7 +1386,7 @@ 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, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl + let type = types.getSchemaType(param.schema, module, { name: param.name, templateDir: state.typeTemplateDir, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl let typeLink = getLinkForSchema(param.schema, module, { name: param.name }) let jsonType = types.getJsonType(param.schema, module, { name: param.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) @@ -1409,10 +1447,11 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te } let interfaceShape = getTemplate('/codeblocks/interface', templates) + let interfaceDeclaration = getTemplate('/declarations/interface', templates) interfaceShape = interfaceShape.replace(/\$\{name\}/g, name) .replace(/\$\{capability\}/g, capability) - .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => `\t${types.getMethodSignature(method, moduleJson, { destination: state.destination, section: state.section, isInterface: true })}`).join('\n') + '\n') + .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => insertMethodMacros(interfaceDeclaration, method, moduleJson, { destination: state.destination, section: state.section, isInterface: true })).join('\n') + '\n') if (iface.length === 0) { template = template.replace(/\$\{provider\.methods\}/gms, '') @@ -1431,7 +1470,7 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te name: 'provider' }) const parametersSchema = method.params[0].schema - const parametersShape = types.getSchemaShape(parametersSchema, moduleJson, { destination: state.destination, section: state.section }) + const parametersShape = types.getSchemaShape(parametersSchema, moduleJson, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) let methodBlock = insertMethodMacros(getTemplateForMethod(method, templates), method, moduleJson, templates) methodBlock = methodBlock.replace(/\${parameters\.shape\}/g, parametersShape) const hasProviderParameters = parametersSchema && parametersSchema.properties && Object.keys(parametersSchema.properties).length > 0 @@ -1510,7 +1549,7 @@ function insertProviderParameterMacros(data = '', parameters, module = {}, optio Object.entries(parameters.properties).forEach(([name, param]) => { let constraints = getSchemaConstraints(param, module) - let type = types.getSchemaType(param, module, { destination: state.destination, section: state.section, code: true, link: true, title: true, asPath: options.asPath, baseUrl: options.baseUrl }) + let type = types.getSchemaType(param, module, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section, code: true, link: true, title: true, asPath: options.asPath, baseUrl: options.baseUrl }) if (constraints && type) { constraints = '
' + constraints diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 50bcfc76..ba3efd7a 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -47,8 +47,10 @@ const macrofy = async ( createModuleDirectories, copySchemasIntoModules, extractSubSchemas, + additionalSchemaTemplates, aggregateFile, operators, + primitives, hidePrivate = true, hideExcluded = false, staticModuleNames = [], @@ -69,19 +71,23 @@ const macrofy = async ( let typer try { - const typerModule = await import(path.join(sharedTemplates, '..', 'Types.mjs')) - typer = typerModule.default +// const typerModule = await import(path.join(sharedTemplates, '..', 'Types.mjs')) +// typer = typerModule.default } catch (_) { - typer = (await import('../shared/typescript.mjs')).default +// typer = (await import('../shared/typescript.mjs')).default } + typer = (await import('./types.mjs')).default + engine.setTyper(typer) engine.setConfig({ copySchemasIntoModules, createModuleDirectories, extractSubSchemas, - operators + operators, + primitives, + additionalSchemaTemplates }) const moduleList = [...(new Set(openrpc.methods.map(method => method.name.split('.').shift())))] @@ -89,6 +95,10 @@ const macrofy = async ( const sharedTemplateList = await readDir(sharedTemplates, { recursive: true }) const templates = Object.assign(await readFiles(sharedTemplateList, sharedTemplates), await readFiles(sdkTemplateList, template)) // sdkTemplates are second so they win ties + + typer.setTemplates && typer.setTemplates(templates) + typer.setPrimitives(primitives) + let templatesPermission = {} if (persistPermission) { templatesPermission = Object.assign(await readFilesPermissions(sharedTemplateList, sharedTemplates), diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs new file mode 100644 index 00000000..00dc6400 --- /dev/null +++ b/src/macrofier/types.mjs @@ -0,0 +1,499 @@ +/* + * Copyright 2021 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 + */ + +import deepmerge from 'deepmerge' +import { getPath, localizeDependencies } from '../shared/json-schema.mjs' +import path from "path" + +const templates = {} +const state = {} +const primitives = { + "integer": "number", + "number": "number", + "boolean": "boolean", + "string": "string" +} + +function setTemplates(t) { + Object.assign(templates, t) +} + +function setPrimitives(p) { + Object.assign(primitives, p) +} + +const capitalize = str => str ? str[0].toUpperCase() + str.substr(1) : str +const safeName = value => value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + +function getMethodSignatureParams(method, module, { destination }) { + const paramRequired = getTemplate('/parameters/default') + const paramOptional = getTemplate('/parameters/optional') + return method.params.map( param => (param.required ? paramRequired : paramOptional).replace(/\$\{method\.param\.name\}/g, param.name).replace(/\$\{method\.param\.type\}/g, getSchemaType(param.schema, module, {title: true, destination }))).join(', ') +} + +const getTemplate = (name) => { + if (name[0] !== '/') { + name = '/' + name + } + return templates[Object.keys(templates).find(k => k === name)] || templates[Object.keys(templates).find(k => k.startsWith(name.split('.').shift() + '.'))] || '' +} + +function insertSchemaMacros(content, schema, module, name, recursive=true) { + const title = name || schema.title || '' + let moduleTitle = module.info.title + + // TODO: this assumes the same title doesn't exist in multiple x-schema groups! + if (schema.title && module['x-schemas']) { + Object.entries(module['x-schemas']).forEach(([title, module]) => { + Object.values(module).forEach(s => { + if (schema.title === s.title) { + moduleTitle = title + } + }) + }) + } + + content = content + .replace(/\$\{title\}/g, title) + .replace(/\$\{Title\}/g, capitalize(title)) + .replace(/\$\{TITLE\}/g, title.toUpperCase()) + .replace(/\$\{description\}/g, schema.description ? schema.description : '') + .replace(/\$\{summary\}/g, schema.description ? schema.description.split('\n')[0] : '') + .replace(/\$\{name\}/g, title) + .replace(/\$\{NAME\}/g, title.toUpperCase()) + .replace(/\$\{info.title\}/g, moduleTitle) + .replace(/\$\{info.Title\}/g, capitalize(moduleTitle)) + .replace(/\$\{info.TITLE\}/g, moduleTitle.toUpperCase()) + // .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module, { name: title })) + + if (recursive) { + content = content.replace(/\$\{type\}/g, getSchemaType(schema, module, { name: title, destination: state.destination, section: state.section, code: false })) + } + return content +} + +// TODO using JSON.stringify probably won't work for many languages... +const insertConstMacros = (content, schema, module, name) => { + content = content.replace(/\$\{value\}/g, JSON.stringify(schema.const)) + return content +} + +const insertEnumMacros = (content, schema, module, name) => { + const template = content.split('\n') + + for (var i = 0; i < template.length; i++) { + if (template[i].indexOf('${key}') >= 0) { + template[i] = schema.enum.map(value => { + return template[i].replace(/\$\{key\}/g, safeName(value)) + .replace(/\$\{value\}/g, value) + }).join('\n') + } + } + + return template.join('\n') +} + +const insertObjectMacros = (content, schema, module, name, options) => { + options = JSON.parse(JSON.stringify(options)) + options.level = options.level + 1 + options.name = '' + + const template = content.split('\n') + const indent = (template.find(line => line.includes("${property}")).match(/^\s+/) || [''])[0] + + for (var i = 0; i < template.length; i++) { + if (template[i].indexOf('${property}') >= 0) { + const propertyTemplate = template[i] + template[i] = '' + if (schema.properties) { + template[i] = Object.entries(schema.properties).map(([name, prop], i) => { + + const schemaShape = getSchemaShape(prop, module, options) + return propertyTemplate + .replace(/(^\s+)/g, '$1'.repeat(options.level)) + .replace(/\$\{property\}/g, name) + .replace(/\$\{shape\}/g, schemaShape) + .replace(/\$\{description\}/g, prop.description || '') + .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') + .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, i === schema.properties.length-1 ? '' : '$1') + .replace(/\$\{if\.optional\}(.*?)\$\{end\.optional\}/g, schema.required && schema.required.includes(name) ? '' : '$1') + + }).join('\n') + } + else if (schema.propertyNames) { + const { propertyNames } = localizeDependencies(schema, module) + if (propertyNames.enum) { + template[i] = propertyNames.enum.map((prop, i) => { + // TODO: add language config feature for 'unknown' type + let type = { type: "null" } + + if (schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { + type = schema.additionalProperties + } + + if (schema.patternProperties) { + Object.entries(schema.patternProperties).forEach(([pattern, schema]) => { + let regex = new RegExp(pattern) + if (prop.match(regex)) { + type = schema + } + }) + } + + const schemaShape = getSchemaShape(type, module, options) + return propertyTemplate + .replace(/\$\{property\}/g, safeName(prop)) + .replace(/\$\{shape\}/g, schemaShape) + .replace(/\$\{description\}/g, prop.description || '') + .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') + .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, i === propertyNames.enum.length-1 ? '' : '$1') + .replace(/\$\{if\.optional\}(.*?)\$\{end\.optional\}/g, schema.required && schema.required.includes(prop) ? '' : '$1') + }).join('\n') + } + } + else if (schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { + // TODO: this won't work for custom types, only primatives... + // TODO: not all languages support additional properties... + // TODO: this is hard coded to typescript + let type = getSchemaType(schema.additionalProperties, module, options) + const shape = getSchemaShape({ type: type }, module, options) + template[i] = propertyTemplate + .replace(/\$\{property\}/g, '[property: string]') + .replace(/\$\{shape\}/g, shape) + .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, '') + .replace(/\$\{if\.optional\}(.*?)\$\{end\.optional\}/g, '') + } + } + else if (i !== 0) { + template[i] = indent.repeat(options.level-1) + template[i] + } + } + + return template.join('\n') +} + +const insertArrayMacros = (content, schema, module, name) => { + return content +} + +const insertTupleMacros = (content, schema, module, name, options) => { + const template = content.split('\n') + options.level = options.level + 1 + options.name = '' + + for (var i = 0; i < template.length; i++) { + if (template[i].indexOf('${property}') >= 0) { + const propertyTemplate = template[i] + template[i] = '' + template[i] = schema.items.map((prop, i) => { + + const schemaShape = getSchemaShape(prop, module, options) + return propertyTemplate + .replace(/\$\{property\}/g, prop['x-property']) + .replace(/\$\{shape\}/g, schemaShape) + .replace(/\$\{description\}/g, prop.description || '') + .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') + .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, i === schema.items.length-1 ? '' : '$1') + + }).join('\n') + } + } + + return template.join('\n') +} + +const insertPrimitiveMacros = (content, schema, module, name) => { + content = content.replace(/\$\{type\}/g, primitives[schema.type]) + return content +} + +const insertAnyOfMacros = (content, schema, module, name) => { + const itemTemplate = content + content = schema.anyOf.map((item, i) => itemTemplate + .replace(/\$\{type\}/g, getSchemaType(item, module)) + .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, i === schema.anyOf.length-1 ? '' : '$1') + ).join('') + return content +} + +function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', name = '', property = '', level = 0, summary, descriptions = true, destination, section, enums = true } = {}) { + schema = JSON.parse(JSON.stringify(schema)) + + state.destination = destination + state.section = section + + if (level === 0 && !schema.title) { + return '' + } + + const suffix = destination && ('.' + destination.split('.').pop()) || '' + const theTitle = insertSchemaMacros(getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, schema.title || '', false) + + let result = level === 0 ? getTemplate(path.join(templateDir, 'default' + suffix)) : '${shape}' + + if (enums && level === 0 && schema.type === "string" && Array.isArray(schema.enum)) { + result = getTemplate(path.join(templateDir, 'enum' + suffix)) + return insertSchemaMacros(insertEnumMacros(result, schema, module, theTitle), schema, module, theTitle) + } + + if (schema['$ref']) { + const someJson = getPath(schema['$ref'], module) + if (someJson) { + return getSchemaShape(someJson, module, { name, level, summary, descriptions, destination, enums: false }) + } + throw "Unresolvable $ref: " + schema['ref'] + ", in " + module.info.title + } + else if (schema.hasOwnProperty('const')) { + const shape = insertConstMacros(getTemplate(path.join(templateDir, 'const' + suffix)), schema, module, theTitle) + result = insertSchemaMacros(result.replace(/\$\{shape\}/g, shape), schema, module, theTitle) + return result + } + else if (level > 0 && schema.title) { + const shape = getTemplate(path.join(templateDir, 'ref' + suffix)) + result = result.replace(/\$\{shape\}/g, shape) + return insertSchemaMacros(result, schema, module, theTitle) + } + else if (schema.type === 'object') { + const shape = insertObjectMacros(getTemplate(path.join(templateDir, 'object' + suffix)), schema, module, theTitle, {level, descriptions, destination, section, enums }) + result = result.replace(/\$\{shape\}/g, shape) + return insertSchemaMacros(result, schema, module, theTitle) + } + else if (schema.anyOf || schema.oneOf) { + // borry anyOf logic, note that schema is a copy, so we're not breaking it. + if (!schema.anyOf) { + schema.anyOf = schema.oneOf + } + const shape = insertAnyOfMacros(getTemplate(path.join(templateDir, 'anyOf' + suffix)), schema, module, theTitle) + result = result.replace(/\$\{shape\}/g, shape) + return insertSchemaMacros(result, schema, module, theTitle) + } + else if (schema.allOf) { + const merger = (key) => function(a, b) { + if (a.const) { + return JSON.parse(JSON.stringify(a)) + } + else if (b.const) { + return JSON.parse(JSON.stringify(b)) + } + else { + return deepmerge(a, b, {customMerge: merger}) + } + } + + let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x).reverse()], { + customMerge: merger + }) + + if (schema.title) { + union.title = schema.title + } + delete union['$ref'] + + return getSchemaShape(union, module, { name, level, summary, descriptions, destination }) + } + else if (schema.type === "array" && schema.items && !Array.isArray(schema.items)) { + // array + const items = getSchemaShape(schema.items, module, { name, level, summary, descriptions, destination }) + const shape = insertArrayMacros(getTemplate(path.join(templateDir, 'array' + suffix)), schema, module, items) + result = result.replace(/\$\{shape\}/g, shape) + return insertSchemaMacros(result, schema, module, items) + } + else if (schema.type === "array" && schema.items && Array.isArray(schema.items)) { + // tuple + const shape = insertTupleMacros(getTemplate(path.join(templateDir, 'tuple' + suffix)), schema, module, theTitle, {level, descriptions, destination, section, enums }) + result = result.replace(/\$\{shape\}/g, shape) + return insertSchemaMacros(result, schema, module, theTitle) + } + else if (schema.type) { + const shape = insertPrimitiveMacros(getTemplate(path.join(templateDir, 'primitive' + suffix)), schema, module, theTitle) + result = result.replace(/\$\{shape\}/g, shape) + if (theTitle || level > 0) { + return insertSchemaMacros(result, schema, module, theTitle) + } + } + + return '' + } + + function getSchemaType(schema, module, { destination, templateDir = 'types', link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + const wrap = (str, wrapper) => wrapper + str + wrapper + + const suffix = destination && ('.' + destination.split('.').pop()) || '' + const theTitle = insertSchemaMacros(getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, schema.title || '', false) + + if (schema['$ref']) { + if (schema['$ref'][0] === '#') { + return getSchemaType(getPath(schema['$ref'], module), module, {title: true, link: link, code: code, destination}) + } + else { + // TODO: This never happens... but might be worth keeping in case we link to an opaque external schema at some point? + + if (link) { + return '[' + wrap(theTitle, code ? '`' : '') + '](' + schema['$ref'] + ')' + } + else { + return wrap(theTitle, code ? '`' : '') + } + } + } + else if (title && schema.title) { + if (link) { + return '[' + wrap(theTitle, code ? '`' : '') + '](#' + schema.title.toLowerCase() + ')' + } + else { + return wrap(theTitle, code ? '`' : '') + } + } + else if (schema.const) { + return (typeof schema.const === 'string' ? `'${schema.const}'` : schema.const) + } + else if (schema['x-method']) { + const target = JSON.parse(JSON.stringify(module.methods.find(m => m.name === schema['x-method'].split('.').pop()))) + + // transform the method copy params to be in the order of the x-additional-params array (and leave out any we don't want) + if (schema['x-additional-params']) { + const params = [] + schema['x-additional-params'].forEach(key => { + params.push(target.params.find(p => p.name === key)) + }) + target.params = params + } + else { + target.params = [] + } + + // TODO: this is TypeScript specific + const params = getMethodSignatureParams(target, module, { destination }) + const result = getSchemaType(target.result.schema, module, { destination }) + return `(${params}) => Promise<${result}>` + } + else if (schema.type === 'string' && schema.enum) { + let type = expandEnums ? schema.enum.map(e => wrap(e, '\'')).join(' | ') : schema.type + if (code) { + type = wrap(type, '`') + } + return type + } + // else if (schema.type === 'array' && Array.isArray(schema.items)) { + // // tuple + // } + else if ((schema.type === 'object' || (schema.type === 'array' && Array.isArray(schema.items))) && schema.title) { + const maybeGetPath = (path, json) => { + try { + return getPath(path, json) + } + catch (e) { + return null + } + } + + const def = maybeGetPath('#/definitions/' + schema.title, module) || maybeGetPath('#/components/schemas/' + schema.title, module) + + if (def && link) { + return '[' + wrap(theTitle, code ? '`' : '') + '](./' + '#' + schema.title.toLowerCase() + ')' + } + else { + return wrap(theTitle, code ? '`' : '') + } + } + else if (schema.type === 'array' && schema.items) { + if (Array.isArray(schema.items)) { + let type = '[' + schema.items.map(x => getSchemaType(x, module, { destination })).join(', ') + ']' // no links, no code + + if (code) { + type = wrap(type, '`') + } + + return type + } + else { + // grab the type for the non-array schema, so we get the link for free + let type = getSchemaType(schema.items, module, {code: code, link: link, title: title, destination}) + // insert the [] into the type + if (link) { + type = type.replace(/\[(`?)(.*)(`?)\]/, '\[$1$2\[\]$3\]') + } + else { + type = type.replace(/(`?)(.*)(`?)/, '$1$2\[\]$3') + } + return type + } + } + else if (schema.allOf) { + let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x)]) + if (schema.title) { + union.title = schema.title + } + return getSchemaType(union, module, { destination, link, title, code, asPath, baseUrl }) + } + else if (schema.oneOf || schema.anyOf) { + if (event) { + return getSchemaType((schema.oneOf || schema.anyOf)[0], module, { destination, link, title, code, asPath, baseUrl }) + } + else { + const newOptions = JSON.parse(JSON.stringify({ destination, link, title, code, asPath, baseUrl })) + newOptions.code = false + const result = (schema.oneOf || schema.anyOf).map(s => getSchemaType(s, module, newOptions)).join(' | ') + + return code ? wrap(result, '`') : result + } + } + else if (schema.type) { + const type = !Array.isArray(schema.type) ? primitives[schema.type] : primitives[schema.type.find(t => t !== 'null')] + return wrap(type, code ? '`' : '') + } + else { + return wrap('void', code ? '`' : '') + } + } + + function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + return '' + } + + function getTypeScriptType(jsonType) { + if (jsonType === 'integer') { + return 'number' + } + else { + return jsonType + } + } + + const enumReducer = (acc, val, i, arr) => { + const keyName = val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + acc = acc + ` ${keyName} = '${val}'` + if (i < arr.length-1) { + acc = acc.concat(',\n') + } + return acc + } + + function getSchemaInstantiation(schema, module, { instantiationType }) { + return '' + } + + export default { + setTemplates, + setPrimitives, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, + getJsonType, + getSchemaInstantiation + } \ No newline at end of file diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index 7e85fab9..b5103055 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -59,9 +59,11 @@ const run = async ({ templatesPerSchema: config.templatesPerSchema, persistPermission: config.persistPermission, operators: config.operators, + primitives: config.primitives, createModuleDirectories: config.createModuleDirectories, copySchemasIntoModules: config.copySchemasIntoModules, extractSubSchemas: config.extractSubSchemas, + additionalSchemaTemplates: config.additionalSchemaTemplates, staticModuleNames: staticModuleNames, hideExcluded: true, aggregateFile: config.aggregateFile, diff --git a/src/shared/typescript.mjs b/src/shared/typescript.mjs index 5982137e..d5b49269 100644 --- a/src/shared/typescript.mjs +++ b/src/shared/typescript.mjs @@ -54,6 +54,7 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, if (schema['$ref']) { if (level === 0) { + throw "Ref at level 0!" return `${prefix}${theTitle};` } else { @@ -62,6 +63,7 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, return getSchemaShape(someJson, module, { name, level, title, summary, descriptions, destination, enums: false }) } else { + throw "unknown $ref!!" ' '.repeat(level) + `${prefix}${theTitle}${operator}` } } diff --git a/src/validate/index.mjs b/src/validate/index.mjs index 33cc6aea..629b5f69 100644 --- a/src/validate/index.mjs +++ b/src/validate/index.mjs @@ -105,7 +105,7 @@ const run = async ({ addFormats(ajv) // explicitly add our custom extensions so we can keep strict mode on (TODO: put these in a JSON config?) - ajv.addVocabulary(['x-method', 'x-this-param', 'x-additional-params', 'x-schemas', 'components']) + ajv.addVocabulary(['x-method', 'x-this-param', 'x-additional-params', 'x-schemas', 'components', 'x-property']) const firebolt = ajv.compile(fireboltOpenRpcSpec) const jsonschema = ajv.compile(jsonSchemaSpec) From 4d22a4d6c68f938308a732abdc96b13eef186672 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Wed, 12 Jul 2023 09:16:41 +0530 Subject: [PATCH 024/137] Naming + void* to struct* changes based on sky review, removed redundant code, array handling fix (#109) Naming + void* to struct* changes based on sky review, removed redundant code, array handling fix --- languages/c/Types.mjs | 34 ++- languages/c/language.config.json | 10 +- languages/c/src/types/ImplHelpers.mjs | 141 +++++++------ languages/c/src/types/JSONHelpers.mjs | 3 +- languages/c/src/types/NativeHelpers.mjs | 74 ++----- languages/c/templates/imports/default.cpp | 2 +- languages/c/templates/imports/default.h | 2 +- .../c/templates/imports/default.jsondata | 2 +- .../modules/include/{Module.h => module.h} | 6 +- .../modules/src/{Module.cpp => module.cpp} | 4 +- .../{Common/Module.h => common/module.h} | 6 +- .../{JsonData_Module.h => jsondata_module.h} | 4 +- .../{Module_Common.cpp => module_common.cpp} | 2 +- .../sdk/include/{Error.h => error.h} | 6 +- .../sdk/include/{Firebolt.h => firebolt.h} | 10 +- .../sdk/include/{Types.h => types.h} | 12 +- languages/c/templates/sdk/scripts/build.sh | 42 +++- languages/c/templates/sdk/src/CMakeLists.txt | 5 - languages/c/templates/sdk/src/FireboltSDK.h | 2 +- .../c/templates/sdk/src/Logger/Logger.cpp | 2 +- languages/c/templates/sdk/src/Logger/Logger.h | 2 +- .../c/templates/sdk/src/Transport/Transport.h | 2 +- languages/c/templates/sdk/src/Types.cpp | 10 +- .../sdk/src/{Firebolt.cpp => firebolt.cpp} | 0 languages/c/templates/sdk/test/CMakeLists.txt | 2 +- languages/c/templates/sdk/test/Main.c | 1 + languages/c/templates/sdk/test/Module.h | 1 - .../c/templates/sdk/test/OpenRPCCTests.h | 11 +- .../c/templates/sdk/test/OpenRPCTests.cpp | 199 ++++++++++++++---- languages/c/templates/sdk/test/OpenRPCTests.h | 23 +- languages/c/templates/sdk/test/TestUtils.h | 10 +- languages/c/templates/types/enum.cpp | 4 +- languages/c/templates/types/enum.h | 2 +- src/macrofier/engine.mjs | 7 +- src/macrofier/index.mjs | 4 +- 35 files changed, 392 insertions(+), 255 deletions(-) rename languages/c/templates/modules/include/{Module.h => module.h} (92%) rename languages/c/templates/modules/src/{Module.cpp => module.cpp} (93%) rename languages/c/templates/schemas/include/{Common/Module.h => common/module.h} (90%) rename languages/c/templates/schemas/src/{JsonData_Module.h => jsondata_module.h} (91%) rename languages/c/templates/schemas/src/{Module_Common.cpp => module_common.cpp} (94%) rename languages/c/templates/sdk/include/{Error.h => error.h} (93%) rename languages/c/templates/sdk/include/{Firebolt.h => firebolt.h} (93%) rename languages/c/templates/sdk/include/{Types.h => types.h} (73%) rename languages/c/templates/sdk/src/{Firebolt.cpp => firebolt.cpp} (100%) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 2a8f5aa0..1ed84940 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -20,7 +20,7 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation, getCallbackParametersInstantiation, getCallbackResultInstantiation, getCallbackResponseInstantiation } from './src/types/ImplHelpers.mjs' -import { getJsonContainerDefinition, getJsonDataStructName } from './src/types/JSONHelpers.mjs' +import { getJsonContainerDefinition, getJsonDataStructName, getJsonDataPrefix } from './src/types/JSONHelpers.mjs' const getSdkNameSpace = () => 'FireboltSDK' const getJsonNativeTypeForOpaqueString = () => getSdkNameSpace() + '::JSON::String' @@ -262,17 +262,14 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref structure.json = res.json structure.name = res.name structure.namespace = res.namespace - return structure } } else if (json.const) { structure.type = getNativeType(json, fireboltString) structure.json = json - return structure } else if (json['x-method']) { console.log(`WARNING UNHANDLED: x-method in ${name}`) - return structure //throw "x-methods not supported yet" } else if (json.type === 'string' && json.enum) { @@ -283,13 +280,12 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref structure.json = json structure.type = typeName structure.namespace = getModuleName(module) - return structure } else if (Array.isArray(json.type)) { let type = json.type.find(t => t !== 'null') let sch = JSON.parse(JSON.stringify(json)) sch.type = type - return getSchemaTypeInfo(module, sch, name, schemas, prefix, options) + structure = getSchemaTypeInfo(module, sch, name, schemas, prefix, options) } else if (json.type === 'array' && json.items && (validJsonObjectProperties(json) === true)) { let res = '' @@ -306,13 +302,11 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref res = getSchemaTypeInfo(module, json.items, json.items.name || name, schemas, prefix) } - let arrayName = capitalize(res.name) + capitalize(res.json.type) - let n = getTypeName(getModuleName(module), arrayName, prefix) + let n = getTypeName(getModuleName(module), capitalize(res.name), prefix) structure.name = res.name || name && (capitalize(name)) - structure.type = n + 'ArrayHandle' + structure.type = n + 'Array_t' structure.json = json structure.namespace = getModuleName(module) - return structure } else if (json.allOf) { let title = json.title ? json.title : name @@ -320,22 +314,21 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref union['title'] = title delete union['$ref'] - return getSchemaTypeInfo(module, union, '', schemas, '', options) + structure = getSchemaTypeInfo(module, union, '', schemas, '', options) } else if (json.oneOf) { structure.type = fireboltString ? getFireboltStringType() : 'char*' structure.json.type = 'string' - return structure } else if (json.anyOf) { let mergedSchema = getMergedSchema(module, json, name, schemas) let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) - return getSchemaTypeInfo(module, mergedSchema, '', schemas, prefixName, options) + structure = getSchemaTypeInfo(module, mergedSchema, '', schemas, prefixName, options) } else if (json.type === 'object') { structure.json = json if (hasProperties(json)) { - structure.type = getTypeName(getModuleName(module), json.title || name, prefix) + 'Handle' + structure.type = getTypeName(getModuleName(module), json.title || name, prefix) + '_t' structure.name = (json.name ? json.name : (json.title ? json.title : name)) structure.namespace = (json.namespace ? json.namespace : getModuleName(module)) } @@ -345,8 +338,6 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref if (name) { structure.name = capitalize(name) } - - return structure } else if (json.type) { if (!IsResultBooleanSuccess(json, name) && !IsResultConstNullSuccess(json, name)) { @@ -370,8 +361,9 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' let shape = '' if (destination && section) { - const isHeader = (destination.includes("JsonData_") !== true) && destination.endsWith(".h") - const isCPP = ((destination.endsWith(".cpp") || destination.includes("JsonData_")) && (section.includes('accessors') !== true)) + const isHeader = (destination.includes(getJsonDataPrefix().toLowerCase()) !== true) && destination.endsWith(".h") + const isCPP = ((destination.endsWith(".cpp") || destination.includes(getJsonDataPrefix().toLowerCase())) && (section.includes('accessors') !== true)) + json = JSON.parse(JSON.stringify(json)) name = json.title || name @@ -437,7 +429,7 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, schemas, prefix) let t = description(capitalize(info.name), json.description) + '\n' - t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + '_t'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) c_shape += '\n' + t props.push({name: `${pname}`, type: `WPEFramework::Core::JSON::ArrayType<${subModuleProperty.type}>`}) } @@ -556,7 +548,7 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' t += description(capitalize(info.name), json.description) + '\n' t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, moduleProperty.type)) } - t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, '', info.type, info.json)) + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + '_t'), subModuleProperty.type, '', info.type, info.json)) shape += '\n' + t } } @@ -775,7 +767,7 @@ function getSchemaInstantiation(schema, module, name, { instantiationType = '' } } else if (instantiationType === 'pull.param.name') { let resultJsonType = getJsonType(schema, module, { name: name }) || '' - return resultJsonType && resultJsonType[0].split('_')[1] || '' + return resultJsonType.length && resultJsonType[0].split('_')[1] || '' } return '' diff --git a/languages/c/language.config.json b/languages/c/language.config.json index 77cde389..ee3604d7 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -4,13 +4,13 @@ "createModuleDirectories": false, "extractSubSchemas": true, "templatesPerModule": [ - "/include/Module.h", - "/src/Module.cpp" + "/include/module.h", + "/src/module.cpp" ], "templatesPerSchema": [ - "/include/Common/Module.h", - "/src/Module_Common.cpp", - "/src/JsonData_Module.h" + "/include/common/module.h", + "/src/module_common.cpp", + "/src/jsondata_module.h" ], "persistPermission": true } diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index 3d5403d4..5b373377 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -4,35 +4,36 @@ const Indent = '\t' const getSdkNameSpace = () => 'FireboltSDK' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' +const camelcase = str => str[0].toLowerCase() + str.substr(1) const getObjectHandleManagementImpl = (varName, jsonDataName) => { - let result = `${varName}Handle ${varName}Handle_Create(void) + let result = `${varName}_t ${varName}Handle_Acquire(void) { WPEFramework::Core::ProxyType<${jsonDataName}>* type = new WPEFramework::Core::ProxyType<${jsonDataName}>(); *type = WPEFramework::Core::ProxyType<${jsonDataName}>::Create(); - return (static_cast<${varName}Handle>(type)); + return (reinterpret_cast<${varName}_t>(type)); } -void ${varName}Handle_Addref(${varName}Handle handle) +void ${varName}Handle_Addref(${varName}_t handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); var->AddRef(); } -void ${varName}Handle_Release(${varName}Handle handle) +void ${varName}Handle_Release(${varName}_t handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = reinterpret_cast*>(handle); var->Release(); if (var->IsValid() != true) { delete var; } } -bool ${varName}Handle_IsValid(${varName}Handle handle) +bool ${varName}Handle_IsValid(${varName}_t handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); return var->IsValid(); } @@ -42,17 +43,17 @@ bool ${varName}Handle_IsValid(${varName}Handle handle) const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, subPropertyName, accessorPropertyType, json = {}, options = {readonly:false, optional:false}) => { let result = '' - result += `${accessorPropertyType} ${objName}_Get_${subPropertyName}(${objName}Handle handle) + result += `${accessorPropertyType} ${objName}_Get_${subPropertyName}(${objName}_t handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ` + '\n' if ((json.type === 'object') && (accessorPropertyType !== 'char*')) { result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); *(*element) = (*var)->${subPropertyName}; - return (static_cast<${accessorPropertyType}>(element));` + '\n' + return (reinterpret_cast<${accessorPropertyType}>(element));` + '\n' } else { if ((typeof json.const === 'string') || (json.type === 'string' && !json.enum) || (accessorPropertyType === 'char*')) { @@ -66,14 +67,14 @@ const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, if (!options.readonly) { let type = (accessorPropertyType === getFireboltStringType()) ? 'char*' : accessorPropertyType - result += `void ${objName}_Set_${subPropertyName}(${objName}Handle handle, ${type} value)\n{ + result += `void ${objName}_Set_${subPropertyName}(${objName}_t handle, ${type} value)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ` + '\n' if (json.type === 'object' && (accessorPropertyType !== 'char*')) { - result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* object = static_cast*>(value); + result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* object = reinterpret_cast*>(value); (*var)->${subPropertyName} = *(*object);` + '\n' } else { @@ -83,16 +84,16 @@ const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, } if (options.optional === true) { - result += `bool ${objName}_Has_${subPropertyName}(${objName}Handle handle)\n{ + result += `bool ${objName}_Has_${subPropertyName}(${objName}_t handle)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); return ((*var)->${subPropertyName}.IsSet()); }` + '\n' - result += `void ${objName}_Clear_${subPropertyName}(${objName}Handle handle)\n{ + result += `void ${objName}_Clear_${subPropertyName}(${objName}_t handle)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ((*var)->${subPropertyName}.Clear()); }` + '\n' @@ -113,7 +114,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr let result = `uint32_t ${objName}Array_Size(${objHandleType} handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); return (${propertyName}.Length()); @@ -122,7 +123,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr result += `${accessorPropertyType} ${objName}Array_Get(${objHandleType} handle, uint32_t index) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid());` + '\n' if ((json.type === 'object') || (json.type === 'array')) { @@ -130,7 +131,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr *object = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); *(*object) = ${propertyName}.Get(index); - return (static_cast<${accessorPropertyType}>(object));` + '\n' + return (reinterpret_cast<${accessorPropertyType}>(object));` + '\n' } else { if ((typeof json.const === 'string') || (json.type === 'string' && !json.enum)) { @@ -146,23 +147,25 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr result += `void ${objName}Array_Add(${objHandleType} handle, ${type} value) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid());` + '\n' if ((json.type === 'object') || (json.type === 'array')) { - result += ` ${subPropertyType}& element = *(*(static_cast*>(value)));` + '\n' + result += ` ${subPropertyType} element; + element = *(*(reinterpret_cast*>(value)));` + '\n' } else { - result += ` ${subPropertyType} element(value);` + '\n' + result += ` ${subPropertyType} element;` + '\n' + result += ` element = value;` + '\n' } result += ` - ${propertyName}.Add(element); + ${propertyName}.Add() = element; }` + '\n' result += `void ${objName}Array_Clear(${objHandleType} handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ${propertyName}.Clear(); @@ -172,10 +175,10 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr } const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPropertyType, json = {}, options = {readonly:false, optional:false}) => { - let result = `uint32_t ${objName}_KeysCount(${objName}Handle handle) + let result = `uint32_t ${objName}_KeysCount(${objName}_t handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ${containerType}::Iterator elements = (*var)->Variants(); uint32_t count = 0; @@ -184,10 +187,10 @@ const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPr } return (count); }` + '\n' - result += `void ${objName}_AddKey(${objName}Handle handle, char* key, ${accessorPropertyType} value) + result += `void ${objName}_AddKey(${objName}_t handle, char* key, ${accessorPropertyType} value) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ` + '\n' let elementContainer = subPropertyType @@ -196,14 +199,14 @@ const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPr } if ((json.type === 'object') || (json.type === 'array' && json.items)) { if (containerType.includes('VariantContainer')) { - result += ` ${subPropertyType}& container = *(*(static_cast*>(value)));` + '\n' + result += ` ${subPropertyType}& container = *(*(reinterpret_cast*>(value)));` + '\n' result += ` string containerStr;` + '\n' result += ` element.ToString(containerStr);` + '\n' result += ` WPEFramework::Core::JSON::VariantContainer containerVariant(containerStr);` + '\n' result += ` WPEFramework::Core::JSON::Variant element = containerVariant;` + '\n' } else { - result += ` ${subPropertyType}& element = *(*(static_cast*>(value)));` + '\n' + result += ` ${subPropertyType}& element = *(*(reinterpret_cast*>(value)));` + '\n' } } else { result += ` ${elementContainer} element(value);` + '\n' @@ -211,19 +214,19 @@ const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPr result += ` (*var)->Set(const_cast(key), element); }` + '\n' - result += `void ${objName}_RemoveKey(${objName}Handle handle, char* key) + result += `void ${objName}_RemoveKey(${objName}_t handle, char* key) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); (*var)->Remove(key); }` + '\n' - result += `${accessorPropertyType} ${objName}_FindKey(${objName}Handle handle, char* key) + result += `${accessorPropertyType} ${objName}_FindKey(${objName}_t handle, char* key) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid());` + '\n' if ((json.type === 'object') || (json.type === 'array') || ((json.type === 'string' || (typeof json.const === 'string')) && !json.enum)) { @@ -249,14 +252,14 @@ const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPr *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); *(*element) = objectMap; - status = (static_cast<${accessorPropertyType}>(element));` + '\n' + status = (reinterpret_cast<${accessorPropertyType}>(element));` + '\n' } else if (json.type === 'array' && json.items) { result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); *(*element) = (*var)->Get(key).Array(); - status = (static_cast<${accessorPropertyType}>(element));` + '\n' + status = (reinterpret_cast<${accessorPropertyType}>(element));` + '\n' } else { if (json.type === 'string' || (typeof json.const === 'string')) { @@ -298,25 +301,41 @@ function getParameterInstantiation(paramList, container = '') { paramList.forEach(param => { impl += `\n` const jsonType = param.jsonType + const name = param.name if (jsonType.length) { if (param.required) { - if (param.nativeType.includes('FireboltTypes_StringHandle')) { - impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = *(static_cast<${jsonType}*>(${param.name}));\n` + if (param.nativeType.includes('FireboltTypes_String_t')) { + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = *(reinterpret_cast<${jsonType}*>(${name}));\n` + } + else if (param.nativeType.includes('_t')) { + impl += ` ${jsonType}& ${capitalize(name)}Container = *(*(reinterpret_cast*>(${camelcase(name)})));\n` + impl += ` string ${capitalize(name)}Str;\n` + impl += ` ${capitalize(name)}Container.ToString(${capitalize(name)}Str);\n` + impl += ` WPEFramework::Core::JSON::VariantContainer ${capitalize(name)}VariantContainer(${capitalize(name)}Str);\n` + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = ${capitalize(name)}VariantContainer;\n` } else { - impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = ${param.name};\n` + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = ${name};\n` } - impl += ` jsonParameters.Set(_T("${param.name}"), ${capitalize(param.name)});` + impl += ` jsonParameters.Set(_T("${name}"), ${capitalize(name)});` } else { - impl += ` if (${param.name} != nullptr) {\n` + + impl += ` if (${name} != nullptr) {\n` if (param.nativeType.includes('char*')) { - impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = ${param.name};\n` + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = ${name};\n` + } + else if (param.nativeType.includes('_t')) { + impl += ` ${jsonType}& ${capitalize(name)}Container = *(*(reinterpret_cast*>(${camelcase(name)})));\n` + impl += ` string ${capitalize(name)}Str;\n` + impl += ` ${capitalize(name)}Container.ToString(${capitalize(name)}Str);\n` + impl += ` WPEFramework::Core::JSON::VariantContainer ${capitalize(name)}VariantContainer(${capitalize(name)}Str);\n` + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = ${capitalize(name)}VariantContainer;\n` } else { - impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = *(${param.name});\n` + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = *(${name});\n` } - impl += ` jsonParameters.Set(_T("${param.name}"), ${capitalize(param.name)});\n` + impl += ` jsonParameters.Set(_T("${name}"), ${capitalize(name)});\n` impl += ` }` } impl += '\n' @@ -347,7 +366,7 @@ function getCallbackParametersInstantiation(paramList, container = '') { } }) impl += `\n WPEFramework::Core::ProxyType<${container}>* jsonResponse;\n` - impl += ` WPEFramework::Core::ProxyType& var = *(static_cast*>(response)); + impl += ` WPEFramework::Core::ProxyType& var = *(reinterpret_cast*>(response)); ASSERT(var.IsValid() == true); if (var.IsValid() == true) { @@ -378,7 +397,7 @@ function getCallbackParametersInstantiation(paramList, container = '') { if (param.nativeType === 'char*') { contextParams += ` ${getSdkNameSpace()}::JSON::String* ${param.name}Value = new ${getSdkNameSpace()}::JSON::String(); *${param.name}Value = elements.Current().Value().c_str(); - ${param.name} = ${param.name}Value;\n` + ${param.name} = reinterpret_cast<${getFireboltStringType()}>(${param.name}Value);\n` } else if (param.nativeType === 'bool') { contextParams += ` ${param.name} = elements.Current().Boolean();\n` @@ -402,7 +421,7 @@ function getCallbackParametersInstantiation(paramList, container = '') { }\n` } else { - impl +=` WPEFramework::Core::ProxyType<${container}>* jsonResponse = static_cast*>(response);\n` + impl +=` WPEFramework::Core::ProxyType<${container}>* jsonResponse = reinterpret_cast*>(response);\n` } return impl @@ -410,7 +429,7 @@ function getCallbackParametersInstantiation(paramList, container = '') { function getCallbackResultInstantiation(nativeType, container = '') { let impl = '' - if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + if (nativeType === 'char*' || nativeType === 'FireboltTypes_String_t') { impl +=` ${container}* jsonStrResponse = new ${container}(); *jsonStrResponse = *(*jsonResponse); @@ -426,7 +445,7 @@ function getCallbackResponseInstantiation(paramList, nativeType, container = '') paramList.forEach(param => { if (param.required !== undefined) { if (param.nativeType === 'char*') { - impl += `static_cast<${getFireboltStringType()}>(${param.name}), ` + impl += `reinterpret_cast<${getFireboltStringType()}>(${param.name}), ` } else if (param.required === true) { impl += `${param.name}, ` @@ -438,11 +457,11 @@ function getCallbackResponseInstantiation(paramList, nativeType, container = '') }) } - if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { - impl += `static_cast<${nativeType}>(jsonStrResponse)` + if (nativeType === 'char*' || nativeType === 'FireboltTypes_String_t') { + impl += `reinterpret_cast<${nativeType}>(jsonStrResponse)` } - else if (nativeType.includes('Handle')) { - impl += `static_cast<${nativeType}>(jsonResponse)` + else if (nativeType.includes('_t')) { + impl += `reinterpret_cast<${nativeType}>(jsonResponse)` } else { impl += `static_cast<${nativeType}>((*jsonResponse)->Value())` @@ -457,16 +476,16 @@ function getResultInstantiation (name, nativeType, container, indentLevel = 3) { if (nativeType) { impl += `${' '.repeat(indentLevel)}if (${name} != nullptr) {` + '\n' - if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + if (nativeType === 'char*' || nativeType === 'FireboltTypes_String_t') { impl += `${' '.repeat(indentLevel + 1)}${container}* strResult = new ${container}(jsonResult);` + '\n' - impl += `${' '.repeat(indentLevel + 1)}*${name} = static_cast<${getFireboltStringType()}>(strResult);` - } else if (nativeType.includes('Handle')) { + impl += `${' '.repeat(indentLevel + 1)}*${name} = reinterpret_cast<${getFireboltStringType()}>(strResult);` + '\n' + } else if (nativeType.includes('_t')) { impl += `${' '.repeat(indentLevel + 1)}WPEFramework::Core::ProxyType<${container}>* resultPtr = new WPEFramework::Core::ProxyType<${container}>();\n` impl += `${' '.repeat(indentLevel + 1)}*resultPtr = WPEFramework::Core::ProxyType<${container}>::Create();\n` impl += `${' '.repeat(indentLevel + 1)}*(*resultPtr) = jsonResult;\n` - impl += `${' '.repeat(indentLevel + 1)}*${name} = static_cast<${nativeType}>(resultPtr);` - } else { - impl += `${' '.repeat(indentLevel + 1)}*${name} = jsonResult.Value();` + impl += `${' '.repeat(indentLevel + 1)}*${name} = reinterpret_cast<${nativeType}>(resultPtr);` + '\n' + } else { + impl += `${' '.repeat(indentLevel + 1)}*${name} = jsonResult.Value();` + '\n' } impl += `${' '.repeat(indentLevel)}}` + '\n' } else if (name === 'success') { diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index b2a260b5..cc31b14a 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -52,5 +52,6 @@ function getJsonContainerDefinition (schema, name, props) { export { getJsonContainerDefinition, - getJsonDataStructName + getJsonDataStructName, + getJsonDataPrefix } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 1460e22e..7bfef987 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -29,7 +29,7 @@ const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = pre const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' -const getFireboltStringType = () => 'FireboltTypes_StringHandle' +const getFireboltStringType = () => 'FireboltTypes_String_t' const getHeaderText = () => { return `/* @@ -42,40 +42,6 @@ const getHeaderText = () => { ` } -const getIncludeGuardOpen = (json, prefix=null) => { - prefix = prefix ? `${prefix.toUpperCase()}_` : '' - return ` -#ifndef _${prefix}${getModuleName(json).toUpperCase()}_H -#define _${prefix}${getModuleName(json).toUpperCase()}_H - -` -} - -const getStyleGuardOpen = () => { - return ` -#ifdef __cplusplus -extern "C" { -#endif - -` -} - -const getStyleGuardClose = () => { - return ` - -#ifdef __cplusplus -} -#endif - -` -} - -const getIncludeGuardClose = () => { - return ` -#endif // Header Include Guard -` -} - const capitalize = str => str[0].toUpperCase() + str.substr(1) const description = (title, str='') => '/* ' + title + (str.length > 0 ? ' - ' + str : '') + ' */' const isOptional = (prop, json) => (!json.required || !json.required.includes(prop)) @@ -142,26 +108,26 @@ const getNativeType = (json, fireboltString = false) => { const getObjectHandleManagement = varName => { - let result = `typedef void* ${varName}Handle; -${varName}Handle ${varName}Handle_Create(void); -void ${varName}Handle_Addref(${varName}Handle handle); -void ${varName}Handle_Release(${varName}Handle handle); -bool ${varName}Handle_IsValid(${varName}Handle handle); + let result = `typedef struct ${varName}_s* ${varName}_t; +${varName}_t ${varName}Handle_Acquire(void); +void ${varName}Handle_Addref(${varName}_t handle); +void ${varName}Handle_Release(${varName}_t handle); +bool ${varName}Handle_IsValid(${varName}_t handle); ` return result } const getPropertyAccessors = (objName, propertyName, propertyType, options = {level:0, readonly:false, optional:false}) => { - let result = `${Indent.repeat(options.level)}${propertyType} ${objName}_Get_${propertyName}(${objName}Handle handle);` + '\n' + let result = `${Indent.repeat(options.level)}${propertyType} ${objName}_Get_${propertyName}(${objName}_t handle);` + '\n' if (!options.readonly) { let type = (propertyType === getFireboltStringType()) ? 'char*' : propertyType - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${type} ${propertyName.toLowerCase()});` + '\n' + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}_t handle, ${type} ${propertyName.toLowerCase()});` + '\n' } if (options.optional === true) { - result += `${Indent.repeat(options.level)}bool ${objName}_Has_${propertyName}(${objName}Handle handle);` + '\n' - result += `${Indent.repeat(options.level)}void ${objName}_Clear_${propertyName}(${objName}Handle handle);` + '\n' + result += `${Indent.repeat(options.level)}bool ${objName}_Has_${propertyName}(${objName}_t handle);` + '\n' + result += `${Indent.repeat(options.level)}void ${objName}_Clear_${propertyName}(${objName}_t handle);` + '\n' } return result @@ -171,10 +137,10 @@ const getMapAccessors = (typeName, accessorPropertyType, level = 0) => { let res - res = `${Indent.repeat(level)}uint32_t ${typeName}_KeysCount(${typeName}Handle handle);` + '\n' - res += `${Indent.repeat(level)}void ${typeName}_AddKey(${typeName}Handle handle, char* key, ${accessorPropertyType} value);` + '\n' - res += `${Indent.repeat(level)}void ${typeName}_RemoveKey(${typeName}Handle handle, char* key);` + '\n' - res += `${Indent.repeat(level)}${accessorPropertyType} ${typeName}_FindKey(${typeName}Handle handle, char* key);` + '\n' + res = `${Indent.repeat(level)}uint32_t ${typeName}_KeysCount(${typeName}_t handle);` + '\n' + res += `${Indent.repeat(level)}void ${typeName}_AddKey(${typeName}_t handle, char* key, ${accessorPropertyType} value);` + '\n' + res += `${Indent.repeat(level)}void ${typeName}_RemoveKey(${typeName}_t handle, char* key);` + '\n' + res += `${Indent.repeat(level)}${accessorPropertyType} ${typeName}_FindKey(${typeName}_t handle, char* key);` + '\n' return res } @@ -193,10 +159,10 @@ const getTypeName = (moduleName, varName, prefix = '', upperCase = false, capita const getArrayAccessors = (arrayName, propertyType, valueType) => { - let res = `uint32_t ${arrayName}Array_Size(${propertyType}Handle handle);` + '\n' - res += `${valueType} ${arrayName}Array_Get(${propertyType}Handle handle, uint32_t index);` + '\n' - res += `void ${arrayName}Array_Add(${propertyType}Handle handle, ${valueType} value);` + '\n' - res += `void ${arrayName}Array_Clear(${propertyType}Handle handle);` + '\n' + let res = `uint32_t ${arrayName}Array_Size(${propertyType}_t handle);` + '\n' + res += `${valueType} ${arrayName}Array_Get(${propertyType}_t handle, uint32_t index);` + '\n' + res += `void ${arrayName}Array_Add(${propertyType}_t handle, ${valueType} value);` + '\n' + res += `void ${arrayName}Array_Clear(${propertyType}_t handle);` + '\n' return res } @@ -270,10 +236,6 @@ function getPropertyEventUnregisterSignature(property, module) { export { getHeaderText, - getIncludeGuardOpen, - getStyleGuardOpen, - getStyleGuardClose, - getIncludeGuardClose, getNativeType, getModuleName, getPropertyGetterSignature, diff --git a/languages/c/templates/imports/default.cpp b/languages/c/templates/imports/default.cpp index 69e241f9..caf84bc9 100644 --- a/languages/c/templates/imports/default.cpp +++ b/languages/c/templates/imports/default.cpp @@ -1 +1 @@ -#include "JsonData_${info.title}.h" +#include "jsondata_${info.title.lowercase}.h" diff --git a/languages/c/templates/imports/default.h b/languages/c/templates/imports/default.h index a38b58ef..56a97a40 100644 --- a/languages/c/templates/imports/default.h +++ b/languages/c/templates/imports/default.h @@ -1 +1 @@ -#include "Common/${info.title}.h" +#include "common/${info.title.lowercase}.h" diff --git a/languages/c/templates/imports/default.jsondata b/languages/c/templates/imports/default.jsondata index 69e241f9..caf84bc9 100644 --- a/languages/c/templates/imports/default.jsondata +++ b/languages/c/templates/imports/default.jsondata @@ -1 +1 @@ -#include "JsonData_${info.title}.h" +#include "jsondata_${info.title.lowercase}.h" diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/module.h similarity index 92% rename from languages/c/templates/modules/include/Module.h rename to languages/c/templates/modules/include/module.h index a202f643..00c5d595 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/module.h @@ -16,10 +16,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _${info.TITLE}_H -#define _${info.TITLE}_H +#ifndef ${info.TITLE}_H +#define ${info.TITLE}_H -#include "Firebolt.h" +#include /* ${IMPORTS} */ #ifdef __cplusplus diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/module.cpp similarity index 93% rename from languages/c/templates/modules/src/Module.cpp rename to languages/c/templates/modules/src/module.cpp index 65721f1e..2b467ae1 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/module.cpp @@ -18,10 +18,10 @@ #include "FireboltSDK.h" /* ${IMPORTS} */ -#include "${info.title}.h" +#include "${info.title.lowercase}.h" namespace FireboltSDK { - namespace ${info.title} { + namespace ${info.Title} { // Types /* ${TYPES} */ } diff --git a/languages/c/templates/schemas/include/Common/Module.h b/languages/c/templates/schemas/include/common/module.h similarity index 90% rename from languages/c/templates/schemas/include/Common/Module.h rename to languages/c/templates/schemas/include/common/module.h index ff037fba..939b3988 100644 --- a/languages/c/templates/schemas/include/Common/Module.h +++ b/languages/c/templates/schemas/include/common/module.h @@ -16,10 +16,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _COMMON_${info.TITLE}_H -#define _COMMON_${info.TITLE}_H +#ifndef COMMON_${info.TITLE}_H +#define COMMON_${info.TITLE}_H -#include "Firebolt.h" +#include /* ${IMPORTS} */ #ifdef __cplusplus diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/jsondata_module.h similarity index 91% rename from languages/c/templates/schemas/src/JsonData_Module.h rename to languages/c/templates/schemas/src/jsondata_module.h index d0ecbbac..f80be03e 100644 --- a/languages/c/templates/schemas/src/JsonData_Module.h +++ b/languages/c/templates/schemas/src/jsondata_module.h @@ -19,10 +19,10 @@ #pragma once /* ${IMPORTS} */ -#include "Common/${info.title}.h" +#include "common/${info.title.lowercase}.h" namespace FireboltSDK { - namespace ${info.title} { + namespace ${info.Title} { // Types /* ${SCHEMAS} */ diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/module_common.cpp similarity index 94% rename from languages/c/templates/schemas/src/Module_Common.cpp rename to languages/c/templates/schemas/src/module_common.cpp index 0ccdfc28..0d8c74d2 100644 --- a/languages/c/templates/schemas/src/Module_Common.cpp +++ b/languages/c/templates/schemas/src/module_common.cpp @@ -18,7 +18,7 @@ #include "FireboltSDK.h" /* ${IMPORTS} */ -#include "JsonData_${info.title}.h" +#include "jsondata_${info.title.lowercase}.h" /* ${ENUMS} */ diff --git a/languages/c/templates/sdk/include/Error.h b/languages/c/templates/sdk/include/error.h similarity index 93% rename from languages/c/templates/sdk/include/Error.h rename to languages/c/templates/sdk/include/error.h index 87cda9dd..07d6268a 100644 --- a/languages/c/templates/sdk/include/Error.h +++ b/languages/c/templates/sdk/include/error.h @@ -16,8 +16,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _FIREBOLT_ERROR_H -#define _FIREBOLT_ERROR_H +#ifndef FIREBOLT_ERROR_H +#define FIREBOLT_ERROR_H #ifdef __cplusplus extern "C" { @@ -38,4 +38,4 @@ typedef enum FireboltSDKError { } #endif -#endif // _FIREBOLT_ERROR_H +#endif // FIREBOLT_ERROR_H diff --git a/languages/c/templates/sdk/include/Firebolt.h b/languages/c/templates/sdk/include/firebolt.h similarity index 93% rename from languages/c/templates/sdk/include/Firebolt.h rename to languages/c/templates/sdk/include/firebolt.h index 2223bad3..0957973f 100644 --- a/languages/c/templates/sdk/include/Firebolt.h +++ b/languages/c/templates/sdk/include/firebolt.h @@ -16,11 +16,11 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _FIREBOLT_H -#define _FIREBOLT_H +#ifndef FIREBOLT_H +#define FIREBOLT_H -#include "Error.h" -#include "Types.h" +#include "error.h" +#include "types.h" #ifdef __cplusplus extern "C" { @@ -62,4 +62,4 @@ uint32_t FireboltSDK_Deinitialize(void); #endif -#endif // _FIREBOLT_H +#endif // FIREBOLT_H diff --git a/languages/c/templates/sdk/include/Types.h b/languages/c/templates/sdk/include/types.h similarity index 73% rename from languages/c/templates/sdk/include/Types.h rename to languages/c/templates/sdk/include/types.h index 4fd16256..26efc54f 100644 --- a/languages/c/templates/sdk/include/Types.h +++ b/languages/c/templates/sdk/include/types.h @@ -16,8 +16,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _FIREBOLT_TYPES_H -#define _FIREBOLT_TYPES_H +#ifndef FIREBOLT_TYPES_H +#define FIREBOLT_TYPES_H #include #include @@ -26,12 +26,12 @@ extern "C" { #endif -typedef void* FireboltTypes_StringHandle; -const char* FireboltTypes_String(FireboltTypes_StringHandle handle); -void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle); +typedef struct FireboltTypes_String_s* FireboltTypes_String_t; +const char* FireboltTypes_String(FireboltTypes_String_t handle); +void FireboltTypes_StringHandle_Release(FireboltTypes_String_t handle); #ifdef __cplusplus } #endif -#endif // _FIREBOLT_TYPES_H +#endif // FIREBOLT_TYPES_H diff --git a/languages/c/templates/sdk/scripts/build.sh b/languages/c/templates/sdk/scripts/build.sh index e9b01f20..d50295a6 100755 --- a/languages/c/templates/sdk/scripts/build.sh +++ b/languages/c/templates/sdk/scripts/build.sh @@ -1,11 +1,37 @@ #!/bin/bash -SDK_PATH="." -if [ "$1" != "" ] +usage() +{ + echo "options:" + echo " -p sdk path" + echo " -s sysroot path" + echo " -t enable test" + echo " -c clear build" + echo " -h : help" + echo + echo "usage: " + echo " ./build.sh -p path -tc" +} + +SdkPath="." +EnableTest="OFF" +SysrootPath=${SYSROOT_PATH} +ClearBuild="N" +while getopts p:s:tch flag +do + case "${flag}" in + p) SdkPath="${OPTARG}";; + s) SysrootPath="${OPTARG}";; + t) EnableTest="ON";; + c) ClearBuild="Y";; + h) usage && exit 1;; + esac +done + +if [ "${ClearBuild}" == "Y" ]; then - SDK_PATH=$1 - echo "inside ${1}" + rm -rf ${SdkPath}/build fi -echo ${SDK_PATH} -rm -rf ${SDK_PATH}/build -cmake -B${SDK_PATH}/build -S${SDK_PATH} -DSYSROOT_PATH=${SYSROOT_PATH} -cmake --build ${SDK_PATH}/build + +cmake -B${SdkPath}/build -S${SdkPath} -DSYSROOT_PATH=${SysrootPath} -DENABLE_TESTS=${EnableTest} +cmake --build ${SdkPath}/build +cmake --install ${SdkPath}/build --prefix=${SdkPath}/build/Firebolt diff --git a/languages/c/templates/sdk/src/CMakeLists.txt b/languages/c/templates/sdk/src/CMakeLists.txt index 2f00bdf1..b565d6b1 100644 --- a/languages/c/templates/sdk/src/CMakeLists.txt +++ b/languages/c/templates/sdk/src/CMakeLists.txt @@ -20,7 +20,6 @@ project(FireboltSDK) project_version(1.0.0) set(TARGET ${PROJECT_NAME}) message("Setup ${TARGET} v${PROJECT_VERSION}") -file(GLOB GENERATED_SOURCES "${GENERATED_CODE_PATH}/src/*.cpp") file(GLOB SOURCES *.cpp) add_library(${TARGET} ${FIREBOLT_LIBRARY_TYPE} @@ -41,8 +40,6 @@ target_link_libraries(${TARGET} target_include_directories(${TARGET} PRIVATE - $ - $ $ $ ) @@ -64,8 +61,6 @@ install( ) InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION ${FIREBOLT_NAMESPACE}SDK) -InstallHeaders(TARGET ${TARGET} EXCLUDE_ROOT_DIR HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} - SOURCE ${GENERATED_CODE_PATH}/include DESTINATION ${FIREBOLT_NAMESPACE}/generated) InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../include DESTINATION ${FIREBOLT_NAMESPACE}) diff --git a/languages/c/templates/sdk/src/FireboltSDK.h b/languages/c/templates/sdk/src/FireboltSDK.h index 19946126..d78687dc 100644 --- a/languages/c/templates/sdk/src/FireboltSDK.h +++ b/languages/c/templates/sdk/src/FireboltSDK.h @@ -23,4 +23,4 @@ #include "Accessor/Accessor.h" #include "Logger/Logger.h" #include "TypesPriv.h" -#include "Types.h" +#include "types.h" diff --git a/languages/c/templates/sdk/src/Logger/Logger.cpp b/languages/c/templates/sdk/src/Logger/Logger.cpp index 0e49dfce..a9750a6e 100644 --- a/languages/c/templates/sdk/src/Logger/Logger.cpp +++ b/languages/c/templates/sdk/src/Logger/Logger.cpp @@ -17,7 +17,7 @@ */ #include "Module.h" -#include "Error.h" +#include "error.h" #include "Logger.h" namespace WPEFramework { diff --git a/languages/c/templates/sdk/src/Logger/Logger.h b/languages/c/templates/sdk/src/Logger/Logger.h index cffeff54..2c864c7b 100644 --- a/languages/c/templates/sdk/src/Logger/Logger.h +++ b/languages/c/templates/sdk/src/Logger/Logger.h @@ -18,7 +18,7 @@ #pragma once -#include "Types.h" +#include "types.h" namespace FireboltSDK { diff --git a/languages/c/templates/sdk/src/Transport/Transport.h b/languages/c/templates/sdk/src/Transport/Transport.h index d12312a5..109e2431 100644 --- a/languages/c/templates/sdk/src/Transport/Transport.h +++ b/languages/c/templates/sdk/src/Transport/Transport.h @@ -19,7 +19,7 @@ #pragma once #include "Module.h" -#include "Error.h" +#include "error.h" namespace FireboltSDK { diff --git a/languages/c/templates/sdk/src/Types.cpp b/languages/c/templates/sdk/src/Types.cpp index f19cfe63..b9620436 100644 --- a/languages/c/templates/sdk/src/Types.cpp +++ b/languages/c/templates/sdk/src/Types.cpp @@ -17,7 +17,7 @@ */ #include "Module.h" -#include "Types.h" +#include "types.h" #include "TypesPriv.h" #ifdef __cplusplus @@ -25,14 +25,14 @@ extern "C" { #endif // String Type Handler Interfaces -const char* FireboltTypes_String(FireboltTypes_StringHandle handle) +const char* FireboltTypes_String(FireboltTypes_String_t handle) { - return ((static_cast(handle))->Value().c_str()); + return ((reinterpret_cast(handle))->Value().c_str()); } -void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle) +void FireboltTypes_StringHandle_Release(FireboltTypes_String_t handle) { - delete static_cast(handle); + delete reinterpret_cast(handle); } #ifdef __cplusplus diff --git a/languages/c/templates/sdk/src/Firebolt.cpp b/languages/c/templates/sdk/src/firebolt.cpp similarity index 100% rename from languages/c/templates/sdk/src/Firebolt.cpp rename to languages/c/templates/sdk/src/firebolt.cpp diff --git a/languages/c/templates/sdk/test/CMakeLists.txt b/languages/c/templates/sdk/test/CMakeLists.txt index a56ca20a..21ee1f55 100644 --- a/languages/c/templates/sdk/test/CMakeLists.txt +++ b/languages/c/templates/sdk/test/CMakeLists.txt @@ -57,7 +57,7 @@ install( InstallCMakeConfig(TARGETS ${TESTLIB}) InstallCMakeConfigs(TARGET ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) InstallHeaders(TARGET ${TESTLIB} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION FireboltTest) -InstallLibraries(TARGET ${TESTLIB} LIBRARIES ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallLibraries(TARGET ${TESTLIB} STATIC LIBRARIES ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) set(TESTAPP "FireboltSDKTestApp") diff --git a/languages/c/templates/sdk/test/Main.c b/languages/c/templates/sdk/test/Main.c index 7c4c94a5..6161792e 100644 --- a/languages/c/templates/sdk/test/Main.c +++ b/languages/c/templates/sdk/test/Main.c @@ -35,6 +35,7 @@ int main() EXECUTE("test_properties_set", test_properties_set); EXECUTE("test_eventregister_by_providing_callback", test_eventregister_by_providing_callback); EXECUTE("test_eventregister", test_eventregister); + EXECUTE("test_eventregister_with_same_callback", test_eventregister_with_same_callback); EXECUTE("test_string_set_get_value", test_string_set_get_value); test_firebolt_dispose_instance(); diff --git a/languages/c/templates/sdk/test/Module.h b/languages/c/templates/sdk/test/Module.h index d5340b68..a147ff75 100644 --- a/languages/c/templates/sdk/test/Module.h +++ b/languages/c/templates/sdk/test/Module.h @@ -23,7 +23,6 @@ #endif #include -#include #undef EXTERNAL #define EXTERNAL diff --git a/languages/c/templates/sdk/test/OpenRPCCTests.h b/languages/c/templates/sdk/test/OpenRPCCTests.h index 7f2fb59e..4fe5eb5b 100644 --- a/languages/c/templates/sdk/test/OpenRPCCTests.h +++ b/languages/c/templates/sdk/test/OpenRPCCTests.h @@ -16,8 +16,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _OPENRPC_C_TESTS_H -#define _OPENRPC_C_TESTS_H +#ifndef OPENRPC_C_TESTS_H +#define OPENRPC_C_TESTS_H #include "TestUtils.h" @@ -25,13 +25,14 @@ extern "C" { #endif -uint32_t test_firebolt_create_instance(); -uint32_t test_firebolt_dispose_instance(); +void test_firebolt_create_instance(); +void test_firebolt_dispose_instance(); uint32_t test_firebolt_main(); uint32_t test_properties_get_device_id(); uint32_t test_properties_set(); uint32_t test_eventregister(); +uint32_t test_eventregister_with_same_callback(); uint32_t test_eventregister_by_providing_callback(); uint32_t test_string_set_get_value(); @@ -39,4 +40,4 @@ uint32_t test_string_set_get_value(); } #endif -#endif // _OPENRPC_C_TESTS_H +#endif // OPENRPC_C_TESTS_H diff --git a/languages/c/templates/sdk/test/OpenRPCTests.cpp b/languages/c/templates/sdk/test/OpenRPCTests.cpp index cf9ea5a0..b74f17ae 100644 --- a/languages/c/templates/sdk/test/OpenRPCTests.cpp +++ b/languages/c/templates/sdk/test/OpenRPCTests.cpp @@ -38,11 +38,20 @@ ENUM_CONVERSION_BEGIN(TestEnum) { TestEnum::Test4, _TXT("Test4ValueCheck") }, ENUM_CONVERSION_END(TestEnum) } + +typedef void (*OnNotifyDeviceNameChanged)(const void* userData, const char* data); +static void NotifyEvent(const void* userData, const char* data) +{ + printf("NotifyEvent data : %s\n", data); +} + namespace FireboltSDK { Tests::Tests() { _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEventWithMultipleCallback"), std::forward_as_tuple(&SubscribeEventWithMultipleCallback)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEventwithSameCallback"), + std::forward_as_tuple(&SubscribeEventwithSameCallback)); _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEvent"), std::forward_as_tuple(&SubscribeEvent)); @@ -147,25 +156,55 @@ namespace FireboltSDK { return status; } - static void deviceNameChangeCallback(const void* userData, void* response) + static void deviceNameChangeCallback(void* userCB, const void* userData, void* response) { - WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + WPEFramework::Core::ProxyType& jsonResponse = *(reinterpret_cast*>(response)); FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Received a new event: %s", jsonResponse->Value().c_str()); - jsonResponse.Release(); FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + OnNotifyDeviceNameChanged notifyDeviceNameChanged = reinterpret_cast(userCB); + notifyDeviceNameChanged(userData, jsonResponse->Value().c_str()); eventControl->NotifyEvent(); + jsonResponse.Release(); } /* static */ uint32_t Tests::SubscribeEvent() { - FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl("EventControl"); const string eventName = _T("device.Name"); const void* userdata = static_cast(eventControl); - uint32_t id = 0; + eventControl->ResetEvent(); + + JsonObject jsonParameters; + uint32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), + "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered successfully, Waiting for event...", __func__); + + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + delete eventControl; + + return status; + } + + /* static */ uint32_t Tests::SubscribeEventwithSameCallback() + { + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl("EventControl"); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); eventControl->ResetEvent(); - uint32_t status = Properties::Subscribe(eventName, deviceNameChangeCallback, userdata, id); + + JsonObject jsonParameters; + uint32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -174,40 +213,71 @@ namespace FireboltSDK { } else { FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "%s Yes registered successfully", __func__); - eventControl->WaitForEvent(WPEFramework::Core::infinite); + + status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback, reinterpret_cast(NotifyEvent), userdata); + EXPECT_EQ(status, FireboltSDKErrorInUse); + if (status == FireboltSDKErrorInUse) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes this device.name event is already registered with same callback", __func__); + } + status = ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone : status); } - EXPECT_EQ(Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); delete eventControl; return status; } + + static void NotifyEvent1(const void* userData, const char* data) + { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent1 data : %s", data); + if (userData) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent1 userData : %s\n", reinterpret_cast(userData)->Name().c_str()); + } + } + static void NotifyEvent2(const void* userData, const char* data) + { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent2 data : %s", data); + if (userData) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent2 userData : %s\n", reinterpret_cast(userData)->Name().c_str()); + } + } + template - /* static */ uint32_t Tests::SubscribeEventForC(const string& eventName, CALLBACK& callbackFunc, const void* userdata, uint32_t& id) + /* static */ uint32_t Tests::SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata) { - return Properties::Subscribe(eventName, callbackFunc, userdata, id);; + return Properties::Subscribe(eventName, jsonParameters, callbackFunc, usercb, userdata); } - static void deviceNameChangeMultipleCallback(const void* userData, void* response) + static void deviceNameChangeMultipleCallback(void* userCB, const void* userData, void* response) { - WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + WPEFramework::Core::ProxyType& jsonResponse = *(reinterpret_cast*>(response)); FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Received a new event from deviceNameChangeMultipleCallback: %s", jsonResponse->Value().c_str()); - jsonResponse.Release(); FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + OnNotifyDeviceNameChanged notifyDeviceNameChanged = reinterpret_cast(userCB); + notifyDeviceNameChanged(userData, jsonResponse->Value().c_str()); + eventControl->NotifyEvent(); + jsonResponse.Release(); } /* static */ uint32_t Tests::SubscribeEventWithMultipleCallback() { - FireboltSDK::Tests::EventControl* eventControl1 = new FireboltSDK::Tests::EventControl(); + FireboltSDK::Tests::EventControl* eventControl1 = new FireboltSDK::Tests::EventControl("EventControl1"); const string eventName = _T("device.Name"); const void* userdata = static_cast(eventControl1); - uint32_t id1 = 0, id2 = 0; eventControl1->ResetEvent(); - uint32_t status = Properties::Subscribe(eventName, deviceNameChangeCallback, userdata, id1); + + JsonObject jsonParameters; + uint32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent1), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -215,28 +285,33 @@ namespace FireboltSDK { "Set %s status = %d", eventName.c_str(), status); } else { FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), - "%s Yes registered successfully", __func__); + "%s Yes registered successfully, Waiting for event...", __func__); } if (status == FireboltSDKErrorNone) { - FireboltSDK::Tests::EventControl* eventControl2 = new FireboltSDK::Tests::EventControl(); + FireboltSDK::Tests::EventControl* eventControl2 = new FireboltSDK::Tests::EventControl("EventControl2"); userdata = static_cast(eventControl2); - status = Properties::Subscribe(eventName, deviceNameChangeMultipleCallback, userdata, id2); + status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent2), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", eventName.c_str(), status); } else { + status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent2), userdata); + EXPECT_EQ(status, FireboltSDKErrorInUse); + status = ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone : status); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), - "%s Yes registered second callback also successfully", __func__); + "%s Yes registered second callback also successfully, waiting for events...\n", __func__); + eventControl1->WaitForEvent(WPEFramework::Core::infinite); eventControl2->WaitForEvent(WPEFramework::Core::infinite); } - EXPECT_EQ(Properties::Unsubscribe(eventName, id1), FireboltSDKErrorNone); + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent2)), FireboltSDKErrorNone); delete eventControl2; } - EXPECT_EQ(Properties::Unsubscribe(eventName, id2), FireboltSDKErrorNone); + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent1)), FireboltSDKErrorNone); delete eventControl1; return status; @@ -248,12 +323,21 @@ namespace FireboltSDK { extern "C" { #endif -uint32_t test_firebolt_create_instance() +void test_firebolt_create_instance() { - FireboltSDK::Accessor::Instance(); + 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); } -uint32_t test_firebolt_dispose_instance() +void test_firebolt_dispose_instance() { FireboltSDK::Accessor::Dispose(); } @@ -297,28 +381,27 @@ uint32_t test_properties_set() return status; } -static void deviceNameChangeCallbackForC(const void* userData, void* response) +static void deviceNameChangeCallbackForC(void* userCB, const void* userData, void* response) { - WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + WPEFramework::Core::ProxyType& jsonResponse = *(reinterpret_cast*>(response)); FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", "Received a new event--->: %s", jsonResponse->Value().c_str()); - jsonResponse.Release(); FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); eventControl->NotifyEvent(); + jsonResponse.Release(); } uint32_t test_eventregister() { FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); - JsonObject parameters; - const string eventName = _T("device.Name"); const void* userdata = static_cast(eventControl); - uint32_t id = 0; eventControl->ResetEvent(); - uint32_t status = FireboltSDK::Properties::Subscribe(eventName, deviceNameChangeCallbackForC, userdata, id); + + JsonObject jsonParameters; + uint32_t status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -326,26 +409,60 @@ uint32_t test_eventregister() "%s Set %s status = %d", __func__, eventName.c_str(), status); } else { FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "%s Yes registered successfully", __func__); + "%s Yes registered successfully, Waiting for event...", __func__); eventControl->WaitForEvent(WPEFramework::Core::infinite); } delete eventControl; - EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); return status; } +uint32_t test_eventregister_with_same_callback() +{ + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + + eventControl->ResetEvent(); + + JsonObject jsonParameters; + uint32_t status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Set %s status = %d", __func__, eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes registered successfully", __func__); + + status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); + EXPECT_EQ(status, FireboltSDKErrorInUse); + if (status == FireboltSDKErrorInUse) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes this device.name event is already registered with same callback", __func__); + } + status = ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone : status); + } + + delete eventControl; + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + + return status; +} uint32_t test_eventregister_by_providing_callback() { FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); const string eventName = _T("device.Name"); const void* userdata = static_cast(eventControl); - uint32_t id = 0; eventControl->ResetEvent(); - uint32_t status = FireboltSDK::Tests::SubscribeEventForC(eventName, deviceNameChangeCallbackForC, userdata, id); + + JsonObject jsonParameters; + uint32_t status = FireboltSDK::Tests::SubscribeEventForC(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -353,20 +470,22 @@ uint32_t test_eventregister_by_providing_callback() "%s Set %s status = %d", __func__, eventName.c_str(), status); } else { FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "%s Yes registered successfully", __func__); + "%s Yes registered successfully, Waiting for event...", __func__); eventControl->WaitForEvent(WPEFramework::Core::infinite); } delete eventControl; - EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + return status; } #include "TypesPriv.h" uint32_t test_string_set_get_value() { uint32_t status = FireboltSDKErrorNone; - FireboltSDK::String* str = new FireboltSDK::String("testString"); - void* handle = static_cast(str); + FireboltSDK::JSON::String* str = new FireboltSDK::JSON::String(); + WPEFramework::Core::JSON::String wpeJsonStr("TestString"); + FireboltTypes_String_t handle = reinterpret_cast(str); const char* value = FireboltTypes_String(handle); EXPECT_EQ(strncmp(value, str->Value().c_str(), str->Value().length()), 0); diff --git a/languages/c/templates/sdk/test/OpenRPCTests.h b/languages/c/templates/sdk/test/OpenRPCTests.h index 00abd364..e82665d0 100644 --- a/languages/c/templates/sdk/test/OpenRPCTests.h +++ b/languages/c/templates/sdk/test/OpenRPCTests.h @@ -18,8 +18,15 @@ #pragma once +#include "FireboltSDK.h" #include "TestUtils.h" -#include "Firebolt.h" + +typedef enum { + Test1, + Test2, + Test3, + Test4 +} TestEnum; namespace FireboltSDK { typedef uint32_t (*Func)(); @@ -30,6 +37,12 @@ namespace FireboltSDK { public: EventControl() : _event(false, true) + , _name("EventControl") + { + } + EventControl(string name) + : _event(false, true) + , _name(name) { } ~EventControl() = default; @@ -47,8 +60,13 @@ namespace FireboltSDK { { _event.ResetEvent(); } + string Name() const + { + return _name; + } private: WPEFramework::Core::Event _event; + string _name; }; private: @@ -84,10 +102,11 @@ namespace FireboltSDK { static uint32_t SetUnKnownMethod(); static uint32_t SubscribeEvent(); + static uint32_t SubscribeEventwithSameCallback(); static uint32_t SubscribeEventWithMultipleCallback(); template - static uint32_t SubscribeEventForC(const string& eventName, CALLBACK& callbackFunc, const void* userdata, uint32_t& id); + static uint32_t SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata); protected: static void PrintJsonObject(const JsonObject::Iterator& iterator); diff --git a/languages/c/templates/sdk/test/TestUtils.h b/languages/c/templates/sdk/test/TestUtils.h index 8c3cb732..c54db9f0 100644 --- a/languages/c/templates/sdk/test/TestUtils.h +++ b/languages/c/templates/sdk/test/TestUtils.h @@ -1,5 +1,5 @@ -#ifndef _TEST_UTILS_H -#define _TEST_UTILS_H +#ifndef TEST_UTILS_H +#define TEST_UTILS_H #include #include @@ -8,8 +8,8 @@ #define MAX(x, y) (((x) > (y)) ? (x) : (y)) #define MIN(x, y) (((x) < (y)) ? (x) : (y)) -#define _RESULT(expr, exprorig, result) if (expr) { printf(" SUCCESS: %s\n", #exprorig); __pass++; } else printf(" FAILED: %s, actual: %u\n", #exprorig, result) -#define _EVAL(result, expected, op) do { __cnt++; uint32_t resval = ((uint32_t)(result)); uint32_t expval = ((uint32_t)(expected)); _RESULT(resval op expval, result op expected, resval); } while(0) +#define _RESULT(expr, exprorig, result) if (expr) { printf("TestStatus: SUCCESS: %s\n", #exprorig); __pass++; } else printf("TestStatus: FAILED: %s, actual: %lu\n", #exprorig, result) +#define _EVAL(result, expected, op) do { __cnt++; long resval = ((long)(result)); long expval = ((long)(expected)); _RESULT(resval op expval, result op expected, resval); } while(0) #define _HEAD(name) printf("\n======== %s\n", name); __cnt = 0; __pass = 0 #define _FOOT(name) printf("\n======== %s - %i PASSED, %i FAILED\n", name, __pass, (__cnt - __pass)); TotalTests += __cnt; TotalTestsPassed += __pass; @@ -35,4 +35,4 @@ extern int TotalTestsPassed; } #endif -#endif // _TEST_UTILS_H +#endif // TEST_UTILS_H diff --git a/languages/c/templates/types/enum.cpp b/languages/c/templates/types/enum.cpp index ddda2ae9..9c98f888 100644 --- a/languages/c/templates/types/enum.cpp +++ b/languages/c/templates/types/enum.cpp @@ -1,4 +1,4 @@ /* ${title} ${description} */ - ENUM_CONVERSION_BEGIN(${info.title}_${name}) + ENUM_CONVERSION_BEGIN(${info.Title}_${name}) { ${info.TITLE}_${NAME}_${key}, _T("${value}") }, - ENUM_CONVERSION_END(${info.title}_${name}) + ENUM_CONVERSION_END(${info.Title}_${name}) diff --git a/languages/c/templates/types/enum.h b/languages/c/templates/types/enum.h index 6926fa77..906d908d 100644 --- a/languages/c/templates/types/enum.h +++ b/languages/c/templates/types/enum.h @@ -1,4 +1,4 @@ /* ${title} ${description} */ typedef enum { ${info.TITLE}_${NAME}_${key}, -} ${info.title}_${name}; +} ${info.Title}_${name}; diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index b4f4f9c8..bff898ca 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -506,6 +506,8 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{minor\}/g, macros.version.minor) fContents = fContents.replace(/\$\{patch\}/g, macros.version.patch) fContents = fContents.replace(/\$\{info\.title\}/g, macros.title) + fContents = fContents.replace(/\$\{info\.title\.lowercase\}/g, macros.title.toLowerCase()) + fContents = fContents.replace(/\$\{info\.Title\}/g, capitalize(macros.title)) fContents = fContents.replace(/\$\{info\.TITLE\}/g, macros.title.toUpperCase()) fContents = fContents.replace(/\$\{info\.description\}/g, macros.description) fContents = fContents.replace(/\$\{info\.version\}/g, macros.version.readable) @@ -828,12 +830,12 @@ const generateImports = (json, templates, options = { destination: '' }) => { } if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0 && !json.info['x-uri-titles']) { - imports += Object.keys(json['x-schemas']).map(shared => template.replace(/\$\{info.title\}/g, shared)).join('') + imports += Object.keys(json['x-schemas']).map(shared => template.replace(/\$\{info.title.lowercase\}/g, shared.toLowerCase())).join('') } let componentExternalSchema = getComponentExternalSchema(json) if (componentExternalSchema.length && json.info['x-uri-titles']) { - imports += componentExternalSchema.map(shared => template.replace(/\$\{info.title\}/g, shared)).join('') + imports += componentExternalSchema.map(shared => template.replace(/\$\{info.title.lowercase\}/g, shared.toLowerCase())).join('') } return imports } @@ -1146,6 +1148,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{event\.callback\.params\.serialization\}/g, callbackSerializedParams) .replace(/\$\{event\.callback\.result\.instantiation\}/g, callbackResultInst) .replace(/\$\{event\.callback\.response\.instantiation\}/g, callbackResponseInst) + .replace(/\$\{info\.title\.lowercase\}/g, info.title.toLowerCase()) .replace(/\$\{info\.title\}/g, info.title) .replace(/\$\{info\.Title\}/g, capitalize(info.title)) .replace(/\$\{info\.TITLE\}/g, info.title.toUpperCase()) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 3db5d17a..dc5f30e8 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -167,7 +167,7 @@ const macrofy = async ( content = engine.insertMacros(content, macros) content = engine.insertAggregateMacros(content, aggregateMacros) - const location = createModuleDirectories ? path.join(output, module.info.title, t) : path.join(output, t.replace(/Module/, module.info.title).replace(/index/, module.info.title)) + const location = createModuleDirectories ? path.join(output, module.info.title, t) : path.join(output, t.replace(/module/, module.info.title.toLowerCase()).replace(/index/, module.info.title)) outputFiles[location] = content logSuccess(`Generated macros for module ${path.relative(output, location)}`) @@ -262,7 +262,7 @@ const macrofy = async ( // NOTE: whichever insert is called first also needs to be called again last, so each phase can insert recursive macros from the other content = engine.insertMacros(content, macros) - const location = createModuleDirectories ? path.join(output, document.info.title, t) : path.join(output, t.replace(/Module/, document.info.title).replace(/index/, document.info.title)) + const location = createModuleDirectories ? path.join(output, document.info.title, t) : path.join(output, t.replace(/module/, document.info.title.toLowerCase()).replace(/index/, document.info.title)) outputFiles[location] = content logSuccess(`Generated macros for schema ${path.relative(output, location)}`) From 8d231a1682e1450590f15fdc58223f4baa2043f7 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 09:15:34 +0530 Subject: [PATCH 025/137] language-c: re-arrange files locations (#112) language-c: re-arrange files locations --- .../sdk => src/shared}/CMakeLists.txt | 0 .../shared}/cmake/HelperFunctions.cmake | 0 .../sdk => src/shared}/cmake/project.cmake.in | 0 .../sdk => src/shared}/include/error.h | 0 .../sdk => src/shared}/include/firebolt.h | 0 .../sdk => src/shared}/include/types.h | 0 .../shared}/src/Accessor/Accessor.cpp | 0 .../shared}/src/Accessor/Accessor.h | 0 .../shared}/src/Accessor/WorkerPool.h | 0 .../sdk => src/shared}/src/CMakeLists.txt | 0 .../sdk => src/shared}/src/Event/Event.cpp | 0 .../sdk => src/shared}/src/Event/Event.h | 0 .../shared}/src/FireboltSDK.conf.in | 0 .../sdk => src/shared}/src/FireboltSDK.h | 0 .../sdk => src/shared}/src/Logger/Logger.cpp | 0 .../sdk => src/shared}/src/Logger/Logger.h | 0 .../sdk => src/shared}/src/Module.cpp | 0 .../sdk => src/shared}/src/Module.h | 0 .../shared}/src/Properties/Properties.h | 0 .../shared}/src/Transport/Transport.cpp | 0 .../shared}/src/Transport/Transport.h | 0 .../sdk => src/shared}/src/Types.cpp | 0 .../sdk => src/shared}/src/TypesPriv.h | 0 .../sdk => src/shared}/src/firebolt.cpp | 0 .../sdk => src/shared}/test/CMakeLists.txt | 0 .../{templates/sdk => src/shared}/test/Main.c | 0 .../sdk => src/shared}/test/Module.cpp | 0 .../sdk => src/shared}/test/Module.h | 0 .../sdk => src/shared}/test/OpenRPCCTests.h | 0 .../sdk => src/shared}/test/OpenRPCTests.cpp | 0 .../sdk => src/shared}/test/OpenRPCTests.h | 0 .../sdk => src/shared}/test/TestUtils.h | 0 languages/c/templates/sdk/scripts/install.js | 32 --------- languages/c/templates/sdk/scripts/install.sh | 65 +++++++++++++++++++ 34 files changed, 65 insertions(+), 32 deletions(-) rename languages/c/{templates/sdk => src/shared}/CMakeLists.txt (100%) rename languages/c/{templates/sdk => src/shared}/cmake/HelperFunctions.cmake (100%) rename languages/c/{templates/sdk => src/shared}/cmake/project.cmake.in (100%) rename languages/c/{templates/sdk => src/shared}/include/error.h (100%) rename languages/c/{templates/sdk => src/shared}/include/firebolt.h (100%) rename languages/c/{templates/sdk => src/shared}/include/types.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Accessor/Accessor.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/Accessor/Accessor.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Accessor/WorkerPool.h (100%) rename languages/c/{templates/sdk => src/shared}/src/CMakeLists.txt (100%) rename languages/c/{templates/sdk => src/shared}/src/Event/Event.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/Event/Event.h (100%) rename languages/c/{templates/sdk => src/shared}/src/FireboltSDK.conf.in (100%) rename languages/c/{templates/sdk => src/shared}/src/FireboltSDK.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Logger/Logger.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/Logger/Logger.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Module.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/Module.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Properties/Properties.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Transport/Transport.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/Transport/Transport.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Types.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/TypesPriv.h (100%) rename languages/c/{templates/sdk => src/shared}/src/firebolt.cpp (100%) rename languages/c/{templates/sdk => src/shared}/test/CMakeLists.txt (100%) rename languages/c/{templates/sdk => src/shared}/test/Main.c (100%) rename languages/c/{templates/sdk => src/shared}/test/Module.cpp (100%) rename languages/c/{templates/sdk => src/shared}/test/Module.h (100%) rename languages/c/{templates/sdk => src/shared}/test/OpenRPCCTests.h (100%) rename languages/c/{templates/sdk => src/shared}/test/OpenRPCTests.cpp (100%) rename languages/c/{templates/sdk => src/shared}/test/OpenRPCTests.h (100%) rename languages/c/{templates/sdk => src/shared}/test/TestUtils.h (100%) delete mode 100644 languages/c/templates/sdk/scripts/install.js create mode 100755 languages/c/templates/sdk/scripts/install.sh diff --git a/languages/c/templates/sdk/CMakeLists.txt b/languages/c/src/shared/CMakeLists.txt similarity index 100% rename from languages/c/templates/sdk/CMakeLists.txt rename to languages/c/src/shared/CMakeLists.txt diff --git a/languages/c/templates/sdk/cmake/HelperFunctions.cmake b/languages/c/src/shared/cmake/HelperFunctions.cmake similarity index 100% rename from languages/c/templates/sdk/cmake/HelperFunctions.cmake rename to languages/c/src/shared/cmake/HelperFunctions.cmake diff --git a/languages/c/templates/sdk/cmake/project.cmake.in b/languages/c/src/shared/cmake/project.cmake.in similarity index 100% rename from languages/c/templates/sdk/cmake/project.cmake.in rename to languages/c/src/shared/cmake/project.cmake.in diff --git a/languages/c/templates/sdk/include/error.h b/languages/c/src/shared/include/error.h similarity index 100% rename from languages/c/templates/sdk/include/error.h rename to languages/c/src/shared/include/error.h diff --git a/languages/c/templates/sdk/include/firebolt.h b/languages/c/src/shared/include/firebolt.h similarity index 100% rename from languages/c/templates/sdk/include/firebolt.h rename to languages/c/src/shared/include/firebolt.h diff --git a/languages/c/templates/sdk/include/types.h b/languages/c/src/shared/include/types.h similarity index 100% rename from languages/c/templates/sdk/include/types.h rename to languages/c/src/shared/include/types.h diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.cpp b/languages/c/src/shared/src/Accessor/Accessor.cpp similarity index 100% rename from languages/c/templates/sdk/src/Accessor/Accessor.cpp rename to languages/c/src/shared/src/Accessor/Accessor.cpp diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.h b/languages/c/src/shared/src/Accessor/Accessor.h similarity index 100% rename from languages/c/templates/sdk/src/Accessor/Accessor.h rename to languages/c/src/shared/src/Accessor/Accessor.h diff --git a/languages/c/templates/sdk/src/Accessor/WorkerPool.h b/languages/c/src/shared/src/Accessor/WorkerPool.h similarity index 100% rename from languages/c/templates/sdk/src/Accessor/WorkerPool.h rename to languages/c/src/shared/src/Accessor/WorkerPool.h diff --git a/languages/c/templates/sdk/src/CMakeLists.txt b/languages/c/src/shared/src/CMakeLists.txt similarity index 100% rename from languages/c/templates/sdk/src/CMakeLists.txt rename to languages/c/src/shared/src/CMakeLists.txt diff --git a/languages/c/templates/sdk/src/Event/Event.cpp b/languages/c/src/shared/src/Event/Event.cpp similarity index 100% rename from languages/c/templates/sdk/src/Event/Event.cpp rename to languages/c/src/shared/src/Event/Event.cpp diff --git a/languages/c/templates/sdk/src/Event/Event.h b/languages/c/src/shared/src/Event/Event.h similarity index 100% rename from languages/c/templates/sdk/src/Event/Event.h rename to languages/c/src/shared/src/Event/Event.h diff --git a/languages/c/templates/sdk/src/FireboltSDK.conf.in b/languages/c/src/shared/src/FireboltSDK.conf.in similarity index 100% rename from languages/c/templates/sdk/src/FireboltSDK.conf.in rename to languages/c/src/shared/src/FireboltSDK.conf.in diff --git a/languages/c/templates/sdk/src/FireboltSDK.h b/languages/c/src/shared/src/FireboltSDK.h similarity index 100% rename from languages/c/templates/sdk/src/FireboltSDK.h rename to languages/c/src/shared/src/FireboltSDK.h diff --git a/languages/c/templates/sdk/src/Logger/Logger.cpp b/languages/c/src/shared/src/Logger/Logger.cpp similarity index 100% rename from languages/c/templates/sdk/src/Logger/Logger.cpp rename to languages/c/src/shared/src/Logger/Logger.cpp diff --git a/languages/c/templates/sdk/src/Logger/Logger.h b/languages/c/src/shared/src/Logger/Logger.h similarity index 100% rename from languages/c/templates/sdk/src/Logger/Logger.h rename to languages/c/src/shared/src/Logger/Logger.h diff --git a/languages/c/templates/sdk/src/Module.cpp b/languages/c/src/shared/src/Module.cpp similarity index 100% rename from languages/c/templates/sdk/src/Module.cpp rename to languages/c/src/shared/src/Module.cpp diff --git a/languages/c/templates/sdk/src/Module.h b/languages/c/src/shared/src/Module.h similarity index 100% rename from languages/c/templates/sdk/src/Module.h rename to languages/c/src/shared/src/Module.h diff --git a/languages/c/templates/sdk/src/Properties/Properties.h b/languages/c/src/shared/src/Properties/Properties.h similarity index 100% rename from languages/c/templates/sdk/src/Properties/Properties.h rename to languages/c/src/shared/src/Properties/Properties.h diff --git a/languages/c/templates/sdk/src/Transport/Transport.cpp b/languages/c/src/shared/src/Transport/Transport.cpp similarity index 100% rename from languages/c/templates/sdk/src/Transport/Transport.cpp rename to languages/c/src/shared/src/Transport/Transport.cpp diff --git a/languages/c/templates/sdk/src/Transport/Transport.h b/languages/c/src/shared/src/Transport/Transport.h similarity index 100% rename from languages/c/templates/sdk/src/Transport/Transport.h rename to languages/c/src/shared/src/Transport/Transport.h diff --git a/languages/c/templates/sdk/src/Types.cpp b/languages/c/src/shared/src/Types.cpp similarity index 100% rename from languages/c/templates/sdk/src/Types.cpp rename to languages/c/src/shared/src/Types.cpp diff --git a/languages/c/templates/sdk/src/TypesPriv.h b/languages/c/src/shared/src/TypesPriv.h similarity index 100% rename from languages/c/templates/sdk/src/TypesPriv.h rename to languages/c/src/shared/src/TypesPriv.h diff --git a/languages/c/templates/sdk/src/firebolt.cpp b/languages/c/src/shared/src/firebolt.cpp similarity index 100% rename from languages/c/templates/sdk/src/firebolt.cpp rename to languages/c/src/shared/src/firebolt.cpp diff --git a/languages/c/templates/sdk/test/CMakeLists.txt b/languages/c/src/shared/test/CMakeLists.txt similarity index 100% rename from languages/c/templates/sdk/test/CMakeLists.txt rename to languages/c/src/shared/test/CMakeLists.txt diff --git a/languages/c/templates/sdk/test/Main.c b/languages/c/src/shared/test/Main.c similarity index 100% rename from languages/c/templates/sdk/test/Main.c rename to languages/c/src/shared/test/Main.c diff --git a/languages/c/templates/sdk/test/Module.cpp b/languages/c/src/shared/test/Module.cpp similarity index 100% rename from languages/c/templates/sdk/test/Module.cpp rename to languages/c/src/shared/test/Module.cpp diff --git a/languages/c/templates/sdk/test/Module.h b/languages/c/src/shared/test/Module.h similarity index 100% rename from languages/c/templates/sdk/test/Module.h rename to languages/c/src/shared/test/Module.h diff --git a/languages/c/templates/sdk/test/OpenRPCCTests.h b/languages/c/src/shared/test/OpenRPCCTests.h similarity index 100% rename from languages/c/templates/sdk/test/OpenRPCCTests.h rename to languages/c/src/shared/test/OpenRPCCTests.h diff --git a/languages/c/templates/sdk/test/OpenRPCTests.cpp b/languages/c/src/shared/test/OpenRPCTests.cpp similarity index 100% rename from languages/c/templates/sdk/test/OpenRPCTests.cpp rename to languages/c/src/shared/test/OpenRPCTests.cpp diff --git a/languages/c/templates/sdk/test/OpenRPCTests.h b/languages/c/src/shared/test/OpenRPCTests.h similarity index 100% rename from languages/c/templates/sdk/test/OpenRPCTests.h rename to languages/c/src/shared/test/OpenRPCTests.h diff --git a/languages/c/templates/sdk/test/TestUtils.h b/languages/c/src/shared/test/TestUtils.h similarity index 100% rename from languages/c/templates/sdk/test/TestUtils.h rename to languages/c/src/shared/test/TestUtils.h diff --git a/languages/c/templates/sdk/scripts/install.js b/languages/c/templates/sdk/scripts/install.js deleted file mode 100644 index 5c332ceb..00000000 --- a/languages/c/templates/sdk/scripts/install.js +++ /dev/null @@ -1,32 +0,0 @@ -import { createRequire } from 'module'; -const require = createRequire(import.meta.url); -const fs = require('fs'); -const path = require('path'); - -var dest = process.env.NODE_INSTALL_PATH; -var src = 'src/native/build/' + process.env.TARGET_NAME; - -installFiles(src, dest); -function installFiles(src, dest) { - if (!fs.existsSync(dest)) { - fs.mkdirSync(dest); - } - - var entries = fs.readdirSync(src); - entries.forEach((entry) => { - const srcPath = path.join(src, entry); - const destPath = path.join(dest, entry); - const stat = fs.lstatSync(srcPath); - - if (stat.isFile()) { - fs.copyFileSync(srcPath, destPath); - } else if (stat.isDirectory()) { - installFiles(srcPath, destPath); - } else if (stat.isSymbolicLink()) { - if (fs.existsSync(destPath)) { - fs.unlinkSync(destPath); - } - fs.symlinkSync(fs.readlinkSync(srcPath), destPath); - } - }); -} diff --git a/languages/c/templates/sdk/scripts/install.sh b/languages/c/templates/sdk/scripts/install.sh new file mode 100755 index 00000000..69c2d66a --- /dev/null +++ b/languages/c/templates/sdk/scripts/install.sh @@ -0,0 +1,65 @@ +#!/bin/bash +usage() +{ + echo "options:" + echo " -i install path" + echo " -s sdk path" + echo " -t include test" + echo " -m module name. i.e, core/manage" + echo + echo "usage: " + echo " ./install.sh -p path" +} + +SdkPath=".." +InstallPath=".." +IncludeTest="OFF" +ModuleName="core" +while getopts i:s:m:th flag +do + case "${flag}" in + i) InstallPath="${OPTARG}";; + s) SdkPath="${OPTARG}";; + m) ModuleName="${OPTARG}";; + t) IncludeTest="ON";; + h) usage && exit 1;; + esac +done + +GetVersion() +{ + PackagePath=${SdkPath}/../../../../../../package-lock.json + InputKey="name\": \"@firebolt-js/openrpc" + LineNo="$(grep -n "${InputKey}" ${PackagePath} | head -n 1 | cut -d: -f1)" + VersionLine=$((LineNo++)) + eval "array=(`sed -n "${LineNo}p" < ${PackagePath} | sed 's/\"/\n/g'`)" + Version=${array[2]} +} + +Version=0.0 +GetVersion +ReleaseName=firebolt-${ModuleName}-native-sdk-${Version} +ReleasePath=${InstallPath}/${ReleaseName} + +rm -rf ${ReleasePath} +mkdir -p ${ReleasePath} +cp -ar ${SdkPath}/src ${ReleasePath} +cp -ar ${SdkPath}/include ${ReleasePath} +cp -ar ${SdkPath}/cmake ${ReleasePath} +cp -ar ${SdkPath}/scripts/build.sh ${ReleasePath} +cp -ar ${SdkPath}/CMakeLists.txt ${ReleasePath} + +if [ "${IncludeTest}" == "ON" ]; +then + cp -ar ${SdkPath}/ctest ${ReleasePath}/test +fi + +sed -i '/EnableTest="ON";;/d' ${ReleasePath}/build.sh +sed -i 's/getopts p:s:tch/getopts p:s:ch/g' ${ReleasePath}/build.sh +sed -i '/enable test/d' ${ReleasePath}/build.sh +sed -i '/EnableTest="OFF"/d' ${ReleasePath}/build.sh +sed -i 's/ -DENABLE_TESTS=${EnableTest}//g' ${ReleasePath}/build.sh + +cd ${ReleasePath}/../ +tar -cvzf ${ReleaseName}.tgz ${ReleaseName}/* +cd - From 335e64a8265c34e5f46bc0c422c97fe0151cb8a2 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 09:16:03 +0530 Subject: [PATCH 026/137] fixes to generate array inside subschemas (#111) --- languages/c/Types.mjs | 35 ++++++++--------- languages/c/src/types/ImplHelpers.mjs | 4 +- languages/c/src/types/JSONHelpers.mjs | 2 +- languages/c/src/types/NativeHelpers.mjs | 48 +---------------------- languages/c/templates/codeblocks/export.c | 1 - src/macrofier/engine.mjs | 25 +++++++----- 6 files changed, 38 insertions(+), 77 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 1ed84940..d8cae205 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -18,7 +18,7 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' -import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' +import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation, getCallbackParametersInstantiation, getCallbackResultInstantiation, getCallbackResponseInstantiation } from './src/types/ImplHelpers.mjs' import { getJsonContainerDefinition, getJsonDataStructName, getJsonDataPrefix } from './src/types/JSONHelpers.mjs' @@ -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 } @@ -302,8 +303,10 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref res = getSchemaTypeInfo(module, json.items, json.items.name || name, schemas, prefix) } + + prefix = prefix ? prefix + name : name let n = getTypeName(getModuleName(module), capitalize(res.name), prefix) - structure.name = res.name || name && (capitalize(name)) + structure.name = name ? name + capitalize(res.name) : res.name structure.type = n + 'Array_t' structure.json = json structure.namespace = getModuleName(module) @@ -525,24 +528,19 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' else { j = json.items } - shape += getSchemaShapeInfo(j, module, schemas, { name: j.title || name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) if (!isCPP) { - let info = getSchemaTypeInfo(module, j, j.title || name, schemas, prefix, {level : level, descriptions: descriptions, title: true}) + let subPrefix = prefix ? prefix + name : name + let info = getSchemaTypeInfo(module, j, j.title || name, schemas, subPrefix, {level : level, descriptions: descriptions, title: true}) if (info.type && info.type.length > 0) { - let type = getArrayElementSchema(json, module, schemas, info.name) - let arrayName = capitalize(info.name) + capitalize(type.type) - let namespace = info.namespace - if (type && type.type === 'object') { - namespace = getModuleName(module) - } - let objName = getTypeName(namespace, arrayName, prefix) + let arrayName = capitalize(info.name); + let objName = getTypeName(getModuleName(module), arrayName, subPrefix) let tName = objName + 'Array' info.json.namespace = info.namespace let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) - let subModuleProperty = getJsonTypeInfo(module, j, j.title, schemas, prefix) + let subModuleProperty = getJsonTypeInfo(module, j, j.title || name, schemas, prefix) let t = '' if (level === 0) { t += description(capitalize(info.name), json.description) + '\n' @@ -666,6 +664,7 @@ function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '' items = json.items // grab the type for the non-array schema } + res = getJsonTypeInfo(module, items, items.name || name, schemas, prefix) structure.deps = res.deps structure.type.push(`WPEFramework::Core::JSON::ArrayType<${res.type}>`) @@ -733,7 +732,7 @@ const enumReducer = (acc, val, i, arr) => { return acc } -function getSchemaInstantiation(schema, module, name, { instantiationType = '' } = {}) { +function getSchemaInstantiation(schema, module, name, { instantiationType = '', prefix = '' } = {}) { if (instantiationType === 'params') { return getParameterInstantiation(getParamList(schema, module)) @@ -752,17 +751,17 @@ function getSchemaInstantiation(schema, module, name, { instantiationType = '' } return result } else if (instantiationType === 'callback.params') { - let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' + let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name, prefix }) || '' return getCallbackParametersInstantiation(getParamList(schema, module), resultJsonType) } else if (instantiationType === 'callback.result') { - let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' + let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, prefix, resultSchema: true}) || '' let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' return getCallbackResultInstantiation(resultType, resultJsonType) } else if (instantiationType === 'callback.response') { - let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' - let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' + let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, prefix, resultSchema: true}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name, prefix }) || '' return getCallbackResponseInstantiation(getParamList(schema, module), resultType, resultJsonType) } else if (instantiationType === 'pull.param.name') { diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index 5b373377..8dbe8f08 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -49,7 +49,7 @@ const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ` + '\n' - if ((json.type === 'object') && (accessorPropertyType !== 'char*')) { + if (((json.type === 'object') || (json.type === 'array')) && (accessorPropertyType !== 'char*')) { result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); *(*element) = (*var)->${subPropertyName}; @@ -73,7 +73,7 @@ const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, ASSERT(var->IsValid()); ` + '\n' - if (json.type === 'object' && (accessorPropertyType !== 'char*')) { + if (((json.type === 'object') || (json.type === 'array')) && (accessorPropertyType !== 'char*')) { result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* object = reinterpret_cast*>(value); (*var)->${subPropertyName} = *(*object);` + '\n' } diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index cc31b14a..009beb99 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -4,7 +4,7 @@ const getJsonDataPrefix = () => 'JsonData_' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' const getJsonDataStructName = (modName, name, prefix = '') => { - let result =((prefix.length > 0) && (!name.startsWith(prefix))) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}_${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` + let result =((prefix.length > 0) && (prefix !== name)) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` return ((result.includes(wpeJsonNameSpace()) === true) ? result : `${getSdkNameSpace()}::${result}`) } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 7bfef987..8d00199e 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -30,18 +30,7 @@ const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = pre const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' const getFireboltStringType = () => 'FireboltTypes_String_t' -const getHeaderText = () => { - return `/* -* Copyright 2022 Comcast -* -* Auto Generated using firebolt-openrpc tools. DO NOT EDIT. -* -*/ - -` -} - const capitalize = str => str[0].toUpperCase() + str.substr(1) const description = (title, str='') => '/* ' + title + (str.length > 0 ? ' - ' + str : '') + ' */' const isOptional = (prop, json) => (!json.required || !json.required.includes(prop)) @@ -50,37 +39,6 @@ const SdkTypesPrefix = 'Firebolt' const Indent = ' ' -const getArrayElementSchema = (json, module, schemas = {}, name) => { - let result = '' - if (json.type === 'array' && json.items) { - if (Array.isArray(json.items)) { - result = json.items[0] - } - else { - // grab the type for the non-array schema - result = json.items - } - if (result['$ref']) { - result = getPath(result['$ref'], module, schemas) - } - } - else if (json.type == 'object') { - if (json.properties) { - Object.entries(json.properties).every(([pname, prop]) => { - if (prop.type === 'array') { - result = getArrayElementSchema(prop, module, schemas) - if (name === capitalize(pname)) { - return false - } - } - return true - }) - } - } - - return result -} - const getNativeType = (json, fireboltString = false) => { let type let jsonType = json.const ? typeof json.const : json.type @@ -150,10 +108,10 @@ const getTypeName = (moduleName, varName, prefix = '', upperCase = false, capita let mName = upperCase ? moduleName.toUpperCase() : capitalize(moduleName) let vName = upperCase ? varName.toUpperCase() : capitalCase ? capitalize(varName) : varName if (prefix.length > 0) { - prefix = (!varName.startsWith(prefix)) ? (upperCase ? prefix.toUpperCase() : capitalize(prefix)) : '' + prefix = (prefix !== varName) ? (upperCase ? prefix.toUpperCase() : capitalize(prefix)) : '' } prefix = (prefix.length > 0) ?(upperCase ? prefix.toUpperCase() : capitalize(prefix)) : prefix - let name = (prefix.length > 0) ? `${mName}_${prefix}_${vName}` : `${mName}_${vName}` + let name = (prefix.length > 0) ? `${mName}_${prefix}${vName}` : `${mName}_${vName}` return name } @@ -235,7 +193,6 @@ function getPropertyEventUnregisterSignature(property, module) { export { - getHeaderText, getNativeType, getModuleName, getPropertyGetterSignature, @@ -252,6 +209,5 @@ export { getPropertyAccessors, isOptional, generateEnum, - getArrayElementSchema, getFireboltStringType } diff --git a/languages/c/templates/codeblocks/export.c b/languages/c/templates/codeblocks/export.c index c98498e4..e69de29b 100644 --- a/languages/c/templates/codeblocks/export.c +++ b/languages/c/templates/codeblocks/export.c @@ -1 +0,0 @@ -export { default as ${info.title} } from './${info.title}/index.mjs' \ No newline at end of file diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index bff898ca..61eebd3d 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -361,7 +361,7 @@ const addContentDescriptorSubSchema = (descriptor, prefix, obj) => { } // only consider sub-objects and sub enums to be sub-schemas -const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) +const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) || (schema.type === 'array' && schema.items) const promoteAndNameSubSchemas = (obj) => { // make a copy so we don't polute our inputs @@ -384,7 +384,7 @@ const promoteAndNameSubSchemas = (obj) => { while (more) { more = false Object.entries(obj.components.schemas).forEach(([key, schema]) => { - if (schema.type === "object" && schema.properties) { + if ((schema.type === "object") && schema.properties) { Object.entries(schema.properties).forEach(([name, propSchema]) => { if (isSubSchema(propSchema)) { more = true @@ -584,10 +584,11 @@ function insertTableofContents(content) { } const convertEnumTemplate = (schema, templateName, templates) => { + let enumSchema = isArraySchema(schema) ? schema.items : schema const template = getTemplate(templateName, templates).split('\n') for (var i = 0; i < template.length; i++) { if (template[i].indexOf('${key}') >= 0) { - template[i] = schema.enum.map(value => { + template[i] = enumSchema.enum.map(value => { const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() return template[i].replace(/\$\{key\}/g, safeName) .replace(/\$\{value\}/g, value) @@ -693,7 +694,12 @@ function sortSchemasByReference(schemas = []) { return schemas } -const isEnum = x => x.type && x.type === 'string' && Array.isArray(x.enum) && x.title +const isArraySchema = x => x.type && x.type === 'array' && x.items + +const isEnum = x => { + let schema = isArraySchema(x) ? x.items : x + return schema.type && schema.type === 'string' && Array.isArray(schema.enum) && x.title +} function generateSchemas(json, templates, options) { let results = [] @@ -1089,9 +1095,10 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, { instantiationType: 'params' }) const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' } ) const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'params' }), ' ') : '' - const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.params' }) : '' - const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.result' }) : '' - const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.response' }) : '' + const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.params', prefix: method.alternative }) : '' + const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.result', prefix: method.alternative }) : '' + const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.response', prefix: method.alternative }) : '' + const callbackResultJsonType = event && result.schema ? types.getJsonType(result.schema, json, { name: result.name, prefix: method.alternative }) : '' const resultType = result.schema ? types.getSchemaType(result.schema, json, { name: result.name }) : '' const resultJsonType = result.schema ? types.getJsonType(result.schema, json, { name: result.name }) : '' @@ -1166,8 +1173,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .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, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, baseUrl: options.baseUrl .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') - .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, prefix: method.alternative, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') + .replace(/\$\{event\.result\.json\.type\}/g, callbackResultJsonType) .replace(/\$\{event\.pulls\.param\.name\}/g, pullsEventParamName) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) .replace(/\$\{method\.result\.json\.type\}/g, resultJsonType) From 5c194a611f3550d30696a040d54f2019d886f51b Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 20:09:16 +0530 Subject: [PATCH 027/137] include test always (#113) --- languages/c/templates/sdk/scripts/install.sh | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/languages/c/templates/sdk/scripts/install.sh b/languages/c/templates/sdk/scripts/install.sh index 69c2d66a..15596524 100755 --- a/languages/c/templates/sdk/scripts/install.sh +++ b/languages/c/templates/sdk/scripts/install.sh @@ -4,24 +4,21 @@ usage() echo "options:" echo " -i install path" echo " -s sdk path" - echo " -t include test" echo " -m module name. i.e, core/manage" echo echo "usage: " - echo " ./install.sh -p path" + echo " ./install.sh -i path -s sdk path-m core" } SdkPath=".." InstallPath=".." -IncludeTest="OFF" ModuleName="core" -while getopts i:s:m:th flag +while getopts i:s:m:h flag do case "${flag}" in i) InstallPath="${OPTARG}";; s) SdkPath="${OPTARG}";; m) ModuleName="${OPTARG}";; - t) IncludeTest="ON";; h) usage && exit 1;; esac done @@ -48,11 +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} - -if [ "${IncludeTest}" == "ON" ]; -then - cp -ar ${SdkPath}/ctest ${ReleasePath}/test -fi +cp -ar ${SdkPath}/ctest ${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 From 30246aa2f54ed23695427ede1a090f0ce4940ebd Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 20:09:40 +0530 Subject: [PATCH 028/137] use String type if there is any issue with anyOf merge (#114) --- languages/c/Types.mjs | 27 ++++++++++++++++++------- languages/c/src/types/JSONHelpers.mjs | 2 +- languages/c/src/types/NativeHelpers.mjs | 6 +++--- 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index d8cae205..1ee99224 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -82,7 +82,7 @@ function union(schemas, module, commonSchemas) { //console.warn(`Ignoring "${key}" that is already present and same`) } else { console.warn(`ERROR "${key}" is not same -${JSON.stringify(result, null, 4)} ${key} ${result[key]} - ${value}`); - throw "ERROR: type is not same" + return {} } } else { //If the Key is a const then merge them into an enum @@ -325,8 +325,14 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref } else if (json.anyOf) { let mergedSchema = getMergedSchema(module, json, name, schemas) - let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) - structure = getSchemaTypeInfo(module, mergedSchema, '', schemas, prefixName, options) + if (mergedSchema.type) { + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + structure = getSchemaTypeInfo(module, mergedSchema, '', schemas, prefixName, options) + } + else { + structure.type = fireboltString ? getFireboltStringType() : 'char*' + structure.json.type = 'string' + } } else if (json.type === 'object') { structure.json = json @@ -499,8 +505,10 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' else if (json.anyOf) { if (level > 0) { let mergedSchema = getMergedSchema(module, json, name, schemas) - let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) - shape += getSchemaShapeInfo(mergedSchema, module, schemas, { name, prefix: prefixName, merged, level, title, summary, descriptions, destination, section, enums }) + if (mergedSchema.type) { + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + shape += getSchemaShapeInfo(mergedSchema, module, schemas, { name, prefix: prefixName, merged, level, title, summary, descriptions, destination, section, enums }) + } } } else if (json.oneOf) { @@ -689,8 +697,13 @@ function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '' } else if (json.anyOf) { let mergedSchema = getMergedSchema(module, json, name, schemas) - let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) - structure = getJsonTypeInfo(module, mergedSchema, name, schemas, prefixName, {descriptions, level}) + if (mergedSchema.type) { + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + structure = getJsonTypeInfo(module, mergedSchema, name, schemas, prefixName, {descriptions, level}) + } + else { + structure.type = getJsonNativeTypeForOpaqueString() + } } else if (json.type === 'object') { if (hasProperties(json) !== true) { diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index 009beb99..954ac50d 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -4,7 +4,7 @@ const getJsonDataPrefix = () => 'JsonData_' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' const getJsonDataStructName = (modName, name, prefix = '') => { - let result =((prefix.length > 0) && (prefix !== name)) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` + let result =((prefix && prefix.length > 0) && (prefix !== name)) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` return ((result.includes(wpeJsonNameSpace()) === true) ? result : `${getSdkNameSpace()}::${result}`) } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 8d00199e..3437c3f4 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -107,11 +107,11 @@ const getTypeName = (moduleName, varName, prefix = '', upperCase = false, capita let mName = upperCase ? moduleName.toUpperCase() : capitalize(moduleName) let vName = upperCase ? varName.toUpperCase() : capitalCase ? capitalize(varName) : varName - if (prefix.length > 0) { + if (prefix && prefix.length > 0) { prefix = (prefix !== varName) ? (upperCase ? prefix.toUpperCase() : capitalize(prefix)) : '' } - prefix = (prefix.length > 0) ?(upperCase ? prefix.toUpperCase() : capitalize(prefix)) : prefix - let name = (prefix.length > 0) ? `${mName}_${prefix}${vName}` : `${mName}_${vName}` + prefix = (prefix && prefix.length > 0) ?(upperCase ? prefix.toUpperCase() : capitalize(prefix)) : prefix + let name = (prefix && prefix.length > 0) ? `${mName}_${prefix}${vName}` : `${mName}_${vName}` return name } From ffd97fd3834c288d0d688e83182d5675d0882757 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 21:10:37 +0530 Subject: [PATCH 029/137] calls-metrics: support added (#115) --- languages/c/templates/declarations/rpc-only.c | 0 .../c/templates/imports/calls-metrics.cpp | 1 + languages/c/templates/methods/calls-metrics.c | 30 +++++++++++++++++++ languages/c/templates/methods/rpc-only.c | 0 src/macrofier/engine.mjs | 13 +++++++- src/shared/modules.mjs | 8 +++++ 6 files changed, 51 insertions(+), 1 deletion(-) delete mode 100644 languages/c/templates/declarations/rpc-only.c create mode 100644 languages/c/templates/imports/calls-metrics.cpp create mode 100644 languages/c/templates/methods/calls-metrics.c delete mode 100644 languages/c/templates/methods/rpc-only.c diff --git a/languages/c/templates/declarations/rpc-only.c b/languages/c/templates/declarations/rpc-only.c deleted file mode 100644 index e69de29b..00000000 diff --git a/languages/c/templates/imports/calls-metrics.cpp b/languages/c/templates/imports/calls-metrics.cpp new file mode 100644 index 00000000..4ba289b3 --- /dev/null +++ b/languages/c/templates/imports/calls-metrics.cpp @@ -0,0 +1 @@ +#include "metrics.h" diff --git a/languages/c/templates/methods/calls-metrics.c b/languages/c/templates/methods/calls-metrics.c new file mode 100644 index 00000000..91831a3c --- /dev/null +++ b/languages/c/templates/methods/calls-metrics.c @@ -0,0 +1,30 @@ +/* ${method.rpc.name} - ${method.description} */ +void Metrics_${method.Name}Dispatcher(const void*${if.result} result${end.if.result}) { + Metrics_${method.Name}(${if.result}(static_cast<${method.result.json.type}>(const_cast(result)))${end.if.result}); +} + +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; + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + + ${method.params.serialization.with.indent} + ${method.result.json.type} jsonResult; + status = transport->Invoke("${info.title}.${method.rpc.name}", jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); +${method.result.instantiation} + + void* result = nullptr; + ${if.result}result = static_cast(new ${method.result.json.type});${end.if.result} + WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(Metrics_${method.Name}Dispatcher, result)); + WPEFramework::Core::IWorkerPool::Instance().Submit(job); + } + + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; +} diff --git a/languages/c/templates/methods/rpc-only.c b/languages/c/templates/methods/rpc-only.c deleted file mode 100644 index e69de29b..00000000 diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 61eebd3d..9a2da33f 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -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, isCallsMetricsMethod, isExcludedMethod, hasMethodAttributes, getMethodAttributes, isEventMethodWithContext, getSemanticVersion, getSetterFor, getProvidedCapabilities, isPolymorphicPullMethod, hasPublicAPIs } from '../shared/modules.mjs' import isEmpty from 'crocks/core/isEmpty.js' import { getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies, isDefinitionReferencedBySchema } from '../shared/json-schema.mjs' @@ -282,6 +282,13 @@ const temporalSets = compose( getMethods ) +const callsMetrics = compose( + option([]), + map(filter(not(isExcludedMethod))), + map(filter(isCallsMetricsMethod)), + getMethods +) + const methodsWithXMethodsInResult = compose( option([]), map(filter(hasMethodAttributes)), @@ -830,6 +837,10 @@ const generateImports = (json, templates, options = { destination: '' }) => { const suffix = options.destination.split('.').pop() const prefix = options.destination.split('/').pop().split('_')[0].toLowerCase() + if (callsMetrics(json).length) { + imports += getTemplate(suffix ? `/imports/calls-metrics.${suffix}` : '/imports/calls-metrics', templates) + } + let template = prefix ? getTemplate(`/imports/default.${prefix}`, templates) : '' if (!template) { template = getTemplate(suffix ? `/imports/default.${suffix}` : '/imports/default', templates) diff --git a/src/shared/modules.mjs b/src/shared/modules.mjs index 386b9d6d..a91c076b 100644 --- a/src/shared/modules.mjs +++ b/src/shared/modules.mjs @@ -227,6 +227,13 @@ const isTemporalSetMethod = compose( getPath(['tags']) ) +const isCallsMetricsMethod = compose( + option(false), + map(_ => true), + chain(find(propEq('name', 'calls-metrics'))), + getPath(['tags']) +) + const getMethodAttributes = compose( option(null), map(props => props.reduce( (val, item) => { @@ -1148,6 +1155,7 @@ export { isPolymorphicReducer, isPolymorphicPullMethod, isTemporalSetMethod, + isCallsMetricsMethod, isExcludedMethod, isRPCOnlyMethod, isProviderInterfaceMethod, From 549e4a0b8eeb1ef56f4d2416f44c0170a24de6ff Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 21:13:35 +0530 Subject: [PATCH 030/137] Generate polymorphci methods for anyOf param/result case (#110) --- languages/c/Types.mjs | 1 + languages/c/language.config.json | 3 +- languages/c/templates/codeblocks/setter.c | 4 +- languages/c/templates/methods/default.c | 6 +- languages/c/templates/methods/event.c | 6 +- .../methods/polymorphic-pull-event.c | 10 +- .../c/templates/methods/polymorphic-pull.c | 11 +- languages/c/templates/methods/property.c | 4 +- src/macrofier/engine.mjs | 20 ++- src/macrofier/index.mjs | 7 +- src/sdk/index.mjs | 1 + src/shared/modules.mjs | 137 +++++++++++++++++- 12 files changed, 182 insertions(+), 28 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 1ee99224..4c092a92 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -358,6 +358,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref structure.namespace = getModuleName(module) } } + return structure } diff --git a/languages/c/language.config.json b/languages/c/language.config.json index ee3604d7..b684e11b 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -12,5 +12,6 @@ "/src/module_common.cpp", "/src/jsondata_module.h" ], - "persistPermission": true + "persistPermission": true, + "createPolymorphicMethods": true } diff --git a/languages/c/templates/codeblocks/setter.c b/languages/c/templates/codeblocks/setter.c index 342a98d6..411d4542 100644 --- a/languages/c/templates/codeblocks/setter.c +++ b/languages/c/templates/codeblocks/setter.c @@ -1,7 +1,7 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.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.lowercase}.${method.rpc.name}"); ${if.params}${method.params.serialization}${end.if.params} return FireboltSDK::Properties::Set(method, jsonParameters); } diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 6fbca47e..881b592c 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -1,4 +1,4 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.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; @@ -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.lowercase}.${method.rpc.name}", jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully invoked"); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); ${method.result.instantiation} } diff --git a/languages/c/templates/methods/event.c b/languages/c/templates/methods/event.c index ec868cd5..c02e74c4 100644 --- a/languages/c/templates/methods/event.c +++ b/languages/c/templates/methods/event.c @@ -1,4 +1,4 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.name} - ${method.description} */ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) { ${event.callback.params.serialization} @@ -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.lowercase}.${method.rpc.name}"); uint32_t status = FireboltSDKErrorNone; if (userCB != nullptr) { @@ -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(userCB)); + return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); } diff --git a/languages/c/templates/methods/polymorphic-pull-event.c b/languages/c/templates/methods/polymorphic-pull-event.c index d2f5ef4c..7c833b71 100644 --- a/languages/c/templates/methods/polymorphic-pull-event.c +++ b/languages/c/templates/methods/polymorphic-pull-event.c @@ -1,4 +1,4 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.name} - ${method.description} */ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) { ${event.callback.params.serialization} @@ -27,9 +27,9 @@ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { WPEFramework::Core::JSON::Boolean jsonResult; - uint32_t status = transport->Invoke(_T("${info.title}.${method.pulls.for}"), jsonParameters, jsonResult); + uint32_t status = transport->Invoke(_T("${info.title.lowercase}.${method.pulls.for}"), jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully pushed with status as %d", jsonResult.Value()); status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; } } else { @@ -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.lowercase}.${method.rpc.name}"); uint32_t status = FireboltSDKErrorNone; if (userCB != nullptr) { @@ -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(userCB)); + return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); } diff --git a/languages/c/templates/methods/polymorphic-pull.c b/languages/c/templates/methods/polymorphic-pull.c index ec052e64..759b0ae9 100644 --- a/languages/c/templates/methods/polymorphic-pull.c +++ b/languages/c/templates/methods/polymorphic-pull.c @@ -1,16 +1,17 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.name} - ${method.description} */ uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ) { uint32_t status = FireboltSDKErrorUnavailable; - string correlationId = ""; -${method.params.serialization} FireboltSDK::Transport* 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.lowercase}.${method.rpc.name}"), jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully pushed with status as %d", jsonResult.Value()); status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; } } else { diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 9a92dce4..7fb5b148 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,7 +1,7 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.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.lowercase}.${method.rpc.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} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 9a2da33f..1ad8b6e6 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -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, isCallsMetricsMethod, isExcludedMethod, 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' @@ -416,6 +416,21 @@ const generateMacros = (obj, templates, languages, options = {}) => { if (config.extractSubSchemas) { obj = promoteAndNameSubSchemas(obj) } + if (options.createPolymorphicMethods) { + let methods = [] + obj.methods && obj.methods.forEach(method => { + let polymorphicMethods = createPolymorphicMethods(method, obj) + if (polymorphicMethods.length > 1) { + polymorphicMethods.forEach(polymorphicMethod => { + methods.push(polymorphicMethod) + }) + } + else { + methods.push(method) + } + }) + obj.methods = methods + } // grab the options so we don't have to pass them from method to method Object.assign(state, options) @@ -1022,7 +1037,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, examples={}) { const moduleName = getModuleName(json) const info = { @@ -1131,6 +1146,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\.rpc\.name\}/g, methodObj.title || methodObj.name) .replace(/\$\{method\.summary\}/g, methodObj.summary) .replace(/\$\{method\.description\}/g, methodObj.description || methodObj.summary) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index dc5f30e8..86483fad 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -44,6 +44,7 @@ const macrofy = async ( templatesPerModule, templatesPerSchema, persistPermission, + createPolymorphicMethods, createModuleDirectories, copySchemasIntoModules, extractSubSchemas, @@ -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 @@ -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) } @@ -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 diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index 7e85fab9..2e72ba9b 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -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, diff --git a/src/shared/modules.mjs b/src/shared/modules.mjs index a91c076b..927092c2 100644 --- a/src/shared/modules.mjs +++ b/src/shared/modules.mjs @@ -29,6 +29,7 @@ const { and, not } = logic import isString from 'crocks/core/isString.js' import predicates from 'crocks/predicates/index.js' import { getExternalSchemaPaths, isDefinitionReferencedBySchema, isNull, localizeDependencies, isSchema, getLocalSchemaPaths, replaceRef } from './json-schema.mjs' +import { getPath as getRefDefinition } from './json-schema.mjs' const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = predicates // util for visually debugging crocks ADTs @@ -861,6 +862,137 @@ const generateEventListenResponse = json => { return json } +const getAnyOfSchema = (inType, json) => { + let anyOfTypes = [] + let outType = localizeDependencies(inType, json) + if (outType.schema.anyOf) { + let definition = '' + if (inType.schema['$ref'] && (inType.schema['$ref'][0] === '#')) { + definition = getRefDefinition(inType.schema['$ref'], json, json['x-schemas']) + } + else { + definition = outType.schema + } + definition.anyOf.forEach(anyOf => { + anyOfTypes.push(anyOf) + }) + outType.schema.anyOf = anyOfTypes + } + return outType +} + +const generateAnyOfSchema = (anyOf, name, summary) => { + let anyOfType = {} + anyOfType["name"] = name[0].toLowerCase() + name.substr(1) + anyOfType["summary"] = summary + anyOfType["schema"] = anyOf + return anyOfType +} + +const generateParamsAnyOfSchema = (methodParams, anyOf, anyOfTypes, title, summary) => { + let params = [] + methodParams.forEach(p => { + if (p.schema.anyOf === anyOfTypes) { + let anyOfType = generateAnyOfSchema(anyOf, title, summary) + anyOfType.required = p.required + params.push(anyOfType) + } + else { + params.push(p) + } + }) + return params +} + +const generateResultAnyOfSchema = (method, methodResult, anyOf, anyOfTypes, title, summary) => { + let methodResultSchema = {} + if (methodResult.schema.anyOf === anyOfTypes) { + let anyOfType = generateAnyOfSchema(anyOf, title, summary) + let index = 0 + if (isEventMethod(method)) { + index = (method.result.schema.anyOf || method.result.schema.oneOf).indexOf(getPayloadFromEvent(method)) + } + else { + index = (method.result.schema.anyOf || method.result.schema.oneOf).indexOf(anyOfType) + } + if (method.result.schema.anyOf) { + methodResultSchema["anyOf"] = Object.assign([], method.result.schema.anyOf) + methodResultSchema.anyOf[index] = anyOfType.schema + } + else if (method.result.schema.oneOf) { + methodResultSchema["oneOf"] = Object.assign([], method.result.schema.oneOf) + methodResultSchema.oneOf[index] = anyOfType.schema + } + else { + methodResultSchema = anyOfType.schema + } + } + return methodResultSchema +} + +const createPolymorphicMethods = (method, json) => { + let anyOfTypes + let methodParams = [] + let methodResult = Object.assign({}, method.result) + method.params.forEach(p => { + if (p.schema) { + let param = getAnyOfSchema(p, json) + if (param.schema.anyOf && anyOfTypes) { + //anyOf is allowed with only one param in the params list + throw `WARNING anyOf is repeated with param:${p}` + } + else if (param.schema.anyOf) { + anyOfTypes = param.schema.anyOf + } + methodParams.push(param) + } + }) + let foundAnyOfParams = anyOfTypes ? true : false + + if (isEventMethod(method)) { + methodResult.schema = getPayloadFromEvent(method) + } + methodResult = getAnyOfSchema(methodResult, json) + let foundAnyOfResult = methodResult.schema.anyOf ? true : false + if (foundAnyOfParams === true && foundAnyOfResult === true) { + throw `WARNING anyOf is already with param schema, it is repeated with ${method.name} result too` + } + else if (foundAnyOfResult === true) { + anyOfTypes = methodResult.schema.anyOf + } + let polymorphicMethodSchemas = [] + //anyOfTypes will be allowed either in any one of the params or in result + if (anyOfTypes) { + let polymorphicMethodSchema = { + name: {}, + tags: {}, + summary: `${method.summary}`, + params: {}, + result: {}, + examples: {} + } + anyOfTypes.forEach(anyOf => { + + let localized = localizeDependencies(anyOf, json) + let title = localized.title || localized.name || '' + let summary = localized.summary || localized.description || '' + polymorphicMethodSchema.title = method.name + polymorphicMethodSchema.name = foundAnyOfParams ? `${method.name}With${title}` : `${method.name}${title}` + polymorphicMethodSchema.tags = method.tags + polymorphicMethodSchema.params = foundAnyOfParams ? generateParamsAnyOfSchema(methodParams, anyOf, anyOfTypes, title, summary) : methodParams + polymorphicMethodSchema.result = Object.assign({}, method.result) + polymorphicMethodSchema.result.schema = foundAnyOfResult ? generateResultAnyOfSchema(method, methodResult, anyOf, anyOfTypes, title, summary) : methodResult + polymorphicMethodSchema.examples = method.examples + polymorphicMethodSchemas.push(Object.assign({}, polymorphicMethodSchema)) + }) + } + else { + polymorphicMethodSchemas = method + } + + return polymorphicMethodSchemas +} + const getPathFromModule = (module, path) => { console.error("DEPRECATED: getPathFromModule") @@ -1183,5 +1315,6 @@ export { getSemanticVersion, addExternalMarkdown, addExternalSchemas, - getExternalMarkdownPaths -} \ No newline at end of file + getExternalMarkdownPaths, + createPolymorphicMethods +} From d58a52c0fc52898c9babe6b3c891d879b2d953f2 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 19 Jul 2023 14:07:32 -0400 Subject: [PATCH 031/137] fix: Split c-structs from c (w/ Accessors) --- .gitignore | 1 + languages/c-structs/language.config.json | 26 + languages/c-structs/src/index.mjs | 19 + .../c-structs/templates/codeblocks/export.c | 1 + .../templates/codeblocks/mock-import.c | 1 + .../templates/codeblocks/mock-parameter.c | 1 + .../templates/codeblocks/module.c} | 0 .../c-structs/templates/codeblocks/setter.c | 9 + .../c-structs/templates/declarations/clear.c | 0 .../templates/declarations/default.c | 5 + .../c-structs/templates/declarations/event.c | 4 + .../c-structs/templates/declarations/listen.c | 0 .../c-structs/templates/declarations/once.c | 0 .../declarations/polymorphic-reducer.c | 5 + .../templates/declarations/property.c | 5 + .../templates/declarations/provide.c | 0 .../templates/declarations/rpc-only.c | 0 .../c-structs/templates/defaults/default.c | 0 .../c-structs/templates/defaults/property.c | 0 .../c-structs/templates/imports/default.cpp | 1 + .../c-structs/templates/imports/default.h | 1 + .../templates/imports/default.jsondata | 1 + .../c-structs/templates/language/enum-item.c | 1 + languages/c-structs/templates/language/enum.c | 3 + .../c-structs/templates/language/parameter.c | 1 + .../templates/language/schema-item.c | 1 + .../c-structs/templates/language/schema.c | 3 + languages/c-structs/templates/methods/clear.c | 0 .../c-structs/templates/methods/default.c | 24 + languages/c-structs/templates/methods/event.c | 26 + .../c-structs/templates/methods/listen.c | 0 languages/c-structs/templates/methods/once.c | 0 .../methods/polymorphic-pull-event.c | 0 .../templates/methods/polymorphic-pull.c | 21 + .../templates/methods/polymorphic-reducer.c | 0 .../c-structs/templates/methods/property.c | 15 + .../c-structs/templates/methods/provide.c | 0 .../c-structs/templates/methods/rpc-only.c | 0 .../c-structs/templates/methods/setter.c | 0 .../templates/modules/include/Module.h | 41 + .../modules/include/Module_Accessors.h | 0 .../templates/modules/src/Module.cpp | 42 + .../c-structs/templates/parameters/default.c | 1 + .../c-structs/templates/parameters/json.c | 3 + .../c-structs/templates/parameters/optional.c | 1 + .../c-structs/templates/parameters/result.c | 1 + .../c-structs/templates/schemas/default.c | 1 + .../templates/schemas/include/Common/Module.h | 39 + .../schemas/include/Common/Module_Accessors.h | 0 .../templates/schemas/src/JsonData_Module.h | 30 + .../templates/schemas/src/Module_Common.cpp | 35 + .../c-structs/templates/sdk/CMakeLists.txt | 61 ++ .../templates/sdk/cmake/HelperFunctions.cmake | 144 +++ .../templates/sdk/cmake/project.cmake.in | 35 + .../c-structs/templates/sdk/include/Error.h | 41 + .../templates/sdk/include/Firebolt.h | 65 ++ .../c-structs/templates/sdk/include/Types.h | 37 + .../c-structs/templates/sdk/scripts/build.sh | 11 + .../templates/sdk/scripts/install.js | 32 + .../templates/sdk/src/Accessor/Accessor.cpp | 117 +++ .../templates/sdk/src/Accessor/Accessor.h | 122 +++ .../templates/sdk/src/Accessor/WorkerPool.h | 102 ++ .../templates/sdk/src/CMakeLists.txt | 84 ++ .../templates/sdk/src/Event/Event.cpp | 147 +++ .../c-structs/templates/sdk/src/Event/Event.h | 165 ++++ .../c-structs/templates/sdk/src/Firebolt.cpp | 40 + .../templates/sdk/src/FireboltSDK.conf.in | 3 + .../c-structs/templates/sdk/src/FireboltSDK.h | 26 + .../templates/sdk/src/Logger/Logger.cpp | 83 ++ .../templates/sdk/src/Logger/Logger.h | 85 ++ .../c-structs/templates/sdk/src/Module.cpp | 21 + .../c-structs/templates/sdk/src/Module.h | 29 + .../templates/sdk/src/Properties/Properties.h | 148 +++ .../templates/sdk/src/Transport/Transport.cpp | 24 + .../templates/sdk/src/Transport/Transport.h | 897 ++++++++++++++++++ .../c-structs/templates/sdk/src/Types.cpp | 40 + .../c-structs/templates/sdk/src/TypesPriv.h | 56 ++ .../templates/sdk/test/CMakeLists.txt | 86 ++ languages/c-structs/templates/sdk/test/Main.c | 44 + .../c-structs/templates/sdk/test/Module.cpp | 21 + .../c-structs/templates/sdk/test/Module.h | 29 + .../templates/sdk/test/OpenRPCCTests.h | 42 + .../templates/sdk/test/OpenRPCTests.cpp | 385 ++++++++ .../templates/sdk/test/OpenRPCTests.h | 99 ++ .../c-structs/templates/sdk/test/TestUtils.h | 38 + .../c-structs/templates/sections/accessors.c | 2 + .../templates/sections/declarations.c | 1 + .../c-structs/templates/sections/enums.c | 1 + .../c-structs/templates/sections/events.c | 1 + .../c-structs/templates/sections/methods.c | 4 + .../templates/sections/methods_accessors.c | 1 + .../templates/sections/methods_types.c | 1 + .../templates/sections/provider-interfaces.c | 11 + .../c-structs/templates/sections/schemas.c | 1 + .../c-structs/templates/sections/types.c | 1 + languages/c-structs/templates/types/anyOf.c | 1 + languages/c-structs/templates/types/array.c | 1 + languages/c-structs/templates/types/const.c | 0 .../templates/types}/default.c | 2 +- .../templates/types}/enum.cpp | 0 .../templates/types}/enum.h | 0 languages/c-structs/templates/types/object.c | 3 + .../c-structs/templates/types/primitive.c | 1 + .../c-structs/templates/types/property.c | 1 + .../templates/types}/ref.c | 0 .../templates/types}/title.c | 0 languages/c-structs/templates/types/tuple.c | 3 + languages/c/language.config.json | 10 +- languages/c/templates/accessors/array.c | 4 - languages/c/templates/accessors/object.c | 7 - languages/c/templates/accessors/primitive.c | 1 - languages/c/templates/accessors/tuple.c | 2 - languages/c/templates/declarations/event.c | 9 +- .../json-types/additionalProperties.c | 1 + .../{accessors => json-types}/anyOf.c | 0 languages/c/templates/json-types/array.c | 4 + languages/c/templates/json-types/boolean.c | 1 + languages/c/templates/json-types/const.c | 0 languages/c/templates/json-types/default.cpp | 1 + languages/c/templates/json-types/enum.cpp | 4 + languages/c/templates/json-types/enum.h | 4 + languages/c/templates/json-types/float.c | 1 + languages/c/templates/json-types/integer.c | 1 + languages/c/templates/json-types/namespace.c | 1 + languages/c/templates/json-types/object.cpp | 25 + languages/c/templates/json-types/primitive.c | 0 .../templates/json-types/property-assign.cpp | 2 + .../json-types/property-register.cpp | 2 + languages/c/templates/json-types/property.cpp | 1 + languages/c/templates/json-types/ref.c | 1 + languages/c/templates/json-types/string.c | 1 + languages/c/templates/json-types/title.c | 1 + languages/c/templates/json-types/tuple.c | 25 + .../c/templates/json-types/types/object.c | 0 languages/c/templates/json-types/x-method.c | 1 + languages/c/templates/methods/default.c | 3 +- languages/c/templates/methods/event.c | 3 +- languages/c/templates/methods/property.c | 1 + languages/c/templates/modules/src/Module.cpp | 6 +- .../parameter-serialization/boolean.cpp | 2 + .../parameter-serialization/default.cpp | 2 + .../parameter-serialization/object.cpp | 2 + .../parameter-serialization/primitive.cpp | 2 + .../parameter-serialization/string.cpp | 2 + .../result-instantiation/boolean.cpp | 2 + .../result-instantiation/default.cpp | 1 + .../templates/result-instantiation/object.cpp | 4 + .../result-instantiation/primitive.cpp | 1 + .../templates/result-instantiation/string.cpp | 2 + .../c/templates/schemas/src/JsonData_Module.h | 2 +- .../c/templates/types/additionalProperties.c | 4 + languages/c/templates/types/anyOf.c | 2 +- languages/c/templates/types/array.c | 5 +- languages/c/templates/types/default.c | 2 +- languages/c/templates/types/object.c | 13 +- languages/c/templates/types/primitive.c | 1 - languages/c/templates/types/property.c | 6 + languages/c/templates/types/ref.c | 2 +- languages/c/templates/types/tuple.c | 11 +- languages/c/templates/types/x-method.c | 1 + languages/javascript/language.config.json | 3 +- .../javascript/templates/types/anyOf.mjs | 2 +- .../javascript/templates/types/items.mjs | 1 + languages/javascript/templates/types/null.mjs | 1 + .../javascript/templates/types/object.mjs | 2 +- .../javascript/templates/types/property.mjs | 1 + .../javascript/templates/types/tuple.mjs | 2 +- .../javascript/templates/types/x-method.mjs | 1 + src/macrofier/engine.mjs | 147 ++- src/macrofier/index.mjs | 7 + src/macrofier/types.mjs | 878 +++++++++-------- src/sdk/index.mjs | 3 + src/shared/json-schema.mjs | 76 +- 173 files changed, 4612 insertions(+), 468 deletions(-) create mode 100644 languages/c-structs/language.config.json create mode 100644 languages/c-structs/src/index.mjs create mode 100644 languages/c-structs/templates/codeblocks/export.c create mode 100644 languages/c-structs/templates/codeblocks/mock-import.c create mode 100644 languages/c-structs/templates/codeblocks/mock-parameter.c rename languages/{c/templates/accessors/const.c => c-structs/templates/codeblocks/module.c} (100%) create mode 100644 languages/c-structs/templates/codeblocks/setter.c create mode 100644 languages/c-structs/templates/declarations/clear.c create mode 100644 languages/c-structs/templates/declarations/default.c create mode 100644 languages/c-structs/templates/declarations/event.c create mode 100644 languages/c-structs/templates/declarations/listen.c create mode 100644 languages/c-structs/templates/declarations/once.c create mode 100644 languages/c-structs/templates/declarations/polymorphic-reducer.c create mode 100644 languages/c-structs/templates/declarations/property.c create mode 100644 languages/c-structs/templates/declarations/provide.c create mode 100644 languages/c-structs/templates/declarations/rpc-only.c create mode 100644 languages/c-structs/templates/defaults/default.c create mode 100644 languages/c-structs/templates/defaults/property.c create mode 100644 languages/c-structs/templates/imports/default.cpp create mode 100644 languages/c-structs/templates/imports/default.h create mode 100644 languages/c-structs/templates/imports/default.jsondata create mode 100644 languages/c-structs/templates/language/enum-item.c create mode 100644 languages/c-structs/templates/language/enum.c create mode 100644 languages/c-structs/templates/language/parameter.c create mode 100644 languages/c-structs/templates/language/schema-item.c create mode 100644 languages/c-structs/templates/language/schema.c create mode 100644 languages/c-structs/templates/methods/clear.c create mode 100644 languages/c-structs/templates/methods/default.c create mode 100644 languages/c-structs/templates/methods/event.c create mode 100644 languages/c-structs/templates/methods/listen.c create mode 100644 languages/c-structs/templates/methods/once.c create mode 100644 languages/c-structs/templates/methods/polymorphic-pull-event.c create mode 100644 languages/c-structs/templates/methods/polymorphic-pull.c create mode 100644 languages/c-structs/templates/methods/polymorphic-reducer.c create mode 100644 languages/c-structs/templates/methods/property.c create mode 100644 languages/c-structs/templates/methods/provide.c create mode 100644 languages/c-structs/templates/methods/rpc-only.c create mode 100644 languages/c-structs/templates/methods/setter.c create mode 100644 languages/c-structs/templates/modules/include/Module.h rename languages/{c => c-structs}/templates/modules/include/Module_Accessors.h (100%) create mode 100644 languages/c-structs/templates/modules/src/Module.cpp create mode 100644 languages/c-structs/templates/parameters/default.c create mode 100644 languages/c-structs/templates/parameters/json.c create mode 100644 languages/c-structs/templates/parameters/optional.c create mode 100644 languages/c-structs/templates/parameters/result.c create mode 100644 languages/c-structs/templates/schemas/default.c create mode 100644 languages/c-structs/templates/schemas/include/Common/Module.h rename languages/{c => c-structs}/templates/schemas/include/Common/Module_Accessors.h (100%) create mode 100644 languages/c-structs/templates/schemas/src/JsonData_Module.h create mode 100644 languages/c-structs/templates/schemas/src/Module_Common.cpp create mode 100644 languages/c-structs/templates/sdk/CMakeLists.txt create mode 100644 languages/c-structs/templates/sdk/cmake/HelperFunctions.cmake create mode 100644 languages/c-structs/templates/sdk/cmake/project.cmake.in create mode 100644 languages/c-structs/templates/sdk/include/Error.h create mode 100644 languages/c-structs/templates/sdk/include/Firebolt.h create mode 100644 languages/c-structs/templates/sdk/include/Types.h create mode 100755 languages/c-structs/templates/sdk/scripts/build.sh create mode 100644 languages/c-structs/templates/sdk/scripts/install.js create mode 100644 languages/c-structs/templates/sdk/src/Accessor/Accessor.cpp create mode 100644 languages/c-structs/templates/sdk/src/Accessor/Accessor.h create mode 100644 languages/c-structs/templates/sdk/src/Accessor/WorkerPool.h create mode 100644 languages/c-structs/templates/sdk/src/CMakeLists.txt create mode 100644 languages/c-structs/templates/sdk/src/Event/Event.cpp create mode 100644 languages/c-structs/templates/sdk/src/Event/Event.h create mode 100644 languages/c-structs/templates/sdk/src/Firebolt.cpp create mode 100644 languages/c-structs/templates/sdk/src/FireboltSDK.conf.in create mode 100644 languages/c-structs/templates/sdk/src/FireboltSDK.h create mode 100644 languages/c-structs/templates/sdk/src/Logger/Logger.cpp create mode 100644 languages/c-structs/templates/sdk/src/Logger/Logger.h create mode 100644 languages/c-structs/templates/sdk/src/Module.cpp create mode 100644 languages/c-structs/templates/sdk/src/Module.h create mode 100644 languages/c-structs/templates/sdk/src/Properties/Properties.h create mode 100644 languages/c-structs/templates/sdk/src/Transport/Transport.cpp create mode 100644 languages/c-structs/templates/sdk/src/Transport/Transport.h create mode 100644 languages/c-structs/templates/sdk/src/Types.cpp create mode 100644 languages/c-structs/templates/sdk/src/TypesPriv.h create mode 100644 languages/c-structs/templates/sdk/test/CMakeLists.txt create mode 100644 languages/c-structs/templates/sdk/test/Main.c create mode 100644 languages/c-structs/templates/sdk/test/Module.cpp create mode 100644 languages/c-structs/templates/sdk/test/Module.h create mode 100644 languages/c-structs/templates/sdk/test/OpenRPCCTests.h create mode 100644 languages/c-structs/templates/sdk/test/OpenRPCTests.cpp create mode 100644 languages/c-structs/templates/sdk/test/OpenRPCTests.h create mode 100644 languages/c-structs/templates/sdk/test/TestUtils.h create mode 100644 languages/c-structs/templates/sections/accessors.c create mode 100644 languages/c-structs/templates/sections/declarations.c create mode 100644 languages/c-structs/templates/sections/enums.c create mode 100644 languages/c-structs/templates/sections/events.c create mode 100644 languages/c-structs/templates/sections/methods.c create mode 100644 languages/c-structs/templates/sections/methods_accessors.c create mode 100644 languages/c-structs/templates/sections/methods_types.c create mode 100644 languages/c-structs/templates/sections/provider-interfaces.c create mode 100644 languages/c-structs/templates/sections/schemas.c create mode 100644 languages/c-structs/templates/sections/types.c create mode 100644 languages/c-structs/templates/types/anyOf.c create mode 100644 languages/c-structs/templates/types/array.c create mode 100644 languages/c-structs/templates/types/const.c rename languages/{c/templates/accessors => c-structs/templates/types}/default.c (57%) rename languages/{c/templates/accessors => c-structs/templates/types}/enum.cpp (100%) rename languages/{c/templates/accessors => c-structs/templates/types}/enum.h (100%) create mode 100644 languages/c-structs/templates/types/object.c create mode 100644 languages/c-structs/templates/types/primitive.c create mode 100644 languages/c-structs/templates/types/property.c rename languages/{c/templates/accessors => c-structs/templates/types}/ref.c (100%) rename languages/{c/templates/accessors => c-structs/templates/types}/title.c (100%) create mode 100644 languages/c-structs/templates/types/tuple.c delete mode 100644 languages/c/templates/accessors/array.c delete mode 100644 languages/c/templates/accessors/object.c delete mode 100644 languages/c/templates/accessors/primitive.c delete mode 100644 languages/c/templates/accessors/tuple.c create mode 100644 languages/c/templates/json-types/additionalProperties.c rename languages/c/templates/{accessors => json-types}/anyOf.c (100%) create mode 100644 languages/c/templates/json-types/array.c create mode 100644 languages/c/templates/json-types/boolean.c create mode 100644 languages/c/templates/json-types/const.c create mode 100644 languages/c/templates/json-types/default.cpp create mode 100644 languages/c/templates/json-types/enum.cpp create mode 100644 languages/c/templates/json-types/enum.h create mode 100644 languages/c/templates/json-types/float.c create mode 100644 languages/c/templates/json-types/integer.c create mode 100644 languages/c/templates/json-types/namespace.c create mode 100644 languages/c/templates/json-types/object.cpp create mode 100644 languages/c/templates/json-types/primitive.c create mode 100644 languages/c/templates/json-types/property-assign.cpp create mode 100644 languages/c/templates/json-types/property-register.cpp create mode 100644 languages/c/templates/json-types/property.cpp create mode 100644 languages/c/templates/json-types/ref.c create mode 100644 languages/c/templates/json-types/string.c create mode 100644 languages/c/templates/json-types/title.c create mode 100644 languages/c/templates/json-types/tuple.c create mode 100644 languages/c/templates/json-types/types/object.c create mode 100644 languages/c/templates/json-types/x-method.c create mode 100644 languages/c/templates/parameter-serialization/boolean.cpp create mode 100644 languages/c/templates/parameter-serialization/default.cpp create mode 100644 languages/c/templates/parameter-serialization/object.cpp create mode 100644 languages/c/templates/parameter-serialization/primitive.cpp create mode 100644 languages/c/templates/parameter-serialization/string.cpp create mode 100644 languages/c/templates/result-instantiation/boolean.cpp create mode 100644 languages/c/templates/result-instantiation/default.cpp create mode 100644 languages/c/templates/result-instantiation/object.cpp create mode 100644 languages/c/templates/result-instantiation/primitive.cpp create mode 100644 languages/c/templates/result-instantiation/string.cpp create mode 100644 languages/c/templates/types/additionalProperties.c create mode 100644 languages/c/templates/types/property.c create mode 100644 languages/c/templates/types/x-method.c create mode 100644 languages/javascript/templates/types/items.mjs create mode 100644 languages/javascript/templates/types/null.mjs create mode 100644 languages/javascript/templates/types/property.mjs create mode 100644 languages/javascript/templates/types/x-method.mjs diff --git a/.gitignore b/.gitignore index 5053bbc0..1b1bb730 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ node_modules/* .DS_Store .DS_Store coverage +.vscode/settings.json diff --git a/languages/c-structs/language.config.json b/languages/c-structs/language.config.json new file mode 100644 index 00000000..1a7e83c0 --- /dev/null +++ b/languages/c-structs/language.config.json @@ -0,0 +1,26 @@ +{ + "name": "C", + "langcode": "c", + "createModuleDirectories": false, + "extractSubSchemas": true, + "convertTuplesToArraysOrObjects": true, + "templatesPerModule": [ + "/include/Module.h", + "/include/Module_Accessors.h", + "/src/Module.cpp" + ], + "templatesPerSchema": [ + "/include/Common/Module.h", + "/include/Common/Module_Accessors.h", + "/src/Module_Common.cpp", + "/src/JsonData_Module.h" + ], + "persistPermission": true, + "primitives": { + "boolean": "bool", + "integer": "int", + "number": "float", + "string": "char*" + }, + "additionalSchemaTemplates": [] +} diff --git a/languages/c-structs/src/index.mjs b/languages/c-structs/src/index.mjs new file mode 100644 index 00000000..51c547a1 --- /dev/null +++ b/languages/c-structs/src/index.mjs @@ -0,0 +1,19 @@ +/* + * Copyright 2021 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 + */ + +export { default as Transport } from './shared/Transport/index.mjs' \ No newline at end of file diff --git a/languages/c-structs/templates/codeblocks/export.c b/languages/c-structs/templates/codeblocks/export.c new file mode 100644 index 00000000..c98498e4 --- /dev/null +++ b/languages/c-structs/templates/codeblocks/export.c @@ -0,0 +1 @@ +export { default as ${info.title} } from './${info.title}/index.mjs' \ No newline at end of file diff --git a/languages/c-structs/templates/codeblocks/mock-import.c b/languages/c-structs/templates/codeblocks/mock-import.c new file mode 100644 index 00000000..5d22512a --- /dev/null +++ b/languages/c-structs/templates/codeblocks/mock-import.c @@ -0,0 +1 @@ +import { default as _${info.title} } from './${info.title}/defaults.mjs' \ No newline at end of file diff --git a/languages/c-structs/templates/codeblocks/mock-parameter.c b/languages/c-structs/templates/codeblocks/mock-parameter.c new file mode 100644 index 00000000..63e63902 --- /dev/null +++ b/languages/c-structs/templates/codeblocks/mock-parameter.c @@ -0,0 +1 @@ + ${info.title}: _${info.title}, \ No newline at end of file diff --git a/languages/c/templates/accessors/const.c b/languages/c-structs/templates/codeblocks/module.c similarity index 100% rename from languages/c/templates/accessors/const.c rename to languages/c-structs/templates/codeblocks/module.c diff --git a/languages/c-structs/templates/codeblocks/setter.c b/languages/c-structs/templates/codeblocks/setter.c new file mode 100644 index 00000000..9f496543 --- /dev/null +++ b/languages/c-structs/templates/codeblocks/setter.c @@ -0,0 +1,9 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.title}_${method.Name}( ${method.signature.params} ) +{ + const string method = _T("${info.title}.${method.name}"); + ${if.params} +${method.params.serialization} + ${end.if.params} + return FireboltSDK::Properties::Set(method, jsonParameters); +} diff --git a/languages/c-structs/templates/declarations/clear.c b/languages/c-structs/templates/declarations/clear.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/declarations/default.c b/languages/c-structs/templates/declarations/default.c new file mode 100644 index 00000000..5d972e4a --- /dev/null +++ b/languages/c-structs/templates/declarations/default.c @@ -0,0 +1,5 @@ +/* + * ${method.summary} + * ${method.params} + */ +int F${info.title}_${method.Name}(${method.signature.params}${if.result.properties}${if.params}, ${end.if.params}${end.if.result.properties}${method.result.properties}); diff --git a/languages/c-structs/templates/declarations/event.c b/languages/c-structs/templates/declarations/event.c new file mode 100644 index 00000000..f91c6a39 --- /dev/null +++ b/languages/c-structs/templates/declarations/event.c @@ -0,0 +1,4 @@ +/* ${method.name} - ${method.description} */ +typedef void (*${info.Title}${method.Name}Callback)( const void* userData, ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${method.result.properties} ); +int ${info.title}_Register_${method.Name}( ${event.signature.params}${if.event.params}, ${end.if.event.params}${info.Title}${method.Name}Callback userCB, const void* userData ); +int ${info.title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); diff --git a/languages/c-structs/templates/declarations/listen.c b/languages/c-structs/templates/declarations/listen.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/declarations/once.c b/languages/c-structs/templates/declarations/once.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/declarations/polymorphic-reducer.c b/languages/c-structs/templates/declarations/polymorphic-reducer.c new file mode 100644 index 00000000..5d972e4a --- /dev/null +++ b/languages/c-structs/templates/declarations/polymorphic-reducer.c @@ -0,0 +1,5 @@ +/* + * ${method.summary} + * ${method.params} + */ +int F${info.title}_${method.Name}(${method.signature.params}${if.result.properties}${if.params}, ${end.if.params}${end.if.result.properties}${method.result.properties}); diff --git a/languages/c-structs/templates/declarations/property.c b/languages/c-structs/templates/declarations/property.c new file mode 100644 index 00000000..77aac221 --- /dev/null +++ b/languages/c-structs/templates/declarations/property.c @@ -0,0 +1,5 @@ +/* + * ${method.summary} + * ${method.params} + */ +int F${info.title}_Get${method.Name}(${method.signature.params}${if.params}, ${end.if.params}${method.result.properties}); diff --git a/languages/c-structs/templates/declarations/provide.c b/languages/c-structs/templates/declarations/provide.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/declarations/rpc-only.c b/languages/c-structs/templates/declarations/rpc-only.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/defaults/default.c b/languages/c-structs/templates/defaults/default.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/defaults/property.c b/languages/c-structs/templates/defaults/property.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/imports/default.cpp b/languages/c-structs/templates/imports/default.cpp new file mode 100644 index 00000000..69e241f9 --- /dev/null +++ b/languages/c-structs/templates/imports/default.cpp @@ -0,0 +1 @@ +#include "JsonData_${info.title}.h" diff --git a/languages/c-structs/templates/imports/default.h b/languages/c-structs/templates/imports/default.h new file mode 100644 index 00000000..a38b58ef --- /dev/null +++ b/languages/c-structs/templates/imports/default.h @@ -0,0 +1 @@ +#include "Common/${info.title}.h" diff --git a/languages/c-structs/templates/imports/default.jsondata b/languages/c-structs/templates/imports/default.jsondata new file mode 100644 index 00000000..69e241f9 --- /dev/null +++ b/languages/c-structs/templates/imports/default.jsondata @@ -0,0 +1 @@ +#include "JsonData_${info.title}.h" diff --git a/languages/c-structs/templates/language/enum-item.c b/languages/c-structs/templates/language/enum-item.c new file mode 100644 index 00000000..79aabbeb --- /dev/null +++ b/languages/c-structs/templates/language/enum-item.c @@ -0,0 +1 @@ + ${key} diff --git a/languages/c-structs/templates/language/enum.c b/languages/c-structs/templates/language/enum.c new file mode 100644 index 00000000..0551b99c --- /dev/null +++ b/languages/c-structs/templates/language/enum.c @@ -0,0 +1,3 @@ +typedef enum { + ${items} +} F${info.title}_${title}; diff --git a/languages/c-structs/templates/language/parameter.c b/languages/c-structs/templates/language/parameter.c new file mode 100644 index 00000000..2ff7a678 --- /dev/null +++ b/languages/c-structs/templates/language/parameter.c @@ -0,0 +1 @@ +${type} ${name} \ No newline at end of file diff --git a/languages/c-structs/templates/language/schema-item.c b/languages/c-structs/templates/language/schema-item.c new file mode 100644 index 00000000..ecded7d5 --- /dev/null +++ b/languages/c-structs/templates/language/schema-item.c @@ -0,0 +1 @@ + ${type} ${property}; diff --git a/languages/c-structs/templates/language/schema.c b/languages/c-structs/templates/language/schema.c new file mode 100644 index 00000000..22760540 --- /dev/null +++ b/languages/c-structs/templates/language/schema.c @@ -0,0 +1,3 @@ +typedef struct { + ${properties} +} F${info.title}_${title}; diff --git a/languages/c-structs/templates/methods/clear.c b/languages/c-structs/templates/methods/clear.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/methods/default.c b/languages/c-structs/templates/methods/default.c new file mode 100644 index 00000000..3707e68b --- /dev/null +++ b/languages/c-structs/templates/methods/default.c @@ -0,0 +1,24 @@ +/* ${method.name} - ${method.description} */ +int F${info.title}_${method.Name}(${method.signature.params}${if.result.properties}${if.params}, ${end.if.params}${end.if.result.properties}${method.result.properties}) { + int status = FireboltSDKErrorUnavailable; + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + + JsonObject jsonParameters; + + ${if.params} +${method.params.json} + ${end.if.params} + + WPEFramework::Core::JSON::Boolean jsonResult; + status = transport->Invoke("${info.title}.${method.name}", jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + *success = jsonResult.Value(); + } + + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; +} diff --git a/languages/c-structs/templates/methods/event.c b/languages/c-structs/templates/methods/event.c new file mode 100644 index 00000000..766a78b3 --- /dev/null +++ b/languages/c-structs/templates/methods/event.c @@ -0,0 +1,26 @@ +/* ${method.name} - ${method.description} */ +static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) +{ +${event.callback.params.serialization} + ASSERT(jsonResponse->IsValid() == true); + if (jsonResponse->IsValid() == true) { +${event.callback.result.instantiation} + ${info.Title}${method.Name}Callback callback = reinterpret_cast<${info.Title}${method.Name}Callback>(userCB); + callback(userData, ${event.callback.response.instantiation}); + } +} +int ${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}"); + int status = FireboltSDKErrorNone; + + if (userCB != nullptr) { + ${event.params.serialization} + status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${info.Title}${method.Name}InnerCallback, reinterpret_cast(userCB), userData); + } + return status; +} +int ${info.title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB) +{ + return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title}.${method.name}"), reinterpret_cast(userCB)); +} diff --git a/languages/c-structs/templates/methods/listen.c b/languages/c-structs/templates/methods/listen.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/methods/once.c b/languages/c-structs/templates/methods/once.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/methods/polymorphic-pull-event.c b/languages/c-structs/templates/methods/polymorphic-pull-event.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/methods/polymorphic-pull.c b/languages/c-structs/templates/methods/polymorphic-pull.c new file mode 100644 index 00000000..553b2946 --- /dev/null +++ b/languages/c-structs/templates/methods/polymorphic-pull.c @@ -0,0 +1,21 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.title}_Push${method.Name}(${method.signature.params}) +{ + uint32_t status = FireboltSDKErrorUnavailable; + ${if.params} +${method.params.serialization} + ${end.if.params} + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + WPEFramework::Core::JSON::Boolean jsonResult; + status = transport->Invoke(_T("${info.title}.${method.name}"), jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; + } + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; +} diff --git a/languages/c-structs/templates/methods/polymorphic-reducer.c b/languages/c-structs/templates/methods/polymorphic-reducer.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/methods/property.c b/languages/c-structs/templates/methods/property.c new file mode 100644 index 00000000..7c46f7c1 --- /dev/null +++ b/languages/c-structs/templates/methods/property.c @@ -0,0 +1,15 @@ +/* ${method.name} - ${method.description} */ +int F${info.title}_Get${method.Name}(${method.signature.params}${if.result.properties}${if.params}, ${end.if.params}${end.if.result.properties}${method.result.properties}) { + const string method = _T("${info.title}.${method.name}"); +${if.params}${method.params.serialization}${end.if.params} + ${method.result.json} jsonResult; + ${if.params}int status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult);${end.if.params} + ${if.params.empty}int status = FireboltSDK::Properties::Get(method, jsonResult);${end.if.params.empty} + if (status == FireboltSDKErrorNone) { + if (${method.result.name} != nullptr) { +${method.result.instantiation} + } + } + return status; +} +${method.setter} diff --git a/languages/c-structs/templates/methods/provide.c b/languages/c-structs/templates/methods/provide.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/methods/rpc-only.c b/languages/c-structs/templates/methods/rpc-only.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/methods/setter.c b/languages/c-structs/templates/methods/setter.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/modules/include/Module.h b/languages/c-structs/templates/modules/include/Module.h new file mode 100644 index 00000000..7a192768 --- /dev/null +++ b/languages/c-structs/templates/modules/include/Module.h @@ -0,0 +1,41 @@ +/* + * 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 + */ + +#ifndef _${info.TITLE}_H +#define _${info.TITLE}_H + +#include "Firebolt.h" +/* ${IMPORTS} */ + +#ifdef __cplusplus +extern "C" { +#endif + +// Enums + +/* ${ENUMS} */ + +/* ${TYPES} */ + +/* ${DECLARATIONS} */ + +#ifdef __cplusplus +} +#endif + +#endif // Header Include Guard diff --git a/languages/c/templates/modules/include/Module_Accessors.h b/languages/c-structs/templates/modules/include/Module_Accessors.h similarity index 100% rename from languages/c/templates/modules/include/Module_Accessors.h rename to languages/c-structs/templates/modules/include/Module_Accessors.h diff --git a/languages/c-structs/templates/modules/src/Module.cpp b/languages/c-structs/templates/modules/src/Module.cpp new file mode 100644 index 00000000..65721f1e --- /dev/null +++ b/languages/c-structs/templates/modules/src/Module.cpp @@ -0,0 +1,42 @@ +/* + * 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}.h" + +namespace FireboltSDK { + namespace ${info.title} { + // Types + /* ${TYPES} */ + } +} + +/* ${ENUMS} */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* ${ACCESSORS} */ +/* ${METHODS} */ +/* ${EVENTS} */ + +#ifdef __cplusplus +} +#endif diff --git a/languages/c-structs/templates/parameters/default.c b/languages/c-structs/templates/parameters/default.c new file mode 100644 index 00000000..e6e3b8ba --- /dev/null +++ b/languages/c-structs/templates/parameters/default.c @@ -0,0 +1 @@ +${method.param.type} ${method.param.name} \ No newline at end of file diff --git a/languages/c-structs/templates/parameters/json.c b/languages/c-structs/templates/parameters/json.c new file mode 100644 index 00000000..5ee36bec --- /dev/null +++ b/languages/c-structs/templates/parameters/json.c @@ -0,0 +1,3 @@ + ${json.param.type} ${method.param.Name} = ${method.param.name}; + jsonParameters.Add("_T(${method.param.name})", &${method.param.Name}); + diff --git a/languages/c-structs/templates/parameters/optional.c b/languages/c-structs/templates/parameters/optional.c new file mode 100644 index 00000000..e6e3b8ba --- /dev/null +++ b/languages/c-structs/templates/parameters/optional.c @@ -0,0 +1 @@ +${method.param.type} ${method.param.name} \ No newline at end of file diff --git a/languages/c-structs/templates/parameters/result.c b/languages/c-structs/templates/parameters/result.c new file mode 100644 index 00000000..699c8b5b --- /dev/null +++ b/languages/c-structs/templates/parameters/result.c @@ -0,0 +1 @@ +${method.param.type} *${method.param.name} \ No newline at end of file diff --git a/languages/c-structs/templates/schemas/default.c b/languages/c-structs/templates/schemas/default.c new file mode 100644 index 00000000..9a52cff7 --- /dev/null +++ b/languages/c-structs/templates/schemas/default.c @@ -0,0 +1 @@ +${schema.shape} diff --git a/languages/c-structs/templates/schemas/include/Common/Module.h b/languages/c-structs/templates/schemas/include/Common/Module.h new file mode 100644 index 00000000..ff037fba --- /dev/null +++ b/languages/c-structs/templates/schemas/include/Common/Module.h @@ -0,0 +1,39 @@ +/* + * 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 + */ + +#ifndef _COMMON_${info.TITLE}_H +#define _COMMON_${info.TITLE}_H + +#include "Firebolt.h" +/* ${IMPORTS} */ + +#ifdef __cplusplus +extern "C" { +#endif + +// Enums + +/* ${ENUMS} */ + +/* ${TYPES} */ + +#ifdef __cplusplus +} +#endif + +#endif // Header Include Guard diff --git a/languages/c/templates/schemas/include/Common/Module_Accessors.h b/languages/c-structs/templates/schemas/include/Common/Module_Accessors.h similarity index 100% rename from languages/c/templates/schemas/include/Common/Module_Accessors.h rename to languages/c-structs/templates/schemas/include/Common/Module_Accessors.h diff --git a/languages/c-structs/templates/schemas/src/JsonData_Module.h b/languages/c-structs/templates/schemas/src/JsonData_Module.h new file mode 100644 index 00000000..d0ecbbac --- /dev/null +++ b/languages/c-structs/templates/schemas/src/JsonData_Module.h @@ -0,0 +1,30 @@ +/* + * 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 + +/* ${IMPORTS} */ +#include "Common/${info.title}.h" + +namespace FireboltSDK { + namespace ${info.title} { + // Types + + /* ${SCHEMAS} */ + } +} diff --git a/languages/c-structs/templates/schemas/src/Module_Common.cpp b/languages/c-structs/templates/schemas/src/Module_Common.cpp new file mode 100644 index 00000000..0ccdfc28 --- /dev/null +++ b/languages/c-structs/templates/schemas/src/Module_Common.cpp @@ -0,0 +1,35 @@ +/* + * 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 "JsonData_${info.title}.h" + +/* ${ENUMS} */ + +#ifdef __cplusplus +extern "C" { +#endif + + /* ${ACCESSORS} */ + /* ${METHODS} */ + /* ${EVENTS} */ + +#ifdef __cplusplus +} +#endif diff --git a/languages/c-structs/templates/sdk/CMakeLists.txt b/languages/c-structs/templates/sdk/CMakeLists.txt new file mode 100644 index 00000000..5efcad1a --- /dev/null +++ b/languages/c-structs/templates/sdk/CMakeLists.txt @@ -0,0 +1,61 @@ +# 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 + +cmake_minimum_required(VERSION 3.3) + +project(Firebolt) + +set(FIREBOLT_TRANSPORT_WAITTIME 1000 CACHE STRING "Maximum time to wait for Transport layer to get response") +set(FIREBOLT_LOGLEVEL "Info" CACHE STRING "Log level to be enabled") +option(FIREBOLT_ENABLE_STATIC_LIB "Create Firebolt library as Static library" OFF) +option(ENABLE_TESTS "Build openrpc native test" OFF) + +if (NOT SYSROOT_PATH) + # Set sysroot to support PC builds, sysroot_path not configured case + set(SYSROOT_PATH "${CMAKE_SOURCE_DIR}/../../firebolt") +endif() + +if (FIREBOLT_ENABLE_STATIC_LIB) + set(FIREBOLT_LIBRARY_TYPE STATIC) +else () + set(FIREBOLT_LIBRARY_TYPE SHARED) +endif () + +if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${SYSROOT_PATH}/usr" CACHE INTERNAL "" FORCE) + set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) +endif() + +list(APPEND CMAKE_MODULE_PATH + "${CMAKE_SOURCE_DIR}/cmake" + "${SYSROOT_PATH}/usr/lib/cmake" + "${SYSROOT_PATH}/tools/cmake") +include(HelperFunctions) + +set(FIREBOLT_NAMESPACE ${PROJECT_NAME} CACHE STRING "Namespace of the project") + +find_package(WPEFramework CONFIG REQUIRED) + +add_subdirectory(src) + +if (ENABLE_TESTS) + add_subdirectory(test) +endif() + +# make sure others can make use cmake settings of Firebolt OpenRPC +configure_file( "${CMAKE_SOURCE_DIR}/cmake/project.cmake.in" + "${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake" + @ONLY) diff --git a/languages/c-structs/templates/sdk/cmake/HelperFunctions.cmake b/languages/c-structs/templates/sdk/cmake/HelperFunctions.cmake new file mode 100644 index 00000000..b3647c16 --- /dev/null +++ b/languages/c-structs/templates/sdk/cmake/HelperFunctions.cmake @@ -0,0 +1,144 @@ +# 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 + +macro(GetSubDirs subdirs currentdir) + file(GLOB subdirectories RELATIVE ${currentdir} ${currentdir}/*) + set(subdirs "") + foreach(subdir ${subdirectories}) + if (IS_DIRECTORY ${currentdir}/${subdir}) + list(APPEND subdirs ${subdir}) + endif() + endforeach() +endmacro() + +function(InstallHeaders) + set(optionsArgs EXCLUDE_ROOT_DIR) + set(oneValueArgs TARGET NAMESPACE SOURCE DESTINATION) + set(multiValueArgs HEADERS) + + cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) + if (Argument_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to InstallHeaders(): \"${Argument_UNPARSED_ARGUMENTS}\"") + endif() + if (Argument_HEADERS) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMENT "=================== Installing Headers ======================" + ) + foreach(directory ${Argument_HEADERS}) + if (Argument_EXCLUDE_ROOT_DIR) + set(destination ${Argument_DESTINATION}) + else() + set(destination ${Argument_DESTINATION}/${directory}) + endif() + + if (Argument_SOURCE) + set(source ${Argument_SOURCE}) + else() + set(source ${CMAKE_CURRENT_LIST_DIR}) + endif() + + GetSubDirs(subdirs ${source}/${directory}) + list(APPEND subdirs ${directory}) + + foreach(subdir ${subdirs}) + set(dest ${destination}/${subdir}) + file(GLOB headers "${source}/${directory}/${subdir}/*.h") + if (headers) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_NAMESPACE}/usr/include/${dest} + COMMAND ${CMAKE_COMMAND} -E copy ${source}/${directory}/${subdir}/*.h ${CMAKE_BINARY_DIR}/${Argument_NAMESPACE}/usr/include/${dest} + ) + endif() + endforeach(subdir) + endforeach(directory) + endif() +endfunction(InstallHeaders) + +function(InstallLibraries) + set(optionsArgs SHARED STATIC) + set(oneValueArgs TARGET DESTINATION LIBDIR) + set(multiValueArgs LIBRARIES) + + cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) + if (Argument_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to InstallLibraries(): \"${Argument_UNPARSED_ARGUMENTS}\"") + endif() + if (Argument_LIBRARIES) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMENT "=================== Installing Libraries ======================" + ) + foreach(LIBRARY ${Argument_LIBRARIES}) + if (Argument_SHARED) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_LIBDIR}/lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + COMMAND ${CMAKE_COMMAND} -E create_symlink lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR} + COMMAND ${CMAKE_COMMAND} -E create_symlink lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/lib${LIBRARY}.so + ) + elseif (Argument_STATIC) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/lib${LIBRARY}.a ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + ) + + endif() + endforeach(LIBRARY) + endif() +endfunction(InstallLibraries) + +function(InstallCMakeConfigs) + set(optionsArgs) + set(oneValueArgs TARGET DESTINATION) + set(multiValueArgs) + + cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) + if (Argument_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to InstallCMakeConfigs(): \"${Argument_UNPARSED_ARGUMENTS}\"") + endif() + if (Argument_TARGET) + if (${CMAKE_VERSION} VERSION_LESS "3.25.0") + set(EXPORT_CONFIG_PATH "lib/cmake/${Argument_TARGET}") + else () + set(EXPORT_CONFIG_PATH "*") + endif () + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMENT "=================== Installing CMakeConfigs ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}Config*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Export/${EXPORT_CONFIG_PATH}/${Argument_TARGET}Targets*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} + ) + if (EXISTS ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}.pc) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/pkgconfig + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}.pc ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/pkgconfig + ) + endif() + endif() +endfunction(InstallCMakeConfigs) diff --git a/languages/c-structs/templates/sdk/cmake/project.cmake.in b/languages/c-structs/templates/sdk/cmake/project.cmake.in new file mode 100644 index 00000000..eca32f8c --- /dev/null +++ b/languages/c-structs/templates/sdk/cmake/project.cmake.in @@ -0,0 +1,35 @@ +# 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 + +set(FIREBOLT_NAMESPACE "@FIREBOLT_NAMESPACE@" CACHE INTERNAL "" FORCE) +set("${FIREBOLT_NAMESPACE}_FOUND" TRUE CACHE INTERNAL "" FORCE) + +list(APPEND CMAKE_MODULE_PATH + "${CMAKE_SOURCE_DIR}/cmake" + "${SYSROOT_PATH}/usr/lib/cmake" + "${SYSROOT_PATH}/usr/lib/cmake/Firebolt" + "${SYSROOT_PATH}/tools/cmake") + +if (NOT DEFINED CMAKE_PREFIX_PATH) + set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) +endif() + +if (FIREBOLT_ENABLE_STATIC_LIB) + set(FIREBOLT_LIBRARY_TYPE STATIC) +else () + set(FIREBOLT_LIBRARY_TYPE SHARED) +endif () + diff --git a/languages/c-structs/templates/sdk/include/Error.h b/languages/c-structs/templates/sdk/include/Error.h new file mode 100644 index 00000000..87cda9dd --- /dev/null +++ b/languages/c-structs/templates/sdk/include/Error.h @@ -0,0 +1,41 @@ +/* + * 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 + */ + +#ifndef _FIREBOLT_ERROR_H +#define _FIREBOLT_ERROR_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum FireboltSDKError { + FireboltSDKErrorNone = 0, + FireboltSDKErrorGeneral = 1, + FireboltSDKErrorUnavailable = 2, + FireboltSDKErrorTimedout = 3, + FireboltSDKErrorNotSubscribed = 4, + FireboltSDKErrorUnknown = 5, + FireboltSDKErrorInUse = 6, + FireboltSDKErrorNotSupported = 7 +} FireboltSDKError_t; + +#ifdef __cplusplus +} +#endif + +#endif // _FIREBOLT_ERROR_H diff --git a/languages/c-structs/templates/sdk/include/Firebolt.h b/languages/c-structs/templates/sdk/include/Firebolt.h new file mode 100644 index 00000000..2223bad3 --- /dev/null +++ b/languages/c-structs/templates/sdk/include/Firebolt.h @@ -0,0 +1,65 @@ +/* + * 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 + */ + +#ifndef _FIREBOLT_H +#define _FIREBOLT_H + +#include "Error.h" +#include "Types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Intitialize the Firebolt SDK + * + * @param configLine JSON String with configuration options + * + * CONFIG Format: + * { + * "waitTime": 1000, + * "logLevel": "Info", + * "workerPool":{ + * "queueSize": 8, + * "threadCount": 3 + * }, + * "wsUrl": "ws://127.0.0.1:9998" + * } + * + * + * @return FireboltSDKErrorNone if success, appropriate error otherwise. + * + */ +uint32_t FireboltSDK_Initialize(char* configLine); + + +/** + * @brief Deintitialize the Firebolt SDK + * + * @return FireboltSDKErrorNone if success, appropriate error otherwise. + * + */ +uint32_t FireboltSDK_Deinitialize(void); + +#ifdef __cplusplus +} +#endif + + +#endif // _FIREBOLT_H diff --git a/languages/c-structs/templates/sdk/include/Types.h b/languages/c-structs/templates/sdk/include/Types.h new file mode 100644 index 00000000..4fd16256 --- /dev/null +++ b/languages/c-structs/templates/sdk/include/Types.h @@ -0,0 +1,37 @@ +/* + * 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 + */ + +#ifndef _FIREBOLT_TYPES_H +#define _FIREBOLT_TYPES_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void* FireboltTypes_StringHandle; +const char* FireboltTypes_String(FireboltTypes_StringHandle handle); +void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle); + +#ifdef __cplusplus +} +#endif + +#endif // _FIREBOLT_TYPES_H diff --git a/languages/c-structs/templates/sdk/scripts/build.sh b/languages/c-structs/templates/sdk/scripts/build.sh new file mode 100755 index 00000000..e9b01f20 --- /dev/null +++ b/languages/c-structs/templates/sdk/scripts/build.sh @@ -0,0 +1,11 @@ +#!/bin/bash +SDK_PATH="." +if [ "$1" != "" ] +then + SDK_PATH=$1 + echo "inside ${1}" +fi +echo ${SDK_PATH} +rm -rf ${SDK_PATH}/build +cmake -B${SDK_PATH}/build -S${SDK_PATH} -DSYSROOT_PATH=${SYSROOT_PATH} +cmake --build ${SDK_PATH}/build diff --git a/languages/c-structs/templates/sdk/scripts/install.js b/languages/c-structs/templates/sdk/scripts/install.js new file mode 100644 index 00000000..5c332ceb --- /dev/null +++ b/languages/c-structs/templates/sdk/scripts/install.js @@ -0,0 +1,32 @@ +import { createRequire } from 'module'; +const require = createRequire(import.meta.url); +const fs = require('fs'); +const path = require('path'); + +var dest = process.env.NODE_INSTALL_PATH; +var src = 'src/native/build/' + process.env.TARGET_NAME; + +installFiles(src, dest); +function installFiles(src, dest) { + if (!fs.existsSync(dest)) { + fs.mkdirSync(dest); + } + + var entries = fs.readdirSync(src); + entries.forEach((entry) => { + const srcPath = path.join(src, entry); + const destPath = path.join(dest, entry); + const stat = fs.lstatSync(srcPath); + + if (stat.isFile()) { + fs.copyFileSync(srcPath, destPath); + } else if (stat.isDirectory()) { + installFiles(srcPath, destPath); + } else if (stat.isSymbolicLink()) { + if (fs.existsSync(destPath)) { + fs.unlinkSync(destPath); + } + fs.symlinkSync(fs.readlinkSync(srcPath), destPath); + } + }); +} diff --git a/languages/c-structs/templates/sdk/src/Accessor/Accessor.cpp b/languages/c-structs/templates/sdk/src/Accessor/Accessor.cpp new file mode 100644 index 00000000..e4a5df32 --- /dev/null +++ b/languages/c-structs/templates/sdk/src/Accessor/Accessor.cpp @@ -0,0 +1,117 @@ +/* + * 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 "Accessor.h" + +namespace FireboltSDK { + + Accessor* Accessor::_singleton = nullptr; + + Accessor::Accessor(const string& configLine) + : _workerPool() + , _transport(nullptr) + , _config() + { + _singleton = this; + _config.FromString(configLine); + + Logger::SetLogLevel(WPEFramework::Core::EnumerateType(_config.LogLevel.Value().c_str()).Value()); + + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Url = %s", _config.WsUrl.Value().c_str()); + CreateTransport(_config.WsUrl.Value().c_str(), _config.WaitTime.Value()); + CreateEventHandler(); + + _workerPool = WPEFramework::Core::ProxyType::Create(_config.WorkerPool.ThreadCount.Value(), _config.WorkerPool.StackSize.Value(), _config.WorkerPool.QueueSize.Value()); + WPEFramework::Core::WorkerPool::Assign(&(*_workerPool)); + _workerPool->Run(); + } + + Accessor::~Accessor() + { + DestroyTransport(); + DestroyEventHandler(); + WPEFramework::Core::IWorkerPool::Assign(nullptr); + _workerPool->Stop(); + _singleton = nullptr; + } + + uint32_t Accessor::CreateEventHandler() + { + Event::Instance().Configure(_transport); + return FireboltSDKErrorNone; + } + + uint32_t Accessor::DestroyEventHandler() + { + Event::Dispose(); + return FireboltSDKErrorNone; + } + + Event& Accessor::GetEventManager() + { + return Event::Instance(); + } + + uint32_t Accessor::CreateTransport(const string& url, const uint32_t waitTime = DefaultWaitTime) + { + if (_transport != nullptr) { + delete _transport; + } + + _transport = new Transport(static_cast(url), waitTime); + if (WaitForLinkReady(_transport, waitTime) != FireboltSDKErrorNone) { + delete _transport; + _transport = nullptr; + } + + ASSERT(_transport != nullptr); + return ((_transport != nullptr) ? FireboltSDKErrorNone : FireboltSDKErrorUnavailable); + } + + uint32_t Accessor::DestroyTransport() + { + if (_transport != nullptr) { + delete _transport; + _transport = nullptr; + } + return FireboltSDKErrorNone; + } + + Transport* Accessor::GetTransport() + { + ASSERT(_transport != nullptr); + return _transport; + } + + uint32_t Accessor::WaitForLinkReady(Transport* transport, const uint32_t waitTime = DefaultWaitTime) { + uint32_t waiting = (waitTime == WPEFramework::Core::infinite ? WPEFramework::Core::infinite : waitTime); + static constexpr uint32_t SLEEPSLOT_TIME = 100; + + // Right, a wait till connection is closed is requested.. + while ((waiting > 0) && (transport->IsOpen() == false)) { + + uint32_t sleepSlot = (waiting > SLEEPSLOT_TIME ? SLEEPSLOT_TIME : waiting); + + // Right, lets sleep in slices of 100 ms + SleepMs(sleepSlot); + + waiting -= (waiting == WPEFramework::Core::infinite ? 0 : sleepSlot); + } + return (((waiting == 0) || (transport->IsOpen() == true)) ? FireboltSDKErrorNone : FireboltSDKErrorTimedout); + } +} diff --git a/languages/c-structs/templates/sdk/src/Accessor/Accessor.h b/languages/c-structs/templates/sdk/src/Accessor/Accessor.h new file mode 100644 index 00000000..f12dc51c --- /dev/null +++ b/languages/c-structs/templates/sdk/src/Accessor/Accessor.h @@ -0,0 +1,122 @@ +/* + * 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 "Module.h" +#include "WorkerPool.h" +#include "Transport/Transport.h" +#include "Event/Event.h" +#include "Logger/Logger.h" + +namespace FireboltSDK { + class Accessor { + private: + static constexpr uint8_t JSONVersion = 2; + + private: + //Singleton + Accessor(const string& configLine); + + public: + class EXTERNAL Config : public WPEFramework::Core::JSON::Container { + public: + Config(const Config&) = delete; + Config& operator=(const Config&) = delete; + + class WorkerPoolConfig : public WPEFramework::Core::JSON::Container { + public: + WorkerPoolConfig& operator=(const WorkerPoolConfig&); + + WorkerPoolConfig() + : WPEFramework::Core::JSON::Container() + , QueueSize(8) + , ThreadCount(3) + , StackSize(WPEFramework::Core::Thread::DefaultStackSize()) + { + Add("queueSize", &QueueSize); + Add("threadCount", &ThreadCount); + Add("stackSize", &StackSize); + } + + virtual ~WorkerPoolConfig() = default; + + public: + WPEFramework::Core::JSON::DecUInt32 QueueSize; + WPEFramework::Core::JSON::DecUInt32 ThreadCount; + WPEFramework::Core::JSON::DecUInt32 StackSize; + }; + + + Config() + : WPEFramework::Core::JSON::Container() + , WaitTime(1000) + , LogLevel(_T("Info")) + , WorkerPool() + , WsUrl(_T("ws://127.0.0.1:9998")) + { + Add(_T("waitTime"), &WaitTime); + Add(_T("logLevel"), &LogLevel); + Add(_T("workerPool"), &WorkerPool); + Add(_T("wsUrl"), &WsUrl); + } + + public: + WPEFramework::Core::JSON::DecUInt32 WaitTime; + WPEFramework::Core::JSON::String LogLevel; + WorkerPoolConfig WorkerPool; + WPEFramework::Core::JSON::String WsUrl; + }; + + Accessor(const Accessor&) = delete; + Accessor& operator= (const Accessor&) = delete; + Accessor() = delete; + ~Accessor(); + + static Accessor& Instance(const string& configLine = "") + { + static Accessor *instance = new Accessor(configLine); + ASSERT(instance != nullptr); + return *instance; + } + + static void Dispose() + { + ASSERT(_singleton != nullptr); + + if (_singleton != nullptr) { + delete _singleton; + } + } + Event& GetEventManager(); + Transport* GetTransport(); + + private: + uint32_t CreateEventHandler(); + uint32_t DestroyEventHandler(); + uint32_t CreateTransport(const string& url, const uint32_t waitTime); + uint32_t DestroyTransport(); + uint32_t WaitForLinkReady(Transport* transport, const uint32_t waitTime); + + private: + WPEFramework::Core::ProxyType _workerPool; + Transport* _transport; + static Accessor* _singleton; + Config _config; + }; +} diff --git a/languages/c-structs/templates/sdk/src/Accessor/WorkerPool.h b/languages/c-structs/templates/sdk/src/Accessor/WorkerPool.h new file mode 100644 index 00000000..69005a5e --- /dev/null +++ b/languages/c-structs/templates/sdk/src/Accessor/WorkerPool.h @@ -0,0 +1,102 @@ +/* + * 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 "Module.h" + +namespace FireboltSDK { + + class WorkerPoolImplementation : public WPEFramework::Core::WorkerPool { + public: + WorkerPoolImplementation() = delete; + WorkerPoolImplementation(const WorkerPoolImplementation&) = delete; + WorkerPoolImplementation& operator=(const WorkerPoolImplementation&) = delete; + + WorkerPoolImplementation(const uint8_t threads, const uint32_t stackSize, const uint32_t queueSize) + : WorkerPool(threads, stackSize, queueSize, &_dispatcher) + { + } + + ~WorkerPoolImplementation() + { + // Diable the queue so the minions can stop, even if they are processing and waiting for work.. + Stop(); + } + + public: + void Stop() + { + WPEFramework::Core::WorkerPool::Stop(); + } + + void Run() + { + WPEFramework::Core::WorkerPool::Run(); + } + + private: + class Dispatcher : public WPEFramework::Core::ThreadPool::IDispatcher { + public: + Dispatcher(const Dispatcher&) = delete; + Dispatcher& operator=(const Dispatcher&) = delete; + + Dispatcher() = default; + ~Dispatcher() override = default; + + private: + void Initialize() override { } + void Deinitialize() override { } + void Dispatch(WPEFramework::Core::IDispatch* job) override + { job->Dispatch(); } + }; + + Dispatcher _dispatcher; + }; + + class Worker : public WPEFramework::Core::IDispatch { + public: + typedef std::function Dispatcher; + + protected: + Worker(const Dispatcher& dispatcher, const void* userData) + : _dispatcher(dispatcher) + , _userData(userData) + { + } + + public: + Worker() = delete; + Worker(const Worker&) = delete; + Worker& operator=(const Worker&) = delete; + + ~Worker() = default; + + public: + static WPEFramework::Core::ProxyType Create(const Dispatcher& dispatcher, const void* userData); + + void Dispatch() override + { + _dispatcher(_userData); + } + + private: + Dispatcher _dispatcher; + const void* _userData; + }; +} diff --git a/languages/c-structs/templates/sdk/src/CMakeLists.txt b/languages/c-structs/templates/sdk/src/CMakeLists.txt new file mode 100644 index 00000000..2f00bdf1 --- /dev/null +++ b/languages/c-structs/templates/sdk/src/CMakeLists.txt @@ -0,0 +1,84 @@ +# 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 + +cmake_minimum_required(VERSION 3.3) + +project(FireboltSDK) +project_version(1.0.0) +set(TARGET ${PROJECT_NAME}) +message("Setup ${TARGET} v${PROJECT_VERSION}") +file(GLOB GENERATED_SOURCES "${GENERATED_CODE_PATH}/src/*.cpp") + +file(GLOB SOURCES *.cpp) +add_library(${TARGET} ${FIREBOLT_LIBRARY_TYPE} + ${SOURCES} + Logger/Logger.cpp + Transport/Transport.cpp + Accessor/Accessor.cpp + Event/Event.cpp +) + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +find_package(${NAMESPACE}WebSocket CONFIG REQUIRED) + +target_link_libraries(${TARGET} + PUBLIC + ${NAMESPACE}WebSocket::${NAMESPACE}WebSocket +) + +target_include_directories(${TARGET} + PRIVATE + $ + $ + $ + $ +) + +set_target_properties(${TARGET} PROPERTIES + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED YES + FRAMEWORK FALSE + LINK_WHAT_YOU_USE TRUE + VERSION ${PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} +) + +install( + TARGETS ${TARGET} EXPORT ${TARGET}Targets + LIBRARY DESTINATION lib COMPONENT libs + PUBLIC_HEADER DESTINATION include/${TARGET} COMPONENT devel # headers for mac (note the different component -> different package) + INCLUDES DESTINATION include/${TARGET} # headers +) + +InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION ${FIREBOLT_NAMESPACE}SDK) +InstallHeaders(TARGET ${TARGET} EXCLUDE_ROOT_DIR HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} + SOURCE ${GENERATED_CODE_PATH}/include DESTINATION ${FIREBOLT_NAMESPACE}/generated) +InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} + SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../include DESTINATION ${FIREBOLT_NAMESPACE}) + +InstallLibraries(TARGET ${TARGET} ${FIREBOLT_LIBRARY_TYPE} LIBDIR ${LIBDIR} LIBRARIES ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallCMakeConfig(TARGETS ${TARGET}) +InstallPackageConfig(TARGETS ${TARGET} DESCRIPTION "Firebolt SDK Library") +InstallCMakeConfigs(TARGET ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) + +add_custom_command( + TARGET ${TARGET} + POST_BUILD + COMMENT "=================== Installing FireboltConfig & Helper CMakes ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/cmake/*.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} +) diff --git a/languages/c-structs/templates/sdk/src/Event/Event.cpp b/languages/c-structs/templates/sdk/src/Event/Event.cpp new file mode 100644 index 00000000..5e98a36f --- /dev/null +++ b/languages/c-structs/templates/sdk/src/Event/Event.cpp @@ -0,0 +1,147 @@ +/* + * 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 "Transport/Transport.h" +#include "Event.h" + +namespace FireboltSDK { + Event* Event::_singleton = nullptr; + Event::Event() + : _eventMap() + , _adminLock() + , _transport(nullptr) + { + ASSERT(_singleton == nullptr); + _singleton = this; + } + + Event::~Event() /* override */ + { + _transport->SetEventHandler(nullptr); + _transport = nullptr; + + _singleton = nullptr; + } + + /* static */ Event& Event::Instance() + { + static Event *instance = new Event(); + ASSERT(instance != nullptr); + return *instance; + } + + /* static */ void Event::Dispose() + { + ASSERT(_singleton != nullptr); + + if (_singleton != nullptr) { + delete _singleton; + } + } + + void Event::Configure(Transport* transport) + { + _transport = transport; + _transport->SetEventHandler(this); + } + + uint32_t Event::Unsubscribe(const string& eventName, void* usercb) + { + uint32_t status = Revoke(eventName, usercb); + + if (status == FireboltSDKErrorNone) { + if (_transport != nullptr) { + + const string parameters("{\"listen\":false}"); + status = _transport->Unsubscribe(eventName, parameters); + } + } + return ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone: status); + } + + uint32_t Event::ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) /* override */ + { + uint32_t result = FireboltSDKErrorGeneral; + Response response; + _transport->FromMessage((WPEFramework::Core::JSON::IElement*)&response, *jsonResponse); + if (response.Listening.IsSet() == true) { + result = FireboltSDKErrorNone; + enabled = response.Listening.Value(); + } + return result; + } + + uint32_t Event::Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) /* override */ + { + string response = jsonResponse->Result.Value(); + _adminLock.Lock(); + EventMap::iterator eventIndex = _eventMap.find(eventName); + if (eventIndex != _eventMap.end()) { + CallbackMap::iterator callbackIndex = eventIndex->second.begin(); + while(callbackIndex != eventIndex->second.end()) { + State state; + if (callbackIndex->second.state != State::REVOKED) { + callbackIndex->second.state = State::EXECUTING; + } + state = callbackIndex->second.state; + _adminLock.Unlock(); + if (state == State::EXECUTING) { + callbackIndex->second.lambda(callbackIndex->first, callbackIndex->second.userdata, (jsonResponse->Result.Value())); + } + _adminLock.Lock(); + if (callbackIndex->second.state == State::REVOKED) { + callbackIndex = eventIndex->second.erase(callbackIndex); + if (eventIndex->second.size() == 0) { + _eventMap.erase(eventIndex); + } + } else { + callbackIndex->second.state = State::IDLE; + callbackIndex++; + } + } + } + _adminLock.Unlock(); + + return FireboltSDKErrorNone;; + } + + uint32_t Event::Revoke(const string& eventName, void* usercb) + { + uint32_t status = FireboltSDKErrorNone; + _adminLock.Lock(); + EventMap::iterator eventIndex = _eventMap.find(eventName); + if (eventIndex != _eventMap.end()) { + CallbackMap::iterator callbackIndex = eventIndex->second.find(usercb); + if (callbackIndex->second.state != State::EXECUTING) { + if (callbackIndex != eventIndex->second.end()) { + eventIndex->second.erase(callbackIndex); + } + } else { + callbackIndex->second.state = State::REVOKED; + } + if (eventIndex->second.size() == 0) { + _eventMap.erase(eventIndex); + } else { + status = FireboltSDKErrorInUse; + } + } + _adminLock.Unlock(); + + return status; + } +} diff --git a/languages/c-structs/templates/sdk/src/Event/Event.h b/languages/c-structs/templates/sdk/src/Event/Event.h new file mode 100644 index 00000000..efa8457a --- /dev/null +++ b/languages/c-structs/templates/sdk/src/Event/Event.h @@ -0,0 +1,165 @@ +/* + * 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 "Module.h" + +namespace FireboltSDK { + + static constexpr uint32_t DefaultWaitTime = 1000; + + class Event : public IEventHandler { + public: + typedef std::function DispatchFunction; + private: + enum State : uint8_t { + IDLE, + EXECUTING, + REVOKED + }; + + struct CallbackData { + const DispatchFunction lambda; + const void* userdata; + State state; + }; + using CallbackMap = std::map; + using EventMap = std::map; + + class Response : public WPEFramework::Core::JSON::Container { + public: + Response& operator=(const Response&) = delete; + Response() + : WPEFramework::Core::JSON::Container() + , Listening(false) + { + Add(_T("listening"), &Listening); + } + Response(const Response& copy) + : WPEFramework::Core::JSON::Container() + , Listening(copy.Listening) + { + Add(_T("listening"), &Listening); + } + ~Response() override = default; + + public: + WPEFramework::Core::JSON::Boolean Listening; + }; + + private: + Event(); + public: + ~Event() override; + static Event& Instance(); + static void Dispose(); + void Configure(Transport* transport); + + public: + template + uint32_t Subscribe(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) + { + JsonObject jsonParameters; + return Subscribe(eventName, jsonParameters, callback, usercb, userdata); + } + + template + uint32_t Subscribe(const string& eventName, JsonObject& jsonParameters, const CALLBACK& callback, void* usercb, const void* userdata) + { + uint32_t status = FireboltSDKErrorUnavailable; + if (_transport != nullptr) { + + status = Assign(eventName, callback, usercb, userdata); + if (status == FireboltSDKErrorNone) { + Response response; + + WPEFramework::Core::JSON::Variant Listen = true; + jsonParameters.Set(_T("listen"), Listen); + string parameters; + jsonParameters.ToString(parameters); + + status = _transport->Subscribe(eventName, parameters, response); + + if (status != FireboltSDKErrorNone) { + Revoke(eventName, usercb); + } else if ((response.Listening.IsSet() == true) && + (response.Listening.Value() == true)) { + status = FireboltSDKErrorNone; + } else { + status = FireboltSDKErrorNotSubscribed; + } + } + } + + return status; + } + + uint32_t Unsubscribe(const string& eventName, void* usercb); + + private: + template + uint32_t Assign(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) + { + uint32_t status = FireboltSDKErrorNone; + std::function actualCallback = callback; + DispatchFunction implementation = [actualCallback](void* usercb, const void* userdata, const string& parameters) -> uint32_t { + + WPEFramework::Core::ProxyType* inbound = new WPEFramework::Core::ProxyType(); + *inbound = WPEFramework::Core::ProxyType::Create(); + (*inbound)->FromString(parameters); + actualCallback(usercb, userdata, static_cast(inbound)); + return (FireboltSDKErrorNone); + }; + CallbackData callbackData = {implementation, userdata, State::IDLE}; + + _adminLock.Lock(); + EventMap::iterator eventIndex = _eventMap.find(eventName); + if (eventIndex != _eventMap.end()) { + CallbackMap::iterator callbackIndex = eventIndex->second.find(usercb); + if (callbackIndex == eventIndex->second.end()) { + eventIndex->second.emplace(std::piecewise_construct, std::forward_as_tuple(usercb), std::forward_as_tuple(callbackData)); + } else { + // Already registered, no need to register again; + status = FireboltSDKErrorInUse; + } + } else { + + CallbackMap callbackMap; + callbackMap.emplace(std::piecewise_construct, std::forward_as_tuple(usercb), std::forward_as_tuple(callbackData)); + _eventMap.emplace(std::piecewise_construct, std::forward_as_tuple(eventName), std::forward_as_tuple(callbackMap)); + + } + + _adminLock.Unlock(); + return status; + } + uint32_t Revoke(const string& eventName, void* usercb); + + private: + uint32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) override; + uint32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) override; + + private: + EventMap _eventMap; + WPEFramework::Core::CriticalSection _adminLock; + Transport* _transport; + + static Event* _singleton; + }; +} diff --git a/languages/c-structs/templates/sdk/src/Firebolt.cpp b/languages/c-structs/templates/sdk/src/Firebolt.cpp new file mode 100644 index 00000000..ffc1369a --- /dev/null +++ b/languages/c-structs/templates/sdk/src/Firebolt.cpp @@ -0,0 +1,40 @@ +/* + * 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" + + +#ifdef __cplusplus +extern "C" { +#endif + + + +uint32_t FireboltSDK_Initialize(char* configLine) { + FireboltSDK::Accessor::Instance(configLine); + return FireboltSDKErrorNone; +} + +uint32_t FireboltSDK_Deinitialize(void) { + FireboltSDK::Accessor::Dispose(); + return FireboltSDKErrorNone; +} + +#ifdef __cplusplus +} +#endif diff --git a/languages/c-structs/templates/sdk/src/FireboltSDK.conf.in b/languages/c-structs/templates/sdk/src/FireboltSDK.conf.in new file mode 100644 index 00000000..6964a7bc --- /dev/null +++ b/languages/c-structs/templates/sdk/src/FireboltSDK.conf.in @@ -0,0 +1,3 @@ +url = "@FIREBOLT_SERVER_URL@" +waittime = "@FIREBOLT_TRANSPORT_WAITTIME@" +loglevel = "@FIREBOLT_LOGLEVEL@" diff --git a/languages/c-structs/templates/sdk/src/FireboltSDK.h b/languages/c-structs/templates/sdk/src/FireboltSDK.h new file mode 100644 index 00000000..19946126 --- /dev/null +++ b/languages/c-structs/templates/sdk/src/FireboltSDK.h @@ -0,0 +1,26 @@ +/* + * 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 "Transport/Transport.h" +#include "Properties/Properties.h" +#include "Accessor/Accessor.h" +#include "Logger/Logger.h" +#include "TypesPriv.h" +#include "Types.h" diff --git a/languages/c-structs/templates/sdk/src/Logger/Logger.cpp b/languages/c-structs/templates/sdk/src/Logger/Logger.cpp new file mode 100644 index 00000000..0e49dfce --- /dev/null +++ b/languages/c-structs/templates/sdk/src/Logger/Logger.cpp @@ -0,0 +1,83 @@ +/* + * 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 "Module.h" +#include "Error.h" +#include "Logger.h" + +namespace WPEFramework { + +ENUM_CONVERSION_BEGIN(FireboltSDK::Logger::LogLevel) + + { FireboltSDK::Logger::LogLevel::Error, _TXT("Error") }, + { FireboltSDK::Logger::LogLevel::Warning, _TXT("Warning") }, + { FireboltSDK::Logger::LogLevel::Info, _TXT("Info") }, + { FireboltSDK::Logger::LogLevel::Debug, _TXT("Debug") }, + +ENUM_CONVERSION_END(FireboltSDK::Logger::LogLevel) + +ENUM_CONVERSION_BEGIN(FireboltSDK::Logger::Category) + + { FireboltSDK::Logger::Category::OpenRPC, _TXT("FireboltSDK::OpenRPC") }, + { FireboltSDK::Logger::Category::Core, _TXT("FireboltSDK::Core") }, + { FireboltSDK::Logger::Category::Management, _TXT("FireboltSDK::Management") }, + { FireboltSDK::Logger::Category::Discovery, _TXT("FireboltSDK::Discovery") }, + +ENUM_CONVERSION_END(FireboltSDK::Logger::Category) + +} + +namespace FireboltSDK { + /* static */ Logger::LogLevel Logger::_logLevel = Logger::LogLevel::Error; + + uint32_t Logger::SetLogLevel(Logger::LogLevel logLevel) + { + ASSERT(logLevel < Logger::LogLevel::MaxLevel); + uint32_t status = FireboltSDKErrorNotSupported; + if (logLevel < Logger::LogLevel::MaxLevel) { + _logLevel = logLevel; + status = FireboltSDKErrorNone; + } + return status; + } + + void Logger::Log(LogLevel logLevel, Category category, const std::string& module, const std::string file, const std::string function, const uint16_t line, const std::string& format, ...) + { + if (logLevel <= _logLevel) { + va_list arg; + char msg[Logger::MaxBufSize]; + va_start(arg, format); + int length = vsnprintf(msg, Logger::MaxBufSize, format.c_str(), arg); + va_end(arg); + + uint32_t position = (length >= Logger::MaxBufSize) ? (Logger::MaxBufSize - 1) : length; + msg[position] = '\0'; + + char formattedMsg[Logger::MaxBufSize]; + const string time = WPEFramework::Core::Time::Now().ToTimeOnly(true); + const string categoryName = WPEFramework::Core::EnumerateType(category).Data(); + if (categoryName.empty() != true) { + sprintf(formattedMsg, "--->\033[1;32m[%s]:[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), categoryName.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); + } else { + sprintf(formattedMsg, "--->\033[1;32m[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); + } + LOG_MESSAGE(formattedMsg); + } + } +} + diff --git a/languages/c-structs/templates/sdk/src/Logger/Logger.h b/languages/c-structs/templates/sdk/src/Logger/Logger.h new file mode 100644 index 00000000..cffeff54 --- /dev/null +++ b/languages/c-structs/templates/sdk/src/Logger/Logger.h @@ -0,0 +1,85 @@ +/* + * 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 "Types.h" + +namespace FireboltSDK { + + class Logger { + private: + static constexpr uint16_t MaxBufSize = 512; + + public: + enum class LogLevel : uint8_t { + Error, + Warning, + Info, + Debug, + MaxLevel + }; + + enum class Category : uint8_t { + OpenRPC, + Core, + Management, + Discovery + }; + + public: + Logger() = default; + Logger(const Logger&) = delete; + Logger& operator=(const Logger&) = delete; + ~Logger() = default; + + public: + static uint32_t SetLogLevel(LogLevel logLevel); + static void Log(LogLevel logLevel, Category category, const std::string& module, const std::string file, const std::string function, const uint16_t line, const std::string& format, ...); + + public: + template + static const string Module() + { + return WPEFramework::Core::ClassNameOnly(typeid(CLASS).name()).Text(); + } + + private: + static LogLevel _logLevel; + }; +} + +#define FIREBOLT_LOG(level, category, module, ...) \ + FireboltSDK::Logger::Log(level, category, module, __FILE__, __func__, __LINE__, __VA_ARGS__) + +#define FIREBOLT_LOG_ERROR(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Error, category, module, __VA_ARGS__) +#define FIREBOLT_LOG_WARNING(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Warning, category, module, __VA_ARGS__) +#define FIREBOLT_LOG_INFO(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Info, category, module, __VA_ARGS__) +#define FIREBOLT_LOG_DEBUG(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Debug, category, module, __VA_ARGS__) + +#ifdef ENABLE_SYSLOG +#define LOG_MESSAGE(message) \ + syslog(sLOG_NOTIC, "%s", message); +#else +#define LOG_MESSAGE(message) \ + fprintf(stderr, "%s", message); fflush(stdout); +#endif diff --git a/languages/c-structs/templates/sdk/src/Module.cpp b/languages/c-structs/templates/sdk/src/Module.cpp new file mode 100644 index 00000000..d63badc4 --- /dev/null +++ b/languages/c-structs/templates/sdk/src/Module.cpp @@ -0,0 +1,21 @@ +/* + * 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 "Module.h" + +MODULE_NAME_DECLARATION(BUILD_REFERENCE) diff --git a/languages/c-structs/templates/sdk/src/Module.h b/languages/c-structs/templates/sdk/src/Module.h new file mode 100644 index 00000000..00ea64bb --- /dev/null +++ b/languages/c-structs/templates/sdk/src/Module.h @@ -0,0 +1,29 @@ +/* + * 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 + +#ifndef MODULE_NAME +#define MODULE_NAME OpenRPCNativeSDK +#endif + +#include +#include + +#undef EXTERNAL +#define EXTERNAL diff --git a/languages/c-structs/templates/sdk/src/Properties/Properties.h b/languages/c-structs/templates/sdk/src/Properties/Properties.h new file mode 100644 index 00000000..d75c3ba5 --- /dev/null +++ b/languages/c-structs/templates/sdk/src/Properties/Properties.h @@ -0,0 +1,148 @@ +/* + * 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 "Accessor/Accessor.h" +#include "Event/Event.h" + +namespace FireboltSDK { + + class Properties { + public: + Properties(const Properties&) = delete; + Properties& operator= (const Properties&) = delete; + + Properties() = default; + ~Properties() = default; + + public: + template + static uint32_t Get(const string& propertyName, WPEFramework::Core::ProxyType& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject parameters; + RESPONSETYPE responseType; + status = transport->Invoke(propertyName, parameters, responseType); + if (status == FireboltSDKErrorNone) { + ASSERT(response.IsValid() == false); + if (response.IsValid() == true) { + response.Release(); + } + response = WPEFramework::Core::ProxyType::Create(); + (*response) = responseType; + } + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static uint32_t Get(const string& propertyName, const PARAMETERS& parameters, WPEFramework::Core::ProxyType& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + RESPONSETYPE responseType; + status = transport->Invoke(propertyName, parameters, responseType); + if (status == FireboltSDKErrorNone) { + ASSERT(response.IsValid() == false); + if (response.IsValid() == true) { + response.Release(); + } + response = WPEFramework::Core::ProxyType::Create(); + (*response) = responseType; + } + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + + template + static uint32_t Get(const string& propertyName, RESPONSETYPE& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject parameters; + status = transport->Invoke(propertyName, parameters, response); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static uint32_t Get(const string& propertyName, const PARAMETERS& parameters, RESPONSETYPE& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + status = transport->Invoke(propertyName, parameters, response); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static uint32_t Set(const string& propertyName, const PARAMETERS& parameters) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject responseType; + status = transport->Invoke(propertyName, parameters, responseType); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static uint32_t Subscribe(const string& propertyName, JsonObject& paramsters, const CALLBACK& callback, void* usercb, const void* userdata) + { + return Event::Instance().Subscribe(EventName(propertyName), paramsters, callback, usercb, userdata); + } + + static uint32_t Unsubscribe(const string& propertyName, void* usercb) + { + return Event::Instance().Unsubscribe(EventName(propertyName), usercb); + } + private: + static inline string EventName(const string& propertyName) { + size_t pos = propertyName.find_first_of('.'); + string eventName = propertyName; + if (pos != std::string::npos) { + eventName[pos + 1] = std::toupper(eventName[pos + 1]); + eventName = string(eventName.substr(0, pos + 1) + "on" + eventName.substr(pos + 1) + "Changed"); + } + return eventName; + } + }; +} diff --git a/languages/c-structs/templates/sdk/src/Transport/Transport.cpp b/languages/c-structs/templates/sdk/src/Transport/Transport.cpp new file mode 100644 index 00000000..280944c6 --- /dev/null +++ b/languages/c-structs/templates/sdk/src/Transport/Transport.cpp @@ -0,0 +1,24 @@ +/* + * 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 "Transport.h" + +namespace FireboltSDK { + +} + diff --git a/languages/c-structs/templates/sdk/src/Transport/Transport.h b/languages/c-structs/templates/sdk/src/Transport/Transport.h new file mode 100644 index 00000000..2aff350d --- /dev/null +++ b/languages/c-structs/templates/sdk/src/Transport/Transport.h @@ -0,0 +1,897 @@ +/* + * 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 "Module.h" +#include "Error.h" + +namespace FireboltSDK { + + using namespace WPEFramework::Core::TypeTraits; + + template + class CommunicationChannel { + public: + typedef std::function Callback; + class Entry { + private: + Entry(const Entry&) = delete; + Entry& operator=(const Entry& rhs) = delete; + struct Synchronous { + Synchronous() + : _signal(false, true) + , _response() + { + } + WPEFramework::Core::Event _signal; + std::list> _response; + }; + struct ASynchronous { + ASynchronous(const uint32_t waitTime, const Callback& completed) + : _waitTime(WPEFramework::Core::Time::Now().Add(waitTime).Ticks()) + , _completed(completed) + { + } + uint64_t _waitTime; + Callback _completed; + }; + + public: + Entry() + : _synchronous(true) + , _info() + { + } + Entry(const uint32_t waitTime, const Callback& completed) + : _synchronous(false) + , _info(waitTime, completed) + { + } + ~Entry() + { + if (_synchronous == true) { + _info.sync.~Synchronous(); + } + else { + _info.async.~ASynchronous(); + } + } + + public: + const WPEFramework::Core::ProxyType& Response() const + { + return (*(_info.sync._response.begin())); + } + bool Signal(const WPEFramework::Core::ProxyType& response) + { + if (_synchronous == true) { + _info.sync._response.push_back(response); + _info.sync._signal.SetEvent(); + } + else { + _info.async._completed(*response); + } + + return (_synchronous == false); + } + const uint64_t& Expiry() const + { + return (_info.async._waitTime); + } + void Abort(const uint32_t id) + { + if (_synchronous == true) { + _info.sync._signal.SetEvent(); + } + else { + MESSAGETYPE message; + ToMessage(id, message, WPEFramework::Core::ERROR_ASYNC_ABORTED); + _info.async._completed(message); + } + } + bool Expired(const uint32_t id, const uint64_t& currentTime, uint64_t& nextTime) + { + bool expired = false; + + if (_synchronous == false) { + if (_info.async._waitTime > currentTime) { + if (_info.async._waitTime < nextTime) { + nextTime = _info.async._waitTime; + } + } + else { + MESSAGETYPE message; + ToMessage(id, message, WPEFramework::Core::ERROR_TIMEDOUT); + _info.async._completed(message); + expired = true; + } + } + return (expired); + } + bool WaitForResponse(const uint32_t waitTime) + { + return (_info.sync._signal.Lock(waitTime) == WPEFramework::Core::ERROR_NONE); + } + + private: + void ToMessage(const uint32_t id, WPEFramework::Core::JSONRPC::Message& message, uint32_t error) + { + message.Id = id; + message.Error.Code = error; + switch (error) { + case WPEFramework::Core::ERROR_ASYNC_ABORTED: { + message.Error.Text = _T("Pending a-sync call has been aborted"); + break; + } + case WPEFramework::Core::ERROR_TIMEDOUT: { + message.Error.Text = _T("Pending a-sync call has timed out"); + break; + } + } + } + + bool _synchronous; + union Info { + public: + Info() + : sync() + { + } + Info(const uint32_t waitTime, const Callback& completed) + : async(waitTime, completed) + { + } + ~Info() + { + } + Synchronous sync; + ASynchronous async; + } _info; + }; + + + + private: + class FactoryImpl { + private: + FactoryImpl(const FactoryImpl&) = delete; + FactoryImpl& operator=(const FactoryImpl&) = delete; + + class WatchDog { + private: + WatchDog() = delete; + WatchDog& operator=(const WatchDog&) = delete; + + public: + WatchDog(CLIENT* client) + : _client(client) + { + } + WatchDog(const WatchDog& copy) + : _client(copy._client) + { + } + ~WatchDog() + { + } + + bool operator==(const WatchDog& rhs) const + { + return (rhs._client == _client); + } + bool operator!=(const WatchDog& rhs) const + { + return (!operator==(rhs)); + } + + public: + uint64_t Timed(const uint64_t scheduledTime) { + return (_client->Timed()); + } + + private: + CLIENT* _client; + }; + + friend WPEFramework::Core::SingletonType; + + FactoryImpl() + : _messageFactory(2) + , _watchDog(WPEFramework::Core::Thread::DefaultStackSize(), _T("TransportCleaner")) + { + } + + public: + static FactoryImpl& Instance() + { + return (WPEFramework::Core::SingletonType::Instance()); + } + + ~FactoryImpl() + { + } + + public: + WPEFramework::Core::ProxyType Element(const string&) + { + return (_messageFactory.Element()); + } + void Trigger(const uint64_t& time, CLIENT* client) + { + _watchDog.Trigger(time, client); + } + void Revoke(CLIENT* client) + { + _watchDog.Revoke(client); + } + private: + WPEFramework::Core::ProxyPoolType _messageFactory; + WPEFramework::Core::TimerType _watchDog; + }; + + class ChannelImpl : public WPEFramework::Core::StreamJSONType, FactoryImpl&, INTERFACE> { + private: + ChannelImpl(const ChannelImpl&) = delete; + ChannelImpl& operator=(const ChannelImpl&) = delete; + + typedef WPEFramework::Core::StreamJSONType, FactoryImpl&, INTERFACE> BaseClass; + + public: + ChannelImpl(CommunicationChannel* parent, const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask) + : BaseClass(5, FactoryImpl::Instance(), path, _T("JSON"), query, "", false, mask, false, remoteNode.AnyInterface(), remoteNode, 1024 * 2, 1024 * 2) //TODO Relook this size issue + , _parent(*parent) + { + } + ~ChannelImpl() override = default; + + public: + void Received(WPEFramework::Core::ProxyType& response) override + { + WPEFramework::Core::ProxyType inbound(response); + + ASSERT(inbound.IsValid() == true); + if (inbound.IsValid() == true) { + _parent.Inbound(inbound); + } + } + void Send(WPEFramework::Core::ProxyType& msg) override + { +#ifdef __DEBUG__ + string message; + ToMessage(msg, message); + TRACE_L1("Message: %s send", message.c_str()); +#endif + } + void StateChange() override + { + _parent.StateChange(); + } + bool IsIdle() const override + { + return (true); + } + + private: + void ToMessage(const WPEFramework::Core::ProxyType& jsonObject, string& message) const + { + WPEFramework::Core::ProxyType inbound(jsonObject); + + ASSERT(inbound.IsValid() == true); + if (inbound.IsValid() == true) { + inbound->ToString(message); + } + } + void ToMessage(const WPEFramework::Core::ProxyType& jsonObject, string& message) const + { + WPEFramework::Core::ProxyType inbound(jsonObject); + + ASSERT(inbound.IsValid() == true); + if (inbound.IsValid() == true) { + std::vector values; + inbound->ToBuffer(values); + if (values.empty() != true) { + WPEFramework::Core::ToString(values.data(), static_cast(values.size()), false, message); + } + } + } + + private: + CommunicationChannel& _parent; + }; + + protected: + CommunicationChannel(const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask) + : _channel(this, remoteNode, path, query, mask) + , _sequence(0) + { + } + + public: + ~CommunicationChannel() = default; + static WPEFramework::Core::ProxyType Instance(const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask = true) + { + static WPEFramework::Core::ProxyMapType channelMap; + + string searchLine = remoteNode.HostAddress() + '@' + path; + + return (channelMap.template Instance(searchLine, remoteNode, path, query, mask)); + } + + public: + static void Trigger(const uint64_t& time, CLIENT* client) + { + FactoryImpl::Instance().Trigger(time, client); + } + static WPEFramework::Core::ProxyType Message() + { + return (FactoryImpl::Instance().Element(string())); + } + uint32_t Sequence() const + { + return (++_sequence); + } + void Register(CLIENT& client) + { + _adminLock.Lock(); + ASSERT(std::find(_observers.begin(), _observers.end(), &client) == _observers.end()); + _observers.push_back(&client); + if (_channel.IsOpen() == true) { + client.Opened(); + } + _adminLock.Unlock(); + } + void Unregister(CLIENT& client) + { + _adminLock.Lock(); + typename std::list::iterator index(std::find(_observers.begin(), _observers.end(), &client)); + if (index != _observers.end()) { + _observers.erase(index); + } + FactoryImpl::Instance().Revoke(&client); + _adminLock.Unlock(); + } + + void Submit(const WPEFramework::Core::ProxyType& message) + { + _channel.Submit(message); + } + bool IsSuspended() const + { + return (_channel.IsSuspended()); + } + uint32_t Initialize() + { + return (Open(0)); + } + void Deinitialize() + { + Close(); + } + bool IsOpen() + { + return (_channel.IsOpen() == true); + } + + protected: + void StateChange() + { + _adminLock.Lock(); + typename std::list::iterator index(_observers.begin()); + while (index != _observers.end()) { + if (_channel.IsOpen() == true) { + (*index)->Opened(); + } + else { + (*index)->Closed(); + } + index++; + } + _adminLock.Unlock(); + } + bool Open(const uint32_t waitTime) + { + bool result = true; + if (_channel.IsClosed() == true) { + result = (_channel.Open(waitTime) == WPEFramework::Core::ERROR_NONE); + } + return (result); + } + void Close() + { + _channel.Close(WPEFramework::Core::infinite); + } + + private: + uint32_t Inbound(const WPEFramework::Core::ProxyType& inbound) + { + uint32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + _adminLock.Lock(); + typename std::list::iterator index(_observers.begin()); + while ((result != WPEFramework::Core::ERROR_NONE) && (index != _observers.end())) { + result = (*index)->Submit(inbound); + index++; + } + _adminLock.Unlock(); + + return (result); + } + + private: + WPEFramework::Core::CriticalSection _adminLock; + ChannelImpl _channel; + mutable std::atomic _sequence; + std::list _observers; + }; + + class IEventHandler { + public: + virtual uint32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) = 0; + virtual uint32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) = 0; + virtual ~IEventHandler() = default; + }; + + template + class Transport { + private: + using Channel = CommunicationChannel; + using Entry = typename CommunicationChannel::Entry; + using PendingMap = std::unordered_map; + using EventMap = std::map; + typedef std::function& jsonResponse, bool& enabled)> EventResponseValidatioionFunction; + + class Job : public WPEFramework::Core::IDispatch { + protected: + Job(const WPEFramework::Core::ProxyType& inbound, class Transport* parent) + : _inbound(inbound) + , _parent(parent) + { + } + + public: + Job() = delete; + Job(const Job&) = delete; + Job& operator=(const Job&) = delete; + + ~Job() = default; + + public: + static WPEFramework::Core::ProxyType Create(const WPEFramework::Core::ProxyType& inbound, class Transport* parent); + + void Dispatch() override + { + _parent->Inbound(_inbound); + } + + private: + const WPEFramework::Core::ProxyType _inbound; + class Transport* _parent; + }; + + protected: + static constexpr uint32_t DefaultWaitTime = 10000; + + inline void Announce() { + _channel->Register(*this); + } + + private: + static constexpr const TCHAR* PathPrefix = _T("/"); + public: + Transport() = delete; + Transport(const Transport&) = delete; + Transport& operator=(Transport&) = delete; + Transport(const WPEFramework::Core::URL& url, const uint32_t waitTime) + : _adminLock() + , _connectId(WPEFramework::Core::NodeId(url.Host().Value().c_str(), url.Port().Value())) + , _channel(Channel::Instance(_connectId, ((url.Path().Value().rfind(PathPrefix, 0) == 0) ? url.Path().Value() : string(PathPrefix + url.Path().Value())), url.Query().Value(), true)) + , _eventHandler(nullptr) + , _pendingQueue() + , _scheduledTime(0) + , _waitTime(waitTime) + { + _channel->Register(*this); + } + + virtual ~Transport() + { + _channel->Unregister(*this); + + for (auto& element : _pendingQueue) { + element.second.Abort(element.first); + } + } + + public: + inline bool IsOpen() + { + return _channel->IsOpen(); + } + + void Revoke(const string& eventName) + { + _adminLock.Lock(); + _eventMap.erase(eventName); + _adminLock.Unlock(); + } + + void SetEventHandler(IEventHandler* eventHandler) + { + _eventHandler = eventHandler; + } + + template + uint32_t Invoke(const string& method, const PARAMETERS& parameters, RESPONSE& response) + { + Entry slot; + uint32_t id = _channel->Sequence(); + uint32_t result = Send(method, parameters, id); + if (result == WPEFramework::Core::ERROR_NONE) { + result = WaitForResponse(id, response, _waitTime); + } + + return (FireboltErrorValue(result)); + } + + template + uint32_t Subscribe(const string& eventName, const string& parameters, RESPONSE& response) + { + Entry slot; + uint32_t id = _channel->Sequence(); + uint32_t result = Send(eventName, parameters, id); + if (result == WPEFramework::Core::ERROR_NONE) { + _adminLock.Lock(); + _eventMap.emplace(std::piecewise_construct, + std::forward_as_tuple(eventName), + std::forward_as_tuple(~0)); + _adminLock.Unlock(); + + result = WaitForEventResponse(id, eventName, response, _waitTime); + } + + return (FireboltErrorValue(result)); + } + + uint32_t Unsubscribe(const string& eventName, const string& parameters) + { + Revoke(eventName); + Entry slot; + uint32_t id = _channel->Sequence(); + uint32_t result = Send(eventName, parameters, id); + + return (FireboltErrorValue(result)); + } + + private: + friend Channel; + inline bool IsEvent(const uint32_t id, string& eventName) + { + _adminLock.Lock(); + for (auto& event : _eventMap) { + if (event.second == id) { + eventName = event.first; + break; + } + } + _adminLock.Unlock(); + return (eventName.empty() != true); + } + uint64_t Timed() + { + uint64_t result = ~0; + uint64_t currentTime = WPEFramework::Core::Time::Now().Ticks(); + + // Lets see if some callback are expire. If so trigger and remove... + _adminLock.Lock(); + + typename PendingMap::iterator index = _pendingQueue.begin(); + + while (index != _pendingQueue.end()) { + + if (index->second.Expired(index->first, currentTime, result) == true) { + index = _pendingQueue.erase(index); + } + else { + index++; + } + } + _scheduledTime = (result != static_cast(~0) ? result : 0); + + _adminLock.Unlock(); + + return (_scheduledTime); + } + + virtual void Opened() + { + // Nice to know :-) + } + + void Closed() + { + // Abort any in progress RPC command: + _adminLock.Lock(); + + // See if we issued anything, if so abort it.. + while (_pendingQueue.size() != 0) { + + _pendingQueue.begin()->second.Abort(_pendingQueue.begin()->first); + _pendingQueue.erase(_pendingQueue.begin()); + } + + _adminLock.Unlock(); + } + + uint32_t Submit(const WPEFramework::Core::ProxyType& inbound) + { + uint32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(inbound, this)); + WPEFramework::Core::IWorkerPool::Instance().Submit(job); + return result; + } + + uint32_t Inbound(const WPEFramework::Core::ProxyType& inbound) + { + uint32_t result = WPEFramework::Core::ERROR_INVALID_SIGNATURE; + + ASSERT(inbound.IsValid() == true); + + if ((inbound->Id.IsSet() == true) && (inbound->Result.IsSet() || inbound->Error.IsSet())) { + // Looks like this is a response.. + ASSERT(inbound->Parameters.IsSet() == false); + ASSERT(inbound->Designator.IsSet() == false); + + _adminLock.Lock(); + + // See if we issued this.. + typename PendingMap::iterator index = _pendingQueue.find(inbound->Id.Value()); + + if (index != _pendingQueue.end()) { + + if (index->second.Signal(inbound) == true) { + _pendingQueue.erase(index); + } + + result = WPEFramework::Core::ERROR_NONE; + } else { + + string eventName; + if (IsEvent(inbound->Id.Value(), eventName)) { + _eventHandler->Dispatch(eventName, inbound); + } + + } + _adminLock.Unlock(); + } + + return (result); + } + + + template + uint32_t Send(const string& method, const PARAMETERS& parameters, const uint32_t& id) + { + uint32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + + if ((_channel.IsValid() == true) && (_channel->IsSuspended() == true)) { + result = WPEFramework::Core::ERROR_ASYNC_FAILED; + } + else if (_channel.IsValid() == true) { + + result = WPEFramework::Core::ERROR_ASYNC_FAILED; + + WPEFramework::Core::ProxyType message(Channel::Message()); + message->Id = id; + message->Designator = method; + ToMessage(parameters, message); + + _adminLock.Lock(); + + typename std::pair< typename PendingMap::iterator, bool> newElement = + _pendingQueue.emplace(std::piecewise_construct, + std::forward_as_tuple(id), + std::forward_as_tuple()); + ASSERT(newElement.second == true); + + if (newElement.second == true) { + + _adminLock.Unlock(); + + _channel->Submit(WPEFramework::Core::ProxyType(message)); + + message.Release(); + result = WPEFramework::Core::ERROR_NONE; + } + } + return result; + } + + template + uint32_t WaitForResponse(const uint32_t& id, RESPONSE& response, const uint32_t waitTime) + { + uint32_t result = WPEFramework::Core::ERROR_TIMEDOUT; + _adminLock.Lock(); + typename PendingMap::iterator index = _pendingQueue.find(id); + Entry& slot(index->second); + _adminLock.Unlock(); + + if (slot.WaitForResponse(waitTime) == true) { + WPEFramework::Core::ProxyType jsonResponse = slot.Response(); + + // See if we have a jsonResponse, maybe it was just the connection + // that closed? + if (jsonResponse.IsValid() == true) { + if (jsonResponse->Error.IsSet() == true) { + result = jsonResponse->Error.Code.Value(); + } + else { + result = WPEFramework::Core::ERROR_NONE; + if ((jsonResponse->Result.IsSet() == true) + && (jsonResponse->Result.Value().empty() == false)) { + FromMessage((INTERFACE*)&response, *jsonResponse); + } + } + } + } else { + result = WPEFramework::Core::ERROR_TIMEDOUT; + } + _adminLock.Lock(); + _pendingQueue.erase(id); + _adminLock.Unlock(); + return result; + } + + static constexpr uint32_t WAITSLOT_TIME = 100; + template + uint32_t WaitForEventResponse(const uint32_t& id, const string& eventName, RESPONSE& response, const uint32_t waitTime) + { + uint32_t result = WPEFramework::Core::ERROR_TIMEDOUT; + _adminLock.Lock(); + typename PendingMap::iterator index = _pendingQueue.find(id); + Entry& slot(index->second); + _adminLock.Unlock(); + + uint8_t waiting = waitTime; + do { + uint32_t waitSlot = (waiting > WAITSLOT_TIME ? WAITSLOT_TIME : waiting); + if (slot.WaitForResponse(waitSlot) == true) { + WPEFramework::Core::ProxyType jsonResponse = slot.Response(); + + // See if we have a jsonResponse, maybe it was just the connection + // that closed? + if (jsonResponse.IsValid() == true) { + if (jsonResponse->Error.IsSet() == true) { + result = jsonResponse->Error.Code.Value(); + } else { + if ((jsonResponse->Result.IsSet() == true) + && (jsonResponse->Result.Value().empty() == false)) { + result = WPEFramework::Core::ERROR_NONE; + bool enabled; + result = _eventHandler->ValidateResponse(jsonResponse, enabled); + if (result == WPEFramework::Core::ERROR_NONE) { + FromMessage((INTERFACE*)&response, *jsonResponse); + if (enabled) { + _adminLock.Lock(); + typename EventMap::iterator index = _eventMap.find(eventName); + if (index != _eventMap.end()) { + index->second = id; + } + _adminLock.Unlock(); + } + } + } + } + } + } else { + result = WPEFramework::Core::ERROR_TIMEDOUT; + } + waiting -= (waiting == WPEFramework::Core::infinite ? 0 : waitSlot); + } while ((result != WPEFramework::Core::ERROR_NONE) && (waiting > 0 )); + _adminLock.Lock(); + _pendingQueue.erase(id); + _adminLock.Unlock(); + + return result; + } + + public: + void FromMessage(WPEFramework::Core::JSON::IElement* response, const WPEFramework::Core::JSONRPC::Message& message) const + { + response->FromString(message.Result.Value()); + } + + void FromMessage(WPEFramework::Core::JSON::IMessagePack* response, const WPEFramework::Core::JSONRPC::Message& message) const + { + string value = message.Result.Value(); + std::vector result(value.begin(), value.end()); + response->FromBuffer(result); + } + + + private: + + void ToMessage(const string& parameters, WPEFramework::Core::ProxyType& message) const + { + if (parameters.empty() != true) { + message->Parameters = parameters; + } + } + + template + void ToMessage(PARAMETERS& parameters, WPEFramework::Core::ProxyType& message) const + { + ToMessage((INTERFACE*)(¶meters), message); + return; + } + + void ToMessage(WPEFramework::Core::JSON::IMessagePack* parameters, WPEFramework::Core::ProxyType& message) const + { + std::vector values; + parameters->ToBuffer(values); + if (values.empty() != true) { + string strValues(values.begin(), values.end()); + message->Parameters = strValues; + } + return; + } + + void ToMessage(WPEFramework::Core::JSON::IElement* parameters, WPEFramework::Core::ProxyType& message) const + { + string values; + parameters->ToString(values); + if (values.empty() != true) { + message->Parameters = values; + } + return; + } + + uint32_t FireboltErrorValue(const uint32_t error) + { + + uint32_t fireboltError = FireboltSDKErrorUnknown; + switch (error) { + case WPEFramework::Core::ERROR_NONE: + fireboltError = FireboltSDKErrorNone; + break; + case WPEFramework::Core::ERROR_GENERAL: + fireboltError = FireboltSDKErrorGeneral; + break; + case WPEFramework::Core::ERROR_UNAVAILABLE: + fireboltError = FireboltSDKErrorUnavailable; + break; + case WPEFramework::Core::ERROR_TIMEDOUT: + fireboltError = FireboltSDKErrorTimedout; + break; + default: + break; + } + + return fireboltError; + } + + private: + WPEFramework::Core::CriticalSection _adminLock; + WPEFramework::Core::NodeId _connectId; + WPEFramework::Core::ProxyType _channel; + IEventHandler* _eventHandler; + PendingMap _pendingQueue; + EventMap _eventMap; + uint64_t _scheduledTime; + uint32_t _waitTime; + }; +} diff --git a/languages/c-structs/templates/sdk/src/Types.cpp b/languages/c-structs/templates/sdk/src/Types.cpp new file mode 100644 index 00000000..f19cfe63 --- /dev/null +++ b/languages/c-structs/templates/sdk/src/Types.cpp @@ -0,0 +1,40 @@ +/* + * 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 "Module.h" +#include "Types.h" +#include "TypesPriv.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// String Type Handler Interfaces +const char* FireboltTypes_String(FireboltTypes_StringHandle handle) +{ + return ((static_cast(handle))->Value().c_str()); +} + +void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle) +{ + delete static_cast(handle); +} + +#ifdef __cplusplus +} +#endif diff --git a/languages/c-structs/templates/sdk/src/TypesPriv.h b/languages/c-structs/templates/sdk/src/TypesPriv.h new file mode 100644 index 00000000..6e365ec7 --- /dev/null +++ b/languages/c-structs/templates/sdk/src/TypesPriv.h @@ -0,0 +1,56 @@ +/* + * 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 + +namespace FireboltSDK { +namespace JSON { +class String : public WPEFramework::Core::JSON::String { + using Base = WPEFramework::Core::JSON::String; + public: + String() + : Base() + , _value() + { + } + String(const char value[]) + : Base(value) + , _value(value) + { + } + String& operator=(const char RHS[]) + { + Base::operator = (RHS); + _value = RHS; + return (*this); + } + + public: + const string& Value() const + { + _value = Base::Value(); + return _value; + } + + private: + mutable std::string _value; + }; +} +} diff --git a/languages/c-structs/templates/sdk/test/CMakeLists.txt b/languages/c-structs/templates/sdk/test/CMakeLists.txt new file mode 100644 index 00000000..a56ca20a --- /dev/null +++ b/languages/c-structs/templates/sdk/test/CMakeLists.txt @@ -0,0 +1,86 @@ +# 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 + +cmake_minimum_required(VERSION 3.3) + +project(FireboltSDKTests) +project_version(1.0.0) + +set(TESTLIB ${PROJECT_NAME}) + +message("Setup ${TESTLIB} v${PROJECT_VERSION}") + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +find_package(${NAMESPACE}Core CONFIG REQUIRED) + +add_library(${TESTLIB} STATIC OpenRPCTests.cpp) + +target_link_libraries(${TESTLIB} + PUBLIC + ${NAMESPACE}Core::${NAMESPACE}Core + ${FIREBOLT_NAMESPACE}SDK +) + +target_include_directories(${TESTLIB} + PRIVATE + $ + $ +) + +set_target_properties(${TESTLIB} PROPERTIES + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED YES + LINK_WHAT_YOU_USE TRUE + FRAMEWORK FALSE +) + +install( + TARGETS ${TESTLIB} EXPORT ${TESTLIB}Targets + LIBRARY DESTINATION lib COMPONENT libs + PUBLIC_HEADER DESTINATION include/${FIREBOLT_NAMESPACE}Test COMPONENT devel # headers for mac (note the different component -> different package) + INCLUDES DESTINATION include/${FIREBOLT_NAMESPACE}Test # headers +) + +InstallCMakeConfig(TARGETS ${TESTLIB}) +InstallCMakeConfigs(TARGET ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallHeaders(TARGET ${TESTLIB} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION FireboltTest) +InstallLibraries(TARGET ${TESTLIB} LIBRARIES ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) + +set(TESTAPP "FireboltSDKTestApp") + +message("Setup ${TESTAPP}") + +add_executable(${TESTAPP} Main.c) + +target_link_libraries(${TESTAPP} + PRIVATE + ${TESTLIB} +) + +target_include_directories(${TESTAPP} + PRIVATE + $ + $ +) + +add_custom_command( + TARGET ${TESTAPP} + POST_BUILD + COMMENT "=================== Installing TestApp ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/bin + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${TESTAPP} ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/bin +) + diff --git a/languages/c-structs/templates/sdk/test/Main.c b/languages/c-structs/templates/sdk/test/Main.c new file mode 100644 index 00000000..7c4c94a5 --- /dev/null +++ b/languages/c-structs/templates/sdk/test/Main.c @@ -0,0 +1,44 @@ +/* + * 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 "OpenRPCCTests.h" + +int __cnt = 0; +int __pass = 0; + +int TotalTests = 0; +int TotalTestsPassed = 0; + +int main() +{ + test_firebolt_create_instance(); + test_firebolt_main(); + + // Calling C function sequences + printf("%s:%s:%d Calling C function tests\n", __FILE__, __func__, __LINE__); + EXECUTE("test_properties_get_device_id", test_properties_get_device_id); + EXECUTE("test_properties_set", test_properties_set); + EXECUTE("test_eventregister_by_providing_callback", test_eventregister_by_providing_callback); + EXECUTE("test_eventregister", test_eventregister); + EXECUTE("test_string_set_get_value", test_string_set_get_value); + + test_firebolt_dispose_instance(); + + printf("TOTAL: %i tests; %i PASSED, %i FAILED\n", TotalTests, TotalTestsPassed, (TotalTests - TotalTestsPassed)); +} + diff --git a/languages/c-structs/templates/sdk/test/Module.cpp b/languages/c-structs/templates/sdk/test/Module.cpp new file mode 100644 index 00000000..d63badc4 --- /dev/null +++ b/languages/c-structs/templates/sdk/test/Module.cpp @@ -0,0 +1,21 @@ +/* + * 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 "Module.h" + +MODULE_NAME_DECLARATION(BUILD_REFERENCE) diff --git a/languages/c-structs/templates/sdk/test/Module.h b/languages/c-structs/templates/sdk/test/Module.h new file mode 100644 index 00000000..d5340b68 --- /dev/null +++ b/languages/c-structs/templates/sdk/test/Module.h @@ -0,0 +1,29 @@ +/* + * 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 + +#ifndef MODULE_NAME +#define MODULE_NAME OpenRPCTestApp +#endif + +#include +#include + +#undef EXTERNAL +#define EXTERNAL diff --git a/languages/c-structs/templates/sdk/test/OpenRPCCTests.h b/languages/c-structs/templates/sdk/test/OpenRPCCTests.h new file mode 100644 index 00000000..7f2fb59e --- /dev/null +++ b/languages/c-structs/templates/sdk/test/OpenRPCCTests.h @@ -0,0 +1,42 @@ +/* + * 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 + */ + +#ifndef _OPENRPC_C_TESTS_H +#define _OPENRPC_C_TESTS_H + +#include "TestUtils.h" + +#ifdef __cplusplus +extern "C" { +#endif + +uint32_t test_firebolt_create_instance(); +uint32_t test_firebolt_dispose_instance(); + +uint32_t test_firebolt_main(); +uint32_t test_properties_get_device_id(); +uint32_t test_properties_set(); +uint32_t test_eventregister(); +uint32_t test_eventregister_by_providing_callback(); +uint32_t test_string_set_get_value(); + +#ifdef __cplusplus +} +#endif + +#endif // _OPENRPC_C_TESTS_H diff --git a/languages/c-structs/templates/sdk/test/OpenRPCTests.cpp b/languages/c-structs/templates/sdk/test/OpenRPCTests.cpp new file mode 100644 index 00000000..cf9ea5a0 --- /dev/null +++ b/languages/c-structs/templates/sdk/test/OpenRPCTests.cpp @@ -0,0 +1,385 @@ +/* + * 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 "Module.h" +#include "OpenRPCTests.h" +#include "OpenRPCCTests.h" + +namespace WPEFramework { + +ENUM_CONVERSION_BEGIN(::JsonValue::type) + + { JsonValue::type::EMPTY, _TXT("empty") }, + { JsonValue::type::BOOLEAN, _TXT("boolean") }, + { JsonValue::type::NUMBER, _TXT("number") }, + { JsonValue::type::STRING, _TXT("string") }, + +ENUM_CONVERSION_END(::JsonValue::type) + +ENUM_CONVERSION_BEGIN(TestEnum) + { TestEnum::Test1, _TXT("Test1ValueCheck") }, + { TestEnum::Test2, _TXT("Test2ValueCheck") }, + { TestEnum::Test3, _TXT("Test3ValueCheck") }, + { TestEnum::Test4, _TXT("Test4ValueCheck") }, +ENUM_CONVERSION_END(TestEnum) +} +namespace FireboltSDK { + Tests::Tests() + { + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEventWithMultipleCallback"), + std::forward_as_tuple(&SubscribeEventWithMultipleCallback)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEvent"), + std::forward_as_tuple(&SubscribeEvent)); + + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Set UnKnown Method"), + std::forward_as_tuple(&SetUnKnownMethod)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Set LifeCycle Close"), + std::forward_as_tuple(&SetLifeCycleClose)); + + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Get UnKnown Method"), + std::forward_as_tuple(&GetUnKnownMethod)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Get Device Version"), + std::forward_as_tuple(&GetDeviceVersion)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Get Device Id"), + std::forward_as_tuple(&GetDeviceId)); + } + + /* static */ void Tests::PrintJsonObject(const JsonObject::Iterator& iterator) + { + JsonObject::Iterator index = iterator; + while (index.Next() == true) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "Element [%s]: <%s> = \"%s\"\n", + index.Label(), + WPEFramework::Core::EnumerateType(index.Current().Content()).Data(), + index.Current().Value().c_str()); + } + } + + /* static */ uint32_t Tests::GetDeviceId() + { + const string method = _T("device.id"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "DeviceId : %s", response->Value().c_str()); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d\n", method.c_str(), status); + } + + return status; + } + + /*static */ uint32_t Tests::GetDeviceVersion() + { + const string method = _T("device.version"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "DeviceVersion"); + PrintJsonObject(response->Variants()); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d", method.c_str(), status); + } + + return status; + } + + /* static */ uint32_t Tests::GetUnKnownMethod() + { + const string method = _T("get.unknownMethod"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_NE(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d\n", method.c_str(), status); + } + + return status; + } + + /* static */ uint32_t Tests::SetLifeCycleClose() + { + const string method = _T("lifecycle.close"); + JsonObject parameters; + parameters["reason"] = "remoteButton"; + uint32_t status = FireboltSDK::Properties::Set(method, parameters); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d\n", method.c_str(), status); + } + + return status; + } + + /* static */ uint32_t Tests::SetUnKnownMethod() + { + const string method = _T("set.unknownMethod"); + JsonObject parameters; + uint32_t status = FireboltSDK::Properties::Set(method, parameters); + + EXPECT_NE(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", method.c_str(), status); + } + + return status; + } + + static void deviceNameChangeCallback(const void* userData, void* response) + { + WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Received a new event: %s", jsonResponse->Value().c_str()); + jsonResponse.Release(); + FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + eventControl->NotifyEvent(); + } + + /* static */ uint32_t Tests::SubscribeEvent() + { + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + + uint32_t id = 0; + + eventControl->ResetEvent(); + uint32_t status = Properties::Subscribe(eventName, deviceNameChangeCallback, userdata, id); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), + "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered successfully", __func__); + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + EXPECT_EQ(Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + delete eventControl; + + return status; + } + + template + /* static */ uint32_t Tests::SubscribeEventForC(const string& eventName, CALLBACK& callbackFunc, const void* userdata, uint32_t& id) + { + return Properties::Subscribe(eventName, callbackFunc, userdata, id);; + } + + static void deviceNameChangeMultipleCallback(const void* userData, void* response) + { + WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "Received a new event from deviceNameChangeMultipleCallback: %s", jsonResponse->Value().c_str()); + jsonResponse.Release(); + FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + eventControl->NotifyEvent(); + } + + /* static */ uint32_t Tests::SubscribeEventWithMultipleCallback() + { + FireboltSDK::Tests::EventControl* eventControl1 = new FireboltSDK::Tests::EventControl(); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl1); + uint32_t id1 = 0, id2 = 0; + + eventControl1->ResetEvent(); + uint32_t status = Properties::Subscribe(eventName, deviceNameChangeCallback, userdata, id1); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), + "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered successfully", __func__); + } + + if (status == FireboltSDKErrorNone) { + FireboltSDK::Tests::EventControl* eventControl2 = new FireboltSDK::Tests::EventControl(); + userdata = static_cast(eventControl2); + + status = Properties::Subscribe(eventName, deviceNameChangeMultipleCallback, userdata, id2); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered second callback also successfully", __func__); + eventControl1->WaitForEvent(WPEFramework::Core::infinite); + eventControl2->WaitForEvent(WPEFramework::Core::infinite); + } + EXPECT_EQ(Properties::Unsubscribe(eventName, id1), FireboltSDKErrorNone); + delete eventControl2; + } + EXPECT_EQ(Properties::Unsubscribe(eventName, id2), FireboltSDKErrorNone); + + delete eventControl1; + return status; + } + +} + +#ifdef __cplusplus +extern "C" { +#endif + +uint32_t test_firebolt_create_instance() +{ + FireboltSDK::Accessor::Instance(); +} + +uint32_t test_firebolt_dispose_instance() +{ + FireboltSDK::Accessor::Dispose(); +} + +uint32_t test_firebolt_main() +{ + return FireboltSDK::Tests::Main(); +} + +uint32_t test_properties_get_device_id() +{ + const string method = _T("device.id"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "DeviceId : %s", response->Value().c_str()); + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "Get %s status = %d", method.c_str(), status); + } + + return status; +} + +uint32_t test_properties_set() +{ + const string method = _T("lifecycle.close"); + JsonObject parameters; + parameters["reason"] = "remoteButton"; + uint32_t status = FireboltSDK::Properties::Set(method, parameters); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "Set %s status = %d", method.c_str(), status); + } + + return status; +} + +static void deviceNameChangeCallbackForC(const void* userData, void* response) +{ + WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "Received a new event--->: %s", jsonResponse->Value().c_str()); + jsonResponse.Release(); + + FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + eventControl->NotifyEvent(); +} + +uint32_t test_eventregister() +{ + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + JsonObject parameters; + + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + uint32_t id = 0; + + eventControl->ResetEvent(); + uint32_t status = FireboltSDK::Properties::Subscribe(eventName, deviceNameChangeCallbackForC, userdata, id); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Set %s status = %d", __func__, eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes registered successfully", __func__); + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + delete eventControl; + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + + return status; +} + +uint32_t test_eventregister_by_providing_callback() +{ + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + uint32_t id = 0; + + eventControl->ResetEvent(); + uint32_t status = FireboltSDK::Tests::SubscribeEventForC(eventName, deviceNameChangeCallbackForC, userdata, id); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Set %s status = %d", __func__, eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes registered successfully", __func__); + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + delete eventControl; + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); +} + +#include "TypesPriv.h" +uint32_t test_string_set_get_value() +{ + uint32_t status = FireboltSDKErrorNone; + FireboltSDK::String* str = new FireboltSDK::String("testString"); + void* handle = static_cast(str); + + const char* value = FireboltTypes_String(handle); + EXPECT_EQ(strncmp(value, str->Value().c_str(), str->Value().length()), 0); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + " ---> type name = %s %s", str->Value().c_str(), value); + + WPEFramework::Core::JSON::EnumType<::TestEnum> testEnum = Test4; + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + " EnumTest = %d %s", testEnum.Value(), testEnum.Data()); + FireboltTypes_StringHandle_Release(handle); + return status; +} + +#ifdef __cplusplus +} +#endif diff --git a/languages/c-structs/templates/sdk/test/OpenRPCTests.h b/languages/c-structs/templates/sdk/test/OpenRPCTests.h new file mode 100644 index 00000000..00abd364 --- /dev/null +++ b/languages/c-structs/templates/sdk/test/OpenRPCTests.h @@ -0,0 +1,99 @@ +/* + * 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 "TestUtils.h" +#include "Firebolt.h" + +namespace FireboltSDK { + typedef uint32_t (*Func)(); + + class Tests { + public: + class EventControl { + public: + EventControl() + : _event(false, true) + { + } + ~EventControl() = default; + + public: + void NotifyEvent() + { + _event.SetEvent(); + } + uint32_t WaitForEvent(uint32_t waitTime) + { + return _event.Lock(waitTime); + } + void ResetEvent() + { + _event.ResetEvent(); + } + private: + WPEFramework::Core::Event _event; + }; + + private: + typedef std::unordered_map TestFunctionMap; + + public: + Tests(); + virtual ~Tests() = default; + + inline TestFunctionMap& TestList() + { + return _functionMap; + } + + template + static uint32_t Main() + { + TESTS fireboltTest; + for (auto i = fireboltTest.TestList().begin(); i != fireboltTest.TestList().end(); i++) { + EXECUTE(i->first.c_str(), i->second); + } + + printf("TOTAL: %i tests; %i PASSED, %i FAILED\n", TotalTests, TotalTestsPassed, (TotalTests - TotalTestsPassed)); + + return 0; + } + + static uint32_t GetDeviceId(); + static uint32_t GetDeviceVersion(); + static uint32_t GetUnKnownMethod(); + + static uint32_t SetLifeCycleClose(); + static uint32_t SetUnKnownMethod(); + + static uint32_t SubscribeEvent(); + static uint32_t SubscribeEventWithMultipleCallback(); + + template + static uint32_t SubscribeEventForC(const string& eventName, CALLBACK& callbackFunc, const void* userdata, uint32_t& id); + + protected: + static void PrintJsonObject(const JsonObject::Iterator& iterator); + + protected: + std::list menu; + TestFunctionMap _functionMap; + }; +} diff --git a/languages/c-structs/templates/sdk/test/TestUtils.h b/languages/c-structs/templates/sdk/test/TestUtils.h new file mode 100644 index 00000000..8c3cb732 --- /dev/null +++ b/languages/c-structs/templates/sdk/test/TestUtils.h @@ -0,0 +1,38 @@ +#ifndef _TEST_UTILS_H +#define _TEST_UTILS_H + +#include +#include +#include + +#define MAX(x, y) (((x) > (y)) ? (x) : (y)) +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) + +#define _RESULT(expr, exprorig, result) if (expr) { printf(" SUCCESS: %s\n", #exprorig); __pass++; } else printf(" FAILED: %s, actual: %u\n", #exprorig, result) +#define _EVAL(result, expected, op) do { __cnt++; uint32_t resval = ((uint32_t)(result)); uint32_t expval = ((uint32_t)(expected)); _RESULT(resval op expval, result op expected, resval); } while(0) +#define _HEAD(name) printf("\n======== %s\n", name); __cnt = 0; __pass = 0 +#define _FOOT(name) printf("\n======== %s - %i PASSED, %i FAILED\n", name, __pass, (__cnt - __pass)); TotalTests += __cnt; TotalTestsPassed += __pass; + +#define EXECUTE(name, test) do { _HEAD(name); test(); _FOOT(name); printf("\n"); } while(0) +#define EXPECT_EQ(result, expected) _EVAL(result, expected, ==) +#define EXPECT_NE(result, expected) _EVAL(result, expected, !=) +#define EXPECT_LT(result, expected) _EVAL(result, expected, <) +#define EXPECT_LE(result, expected) _EVAL(result, expected, <=) +#define EXPECT_GT(result, expected) _EVAL(result, expected, >) +#define EXPECT_GE(result, expected) _EVAL(result, expected, >=) + +#ifdef __cplusplus +extern "C" { +#endif + +extern int __cnt; +extern int __pass; + +extern int TotalTests ; +extern int TotalTestsPassed; + +#ifdef __cplusplus +} +#endif + +#endif // _TEST_UTILS_H diff --git a/languages/c-structs/templates/sections/accessors.c b/languages/c-structs/templates/sections/accessors.c new file mode 100644 index 00000000..1c790810 --- /dev/null +++ b/languages/c-structs/templates/sections/accessors.c @@ -0,0 +1,2 @@ +// Accessors +${schema.list} diff --git a/languages/c-structs/templates/sections/declarations.c b/languages/c-structs/templates/sections/declarations.c new file mode 100644 index 00000000..b3ef974d --- /dev/null +++ b/languages/c-structs/templates/sections/declarations.c @@ -0,0 +1 @@ +${declaration.list} diff --git a/languages/c-structs/templates/sections/enums.c b/languages/c-structs/templates/sections/enums.c new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/c-structs/templates/sections/enums.c @@ -0,0 +1 @@ +${schema.list} diff --git a/languages/c-structs/templates/sections/events.c b/languages/c-structs/templates/sections/events.c new file mode 100644 index 00000000..5be10409 --- /dev/null +++ b/languages/c-structs/templates/sections/events.c @@ -0,0 +1 @@ +${event.list} diff --git a/languages/c-structs/templates/sections/methods.c b/languages/c-structs/templates/sections/methods.c new file mode 100644 index 00000000..3ab606c0 --- /dev/null +++ b/languages/c-structs/templates/sections/methods.c @@ -0,0 +1,4 @@ + +// Methods + +${method.list} diff --git a/languages/c-structs/templates/sections/methods_accessors.c b/languages/c-structs/templates/sections/methods_accessors.c new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/c-structs/templates/sections/methods_accessors.c @@ -0,0 +1 @@ +${schema.list} diff --git a/languages/c-structs/templates/sections/methods_types.c b/languages/c-structs/templates/sections/methods_types.c new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/c-structs/templates/sections/methods_types.c @@ -0,0 +1 @@ +${schema.list} diff --git a/languages/c-structs/templates/sections/provider-interfaces.c b/languages/c-structs/templates/sections/provider-interfaces.c new file mode 100644 index 00000000..418d7abf --- /dev/null +++ b/languages/c-structs/templates/sections/provider-interfaces.c @@ -0,0 +1,11 @@ + // Provider Interfaces + + interface ProviderSession { + correlationId(): string // Returns the correlation id of the current provider session + } + + interface FocusableProviderSession extends ProviderSession { + focus(): Promise // Requests that the provider app be moved into focus to prevent a user experience + } + + ${providers.list} \ No newline at end of file diff --git a/languages/c-structs/templates/sections/schemas.c b/languages/c-structs/templates/sections/schemas.c new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/c-structs/templates/sections/schemas.c @@ -0,0 +1 @@ +${schema.list} diff --git a/languages/c-structs/templates/sections/types.c b/languages/c-structs/templates/sections/types.c new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/c-structs/templates/sections/types.c @@ -0,0 +1 @@ +${schema.list} diff --git a/languages/c-structs/templates/types/anyOf.c b/languages/c-structs/templates/types/anyOf.c new file mode 100644 index 00000000..9cc8aaef --- /dev/null +++ b/languages/c-structs/templates/types/anyOf.c @@ -0,0 +1 @@ +/* AnyOf is not supported in C */ \ No newline at end of file diff --git a/languages/c-structs/templates/types/array.c b/languages/c-structs/templates/types/array.c new file mode 100644 index 00000000..6f532328 --- /dev/null +++ b/languages/c-structs/templates/types/array.c @@ -0,0 +1 @@ +${title} * \ No newline at end of file diff --git a/languages/c-structs/templates/types/const.c b/languages/c-structs/templates/types/const.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/accessors/default.c b/languages/c-structs/templates/types/default.c similarity index 57% rename from languages/c/templates/accessors/default.c rename to languages/c-structs/templates/types/default.c index 1f1fe89d..38b05042 100644 --- a/languages/c/templates/accessors/default.c +++ b/languages/c-structs/templates/types/default.c @@ -1,4 +1,4 @@ /* * ${title} - ${description} */ -${shape} +typedef ${shape} ${title}; diff --git a/languages/c/templates/accessors/enum.cpp b/languages/c-structs/templates/types/enum.cpp similarity index 100% rename from languages/c/templates/accessors/enum.cpp rename to languages/c-structs/templates/types/enum.cpp diff --git a/languages/c/templates/accessors/enum.h b/languages/c-structs/templates/types/enum.h similarity index 100% rename from languages/c/templates/accessors/enum.h rename to languages/c-structs/templates/types/enum.h diff --git a/languages/c-structs/templates/types/object.c b/languages/c-structs/templates/types/object.c new file mode 100644 index 00000000..73cef62f --- /dev/null +++ b/languages/c-structs/templates/types/object.c @@ -0,0 +1,3 @@ +struct { + ${shape}${property}; // ${summary} +} \ No newline at end of file diff --git a/languages/c-structs/templates/types/primitive.c b/languages/c-structs/templates/types/primitive.c new file mode 100644 index 00000000..21ae259c --- /dev/null +++ b/languages/c-structs/templates/types/primitive.c @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/c-structs/templates/types/property.c b/languages/c-structs/templates/types/property.c new file mode 100644 index 00000000..56b60ac9 --- /dev/null +++ b/languages/c-structs/templates/types/property.c @@ -0,0 +1 @@ +${title} ${property} diff --git a/languages/c/templates/accessors/ref.c b/languages/c-structs/templates/types/ref.c similarity index 100% rename from languages/c/templates/accessors/ref.c rename to languages/c-structs/templates/types/ref.c diff --git a/languages/c/templates/accessors/title.c b/languages/c-structs/templates/types/title.c similarity index 100% rename from languages/c/templates/accessors/title.c rename to languages/c-structs/templates/types/title.c diff --git a/languages/c-structs/templates/types/tuple.c b/languages/c-structs/templates/types/tuple.c new file mode 100644 index 00000000..e6d948cd --- /dev/null +++ b/languages/c-structs/templates/types/tuple.c @@ -0,0 +1,3 @@ +struct { + ${properties} +} \ No newline at end of file diff --git a/languages/c/language.config.json b/languages/c/language.config.json index c13b1cce..124570d3 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -3,14 +3,13 @@ "langcode": "c", "createModuleDirectories": false, "extractSubSchemas": true, + "unwrapResultObjects": false, "templatesPerModule": [ "/include/Module.h", - "/include/Module_Accessors.h", "/src/Module.cpp" ], "templatesPerSchema": [ "/include/Common/Module.h", - "/include/Common/Module_Accessors.h", "/src/Module_Common.cpp", "/src/JsonData_Module.h" ], @@ -21,7 +20,8 @@ "number": "float", "string": "char*" }, - "additionalSchemaTemplates": [ - "accessors" - ] + "allocatedPrimitiveProxies": { + "string": "FireboltTypes_StringHandle" + }, + "additionalSchemaTemplates": [ "json-types" ] } diff --git a/languages/c/templates/accessors/array.c b/languages/c/templates/accessors/array.c deleted file mode 100644 index 3ebf9f53..00000000 --- a/languages/c/templates/accessors/array.c +++ /dev/null @@ -1,4 +0,0 @@ -uint32_t ${info.Title}_${Title}Array_Size(${type} handle); -${type} ${title}Array_Get(${type} handle, uint32_t index); -void ${info.Title}_${Title}Array_Add(${propertyType}Handle handle, ${valueType} value); -void ${info.Title}_${Title}Array_Clear(${propertyType}Handle handle); diff --git a/languages/c/templates/accessors/object.c b/languages/c/templates/accessors/object.c deleted file mode 100644 index 9aa56c57..00000000 --- a/languages/c/templates/accessors/object.c +++ /dev/null @@ -1,7 +0,0 @@ -typedef void* ${varName}Handle; -${varName}Handle ${varName}Handle_Create(void); -void ${varName}Handle_Addref(${varName}Handle handle); -void ${varName}Handle_Release(${varName}Handle handle); -bool ${varName}Handle_IsValid(${varName}Handle handle); - -${property}${shape} diff --git a/languages/c/templates/accessors/primitive.c b/languages/c/templates/accessors/primitive.c deleted file mode 100644 index 2f470670..00000000 --- a/languages/c/templates/accessors/primitive.c +++ /dev/null @@ -1 +0,0 @@ -int F${info.Title}_GetProperty${type}(); \ No newline at end of file diff --git a/languages/c/templates/accessors/tuple.c b/languages/c/templates/accessors/tuple.c deleted file mode 100644 index f7e6d4fd..00000000 --- a/languages/c/templates/accessors/tuple.c +++ /dev/null @@ -1,2 +0,0 @@ - int Tubple_GET${property}(${shape}handle); - \ No newline at end of file diff --git a/languages/c/templates/declarations/event.c b/languages/c/templates/declarations/event.c index f91c6a39..1ec899b2 100644 --- a/languages/c/templates/declarations/event.c +++ b/languages/c/templates/declarations/event.c @@ -1,4 +1,7 @@ /* ${method.name} - ${method.description} */ -typedef void (*${info.Title}${method.Name}Callback)( const void* userData, ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${method.result.properties} ); -int ${info.title}_Register_${method.Name}( ${event.signature.params}${if.event.params}, ${end.if.event.params}${info.Title}${method.Name}Callback userCB, const void* userData ); -int ${info.title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); +typedef void (*F${info.Title}${method.Name}Callback)( const void* userData, ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${method.result.properties} ); +int F${info.title}_Register_${method.Name}( ${event.signature.params}${if.event.params}, ${end.if.event.params}F${info.Title}${method.Name}Callback userCB, const void* userData ); +int F${info.title}_Unregister_${method.Name}( F${info.Title}${method.Name}Callback userCB); + +// signature callback params: ${event.signature.callback.params} +// method result properties : ${method.result.properties} \ No newline at end of file diff --git a/languages/c/templates/json-types/additionalProperties.c b/languages/c/templates/json-types/additionalProperties.c new file mode 100644 index 00000000..b814e5fb --- /dev/null +++ b/languages/c/templates/json-types/additionalProperties.c @@ -0,0 +1 @@ +// need cpp code to init, get, set, clear additional properties... \ No newline at end of file diff --git a/languages/c/templates/accessors/anyOf.c b/languages/c/templates/json-types/anyOf.c similarity index 100% rename from languages/c/templates/accessors/anyOf.c rename to languages/c/templates/json-types/anyOf.c diff --git a/languages/c/templates/json-types/array.c b/languages/c/templates/json-types/array.c new file mode 100644 index 00000000..508a9eac --- /dev/null +++ b/languages/c/templates/json-types/array.c @@ -0,0 +1,4 @@ +uint32_t ${info.Title}_${Title}Array_Size(${type} handle); +${type} ${title}Array_Get(${type} handle, uint32_t index); +void ${info.Title}_${Title}Array_Add(${propertyType} handle, ${valueType} value); +void ${info.Title}_${Title}Array_Clear(${propertyType} handle); diff --git a/languages/c/templates/json-types/boolean.c b/languages/c/templates/json-types/boolean.c new file mode 100644 index 00000000..18bbeec2 --- /dev/null +++ b/languages/c/templates/json-types/boolean.c @@ -0,0 +1 @@ +WPEFramework::Core::JSON::Boolean \ No newline at end of file diff --git a/languages/c/templates/json-types/const.c b/languages/c/templates/json-types/const.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/json-types/default.cpp b/languages/c/templates/json-types/default.cpp new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/c/templates/json-types/default.cpp @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/c/templates/json-types/enum.cpp b/languages/c/templates/json-types/enum.cpp new file mode 100644 index 00000000..6776b41a --- /dev/null +++ b/languages/c/templates/json-types/enum.cpp @@ -0,0 +1,4 @@ + /* ${title} ${description} */ + ENUM_CONVERSION_BEGIN(${name}) + { ${NAME}_${key}, _T("${value}") }, + ENUM_CONVERSION_END(${name}) diff --git a/languages/c/templates/json-types/enum.h b/languages/c/templates/json-types/enum.h new file mode 100644 index 00000000..92108c75 --- /dev/null +++ b/languages/c/templates/json-types/enum.h @@ -0,0 +1,4 @@ +/* ${title} ${description} */ +typedef enum { + ${NAME}_${key}, +} ${name}; diff --git a/languages/c/templates/json-types/float.c b/languages/c/templates/json-types/float.c new file mode 100644 index 00000000..c38bca91 --- /dev/null +++ b/languages/c/templates/json-types/float.c @@ -0,0 +1 @@ +WPEFramework::Core::JSON::Float \ No newline at end of file diff --git a/languages/c/templates/json-types/integer.c b/languages/c/templates/json-types/integer.c new file mode 100644 index 00000000..b57fe26e --- /dev/null +++ b/languages/c/templates/json-types/integer.c @@ -0,0 +1 @@ +WPEFramework::Core::JSON::DecSInt32 \ No newline at end of file diff --git a/languages/c/templates/json-types/namespace.c b/languages/c/templates/json-types/namespace.c new file mode 100644 index 00000000..8ea9d7de --- /dev/null +++ b/languages/c/templates/json-types/namespace.c @@ -0,0 +1 @@ +FireboltSDK::${info.Title}:: \ No newline at end of file diff --git a/languages/c/templates/json-types/object.cpp b/languages/c/templates/json-types/object.cpp new file mode 100644 index 00000000..db24d12c --- /dev/null +++ b/languages/c/templates/json-types/object.cpp @@ -0,0 +1,25 @@ + class ${title}: public WPEFramework::Core::JSON::Container { + public: + ~${title}() override = default; + + public: + ${title}() + : WPEFramework::Core::JSON::Container() + { + ${properties.register} + } + + ${title}(const ${title}& other) + { + ${properties.assign} + } + + ${title}& operator=(const ${title}& other) + { + ${properties.assign} + return (*this); + } + + public: + ${properties} + }; diff --git a/languages/c/templates/json-types/primitive.c b/languages/c/templates/json-types/primitive.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/json-types/property-assign.cpp b/languages/c/templates/json-types/property-assign.cpp new file mode 100644 index 00000000..88795136 --- /dev/null +++ b/languages/c/templates/json-types/property-assign.cpp @@ -0,0 +1,2 @@ + Add(_T("${property}"), &${Property}); + ${Property} = other.${Property} diff --git a/languages/c/templates/json-types/property-register.cpp b/languages/c/templates/json-types/property-register.cpp new file mode 100644 index 00000000..400b4fd5 --- /dev/null +++ b/languages/c/templates/json-types/property-register.cpp @@ -0,0 +1,2 @@ + Add(_T("${property}"), &${Property}); + \ No newline at end of file diff --git a/languages/c/templates/json-types/property.cpp b/languages/c/templates/json-types/property.cpp new file mode 100644 index 00000000..49f79c0e --- /dev/null +++ b/languages/c/templates/json-types/property.cpp @@ -0,0 +1 @@ + ${title} ${Property}; \ No newline at end of file diff --git a/languages/c/templates/json-types/ref.c b/languages/c/templates/json-types/ref.c new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/c/templates/json-types/ref.c @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/c/templates/json-types/string.c b/languages/c/templates/json-types/string.c new file mode 100644 index 00000000..2d60a3c8 --- /dev/null +++ b/languages/c/templates/json-types/string.c @@ -0,0 +1 @@ +FireboltSDK::JSON::String \ No newline at end of file diff --git a/languages/c/templates/json-types/title.c b/languages/c/templates/json-types/title.c new file mode 100644 index 00000000..ae1512e5 --- /dev/null +++ b/languages/c/templates/json-types/title.c @@ -0,0 +1 @@ +JsonData_${Title} \ No newline at end of file diff --git a/languages/c/templates/json-types/tuple.c b/languages/c/templates/json-types/tuple.c new file mode 100644 index 00000000..db24d12c --- /dev/null +++ b/languages/c/templates/json-types/tuple.c @@ -0,0 +1,25 @@ + class ${title}: public WPEFramework::Core::JSON::Container { + public: + ~${title}() override = default; + + public: + ${title}() + : WPEFramework::Core::JSON::Container() + { + ${properties.register} + } + + ${title}(const ${title}& other) + { + ${properties.assign} + } + + ${title}& operator=(const ${title}& other) + { + ${properties.assign} + return (*this); + } + + public: + ${properties} + }; diff --git a/languages/c/templates/json-types/types/object.c b/languages/c/templates/json-types/types/object.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/json-types/x-method.c b/languages/c/templates/json-types/x-method.c new file mode 100644 index 00000000..573c9f8e --- /dev/null +++ b/languages/c/templates/json-types/x-method.c @@ -0,0 +1 @@ +void* \ No newline at end of file diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 3707e68b..58410ab3 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -7,7 +7,8 @@ int F${info.title}_${method.Name}(${method.signature.params}${if.result.properti JsonObject jsonParameters; ${if.params} -${method.params.json} + //default +${method.params.serialization} ${end.if.params} WPEFramework::Core::JSON::Boolean jsonResult; diff --git a/languages/c/templates/methods/event.c b/languages/c/templates/methods/event.c index 766a78b3..76246f20 100644 --- a/languages/c/templates/methods/event.c +++ b/languages/c/templates/methods/event.c @@ -15,12 +15,13 @@ int ${info.title}_Register_${method.Name}( ${event.signature.params}${if.event.p int status = FireboltSDKErrorNone; if (userCB != nullptr) { - ${event.params.serialization} + ${event.params.serialization} status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${info.Title}${method.Name}InnerCallback, reinterpret_cast(userCB), userData); } return status; } int ${info.title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB) { + return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title}.${method.name}"), reinterpret_cast(userCB)); } diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 7c46f7c1..c2515780 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,6 +1,7 @@ /* ${method.name} - ${method.description} */ int F${info.title}_Get${method.Name}(${method.signature.params}${if.result.properties}${if.params}, ${end.if.params}${end.if.result.properties}${method.result.properties}) { const string method = _T("${info.title}.${method.name}"); +// property ${if.params}${method.params.serialization}${end.if.params} ${method.result.json} jsonResult; ${if.params}int status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult);${end.if.params} diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 65721f1e..1f112bec 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -23,18 +23,18 @@ namespace FireboltSDK { namespace ${info.title} { // Types - /* ${TYPES} */ + /* ${TYPES:json-types} */ } } -/* ${ENUMS} */ +/* ${ENUMS:json-types} */ #ifdef __cplusplus extern "C" { #endif -/* ${ACCESSORS} */ /* ${METHODS} */ + /* ${EVENTS} */ #ifdef __cplusplus diff --git a/languages/c/templates/parameter-serialization/boolean.cpp b/languages/c/templates/parameter-serialization/boolean.cpp new file mode 100644 index 00000000..f924ac94 --- /dev/null +++ b/languages/c/templates/parameter-serialization/boolean.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/c/templates/parameter-serialization/default.cpp b/languages/c/templates/parameter-serialization/default.cpp new file mode 100644 index 00000000..f924ac94 --- /dev/null +++ b/languages/c/templates/parameter-serialization/default.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/c/templates/parameter-serialization/object.cpp b/languages/c/templates/parameter-serialization/object.cpp new file mode 100644 index 00000000..f924ac94 --- /dev/null +++ b/languages/c/templates/parameter-serialization/object.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/c/templates/parameter-serialization/primitive.cpp b/languages/c/templates/parameter-serialization/primitive.cpp new file mode 100644 index 00000000..f924ac94 --- /dev/null +++ b/languages/c/templates/parameter-serialization/primitive.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/c/templates/parameter-serialization/string.cpp b/languages/c/templates/parameter-serialization/string.cpp new file mode 100644 index 00000000..f924ac94 --- /dev/null +++ b/languages/c/templates/parameter-serialization/string.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/c/templates/result-instantiation/boolean.cpp b/languages/c/templates/result-instantiation/boolean.cpp new file mode 100644 index 00000000..036b4a7d --- /dev/null +++ b/languages/c/templates/result-instantiation/boolean.cpp @@ -0,0 +1,2 @@ + *${property} = jsonResult.Value(); + \ No newline at end of file diff --git a/languages/c/templates/result-instantiation/default.cpp b/languages/c/templates/result-instantiation/default.cpp new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/c/templates/result-instantiation/default.cpp @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/c/templates/result-instantiation/object.cpp b/languages/c/templates/result-instantiation/object.cpp new file mode 100644 index 00000000..dcf0b333 --- /dev/null +++ b/languages/c/templates/result-instantiation/object.cpp @@ -0,0 +1,4 @@ + WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); + *resultPtr = WPEFramework::Core::ProxyType::Create(); + *(*resultPtr) = jsonResult; + *${property} = static_cast<${info.Title}_${title}>(resultPtr); diff --git a/languages/c/templates/result-instantiation/primitive.cpp b/languages/c/templates/result-instantiation/primitive.cpp new file mode 100644 index 00000000..23bbace7 --- /dev/null +++ b/languages/c/templates/result-instantiation/primitive.cpp @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/c/templates/result-instantiation/string.cpp b/languages/c/templates/result-instantiation/string.cpp new file mode 100644 index 00000000..b6c9dcb5 --- /dev/null +++ b/languages/c/templates/result-instantiation/string.cpp @@ -0,0 +1,2 @@ + FireboltSDK::JSON::String* strResult = new FireboltSDK::JSON::String(jsonResult); + *value = static_cast(strResult); diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/JsonData_Module.h index d0ecbbac..7c41a2ab 100644 --- a/languages/c/templates/schemas/src/JsonData_Module.h +++ b/languages/c/templates/schemas/src/JsonData_Module.h @@ -25,6 +25,6 @@ namespace FireboltSDK { namespace ${info.title} { // Types - /* ${SCHEMAS} */ + /* ${SCHEMAS:json-types} */ } } diff --git a/languages/c/templates/types/additionalProperties.c b/languages/c/templates/types/additionalProperties.c new file mode 100644 index 00000000..ffe5ab54 --- /dev/null +++ b/languages/c/templates/types/additionalProperties.c @@ -0,0 +1,4 @@ + uint32_t ${parent.title}_KeysCount(${parent.title} handle); + void ${parent.title}_AddKey(${parent.title} handle, char* key, ${title} value); + void ${parent.title}_RemoveKey(${parent.title} handle, char* key); + ${title} ${parent.title}_FindKey(${parent.title} handle, char* key); diff --git a/languages/c/templates/types/anyOf.c b/languages/c/templates/types/anyOf.c index 9cc8aaef..a2682179 100644 --- a/languages/c/templates/types/anyOf.c +++ b/languages/c/templates/types/anyOf.c @@ -1 +1 @@ -/* AnyOf is not supported in C */ \ No newline at end of file +/* AnyOf is not supported in C: ${title} */ \ No newline at end of file diff --git a/languages/c/templates/types/array.c b/languages/c/templates/types/array.c index 6f532328..508a9eac 100644 --- a/languages/c/templates/types/array.c +++ b/languages/c/templates/types/array.c @@ -1 +1,4 @@ -${title} * \ No newline at end of file +uint32_t ${info.Title}_${Title}Array_Size(${type} handle); +${type} ${title}Array_Get(${type} handle, uint32_t index); +void ${info.Title}_${Title}Array_Add(${propertyType} handle, ${valueType} value); +void ${info.Title}_${Title}Array_Clear(${propertyType} handle); diff --git a/languages/c/templates/types/default.c b/languages/c/templates/types/default.c index 38b05042..1f1fe89d 100644 --- a/languages/c/templates/types/default.c +++ b/languages/c/templates/types/default.c @@ -1,4 +1,4 @@ /* * ${title} - ${description} */ -typedef ${shape} ${title}; +${shape} diff --git a/languages/c/templates/types/object.c b/languages/c/templates/types/object.c index 73cef62f..7ff6a7a9 100644 --- a/languages/c/templates/types/object.c +++ b/languages/c/templates/types/object.c @@ -1,3 +1,10 @@ -struct { - ${shape}${property}; // ${summary} -} \ No newline at end of file +/* ${title} */ +typedef void* ${title}; +${title} ${title}_Create(void); +void ${title}_Addref(${title} handle); +void ${title}_Release(${title} handle); +bool ${title}_IsValid(${title} handle); + + +// Property Accessors: +${properties} \ No newline at end of file diff --git a/languages/c/templates/types/primitive.c b/languages/c/templates/types/primitive.c index 21ae259c..e69de29b 100644 --- a/languages/c/templates/types/primitive.c +++ b/languages/c/templates/types/primitive.c @@ -1 +0,0 @@ -${type} \ No newline at end of file diff --git a/languages/c/templates/types/property.c b/languages/c/templates/types/property.c new file mode 100644 index 00000000..abbba725 --- /dev/null +++ b/languages/c/templates/types/property.c @@ -0,0 +1,6 @@ +/* ${property} */ +${title} ${parent.title}_Get_${Property}(${parent.title} handle); +void ${parent.title}_Set_${Property}(${parent.title} handle, ${title} ${property}); +${if.optional}bool ${parent.title}_Has_${Property}(${parent.title} handle); +void ${parent.title}_Clear_${Property}(${parent.title} handle, ${title} ${property}); +${end.if.optional} \ No newline at end of file diff --git a/languages/c/templates/types/ref.c b/languages/c/templates/types/ref.c index 41d15c96..4da5b5d9 100644 --- a/languages/c/templates/types/ref.c +++ b/languages/c/templates/types/ref.c @@ -1 +1 @@ -${title} \ No newline at end of file +${shape} \ No newline at end of file diff --git a/languages/c/templates/types/tuple.c b/languages/c/templates/types/tuple.c index 73cef62f..96a04034 100644 --- a/languages/c/templates/types/tuple.c +++ b/languages/c/templates/types/tuple.c @@ -1,3 +1,8 @@ -struct { - ${shape}${property}; // ${summary} -} \ No newline at end of file +/* ${title} */ +typedef void* ${title}; +${title} ${title}_Create(void); +void ${title}_Addref(${title} handle); +void ${title}_Release(${title} handle); +bool ${title}_IsValid(${title} handle); + +${properties} diff --git a/languages/c/templates/types/x-method.c b/languages/c/templates/types/x-method.c new file mode 100644 index 00000000..573c9f8e --- /dev/null +++ b/languages/c/templates/types/x-method.c @@ -0,0 +1 @@ +void* \ No newline at end of file diff --git a/languages/javascript/language.config.json b/languages/javascript/language.config.json index eee8f599..540e6375 100644 --- a/languages/javascript/language.config.json +++ b/languages/javascript/language.config.json @@ -18,6 +18,7 @@ "boolean": "boolean", "integer": "number", "number": "number", - "string": "string" + "string": "string", + "object": "object" } } \ No newline at end of file diff --git a/languages/javascript/templates/types/anyOf.mjs b/languages/javascript/templates/types/anyOf.mjs index 0ffe8e7a..67f67236 100644 --- a/languages/javascript/templates/types/anyOf.mjs +++ b/languages/javascript/templates/types/anyOf.mjs @@ -1 +1 @@ -${type} ${delimiter} | ${end.delimiter} \ No newline at end of file +${type}${delimiter} | ${end.delimiter} \ No newline at end of file diff --git a/languages/javascript/templates/types/items.mjs b/languages/javascript/templates/types/items.mjs new file mode 100644 index 00000000..56397819 --- /dev/null +++ b/languages/javascript/templates/types/items.mjs @@ -0,0 +1 @@ +${type}${delimiter},${end.delimiter} // ${property} ${summary} item \ No newline at end of file diff --git a/languages/javascript/templates/types/null.mjs b/languages/javascript/templates/types/null.mjs new file mode 100644 index 00000000..ec747fa4 --- /dev/null +++ b/languages/javascript/templates/types/null.mjs @@ -0,0 +1 @@ +null \ No newline at end of file diff --git a/languages/javascript/templates/types/object.mjs b/languages/javascript/templates/types/object.mjs index 1110ba5f..9c30308e 100644 --- a/languages/javascript/templates/types/object.mjs +++ b/languages/javascript/templates/types/object.mjs @@ -1,3 +1,3 @@ { - ${property}${if.optional}?${end.optional}: ${shape} // ${summary} + ${properties} } diff --git a/languages/javascript/templates/types/property.mjs b/languages/javascript/templates/types/property.mjs new file mode 100644 index 00000000..5d3db0f5 --- /dev/null +++ b/languages/javascript/templates/types/property.mjs @@ -0,0 +1 @@ +${property}${if.optional}?${end.if.optional}: ${title} // ${summary} \ No newline at end of file diff --git a/languages/javascript/templates/types/tuple.mjs b/languages/javascript/templates/types/tuple.mjs index 2fb19c56..2c803cd3 100644 --- a/languages/javascript/templates/types/tuple.mjs +++ b/languages/javascript/templates/types/tuple.mjs @@ -1,3 +1,3 @@ [ - ${shape}${delimiter},${end.delimiter} // ${property} ${summary} + ${items} ] \ No newline at end of file diff --git a/languages/javascript/templates/types/x-method.mjs b/languages/javascript/templates/types/x-method.mjs new file mode 100644 index 00000000..607228f3 --- /dev/null +++ b/languages/javascript/templates/types/x-method.mjs @@ -0,0 +1 @@ +(${params}) => Promise<${title}> \ No newline at end of file diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index e1b13ca8..2b261058 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -31,7 +31,7 @@ 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 isEmpty from 'crocks/core/isEmpty.js' -import { getPath as getJsonPath, getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies, isDefinitionReferencedBySchema } from '../shared/json-schema.mjs' +import { getPath as getJsonPath, getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies, isDefinitionReferencedBySchema, mergeAnyOf, mergeOneOf } from '../shared/json-schema.mjs' // util for visually debugging crocks ADTs const _inspector = obj => { @@ -42,23 +42,18 @@ const _inspector = obj => { } } -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) // getSchemaType(schema, module, options = { destination: 'file.txt', title: true }) // getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getJsonType(schema, module, options = { name: 'Foo', prefix: '', descriptions: false, level: 0 }) -// getSchemaInstantiation(schema, module, options = {type: 'params' | 'result' | 'callback.params'| 'callback.result' | 'callback.response'}) let types = { - getMethodSignatureParams: () => null, getSchemaShape: () => null, - getSchemaType: () => null, - getJsonType: () => null, - getSchemaInstantiation: () => null + getSchemaType: () => null } let config = { copySchemasIntoModules: false, - extractSubSchemas: false + extractSubSchemas: false, + unwrapResultObjects: false } const state = { @@ -348,14 +343,24 @@ const generateAggregateMacros = (openrpc, modules, templates, library) => Object }) const addContentDescriptorSubSchema = (descriptor, prefix, obj) => { - const title = prefix.charAt(0).toUpperCase() + prefix.substring(1) + descriptor.name.charAt(0).toUpperCase() + descriptor.name.substring(1) - if (obj.components.schemas[title]) { - throw 'Generated name `' + title + '` already exists...' + const title = getPromotionNameFromContentDescriptor(descriptor, prefix) + promoteSchema(descriptor, 'schema', title, obj, "#/components/schemas") +} + +const getPromotionNameFromContentDescriptor = (descriptor, prefix) => { + const subtitle = descriptor.schema.title || descriptor.name.charAt(0).toUpperCase() + descriptor.name.substring(1) + return (prefix ? prefix.charAt(0).toUpperCase() + prefix.substring(1) : '') + subtitle +} + +const promoteSchema = (location, property, title, document, destinationPath) => { + const destination = getJsonPath(destinationPath, document) + if (destination[title]) { + console.log('Warning: Generated schema `' + title + '` already exists...') } - obj.components.schemas[title] = descriptor.schema - obj.components.schemas[title].title = title - descriptor.schema = { - $ref: "#/components/schemas/" + title + destination[title] = location[property] + destination[title].title = title + location[property] = { + $ref: `${destinationPath}/${title}` } } @@ -369,15 +374,19 @@ const promoteAndNameSubSchemas = (obj) => { obj.methods && obj.methods.forEach(method => { method.params && method.params.forEach(param => { if (isSubSchema(param.schema)) { - addContentDescriptorSubSchema(param, method.name, obj) + addContentDescriptorSubSchema(param, '', obj) } }) - if (isSubSchema(method.result.schema) && method.result.schema.title) { - addContentDescriptorSubSchema(method.result, method.name, obj) + if (isSubSchema(method.result.schema)) { + addContentDescriptorSubSchema(method.result, '', obj) + } + else if (isEventMethod(method) && isSubSchema(getPayloadFromEvent(method))) { + // TODO: the `1` below is brittle... should find the index of the non-ListenResponse schema + promoteSchema(method.result.schema.anyOf, 1, getPromotionNameFromContentDescriptor(method.result, ''), obj, '#/components/schemas') } }) - // find non-primative sub-schemas of components.schemas and name/promote them + // find non-primitive sub-schemas of components.schemas and name/promote them if (obj.components && obj.components.schemas) { let more = true while (more) { @@ -396,6 +405,10 @@ const promoteAndNameSubSchemas = (obj) => { } }) } + + if (!schema.title) { + schema.title = capitalize(key) + } }) } } @@ -403,12 +416,56 @@ const promoteAndNameSubSchemas = (obj) => { return obj } +const skip = ['NavigationIntent'] +const findAll = (tag, obj, transform) => { + if (Array.isArray(obj)) { + obj.forEach(item => findAll(tag, item, transform)) + } + else if (obj && (typeof obj === "object")) { + Object.keys(obj).forEach(key => { + if (!skip.includes(key)) { + if (key === tag) { + if (obj[key].find(schema => schema.$ref.endsWith('/ListenResponse'))) { + + } + else { + Object.assign(obj, transform(obj)) + delete obj[key] + console.dir(obj) + findAll(tag, obj, transform) + } + } + else { + findAll(tag, obj[key], transform) + } + } + }) + } +} + +const mergeAnyOfs = (obj) => { + // make a copy so we don't polute our inputs + obj = JSON.parse(JSON.stringify(obj)) + + findAll('anyOf', obj, anyOf => mergeAnyOf(anyOf)) +// findAll('onyOf', obj, onyOf => mergeOnyOf(onyOf)) + +return obj +} + const generateMacros = (obj, templates, languages, options = {}) => { // for languages that don't support nested schemas, let's promote them to first-class schemas w/ titles if (config.extractSubSchemas) { obj = promoteAndNameSubSchemas(obj) } + // config.mergeAnyOfs = true + // if (config.mergeAnyOfs) { + // obj = mergeAnyOfs(obj) + // } + + console.log('DONE') + // grab the options so we don't have to pass them from method to method Object.assign(state, options) @@ -424,9 +481,6 @@ const generateMacros = (obj, templates, languages, options = {}) => { macros.schemas[dir] = getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).filter(body => body).join('\n')) 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')) - - const cr = schemasArray.find(s => s.name === 'CloseReason') - cr && console.dir(cr) }) const examples = generateExamples(obj, templates, languages) @@ -1086,14 +1140,17 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) : '' - const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, { instantiationType: 'params' }) - const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' }) - const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'params' }), ' ') : '' - const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.params' }) : '' - const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.result' }) : '' - const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.response' }) : '' + const serializedParams = flattenedMethod.params.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') + const resultInst = types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-instantiation', property: flattenedMethod.result.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) // w/out level: 1, getSchemaShape skips anonymous types, like primitives + 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: param.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 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: param.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.getJsonType(result.schema, json, { name: result.name}) : '' + const resultJsonType = result.schema ? types.getSchemaType(result.schema, json, { name: result.name, templateDir: 'json-types' }) : '' const resultParams = generateResultParams(result.schema, json, templates, { name: result.name}) let seeAlso = '' @@ -1161,8 +1218,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .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, resultSchema: true })) //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) + .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result.schema, json, { name: result.name, templateDir: state.typeTemplateDir, 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, code: false, link: false, asPath: false, expandEnums: false, namespace: true })) .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, templateDir: state.typeTemplateDir, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) @@ -1348,28 +1405,34 @@ function generateResultParams(result, json, templates, {name = ''}={}) { return '' } // Objects with no titles get unwrapped - else if (result.type && !result.title && result.type === 'object' && result.properties) { + else if (config.unwrapResultObjects && result.type && !result.title && result.type === 'object' && result.properties) { 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, templateDir: state.typeTemplateDir, moduleTitle: moduleTitle})) - ).join(', ') // most languages separate params w/ a comma, so leaving this here for now + .replace(/\$\{method\.param\.type\}/g, types.getSchemaType(type, json, {name: name, templateDir: state.typeTemplateDir, moduleTitle: moduleTitle, result: true})) + ).join(', ') // most languages separate params w/ a comma, so leaving this here for now } // tuples get unwrapped - else if (result.type && result.type === 'array' && Array.isArray(result.items)) { + else if (config.unwrapResultObjects && result.type && result.type === 'array' && Array.isArray(result.items)) { // TODO: this is hard coded to C 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, templateDir: state.typeTemplateDir, moduleTitle: moduleTitle})) + .replace(/\$\{method\.param\.type\}/g, types.getSchemaType(type, json, {name: name, templateDir: state.typeTemplateDir, moduleTitle: moduleTitle, result: true})) ).join(', ') } // everything else is just output as-is else { const template = getTemplate('/parameters/result', templates) + const type = types.getSchemaType(result, json, {name: name, templateDir: state.typeTemplateDir, moduleTitle: moduleTitle, result: true}) + + if (type === 'undefined') { + console.log(`Warning: undefined type for ${name}`) + } + return template - .replace(/\$\{method\.param\.name\}/g, `name`) - .replace(/\$\{method\.param\.type\}/g, types.getSchemaType(result, json, {name: name, templateDir: state.typeTemplateDir, moduleTitle: moduleTitle})) + .replace(/\$\{method\.param\.name\}/g, `${name}`) + .replace(/\$\{method\.param\.type\}/g, type) } } @@ -1386,9 +1449,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, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl + 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.getJsonType(param.schema, module, { name: param.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) + 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 }) if (constraints && type) { constraints = '
' + constraints @@ -1549,7 +1612,7 @@ function insertProviderParameterMacros(data = '', parameters, module = {}, optio Object.entries(parameters.properties).forEach(([name, param]) => { let constraints = getSchemaConstraints(param, module) - let type = types.getSchemaType(param, module, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section, code: true, link: true, title: true, asPath: options.asPath, baseUrl: options.baseUrl }) + let type = types.getSchemaType(param, module, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section, code: true, link: true, asPath: options.asPath, baseUrl: options.baseUrl }) if (constraints && type) { constraints = '
' + constraints diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index ba3efd7a..07ace94b 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -47,6 +47,9 @@ const macrofy = async ( createModuleDirectories, copySchemasIntoModules, extractSubSchemas, + unwrapResultObjects, + allocatedPrimitiveProxies, + convertTuplesToArraysOrObjects, additionalSchemaTemplates, aggregateFile, operators, @@ -85,8 +88,10 @@ const macrofy = async ( copySchemasIntoModules, createModuleDirectories, extractSubSchemas, + unwrapResultObjects, operators, primitives, + allocatedPrimitiveProxies, additionalSchemaTemplates }) @@ -98,6 +103,8 @@ const macrofy = async ( typer.setTemplates && typer.setTemplates(templates) typer.setPrimitives(primitives) + typer.setAllocatedPrimitiveProxies(allocatedPrimitiveProxies) + typer.setConvertTuples(convertTuplesToArraysOrObjects) let templatesPermission = {} if (persistPermission) { diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index 00dc6400..18adcb69 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -20,480 +20,596 @@ import deepmerge from 'deepmerge' import { getPath, localizeDependencies } from '../shared/json-schema.mjs' import path from "path" +let convertTuplesToArraysOrObjects = false const templates = {} const state = {} const primitives = { - "integer": "number", - "number": "number", - "boolean": "boolean", - "string": "string" + "integer": "number", + "number": "number", + "boolean": "boolean", + "string": "string" } +const allocatedPrimitiveProxies = {} + function setTemplates(t) { - Object.assign(templates, t) + Object.assign(templates, t) } function setPrimitives(p) { - Object.assign(primitives, p) + Object.assign(primitives, p) +} + +function setConvertTuples(t) { + convertTuplesToArraysOrObjects = t +} + +function setAllocatedPrimitiveProxies(m) { + Object.assign(allocatedPrimitiveProxies, m) } const capitalize = str => str ? str[0].toUpperCase() + str.substr(1) : str const safeName = value => value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() -function getMethodSignatureParams(method, module, { destination }) { - const paramRequired = getTemplate('/parameters/default') - const paramOptional = getTemplate('/parameters/optional') - return method.params.map( param => (param.required ? paramRequired : paramOptional).replace(/\$\{method\.param\.name\}/g, param.name).replace(/\$\{method\.param\.type\}/g, getSchemaType(param.schema, module, {title: true, destination }))).join(', ') +// TODO: This is what's left of getMethodSignatureParams. We need to figure out / handle C's `FireboltTypes_StringHandle` +function getMethodSignatureParams(method, module, { destination, callback }) { + const paramRequired = getTemplate('/parameters/default') + const paramOptional = getTemplate('/parameters/optional') + return method.params.map(param => { + let type = getSchemaType(param.schema, module, { destination }) + if (callback && allocatedPrimitiveProxies[type]) { + type = allocatedPrimitiveProxies[type] + } + return (param.required ? paramRequired : paramOptional).replace(/\$\{method\.param\.name\}/g, param.name).replace(/\$\{method\.param\.type\}/g, type) + }).join(', ') } const getTemplate = (name) => { - if (name[0] !== '/') { - name = '/' + name - } - return templates[Object.keys(templates).find(k => k === name)] || templates[Object.keys(templates).find(k => k.startsWith(name.split('.').shift() + '.'))] || '' + if (name[0] !== '/') { + name = '/' + name + } + return templates[Object.keys(templates).find(k => k === name)] || templates[Object.keys(templates).find(k => k.startsWith(name.split('.').shift() + '.'))] || '' } -function insertSchemaMacros(content, schema, module, name, recursive=true) { - const title = name || schema.title || '' - let moduleTitle = module.info.title - - // TODO: this assumes the same title doesn't exist in multiple x-schema groups! - if (schema.title && module['x-schemas']) { - Object.entries(module['x-schemas']).forEach(([title, module]) => { - Object.values(module).forEach(s => { - if (schema.title === s.title) { - moduleTitle = title - } - }) - }) - } +// TODO: this assumes the same title doesn't exist in multiple x-schema groups! +const getXSchemaGroup = (schema, module) => { + let group = module.info.title - content = content - .replace(/\$\{title\}/g, title) - .replace(/\$\{Title\}/g, capitalize(title)) - .replace(/\$\{TITLE\}/g, title.toUpperCase()) - .replace(/\$\{description\}/g, schema.description ? schema.description : '') - .replace(/\$\{summary\}/g, schema.description ? schema.description.split('\n')[0] : '') - .replace(/\$\{name\}/g, title) - .replace(/\$\{NAME\}/g, title.toUpperCase()) - .replace(/\$\{info.title\}/g, moduleTitle) - .replace(/\$\{info.Title\}/g, capitalize(moduleTitle)) - .replace(/\$\{info.TITLE\}/g, moduleTitle.toUpperCase()) - // .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module, { name: title })) + if (schema.title && module['x-schemas']) { + Object.entries(module['x-schemas']).forEach(([title, module]) => { + Object.values(module).forEach(s => { + if (schema.title === s.title) { + group = title + } + }) + }) + } + return group +} - if (recursive) { - content = content.replace(/\$\{type\}/g, getSchemaType(schema, module, { name: title, destination: state.destination, section: state.section, code: false })) - } - return content +function insertSchemaMacros(content, schema, module, name, parent, property, recursive = true) { + const title = name || schema.title || '' + let moduleTitle = getXSchemaGroup(schema, module) + + content = content + .replace(/\$\{title\}/g, title) + .replace(/\$\{Title\}/g, capitalize(title)) + .replace(/\$\{TITLE\}/g, title.toUpperCase()) + .replace(/\$\{property\}/g, property) + .replace(/\$\{Property\}/g, capitalize(property)) + .replace(/\$\{parent\.title\}/g, parent) + .replace(/\$\{parent\.Title\}/g, capitalize(parent)) + .replace(/\$\{description\}/g, schema.description ? schema.description : '') + .replace(/\$\{summary\}/g, schema.description ? schema.description.split('\n')[0] : '') + .replace(/\$\{name\}/g, title) + .replace(/\$\{NAME\}/g, title.toUpperCase()) + .replace(/\$\{info.title\}/g, moduleTitle) + .replace(/\$\{info.Title\}/g, capitalize(moduleTitle)) + .replace(/\$\{info.TITLE\}/g, moduleTitle.toUpperCase()) + // .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module, { name: title })) + + if (recursive) { + content = content.replace(/\$\{type\}/g, getSchemaType(schema, module, { name: title, destination: state.destination, section: state.section, code: false })) + } + return content } // TODO using JSON.stringify probably won't work for many languages... const insertConstMacros = (content, schema, module, name) => { - content = content.replace(/\$\{value\}/g, JSON.stringify(schema.const)) - return content + content = content.replace(/\$\{value\}/g, JSON.stringify(schema.const)) + return content } const insertEnumMacros = (content, schema, module, name) => { - const template = content.split('\n') - - for (var i = 0; i < template.length; i++) { - if (template[i].indexOf('${key}') >= 0) { - template[i] = schema.enum.map(value => { - return template[i].replace(/\$\{key\}/g, safeName(value)) - .replace(/\$\{value\}/g, value) - }).join('\n') - } + const template = content.split('\n') + + for (var i = 0; i < template.length; i++) { + if (template[i].indexOf('${key}') >= 0) { + template[i] = schema.enum.map(value => { + return template[i].replace(/\$\{key\}/g, safeName(value)) + .replace(/\$\{value\}/g, value) + }).join('\n') } + } - return template.join('\n') + return template.join('\n') } -const insertObjectMacros = (content, schema, module, name, options) => { - options = JSON.parse(JSON.stringify(options)) - options.level = options.level + 1 - options.name = '' - - const template = content.split('\n') - const indent = (template.find(line => line.includes("${property}")).match(/^\s+/) || [''])[0] - - for (var i = 0; i < template.length; i++) { - if (template[i].indexOf('${property}') >= 0) { - const propertyTemplate = template[i] - template[i] = '' - if (schema.properties) { - template[i] = Object.entries(schema.properties).map(([name, prop], i) => { - - const schemaShape = getSchemaShape(prop, module, options) - return propertyTemplate - .replace(/(^\s+)/g, '$1'.repeat(options.level)) - .replace(/\$\{property\}/g, name) - .replace(/\$\{shape\}/g, schemaShape) - .replace(/\$\{description\}/g, prop.description || '') - .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') - .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, i === schema.properties.length-1 ? '' : '$1') - .replace(/\$\{if\.optional\}(.*?)\$\{end\.optional\}/g, schema.required && schema.required.includes(name) ? '' : '$1') - - }).join('\n') - } - else if (schema.propertyNames) { - const { propertyNames } = localizeDependencies(schema, module) - if (propertyNames.enum) { - template[i] = propertyNames.enum.map((prop, i) => { - // TODO: add language config feature for 'unknown' type - let type = { type: "null" } - - if (schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { - type = schema.additionalProperties - } - - if (schema.patternProperties) { - Object.entries(schema.patternProperties).forEach(([pattern, schema]) => { - let regex = new RegExp(pattern) - if (prop.match(regex)) { - type = schema - } - }) - } - - const schemaShape = getSchemaShape(type, module, options) - return propertyTemplate - .replace(/\$\{property\}/g, safeName(prop)) - .replace(/\$\{shape\}/g, schemaShape) - .replace(/\$\{description\}/g, prop.description || '') - .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') - .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, i === propertyNames.enum.length-1 ? '' : '$1') - .replace(/\$\{if\.optional\}(.*?)\$\{end\.optional\}/g, schema.required && schema.required.includes(prop) ? '' : '$1') - }).join('\n') - } - } - else if (schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { - // TODO: this won't work for custom types, only primatives... - // TODO: not all languages support additional properties... - // TODO: this is hard coded to typescript - let type = getSchemaType(schema.additionalProperties, module, options) - const shape = getSchemaShape({ type: type }, module, options) - template[i] = propertyTemplate - .replace(/\$\{property\}/g, '[property: string]') - .replace(/\$\{shape\}/g, shape) - .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, '') - .replace(/\$\{if\.optional\}(.*?)\$\{end\.optional\}/g, '') - } - } - else if (i !== 0) { - template[i] = indent.repeat(options.level-1) + template[i] - } +const insertObjectMacros = (content, schema, module, title, property, options) => { + options = options ? JSON.parse(JSON.stringify(options)) : {} + + const options2 = JSON.parse(JSON.stringify(options)) + options2.parent = title + options2.level = options.level + 1 + options2.name = '' + + ;(['properties', 'properties.register', 'properties.assign']).forEach(macro => { + const indent = (content.split('\n').find(line => line.includes("${" + macro + "}")) || '').match(/^\s+/) || [''][0] + const templateType = macro.split('.').slice(1).join('') + const template = getTemplate(path.join(options.templateDir, 'property' + (templateType ? `-${templateType}` : ''))) + + const properties = [] + + if (schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { + const template = getTemplate(path.join(options.templateDir, 'additionalProperties')) + let type = getSchemaType(schema.additionalProperties, module, options2) + const shape = getSchemaShape(schema.additionalProperties, module, options2) + properties.push(template + .replace(/\$\{property\}/g, '') + .replace(/\$\{Property\}/g, '') + .replace(/\$\{shape\}/g, shape) + .replace(/\$\{parent\.title\}/g, title) + .replace(/\$\{title\}/g, type) + .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, '') + .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/g, '')) + } + + if (schema.properties) { + Object.entries(schema.properties).forEach(([name, prop], i) => { + options2.property = name + const schemaShape = getSchemaShape(prop, module, options2) + + properties.push((i !== 0 ? indent : '') + template + .replace(/(^\s+)/g, '$1'.repeat(options2.level)) + .replace(/\$\{property\}/g, name) + .replace(/\$\{Property\}/g, capitalize(name)) + .replace(/\$\{parent\.title\}/g, title) + .replace(/\$\{title\}/g, getSchemaType(prop, module, options2)) + .replace(/\$\{shape\}/g, schemaShape) + .replace(/\$\{description\}/g, prop.description || '') + .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') + .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/gms, i === schema.properties.length - 1 ? '' : '$1') + .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, schema.required && schema.required.includes(name) ? '' : '$1')) + }) + } + + if (schema.propertyNames) { + const { propertyNames } = localizeDependencies(schema, module) + if (propertyNames.enum) { + propertyNames.enum.forEach((prop, i) => { + if (schema.properties && schema.properties[prop]) { + // skip properties that were already defined above + return + } + // TODO: add language config feature for 'unknown' type + let type; // = { type: "null" } + + if (schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { + type = schema.additionalProperties + } + + if (schema.patternProperties) { + Object.entries(schema.patternProperties).forEach(([pattern, schema]) => { + let regex = new RegExp(pattern) + if (prop.match(regex)) { + type = schema + } + }) + } + + if (type) { + options2.property = prop + const schemaShape = getSchemaShape(type, module, options2) + properties.push(template + .replace(/\$\{property\}/g, safeName(prop)) + .replace(/\$\{Property\}/g, capitalize(safeName(prop))) + .replace(/\$\{parent\.title\}/g, title) + .replace(/\$\{title\}/g, getSchemaType(type, module, options2)) + .replace(/\$\{shape\}/g, schemaShape) + .replace(/\$\{description\}/g, prop.description || '') + .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') + .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/gms, i === propertyNames.enum.length - 1 ? '' : '$1') + .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, schema.required && schema.required.includes(prop) ? '' : '$1')) + } + }) + } } + + const regex = new RegExp("\\$\\{" + macro + "\\}", "g") - return template.join('\n') + content = content.replace(regex, properties.join('\n')) + }) + + return content } const insertArrayMacros = (content, schema, module, name) => { - return content + return content } -const insertTupleMacros = (content, schema, module, name, options) => { - const template = content.split('\n') - options.level = options.level + 1 - options.name = '' - - for (var i = 0; i < template.length; i++) { - if (template[i].indexOf('${property}') >= 0) { - const propertyTemplate = template[i] - template[i] = '' - template[i] = schema.items.map((prop, i) => { - - const schemaShape = getSchemaShape(prop, module, options) - return propertyTemplate - .replace(/\$\{property\}/g, prop['x-property']) - .replace(/\$\{shape\}/g, schemaShape) - .replace(/\$\{description\}/g, prop.description || '') - .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') - .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, i === schema.items.length-1 ? '' : '$1') - - }).join('\n') - } - } +const insertTupleMacros = (content, schema, module, title, options) => { + options.level = options.level + 1 + options.name = '' + + const propTemplate = getTemplate(path.join(options.templateDir, 'property')) + const itemsTemplate = getTemplate(path.join(options.templateDir, 'items')) + + const doMacroWork = (str, prop, i) => { + const schemaShape = getSchemaShape(prop, module, options) + + return str + .replace(/\$\{property\}/g, prop['x-property']) + .replace(/\$\{Property\}/g, capitalize(prop['x-property'])) + .replace(/\$\{parent\.title\}/g, title) + .replace(/\$\{shape\}/g, schemaShape) + .replace(/\$\{type\}/g, getSchemaType(prop, module, options)) + .replace(/\$\{description\}/g, prop.description || '') + .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') + .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, i === schema.items.length - 1 ? '' : '$1') + .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, '') + } + + content = content.replace(/\$\{properties\}/g, schema.items.map((prop, i) => doMacroWork(propTemplate, prop, i)).join('\n')) + content = content.replace(/\$\{items\}/g, schema.items.map((prop, i) => doMacroWork(itemsTemplate, prop, i)).join('\n')) - return template.join('\n') + return content } -const insertPrimitiveMacros = (content, schema, module, name) => { - content = content.replace(/\$\{type\}/g, primitives[schema.type]) - return content +const getPrimitiveType = (type, templateDir) => { + const template = getTemplate(path.join(templateDir, type)) + return primitives[type] || template +} + +const pickBestType = types => Array.isArray(types) ? types.find(t => t !== 'null') : types + +const insertPrimitiveMacros = (content, schema, module, name, templateDir) => { + content = content.replace(/\$\{type\}/g, getPrimitiveType(pickBestType(schema.type), templateDir)) + return content } const insertAnyOfMacros = (content, schema, module, name) => { - const itemTemplate = content - content = schema.anyOf.map((item, i) => itemTemplate - .replace(/\$\{type\}/g, getSchemaType(item, module)) - .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, i === schema.anyOf.length-1 ? '' : '$1') - ).join('') - return content + const itemTemplate = content + content = schema.anyOf.map((item, i) => itemTemplate + .replace(/\$\{type\}/g, getSchemaType(item, module)) + .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, i === schema.anyOf.length - 1 ? '' : '$1') + ).join('') + return content } -function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', name = '', property = '', level = 0, summary, descriptions = true, destination, section, enums = true } = {}) { - schema = JSON.parse(JSON.stringify(schema)) +function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', name = '', parent = '', property = '', level = 0, summary, descriptions = true, destination, section, enums = true, skipTitleOnce = false } = {}) { + schema = JSON.parse(JSON.stringify(schema)) - state.destination = destination - state.section = section + state.destination = destination + state.section = section - if (level === 0 && !schema.title) { - return '' - } + if (level === 0 && !schema.title) { + return '' + } + + const suffix = destination && ('.' + destination.split('.').pop()) || '' + const theTitle = insertSchemaMacros(getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, schema.title || name, parent, property, false) - const suffix = destination && ('.' + destination.split('.').pop()) || '' - const theTitle = insertSchemaMacros(getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, schema.title || '', false) + let result = level === 0 ? getTemplate(path.join(templateDir, 'default' + suffix)) : '${shape}' - let result = level === 0 ? getTemplate(path.join(templateDir, 'default' + suffix)) : '${shape}' + if (enums && level === 0 && schema.type === "string" && Array.isArray(schema.enum)) { + result = getTemplate(path.join(templateDir, 'enum' + suffix)) + return insertSchemaMacros(insertEnumMacros(result, schema, module, theTitle), schema, module, theTitle, parent, property) + } - if (enums && level === 0 && schema.type === "string" && Array.isArray(schema.enum)) { - result = getTemplate(path.join(templateDir, 'enum' + suffix)) - return insertSchemaMacros(insertEnumMacros(result, schema, module, theTitle), schema, module, theTitle) + if (schema['$ref']) { + const someJson = getPath(schema['$ref'], module) + if (someJson) { + return getSchemaShape(someJson, module, { templateDir, name, parent, property, level, summary, descriptions, destination, enums: false }) } + throw "Unresolvable $ref: " + schema['ref'] + ", in " + module.info.title + } + else if (schema.hasOwnProperty('const')) { + const shape = insertConstMacros(getTemplate(path.join(templateDir, 'const' + suffix)), schema, module, theTitle) + result = insertSchemaMacros(result.replace(/\$\{shape\}/g, shape), schema, module, theTitle, parent, property) + return result + } + else if (!skipTitleOnce && (level > 0) && schema.title) { + // TODO: allow the 'ref' template to actually insert the shape using getSchemaShape + const innerShape = getSchemaShape(schema, module, { skipTitleOnce: true, templateDir, name, parent, property, level, summary, descriptions, destination, enums: false }) - if (schema['$ref']) { - const someJson = getPath(schema['$ref'], module) - if (someJson) { - return getSchemaShape(someJson, module, { name, level, summary, descriptions, destination, enums: false }) - } - throw "Unresolvable $ref: " + schema['ref'] + ", in " + module.info.title - } - else if (schema.hasOwnProperty('const')) { - const shape = insertConstMacros(getTemplate(path.join(templateDir, 'const' + suffix)), schema, module, theTitle) - result = insertSchemaMacros(result.replace(/\$\{shape\}/g, shape), schema, module, theTitle) - return result - } - else if (level > 0 && schema.title) { - const shape = getTemplate(path.join(templateDir, 'ref' + suffix)) - result = result.replace(/\$\{shape\}/g, shape) - return insertSchemaMacros(result, schema, module, theTitle) - } - else if (schema.type === 'object') { - const shape = insertObjectMacros(getTemplate(path.join(templateDir, 'object' + suffix)), schema, module, theTitle, {level, descriptions, destination, section, enums }) - result = result.replace(/\$\{shape\}/g, shape) - return insertSchemaMacros(result, schema, module, theTitle) - } - else if (schema.anyOf || schema.oneOf) { - // borry anyOf logic, note that schema is a copy, so we're not breaking it. - if (!schema.anyOf) { - schema.anyOf = schema.oneOf - } - const shape = insertAnyOfMacros(getTemplate(path.join(templateDir, 'anyOf' + suffix)), schema, module, theTitle) - result = result.replace(/\$\{shape\}/g, shape) - return insertSchemaMacros(result, schema, module, theTitle) - } - else if (schema.allOf) { - const merger = (key) => function(a, b) { - if (a.const) { - return JSON.parse(JSON.stringify(a)) - } - else if (b.const) { - return JSON.parse(JSON.stringify(b)) - } - else { - return deepmerge(a, b, {customMerge: merger}) - } - } + const shape = getTemplate(path.join(templateDir, 'ref' + suffix)) + .replace(/\$\{shape\}/g, innerShape) - let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x).reverse()], { - customMerge: merger - }) + result = result.replace(/\$\{shape\}/g, shape) + return insertSchemaMacros(result, schema, module, theTitle, parent, property) + } + else if (schema.type === 'object') { + const shape = insertObjectMacros(getTemplate(path.join(templateDir, 'object' + suffix)), schema, module, theTitle, property, { level, parent, property, templateDir, descriptions, destination, section, enums }) - if (schema.title) { - union.title = schema.title + result = result.replace(/\$\{shape\}/g, shape) + return insertSchemaMacros(result, schema, module, theTitle, parent, property) + } + else if (schema.anyOf || schema.oneOf) { + // borrow anyOf logic, note that schema is a copy, so we're not breaking it. + if (!schema.anyOf) { + schema.anyOf = schema.oneOf + } + const shape = insertAnyOfMacros(getTemplate(path.join(templateDir, 'anyOf' + suffix)), schema, module, theTitle) + result = result.replace(/\$\{shape\}/g, shape) + return insertSchemaMacros(result, schema, module, theTitle, parent, property) + } + else if (schema.allOf) { + const merger = (key) => function (a, b) { + if (a.const) { + return JSON.parse(JSON.stringify(a)) + } + else if (b.const) { + return JSON.parse(JSON.stringify(b)) + } + else { + return deepmerge(a, b, { customMerge: merger }) } - delete union['$ref'] - - return getSchemaShape(union, module, { name, level, summary, descriptions, destination }) - } - else if (schema.type === "array" && schema.items && !Array.isArray(schema.items)) { - // array - const items = getSchemaShape(schema.items, module, { name, level, summary, descriptions, destination }) - const shape = insertArrayMacros(getTemplate(path.join(templateDir, 'array' + suffix)), schema, module, items) - result = result.replace(/\$\{shape\}/g, shape) - return insertSchemaMacros(result, schema, module, items) - } - else if (schema.type === "array" && schema.items && Array.isArray(schema.items)) { - // tuple - const shape = insertTupleMacros(getTemplate(path.join(templateDir, 'tuple' + suffix)), schema, module, theTitle, {level, descriptions, destination, section, enums }) - result = result.replace(/\$\{shape\}/g, shape) - return insertSchemaMacros(result, schema, module, theTitle) - } - else if (schema.type) { - const shape = insertPrimitiveMacros(getTemplate(path.join(templateDir, 'primitive' + suffix)), schema, module, theTitle) - result = result.replace(/\$\{shape\}/g, shape) - if (theTitle || level > 0) { - return insertSchemaMacros(result, schema, module, theTitle) - } } - return '' + let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x).reverse()], { + customMerge: merger + }) + + if (schema.title) { + union.title = schema.title + } + delete union['$ref'] + + return getSchemaShape(union, module, { templateDir, name, parent, property, level, summary, descriptions, destination, enums: false }) + } + else if (schema.type === "array" && schema.items && isSupportedTuple(schema)) { + // tuple + const shape = insertTupleMacros(getTemplate(path.join(templateDir, 'tuple' + suffix)), schema, module, theTitle, { level, templateDir, descriptions, destination, section, enums }) + result = result.replace(/\$\{shape\}/g, shape) + return insertSchemaMacros(result, schema, module, theTitle, parent, property) + } + else if (schema.type === "array" && schema.items && !Array.isArray(schema.items)) { + // array + const items = getSchemaShape(schema.items, module, { templateDir, name, parent, property, level, summary, descriptions, destination, enums: false }) + const shape = insertArrayMacros(getTemplate(path.join(templateDir, 'array' + suffix)), schema, module, items) + result = result.replace(/\$\{shape\}/g, shape) + return insertSchemaMacros(result, schema, module, items, parent, property) + } + else if (schema.type) { + const shape = insertPrimitiveMacros(getTemplate(path.join(templateDir, 'primitive' + suffix)), schema, module, theTitle, templateDir) + result = result.replace(/\$\{shape\}/g, shape) + if (level > 0) { + return insertSchemaMacros(result, schema, module, theTitle, parent, property) + } } - function getSchemaType(schema, module, { destination, templateDir = 'types', link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - const wrap = (str, wrapper) => wrapper + str + wrapper - - const suffix = destination && ('.' + destination.split('.').pop()) || '' - const theTitle = insertSchemaMacros(getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, schema.title || '', false) + return '' +} - if (schema['$ref']) { - if (schema['$ref'][0] === '#') { - return getSchemaType(getPath(schema['$ref'], module), module, {title: true, link: link, code: code, destination}) - } - else { - // TODO: This never happens... but might be worth keeping in case we link to an opaque external schema at some point? +const isHomogenous = schema => { + if (schema.items && Array.isArray(schema.items)) { + // all items have a type and they are all the same + if (schema.items.length === 0) { + return true + } + else if (schema.items.every(item => item.type) && schema.items.every(item => item.type === schema.items[0].type)) { + return true + } + else if (schema.items.every(item => item.$ref) && schema.items.every(item => item.$ref === schema.items[0].$ref)) { + return true + } + else { + return false + } + } + return true +} - if (link) { - return '[' + wrap(theTitle, code ? '`' : '') + '](' + schema['$ref'] + ')' - } - else { - return wrap(theTitle, code ? '`' : '') - } - } +const isTuple = schema => schema.items && Array.isArray(schema.items) + +const isSupportedTuple = schema => { + + if (schema.items && Array.isArray(schema.items)) { + // if the convert flag isn't set, then all tuples are supported + if (!convertTuplesToArraysOrObjects) { + return true } - else if (title && schema.title) { - if (link) { - return '[' + wrap(theTitle, code ? '`' : '') + '](#' + schema.title.toLowerCase() + ')' + else { + // if every item has an `x-property` extension, then this tuple is supported (tuple template can use ${property}) + if (schema.items.every(item => item['x-property'])) { + return true + } + // For homogenous tuples just treat them as arrays (i.e. not tuples) + else if (isHomogenous(schema)) { + console.log(`Treating homogenous tuple as array ${schema.items.map(item => item.type||item.$ref).join(' | ')}: ${convertTuplesToArraysOrObjects}`) + return false } else { - return wrap(theTitle, code ? '`' : '') + console.log(`Warning: non-homogenous tuples not supported (schema: ${schema.title})`) } } - else if (schema.const) { - return (typeof schema.const === 'string' ? `'${schema.const}'` : schema.const) + } + else { + return false + } +} + +function getSchemaType(schema, module, { destination, templateDir = 'types', link = false, title = false, code = false, asPath = false, event = false, result = false, expandEnums = true, baseUrl = '', namespace = false } = {}) { + const wrap = (str, wrapper) => wrapper + str + wrapper + + const suffix = destination && ('.' + destination.split('.').pop()) || '' + const namespaceStr = namespace ? getTemplate(path.join(templateDir, 'namespace' + suffix)) : '' + const theTitle = insertSchemaMacros(namespaceStr + getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, schema.title || '', '', '', false) + const allocatedProxy = event || result + + if (schema['$ref']) { + if (schema['$ref'][0] === '#') { + return getSchemaType(getPath(schema['$ref'], module), module, {destination, templateDir, link, title, code, asPath, event, result, expandEnums, baseUrl, namespace })// { link: link, code: code, destination }) } - else if (schema['x-method']) { - const target = JSON.parse(JSON.stringify(module.methods.find(m => m.name === schema['x-method'].split('.').pop()))) + else { + // TODO: This never happens... but might be worth keeping in case we link to an opaque external schema at some point? - // transform the method copy params to be in the order of the x-additional-params array (and leave out any we don't want) - if (schema['x-additional-params']) { - const params = [] - schema['x-additional-params'].forEach(key => { - params.push(target.params.find(p => p.name === key)) - }) - target.params = params + if (link) { + return '[' + wrap(theTitle, code ? '`' : '') + '](' + schema['$ref'] + ')' } else { - target.params = [] + return wrap(theTitle, code ? '`' : '') } - - // TODO: this is TypeScript specific - const params = getMethodSignatureParams(target, module, { destination }) - const result = getSchemaType(target.result.schema, module, { destination }) - return `(${params}) => Promise<${result}>` } - else if (schema.type === 'string' && schema.enum) { - let type = expandEnums ? schema.enum.map(e => wrap(e, '\'')).join(' | ') : schema.type - if (code) { - type = wrap(type, '`') - } - return type + } + else if (title && schema.title) { + if (link) { + return '[' + wrap(theTitle, code ? '`' : '') + '](#' + schema.title.toLowerCase() + ')' } - // else if (schema.type === 'array' && Array.isArray(schema.items)) { - // // tuple - // } - else if ((schema.type === 'object' || (schema.type === 'array' && Array.isArray(schema.items))) && schema.title) { - const maybeGetPath = (path, json) => { - try { - return getPath(path, json) - } - catch (e) { - return null - } - } - - const def = maybeGetPath('#/definitions/' + schema.title, module) || maybeGetPath('#/components/schemas/' + schema.title, module) - - if (def && link) { - return '[' + wrap(theTitle, code ? '`' : '') + '](./' + '#' + schema.title.toLowerCase() + ')' - } - else { - return wrap(theTitle, code ? '`' : '') - } + else { + return wrap(theTitle, code ? '`' : '') } - else if (schema.type === 'array' && schema.items) { - if (Array.isArray(schema.items)) { - let type = '[' + schema.items.map(x => getSchemaType(x, module, { destination })).join(', ') + ']' // no links, no code - - if (code) { - type = wrap(type, '`') - } - - return type - } - else { - // grab the type for the non-array schema, so we get the link for free - let type = getSchemaType(schema.items, module, {code: code, link: link, title: title, destination}) - // insert the [] into the type - if (link) { - type = type.replace(/\[(`?)(.*)(`?)\]/, '\[$1$2\[\]$3\]') - } - else { - type = type.replace(/(`?)(.*)(`?)/, '$1$2\[\]$3') - } - return type - } + } + else if (schema.const) { + return (typeof schema.const === 'string' ? `'${schema.const}'` : schema.const) + } + else if (schema['x-method']) { + const target = JSON.parse(JSON.stringify(module.methods.find(m => m.name === schema['x-method'].split('.').pop()))) + + // transform the method copy params to be in the order of the x-additional-params array (and leave out any we don't want) + if (schema['x-additional-params']) { + const params = [] + schema['x-additional-params'].forEach(key => { + params.push(target.params.find(p => p.name === key)) + }) + target.params = params } - else if (schema.allOf) { - let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x)]) - if (schema.title) { - union.title = schema.title - } - return getSchemaType(union, module, { destination, link, title, code, asPath, baseUrl }) + else { + target.params = [] } - else if (schema.oneOf || schema.anyOf) { - if (event) { - return getSchemaType((schema.oneOf || schema.anyOf)[0], module, { destination, link, title, code, asPath, baseUrl }) - } - else { - const newOptions = JSON.parse(JSON.stringify({ destination, link, title, code, asPath, baseUrl })) - newOptions.code = false - const result = (schema.oneOf || schema.anyOf).map(s => getSchemaType(s, module, newOptions)).join(' | ') - return code ? wrap(result, '`') : result + const params = getMethodSignatureParams(target, module, { destination }) + const template = getTemplate(path.join(templateDir, 'x-method')) + return insertSchemaMacros(template.replace(/\$\{params\}/g, params), target.result.schema, module, theTitle, '', '', false) + } + else if (schema.type === 'string' && schema.enum) { + let type = expandEnums ? schema.enum.map(e => wrap(e, '\'')).join(' | ') : schema.type + if (code) { + type = wrap(type, '`') + } + return type + } + // else if (schema.type === 'array' && Array.isArray(schema.items)) { + // // tuple + // } + else if ((schema.type === 'object' || (schema.type === 'array')) && schema.title) { + const maybeGetPath = (path, json) => { + try { + return getPath(path, json) + } + catch (e) { + return null } } - else if (schema.type) { - const type = !Array.isArray(schema.type) ? primitives[schema.type] : primitives[schema.type.find(t => t !== 'null')] - return wrap(type, code ? '`' : '') + + const def = maybeGetPath('#/definitions/' + schema.title, module) || maybeGetPath('#/components/schemas/' + schema.title, module) + + if (def && link) { + return '[' + wrap(theTitle, code ? '`' : '') + '](./' + '#' + schema.title.toLowerCase() + ')' } else { - return wrap('void', code ? '`' : '') + return wrap(theTitle, code ? '`' : '') } } + else if (schema.type === 'array' && schema.items) { + let firstItem + if (Array.isArray(schema.items)) { + if (!isHomogenous(schema.items)) { + console.log(`Non-homogenous tuples not supported: ${schema.items} in ${module.info.title}, ${theTitle}`) + return '' + } + firstItem = schema.items[0] - function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - return '' - } + // let type = '[' + schema.items.map(x => getSchemaType(x, module, { destination })).join(', ') + ']' // no links, no code + } - function getTypeScriptType(jsonType) { - if (jsonType === 'integer') { - return 'number' + let template + // Tuple -> Array + if (convertTuplesToArraysOrObjects && isTuple(schema) && isHomogenous(schema)) { + template = insertArrayMacros(getTemplate(path.join(templateDir, 'array')), schema, module) + template = insertSchemaMacros(template, firstItem, module, getSchemaType(firstItem, module, {destination, templateDir, link, title, code, asPath, event, result, expandEnums, baseUrl, namespace }), '', '', false) + } + // Normal Array + else if (!isTuple(schema)) { + template = insertArrayMacros(getTemplate(path.join(templateDir, 'array')), schema, module) + template = insertSchemaMacros(template, schema, module, '', '', '', false) } else { - return jsonType + template = insertTupleMacros(getTemplate(path.join(templateDir, 'tuple')), schema, module, '', { templateDir }) + template = insertSchemaMacros(template, schema, module, '', '', '', false) } - } - const enumReducer = (acc, val, i, arr) => { - const keyName = val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() - acc = acc + ` ${keyName} = '${val}'` - if (i < arr.length-1) { - acc = acc.concat(',\n') + if (code) { + template = wrap(template, '`') + } + // TODO need to support link: true + return template + } + else if (schema.allOf) { + let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x)]) + if (schema.title) { + union.title = schema.title } - return acc + return getSchemaType(union, module, { destination, link, title, code, asPath, baseUrl }) } + else if (schema.oneOf || schema.anyOf) { + if (!schema.anyOf) { + schema.anyOf = schema.oneOf + } + const shape = insertAnyOfMacros(getTemplate(path.join(templateDir, 'anyOf' + suffix)), schema, module, theTitle) + return insertSchemaMacros(shape, schema, module, theTitle, '', '', false) - function getSchemaInstantiation(schema, module, { instantiationType }) { - return '' + + // if (event) { + // return getSchemaType((schema.oneOf || schema.anyOf)[0], module, { destination, link, title, code, asPath, baseUrl }) + // } + // else { + // const newOptions = JSON.parse(JSON.stringify({ destination, link, title, code, asPath, baseUrl })) + // newOptions.code = false + // const result = (schema.oneOf || schema.anyOf).map(s => getSchemaType(s, module, newOptions)).join(' | ') + + // return code ? wrap(result, '`') : result + // } + } + else if (schema.type) { + // TODO: this assumes that when type is an array of types, that it's one other primative & 'null', which isn't necessarily true. + const schemaType = !Array.isArray(schema.type) ? schema.type : schema.type.find(t => t !== 'null') + const primitive = getPrimitiveType(schemaType, templateDir) + const type = allocatedProxy ? allocatedPrimitiveProxies[schemaType] || primitive : primitive + return wrap(type, code ? '`' : '') + } + else { + // TODO this is TypeScript specific + return wrap('void', code ? '`' : '') } +} + +function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + return '' +} + +function getSchemaInstantiation(schema, module, { instantiationType }) { + return '' +} - export default { - setTemplates, - setPrimitives, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, - getJsonType, - getSchemaInstantiation - } \ No newline at end of file +export default { + setTemplates, + setPrimitives, + setConvertTuples, + setAllocatedPrimitiveProxies, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, + getJsonType, + getSchemaInstantiation +} \ No newline at end of file diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index b5103055..1316a1a6 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -63,6 +63,9 @@ const run = async ({ createModuleDirectories: config.createModuleDirectories, copySchemasIntoModules: config.copySchemasIntoModules, extractSubSchemas: config.extractSubSchemas, + convertTuplesToArraysOrObjects: config.convertTuplesToArraysOrObjects, + unwrapResultObjects: config.unwrapResultObjects, + allocatedPrimitiveProxies: config.allocatedPrimitiveProxies, additionalSchemaTemplates: config.additionalSchemaTemplates, staticModuleNames: staticModuleNames, hideExcluded: true, diff --git a/src/shared/json-schema.mjs b/src/shared/json-schema.mjs index e7bb1d86..8b65d9a9 100644 --- a/src/shared/json-schema.mjs +++ b/src/shared/json-schema.mjs @@ -355,6 +355,78 @@ const isDefinitionReferencedBySchema = (name = '', moduleJson = {}) => { return (refs.length > 0) } +function union(schemas) { + + const result = {}; + for (const schema of schemas) { + for (const [key, value] of Object.entries(schema)) { + if (!result.hasOwnProperty(key)) { + // If the key does not already exist in the result schema, add it + if (value && value.anyOf) { + result[key] = union(value.anyOf) + } else if (key === 'title' || key === 'description' || key === 'required') { + //console.warn(`Ignoring "${key}"`) + } else { + result[key] = value; + } + } else if (key === '$ref') { + if (result[key].endsWith("/ListenResponse")) { + + } + // If the key is '$ref' make sure it's the same + else if(result[key] === value) { + //console.warn(`Ignoring "${key}" that is already present and same`) + } else { + console.warn(`ERROR "${key}" is not same -${JSON.stringify(result, null, 4)} ${key} ${result[key]} - ${value}`); + throw "ERROR: $ref is not same" + } + } else if (key === 'type') { + // If the key is 'type', merge the types of the two schemas + if(result[key] === value) { + //console.warn(`Ignoring "${key}" that is already present and same`) + } else { + console.warn(`ERROR "${key}" is not same -${JSON.stringify(result, null, 4)} ${key} ${result[key]} - ${value}`); + throw "ERROR: type is not same" + } + } else { + //If the Key is a const then merge them into an enum + if(value && value.const) { + if(result[key].enum) { + result[key].enum = Array.from(new Set([...result[key].enum, value.const])) + } + else { + result[key].enum = Array.from(new Set([result[key].const, value.const])) + delete result[key].const + } + } + // If the key exists in both schemas and is not 'type', merge the values + else if (Array.isArray(result[key])) { + // If the value is an array, concatenate the arrays and remove duplicates + result[key] = Array.from(new Set([...result[key], ...value])) + } else if (result[key] && result[key].enum && value && value.enum) { + //If the value is an enum, merge the enums together and remove duplicates + result[key].enum = Array.from(new Set([...result[key].enum, ...value.enum])) + } else if (typeof result[key] === 'object' && typeof value === 'object') { + // If the value is an object, recursively merge the objects + result[key] = union([result[key], value]); + } else if (result[key] !== value) { + // If the value is a primitive and is not the same in both schemas, ignore it + //console.warn(`Ignoring conflicting value for key "${key}"`) + } + } + } + } + return result; +} + +function mergeAnyOf(schema) { + return union(schema.anyOf) +} + +function mergeOneOf(schema) { + return union(schema.oneOf) +} + export { getSchemaConstraints, getExternalSchemaPaths, @@ -368,5 +440,7 @@ export { localizeDependencies, replaceUri, replaceRef, - removeIgnoredAdditionalItems + removeIgnoredAdditionalItems, + mergeAnyOf, + mergeOneOf } \ No newline at end of file From 2c2067947f23074e86a46a32f51a4120d50ac2c7 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Thu, 27 Jul 2023 14:34:53 -0400 Subject: [PATCH 032/137] fix: Latest work --- languages/c-structs/language.config.json | 17 +++--- .../c-structs/templates/declarations/event.c | 6 +-- .../c-structs/templates/imports/default.cpp | 2 +- .../c-structs/templates/imports/default.h | 2 +- .../templates/imports/default.jsondata | 2 +- .../json-types/additionalProperties.c | 1 + .../c-structs/templates/json-types/anyOf.c | 1 + .../c-structs/templates/json-types/array.c | 4 ++ .../c-structs/templates/json-types/boolean.c | 1 + .../c-structs/templates/json-types/const.c | 0 .../templates/json-types/default.cpp | 1 + .../c-structs/templates/json-types/enum.cpp | 4 ++ .../c-structs/templates/json-types/enum.h | 4 ++ .../c-structs/templates/json-types/float.c | 1 + .../c-structs/templates/json-types/integer.c | 1 + .../templates/json-types/namespace.c | 1 + .../c-structs/templates/json-types/object.cpp | 25 +++++++++ .../templates/json-types/primitive.c | 0 .../templates/json-types/property-assign.cpp | 2 + .../json-types/property-register.cpp | 1 + .../templates/json-types/property.cpp | 1 + .../c-structs/templates/json-types/ref.c | 1 + .../c-structs/templates/json-types/string.c | 1 + .../c-structs/templates/json-types/title.c | 1 + .../c-structs/templates/json-types/tuple.c | 25 +++++++++ .../templates/json-types/types/object.c | 0 .../c-structs/templates/json-types/x-method.c | 1 + languages/c-structs/templates/methods/event.c | 6 +-- .../modules/include/Module_Accessors.h | 41 --------------- .../templates/modules/src/Module.cpp | 5 +- .../parameter-serialization/boolean.cpp | 2 + .../parameter-serialization/default.cpp | 2 + .../parameter-serialization/object.cpp | 2 + .../parameter-serialization/primitive.cpp | 2 + .../parameter-serialization/string.cpp | 2 + .../result-instantiation/boolean.cpp | 2 + .../result-instantiation/default.cpp | 1 + .../templates/result-instantiation/object.cpp | 4 ++ .../result-instantiation/primitive.cpp | 1 + .../templates/result-instantiation/string.cpp | 2 + .../schemas/include/Common/Module_Accessors.h | 39 -------------- .../templates/schemas/src/JsonData_Module.h | 2 +- languages/c-structs/templates/types/object.c | 2 +- .../c-structs/templates/types/property.c | 2 +- languages/c/templates/declarations/default.c | 2 +- languages/c/templates/types/array.c | 4 +- languages/c/templates/types/enum.h | 4 +- .../src/shared/Transport/LegacyTransport.mjs | 12 +++-- .../src/shared/Transport/MockTransport.mjs | 7 ++- .../javascript/src/shared/Transport/index.mjs | 38 +++++++------- src/macrofier/engine.mjs | 16 +++--- src/macrofier/types.mjs | 52 ++++++++++++++----- 52 files changed, 204 insertions(+), 154 deletions(-) create mode 100644 languages/c-structs/templates/json-types/additionalProperties.c create mode 100644 languages/c-structs/templates/json-types/anyOf.c create mode 100644 languages/c-structs/templates/json-types/array.c create mode 100644 languages/c-structs/templates/json-types/boolean.c create mode 100644 languages/c-structs/templates/json-types/const.c create mode 100644 languages/c-structs/templates/json-types/default.cpp create mode 100644 languages/c-structs/templates/json-types/enum.cpp create mode 100644 languages/c-structs/templates/json-types/enum.h create mode 100644 languages/c-structs/templates/json-types/float.c create mode 100644 languages/c-structs/templates/json-types/integer.c create mode 100644 languages/c-structs/templates/json-types/namespace.c create mode 100644 languages/c-structs/templates/json-types/object.cpp create mode 100644 languages/c-structs/templates/json-types/primitive.c create mode 100644 languages/c-structs/templates/json-types/property-assign.cpp create mode 100644 languages/c-structs/templates/json-types/property-register.cpp create mode 100644 languages/c-structs/templates/json-types/property.cpp create mode 100644 languages/c-structs/templates/json-types/ref.c create mode 100644 languages/c-structs/templates/json-types/string.c create mode 100644 languages/c-structs/templates/json-types/title.c create mode 100644 languages/c-structs/templates/json-types/tuple.c create mode 100644 languages/c-structs/templates/json-types/types/object.c create mode 100644 languages/c-structs/templates/json-types/x-method.c delete mode 100644 languages/c-structs/templates/modules/include/Module_Accessors.h create mode 100644 languages/c-structs/templates/parameter-serialization/boolean.cpp create mode 100644 languages/c-structs/templates/parameter-serialization/default.cpp create mode 100644 languages/c-structs/templates/parameter-serialization/object.cpp create mode 100644 languages/c-structs/templates/parameter-serialization/primitive.cpp create mode 100644 languages/c-structs/templates/parameter-serialization/string.cpp create mode 100644 languages/c-structs/templates/result-instantiation/boolean.cpp create mode 100644 languages/c-structs/templates/result-instantiation/default.cpp create mode 100644 languages/c-structs/templates/result-instantiation/object.cpp create mode 100644 languages/c-structs/templates/result-instantiation/primitive.cpp create mode 100644 languages/c-structs/templates/result-instantiation/string.cpp delete mode 100644 languages/c-structs/templates/schemas/include/Common/Module_Accessors.h diff --git a/languages/c-structs/language.config.json b/languages/c-structs/language.config.json index 1a7e83c0..1179d74e 100644 --- a/languages/c-structs/language.config.json +++ b/languages/c-structs/language.config.json @@ -3,17 +3,16 @@ "langcode": "c", "createModuleDirectories": false, "extractSubSchemas": true, + "unwrapResultObjects": true, "convertTuplesToArraysOrObjects": true, "templatesPerModule": [ - "/include/Module.h", - "/include/Module_Accessors.h", - "/src/Module.cpp" + "/include/module.h", + "/src/module.cpp" ], "templatesPerSchema": [ - "/include/Common/Module.h", - "/include/Common/Module_Accessors.h", - "/src/Module_Common.cpp", - "/src/JsonData_Module.h" + "/include/common/module.h", + "/src/module_common.cpp", + "/src/jsondata_module.h" ], "persistPermission": true, "primitives": { @@ -22,5 +21,7 @@ "number": "float", "string": "char*" }, - "additionalSchemaTemplates": [] + "additionalSchemaTemplates": [ + "json-types" + ] } diff --git a/languages/c-structs/templates/declarations/event.c b/languages/c-structs/templates/declarations/event.c index f91c6a39..c2f0e3d2 100644 --- a/languages/c-structs/templates/declarations/event.c +++ b/languages/c-structs/templates/declarations/event.c @@ -1,4 +1,4 @@ /* ${method.name} - ${method.description} */ -typedef void (*${info.Title}${method.Name}Callback)( const void* userData, ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${method.result.properties} ); -int ${info.title}_Register_${method.Name}( ${event.signature.params}${if.event.params}, ${end.if.event.params}${info.Title}${method.Name}Callback userCB, const void* userData ); -int ${info.title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); +typedef void (*F${info.Title}${method.Name}Callback)( const void* userData, ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${method.result.properties} ); +int F${info.title}_Register_${method.Name}( ${event.signature.params}${if.event.params}, ${end.if.event.params}F${info.Title}${method.Name}Callback userCB, const void* userData ); +int F${info.title}_Unregister_${method.Name}( F${info.Title}${method.Name}Callback userCB); diff --git a/languages/c-structs/templates/imports/default.cpp b/languages/c-structs/templates/imports/default.cpp index 69e241f9..caf84bc9 100644 --- a/languages/c-structs/templates/imports/default.cpp +++ b/languages/c-structs/templates/imports/default.cpp @@ -1 +1 @@ -#include "JsonData_${info.title}.h" +#include "jsondata_${info.title.lowercase}.h" diff --git a/languages/c-structs/templates/imports/default.h b/languages/c-structs/templates/imports/default.h index a38b58ef..56a97a40 100644 --- a/languages/c-structs/templates/imports/default.h +++ b/languages/c-structs/templates/imports/default.h @@ -1 +1 @@ -#include "Common/${info.title}.h" +#include "common/${info.title.lowercase}.h" diff --git a/languages/c-structs/templates/imports/default.jsondata b/languages/c-structs/templates/imports/default.jsondata index 69e241f9..caf84bc9 100644 --- a/languages/c-structs/templates/imports/default.jsondata +++ b/languages/c-structs/templates/imports/default.jsondata @@ -1 +1 @@ -#include "JsonData_${info.title}.h" +#include "jsondata_${info.title.lowercase}.h" diff --git a/languages/c-structs/templates/json-types/additionalProperties.c b/languages/c-structs/templates/json-types/additionalProperties.c new file mode 100644 index 00000000..b814e5fb --- /dev/null +++ b/languages/c-structs/templates/json-types/additionalProperties.c @@ -0,0 +1 @@ +// need cpp code to init, get, set, clear additional properties... \ No newline at end of file diff --git a/languages/c-structs/templates/json-types/anyOf.c b/languages/c-structs/templates/json-types/anyOf.c new file mode 100644 index 00000000..a2682179 --- /dev/null +++ b/languages/c-structs/templates/json-types/anyOf.c @@ -0,0 +1 @@ +/* AnyOf is not supported in C: ${title} */ \ No newline at end of file diff --git a/languages/c-structs/templates/json-types/array.c b/languages/c-structs/templates/json-types/array.c new file mode 100644 index 00000000..508a9eac --- /dev/null +++ b/languages/c-structs/templates/json-types/array.c @@ -0,0 +1,4 @@ +uint32_t ${info.Title}_${Title}Array_Size(${type} handle); +${type} ${title}Array_Get(${type} handle, uint32_t index); +void ${info.Title}_${Title}Array_Add(${propertyType} handle, ${valueType} value); +void ${info.Title}_${Title}Array_Clear(${propertyType} handle); diff --git a/languages/c-structs/templates/json-types/boolean.c b/languages/c-structs/templates/json-types/boolean.c new file mode 100644 index 00000000..18bbeec2 --- /dev/null +++ b/languages/c-structs/templates/json-types/boolean.c @@ -0,0 +1 @@ +WPEFramework::Core::JSON::Boolean \ No newline at end of file diff --git a/languages/c-structs/templates/json-types/const.c b/languages/c-structs/templates/json-types/const.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/json-types/default.cpp b/languages/c-structs/templates/json-types/default.cpp new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/c-structs/templates/json-types/default.cpp @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/c-structs/templates/json-types/enum.cpp b/languages/c-structs/templates/json-types/enum.cpp new file mode 100644 index 00000000..6776b41a --- /dev/null +++ b/languages/c-structs/templates/json-types/enum.cpp @@ -0,0 +1,4 @@ + /* ${title} ${description} */ + ENUM_CONVERSION_BEGIN(${name}) + { ${NAME}_${key}, _T("${value}") }, + ENUM_CONVERSION_END(${name}) diff --git a/languages/c-structs/templates/json-types/enum.h b/languages/c-structs/templates/json-types/enum.h new file mode 100644 index 00000000..92108c75 --- /dev/null +++ b/languages/c-structs/templates/json-types/enum.h @@ -0,0 +1,4 @@ +/* ${title} ${description} */ +typedef enum { + ${NAME}_${key}, +} ${name}; diff --git a/languages/c-structs/templates/json-types/float.c b/languages/c-structs/templates/json-types/float.c new file mode 100644 index 00000000..c38bca91 --- /dev/null +++ b/languages/c-structs/templates/json-types/float.c @@ -0,0 +1 @@ +WPEFramework::Core::JSON::Float \ No newline at end of file diff --git a/languages/c-structs/templates/json-types/integer.c b/languages/c-structs/templates/json-types/integer.c new file mode 100644 index 00000000..b57fe26e --- /dev/null +++ b/languages/c-structs/templates/json-types/integer.c @@ -0,0 +1 @@ +WPEFramework::Core::JSON::DecSInt32 \ No newline at end of file diff --git a/languages/c-structs/templates/json-types/namespace.c b/languages/c-structs/templates/json-types/namespace.c new file mode 100644 index 00000000..8ea9d7de --- /dev/null +++ b/languages/c-structs/templates/json-types/namespace.c @@ -0,0 +1 @@ +FireboltSDK::${info.Title}:: \ No newline at end of file diff --git a/languages/c-structs/templates/json-types/object.cpp b/languages/c-structs/templates/json-types/object.cpp new file mode 100644 index 00000000..db24d12c --- /dev/null +++ b/languages/c-structs/templates/json-types/object.cpp @@ -0,0 +1,25 @@ + class ${title}: public WPEFramework::Core::JSON::Container { + public: + ~${title}() override = default; + + public: + ${title}() + : WPEFramework::Core::JSON::Container() + { + ${properties.register} + } + + ${title}(const ${title}& other) + { + ${properties.assign} + } + + ${title}& operator=(const ${title}& other) + { + ${properties.assign} + return (*this); + } + + public: + ${properties} + }; diff --git a/languages/c-structs/templates/json-types/primitive.c b/languages/c-structs/templates/json-types/primitive.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/json-types/property-assign.cpp b/languages/c-structs/templates/json-types/property-assign.cpp new file mode 100644 index 00000000..cc1b2860 --- /dev/null +++ b/languages/c-structs/templates/json-types/property-assign.cpp @@ -0,0 +1,2 @@ +Add(_T("${property}"), &${Property}); +${Property} = other.${Property} \ No newline at end of file diff --git a/languages/c-structs/templates/json-types/property-register.cpp b/languages/c-structs/templates/json-types/property-register.cpp new file mode 100644 index 00000000..f9b86372 --- /dev/null +++ b/languages/c-structs/templates/json-types/property-register.cpp @@ -0,0 +1 @@ +Add(_T("${property}"), &${Property}); \ No newline at end of file diff --git a/languages/c-structs/templates/json-types/property.cpp b/languages/c-structs/templates/json-types/property.cpp new file mode 100644 index 00000000..46e3ef8e --- /dev/null +++ b/languages/c-structs/templates/json-types/property.cpp @@ -0,0 +1 @@ +${title} ${Property}; \ No newline at end of file diff --git a/languages/c-structs/templates/json-types/ref.c b/languages/c-structs/templates/json-types/ref.c new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/c-structs/templates/json-types/ref.c @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/c-structs/templates/json-types/string.c b/languages/c-structs/templates/json-types/string.c new file mode 100644 index 00000000..2d60a3c8 --- /dev/null +++ b/languages/c-structs/templates/json-types/string.c @@ -0,0 +1 @@ +FireboltSDK::JSON::String \ No newline at end of file diff --git a/languages/c-structs/templates/json-types/title.c b/languages/c-structs/templates/json-types/title.c new file mode 100644 index 00000000..ae1512e5 --- /dev/null +++ b/languages/c-structs/templates/json-types/title.c @@ -0,0 +1 @@ +JsonData_${Title} \ No newline at end of file diff --git a/languages/c-structs/templates/json-types/tuple.c b/languages/c-structs/templates/json-types/tuple.c new file mode 100644 index 00000000..db24d12c --- /dev/null +++ b/languages/c-structs/templates/json-types/tuple.c @@ -0,0 +1,25 @@ + class ${title}: public WPEFramework::Core::JSON::Container { + public: + ~${title}() override = default; + + public: + ${title}() + : WPEFramework::Core::JSON::Container() + { + ${properties.register} + } + + ${title}(const ${title}& other) + { + ${properties.assign} + } + + ${title}& operator=(const ${title}& other) + { + ${properties.assign} + return (*this); + } + + public: + ${properties} + }; diff --git a/languages/c-structs/templates/json-types/types/object.c b/languages/c-structs/templates/json-types/types/object.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c-structs/templates/json-types/x-method.c b/languages/c-structs/templates/json-types/x-method.c new file mode 100644 index 00000000..573c9f8e --- /dev/null +++ b/languages/c-structs/templates/json-types/x-method.c @@ -0,0 +1 @@ +void* \ No newline at end of file diff --git a/languages/c-structs/templates/methods/event.c b/languages/c-structs/templates/methods/event.c index 766a78b3..6e0e966a 100644 --- a/languages/c-structs/templates/methods/event.c +++ b/languages/c-structs/templates/methods/event.c @@ -1,5 +1,5 @@ /* ${method.name} - ${method.description} */ -static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) +static void F${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) { ${event.callback.params.serialization} ASSERT(jsonResponse->IsValid() == true); @@ -9,7 +9,7 @@ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* callback(userData, ${event.callback.response.instantiation}); } } -int ${info.title}_Register_${method.Name}( ${event.signature.params}${if.event.params}, ${end.if.event.params}${info.Title}${method.Name}Callback userCB, const void* userData ) +int F${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}"); int status = FireboltSDKErrorNone; @@ -20,7 +20,7 @@ int ${info.title}_Register_${method.Name}( ${event.signature.params}${if.event.p } return status; } -int ${info.title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB) +int F${info.title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB) { return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title}.${method.name}"), reinterpret_cast(userCB)); } diff --git a/languages/c-structs/templates/modules/include/Module_Accessors.h b/languages/c-structs/templates/modules/include/Module_Accessors.h deleted file mode 100644 index fbcd5cfb..00000000 --- a/languages/c-structs/templates/modules/include/Module_Accessors.h +++ /dev/null @@ -1,41 +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 - */ - -#ifndef _${info.TITLE}_H -#define _${info.TITLE}_H - -#include "Firebolt.h" -/* ${IMPORTS} */ - -#ifdef __cplusplus -extern "C" { -#endif - -// Enums - -/* ${ENUMS} */ - -/* ${TYPES:accessors} */ - -/* ${DECLARATIONS} */ - -#ifdef __cplusplus -} -#endif - -#endif // Header Include Guard diff --git a/languages/c-structs/templates/modules/src/Module.cpp b/languages/c-structs/templates/modules/src/Module.cpp index 65721f1e..7d59c172 100644 --- a/languages/c-structs/templates/modules/src/Module.cpp +++ b/languages/c-structs/templates/modules/src/Module.cpp @@ -23,17 +23,16 @@ namespace FireboltSDK { namespace ${info.title} { // Types - /* ${TYPES} */ + /* ${TYPES:json-types} */ } } -/* ${ENUMS} */ +/* ${ENUMS:json-types} */ #ifdef __cplusplus extern "C" { #endif -/* ${ACCESSORS} */ /* ${METHODS} */ /* ${EVENTS} */ diff --git a/languages/c-structs/templates/parameter-serialization/boolean.cpp b/languages/c-structs/templates/parameter-serialization/boolean.cpp new file mode 100644 index 00000000..f924ac94 --- /dev/null +++ b/languages/c-structs/templates/parameter-serialization/boolean.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/c-structs/templates/parameter-serialization/default.cpp b/languages/c-structs/templates/parameter-serialization/default.cpp new file mode 100644 index 00000000..f924ac94 --- /dev/null +++ b/languages/c-structs/templates/parameter-serialization/default.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/c-structs/templates/parameter-serialization/object.cpp b/languages/c-structs/templates/parameter-serialization/object.cpp new file mode 100644 index 00000000..f924ac94 --- /dev/null +++ b/languages/c-structs/templates/parameter-serialization/object.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/c-structs/templates/parameter-serialization/primitive.cpp b/languages/c-structs/templates/parameter-serialization/primitive.cpp new file mode 100644 index 00000000..f924ac94 --- /dev/null +++ b/languages/c-structs/templates/parameter-serialization/primitive.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/c-structs/templates/parameter-serialization/string.cpp b/languages/c-structs/templates/parameter-serialization/string.cpp new file mode 100644 index 00000000..f924ac94 --- /dev/null +++ b/languages/c-structs/templates/parameter-serialization/string.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/c-structs/templates/result-instantiation/boolean.cpp b/languages/c-structs/templates/result-instantiation/boolean.cpp new file mode 100644 index 00000000..036b4a7d --- /dev/null +++ b/languages/c-structs/templates/result-instantiation/boolean.cpp @@ -0,0 +1,2 @@ + *${property} = jsonResult.Value(); + \ No newline at end of file diff --git a/languages/c-structs/templates/result-instantiation/default.cpp b/languages/c-structs/templates/result-instantiation/default.cpp new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/c-structs/templates/result-instantiation/default.cpp @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/c-structs/templates/result-instantiation/object.cpp b/languages/c-structs/templates/result-instantiation/object.cpp new file mode 100644 index 00000000..dcf0b333 --- /dev/null +++ b/languages/c-structs/templates/result-instantiation/object.cpp @@ -0,0 +1,4 @@ + WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); + *resultPtr = WPEFramework::Core::ProxyType::Create(); + *(*resultPtr) = jsonResult; + *${property} = static_cast<${info.Title}_${title}>(resultPtr); diff --git a/languages/c-structs/templates/result-instantiation/primitive.cpp b/languages/c-structs/templates/result-instantiation/primitive.cpp new file mode 100644 index 00000000..23bbace7 --- /dev/null +++ b/languages/c-structs/templates/result-instantiation/primitive.cpp @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/c-structs/templates/result-instantiation/string.cpp b/languages/c-structs/templates/result-instantiation/string.cpp new file mode 100644 index 00000000..b6c9dcb5 --- /dev/null +++ b/languages/c-structs/templates/result-instantiation/string.cpp @@ -0,0 +1,2 @@ + FireboltSDK::JSON::String* strResult = new FireboltSDK::JSON::String(jsonResult); + *value = static_cast(strResult); diff --git a/languages/c-structs/templates/schemas/include/Common/Module_Accessors.h b/languages/c-structs/templates/schemas/include/Common/Module_Accessors.h deleted file mode 100644 index e93a77a2..00000000 --- a/languages/c-structs/templates/schemas/include/Common/Module_Accessors.h +++ /dev/null @@ -1,39 +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 - */ - -#ifndef _COMMON_${info.TITLE}_H -#define _COMMON_${info.TITLE}_H - -#include "Firebolt.h" -/* ${IMPORTS} */ - -#ifdef __cplusplus -extern "C" { -#endif - -// Enums - -/* ${ENUMS} */ - -/* ${TYPES:accessors} */ - -#ifdef __cplusplus -} -#endif - -#endif // Header Include Guard diff --git a/languages/c-structs/templates/schemas/src/JsonData_Module.h b/languages/c-structs/templates/schemas/src/JsonData_Module.h index d0ecbbac..7c41a2ab 100644 --- a/languages/c-structs/templates/schemas/src/JsonData_Module.h +++ b/languages/c-structs/templates/schemas/src/JsonData_Module.h @@ -25,6 +25,6 @@ namespace FireboltSDK { namespace ${info.title} { // Types - /* ${SCHEMAS} */ + /* ${SCHEMAS:json-types} */ } } diff --git a/languages/c-structs/templates/types/object.c b/languages/c-structs/templates/types/object.c index 73cef62f..e6d948cd 100644 --- a/languages/c-structs/templates/types/object.c +++ b/languages/c-structs/templates/types/object.c @@ -1,3 +1,3 @@ struct { - ${shape}${property}; // ${summary} + ${properties} } \ No newline at end of file diff --git a/languages/c-structs/templates/types/property.c b/languages/c-structs/templates/types/property.c index 56b60ac9..7bd100e4 100644 --- a/languages/c-structs/templates/types/property.c +++ b/languages/c-structs/templates/types/property.c @@ -1 +1 @@ -${title} ${property} +${title} ${property}; \ No newline at end of file diff --git a/languages/c/templates/declarations/default.c b/languages/c/templates/declarations/default.c index ac4e7f78..2f8097a5 100644 --- a/languages/c/templates/declarations/default.c +++ b/languages/c/templates/declarations/default.c @@ -1,3 +1,3 @@ /* ${method.name} - ${method.description} ${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation}${end.if.deprecated} */ -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 F${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} ); diff --git a/languages/c/templates/types/array.c b/languages/c/templates/types/array.c index 508a9eac..0b9863c2 100644 --- a/languages/c/templates/types/array.c +++ b/languages/c/templates/types/array.c @@ -1,4 +1,4 @@ uint32_t ${info.Title}_${Title}Array_Size(${type} handle); ${type} ${title}Array_Get(${type} handle, uint32_t index); -void ${info.Title}_${Title}Array_Add(${propertyType} handle, ${valueType} value); -void ${info.Title}_${Title}Array_Clear(${propertyType} handle); +void ${info.Title}_${Title}Array_Add(${type} handle, ${type} value); +void ${info.Title}_${Title}Array_Clear(${type} handle); diff --git a/languages/c/templates/types/enum.h b/languages/c/templates/types/enum.h index 906d908d..92108c75 100644 --- a/languages/c/templates/types/enum.h +++ b/languages/c/templates/types/enum.h @@ -1,4 +1,4 @@ /* ${title} ${description} */ typedef enum { - ${info.TITLE}_${NAME}_${key}, -} ${info.Title}_${name}; + ${NAME}_${key}, +} ${name}; diff --git a/languages/javascript/src/shared/Transport/LegacyTransport.mjs b/languages/javascript/src/shared/Transport/LegacyTransport.mjs index 95632cb6..99b15ecf 100644 --- a/languages/javascript/src/shared/Transport/LegacyTransport.mjs +++ b/languages/javascript/src/shared/Transport/LegacyTransport.mjs @@ -16,6 +16,8 @@ * SPDX-License-Identifier: Apache-2.0 */ +const win = typeof win !== 'undefined' ? window : this + export default class LegacyTransport { constructor (bridge) { this.bridge = bridge @@ -26,18 +28,18 @@ export default class LegacyTransport { } receive (callback) { - window.$badger = window.$badger || {} + win.$badger = win.$badger || {} /** Hold on to real $badger callback and event methods so they can be called for non-jsonrpc messages */ - const badgerCallback = window.$badger.callback ? window.$badger.callback.bind(window.$badger) : null - const badgerEvent = window.$badger.event ? window.$badger.event.bind(window.$badger) : null - window.$badger.callback = (pid, success, json) => { + const badgerCallback = win.$badger.callback ? win.$badger.callback.bind(win.$badger) : null + const badgerEvent = win.$badger.event ? win.$badger.event.bind(win.$badger) : null + win.$badger.callback = (pid, success, json) => { if (json.jsonrpc) { callback(JSON.stringify(json)) } else if (badgerCallback) { badgerCallback(pid, success, json) } } - window.$badger.event = (handlerId, json) => { + win.$badger.event = (handlerId, json) => { if (json.jsonrpc) { callback(JSON.stringify(json)) } else if (badgerEvent) { diff --git a/languages/javascript/src/shared/Transport/MockTransport.mjs b/languages/javascript/src/shared/Transport/MockTransport.mjs index d52366fc..3d1c39be 100644 --- a/languages/javascript/src/shared/Transport/MockTransport.mjs +++ b/languages/javascript/src/shared/Transport/MockTransport.mjs @@ -16,6 +16,9 @@ * SPDX-License-Identifier: Apache-2.0 */ + +const win = typeof win !== 'undefined' ? window : this + let listener export const setMockListener = func => { listener = func } @@ -26,8 +29,8 @@ const eventMap = {} let callback let testHarness -if (window.__firebolt && window.__firebolt.testHarness) { - testHarness = window.__firebolt.testHarness +if (win.__firebolt && win.__firebolt.testHarness) { + testHarness = win.__firebolt.testHarness } function send(message) { diff --git a/languages/javascript/src/shared/Transport/index.mjs b/languages/javascript/src/shared/Transport/index.mjs index 75ca88ef..ce9de030 100644 --- a/languages/javascript/src/shared/Transport/index.mjs +++ b/languages/javascript/src/shared/Transport/index.mjs @@ -28,6 +28,8 @@ let moduleInstance = null const isEventSuccess = x => x && (typeof x.event === 'string') && (typeof x.listening === 'boolean') +const win = typeof win !== 'undefined' ? window : this + export default class Transport { constructor () { this._promises = [] @@ -51,8 +53,8 @@ export default class Transport { } _endpoint () { - if (window.__firebolt && window.__firebolt.endpoint) { - return window.__firebolt.endpoint + if (win.__firebolt && win.__firebolt.endpoint) { + return win.__firebolt.endpoint } return null } @@ -64,14 +66,14 @@ export default class Transport { transport = new WebsocketTransport(endpoint) transport.receive(this.receiveHandler.bind(this)) } else if ( - typeof window.ServiceManager !== 'undefined' && - window.ServiceManager && - window.ServiceManager.version + typeof win.ServiceManager !== 'undefined' && + win.ServiceManager && + win.ServiceManager.version ) { // Wire up the queue transport = this._queue // get the default bridge service, and flush the queue - window.ServiceManager.getServiceForJavaScript(LEGACY_TRANSPORT_SERVICE_NAME, service => { + win.ServiceManager.getServiceForJavaScript(LEGACY_TRANSPORT_SERVICE_NAME, service => { if (LegacyTransport.isLegacy(service)) { transport = new LegacyTransport(service) } else { @@ -194,20 +196,20 @@ export default class Transport { */ static get () { /** Set up singleton and initialize it */ - window.__firebolt = window.__firebolt || {} - if ((window.__firebolt.transport == null) && (moduleInstance == null)) { + win.__firebolt = win.__firebolt || {} + if ((win.__firebolt.transport == null) && (moduleInstance == null)) { const transport = new Transport() transport.init() if (transport.isMock) { /** We should use the mock transport built with the SDK, not a global */ moduleInstance = transport } else { - window.__firebolt = window.__firebolt || {} - window.__firebolt.transport = transport + win.__firebolt = win.__firebolt || {} + win.__firebolt.transport = transport } - window.__firebolt.setTransportLayer = transport.setTransportLayer.bind(transport) + win.__firebolt.setTransportLayer = transport.setTransportLayer.bind(transport) } - return window.__firebolt.transport ? window.__firebolt.transport : moduleInstance + return win.__firebolt.transport ? win.__firebolt.transport : moduleInstance } receiveHandler (message) { @@ -248,12 +250,12 @@ export default class Transport { init () { initSettings({}, { log: true }) this._queue.receive(this.receiveHandler.bind(this)) - if (window.__firebolt) { - if (window.__firebolt.mockTransportLayer === true) { + if (win.__firebolt) { + if (win.__firebolt.mockTransportLayer === true) { this.isMock = true this.setTransportLayer(mock) - } else if (window.__firebolt.getTransportLayer) { - this.setTransportLayer(window.__firebolt.getTransportLayer()) + } else if (win.__firebolt.getTransportLayer) { + this.setTransportLayer(win.__firebolt.getTransportLayer()) } } if (this._transport == null) { @@ -261,7 +263,7 @@ export default class Transport { } } } -window.__firebolt = window.__firebolt || {} -window.__firebolt.setTransportLayer = transport => { +win.__firebolt = win.__firebolt || {} +win.__firebolt.setTransportLayer = transport => { Transport.get().setTransportLayer(transport) } diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index e7378918..c521a58d 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -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, createPolymorphicMethods } from '../shared/modules.mjs' +import { isRPCOnlyMethod, isProviderInterfaceMethod, getProviderInterface, getPayloadFromEvent, providerHasNoParameters, isTemporalSetMethod, hasMethodAttributes, getMethodAttributes, isEventMethodWithContext, getSemanticVersion, getSetterFor, getProvidedCapabilities, isPolymorphicPullMethod, hasPublicAPIs, createPolymorphicMethods, isExcludedMethod, isCallsMetricsMethod } from '../shared/modules.mjs' import isEmpty from 'crocks/core/isEmpty.js' import { getPath as getJsonPath, getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies, isDefinitionReferencedBySchema, mergeAnyOf, mergeOneOf } from '../shared/json-schema.mjs' @@ -486,8 +486,6 @@ const generateMacros = (obj, templates, languages, options = {}) => { // obj = mergeAnyOfs(obj) // } - console.log('DONE') - // grab the options so we don't have to pass them from method to method Object.assign(state, options) @@ -1187,11 +1185,11 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const resultInst = types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-instantiation', property: flattenedMethod.result.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) // w/out level: 1, getSchemaShape skips anonymous types, like primitives 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: param.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) : '' + 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 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: param.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) : '' + 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 resultParams = generateResultParams(result.schema, json, templates, { name: result.name}) @@ -1201,7 +1199,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { 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.getSchemeType(pullsParams, json, { name: pullsParams.title , templateDir: 'json-types' }) : '' + const pullsForParamJsonType = pullsParams ? types.getSchemaType(pullsParams, json, { name: pullsParams.title , templateDir: 'json-types' }) : '' const pullsEventParamName = event ? types.getSchemaInstantiation(event.result, json, event.name, { instantiationType: 'pull.param.name' }) : '' @@ -1473,7 +1471,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, templateDir: state.typeTemplateDir, moduleTitle: moduleTitle, result: true})) + .replace(/\$\{method\.param\.type\}/g, types.getSchemaType(type, json, {name: name, moduleTitle: moduleTitle, result: true})) ).join(', ') // most languages separate params w/ a comma, so leaving this here for now } // tuples get unwrapped @@ -1482,13 +1480,13 @@ 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, templateDir: state.typeTemplateDir, moduleTitle: moduleTitle, result: true})) + .replace(/\$\{method\.param\.type\}/g, types.getSchemaType(type, json, {name: name, moduleTitle: moduleTitle, result: true})) ).join(', ') } // everything else is just output as-is else { const template = getTemplate('/parameters/result', templates) - const type = types.getSchemaType(result, json, {name: name, templateDir: state.typeTemplateDir, moduleTitle: moduleTitle, result: true}) + const type = types.getSchemaType(result, json, {name: name, moduleTitle: moduleTitle, result: true}) if (type === 'undefined') { console.log(`Warning: undefined type for ${name}`) diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index 18adcb69..3c53afcb 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -146,7 +146,7 @@ const insertObjectMacros = (content, schema, module, title, property, options) = ;(['properties', 'properties.register', 'properties.assign']).forEach(macro => { const indent = (content.split('\n').find(line => line.includes("${" + macro + "}")) || '').match(/^\s+/) || [''][0] const templateType = macro.split('.').slice(1).join('') - const template = getTemplate(path.join(options.templateDir, 'property' + (templateType ? `-${templateType}` : ''))) + const template = getTemplate(path.join(options.templateDir, 'property' + (templateType ? `-${templateType}` : ''))).replace(/\n/gms, indent + '\n') const properties = [] @@ -168,18 +168,22 @@ const insertObjectMacros = (content, schema, module, title, property, options) = Object.entries(schema.properties).forEach(([name, prop], i) => { options2.property = name const schemaShape = getSchemaShape(prop, module, options2) - - properties.push((i !== 0 ? indent : '') + template + const type = getSchemaType(prop, module, options2) + + // don't push properties w/ unsupported types + if (type) { + properties.push((i !== 0 ? indent : '') + template .replace(/(^\s+)/g, '$1'.repeat(options2.level)) .replace(/\$\{property\}/g, name) .replace(/\$\{Property\}/g, capitalize(name)) .replace(/\$\{parent\.title\}/g, title) - .replace(/\$\{title\}/g, getSchemaType(prop, module, options2)) + .replace(/\$\{title\}/g, type) .replace(/\$\{shape\}/g, schemaShape) .replace(/\$\{description\}/g, prop.description || '') .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/gms, i === schema.properties.length - 1 ? '' : '$1') .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, schema.required && schema.required.includes(name) ? '' : '$1')) + } }) } @@ -210,7 +214,7 @@ const insertObjectMacros = (content, schema, module, title, property, options) = if (type) { options2.property = prop const schemaShape = getSchemaShape(type, module, options2) - properties.push(template + properties.push((i !== 0 ? indent : '') + template .replace(/\$\{property\}/g, safeName(prop)) .replace(/\$\{Property\}/g, capitalize(safeName(prop))) .replace(/\$\{parent\.title\}/g, title) @@ -243,24 +247,26 @@ const insertTupleMacros = (content, schema, module, title, options) => { const propTemplate = getTemplate(path.join(options.templateDir, 'property')) const itemsTemplate = getTemplate(path.join(options.templateDir, 'items')) + const propIndent = (content.split('\n').find(line => line.includes("${properties}")) || '').match(/^\s+/) || [''][0] + const itemsIndent = (content.split('\n').find(line => line.includes("${items}")) || '').match(/^\s+/) || [''][0] - const doMacroWork = (str, prop, i) => { + const doMacroWork = (str, prop, i, indent) => { const schemaShape = getSchemaShape(prop, module, options) - return str + return (i !== 0 ? indent : '') + str .replace(/\$\{property\}/g, prop['x-property']) .replace(/\$\{Property\}/g, capitalize(prop['x-property'])) .replace(/\$\{parent\.title\}/g, title) .replace(/\$\{shape\}/g, schemaShape) - .replace(/\$\{type\}/g, getSchemaType(prop, module, options)) + .replace(/\$\{title\}/g, getSchemaType(prop, module, options)) .replace(/\$\{description\}/g, prop.description || '') .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, i === schema.items.length - 1 ? '' : '$1') .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, '') } - content = content.replace(/\$\{properties\}/g, schema.items.map((prop, i) => doMacroWork(propTemplate, prop, i)).join('\n')) - content = content.replace(/\$\{items\}/g, schema.items.map((prop, i) => doMacroWork(itemsTemplate, prop, i)).join('\n')) + content = content.replace(/\$\{properties\}/g, schema.items.map((prop, i) => doMacroWork(propTemplate, prop, i, propIndent)).join('\n')) + content = content.replace(/\$\{items\}/g, schema.items.map((prop, i) => doMacroWork(itemsTemplate, prop, i, itemsIndent)).join('\n')) return content } @@ -286,8 +292,24 @@ const insertAnyOfMacros = (content, schema, module, name) => { return content } +const sanitize = (schema) => { + const result = JSON.parse(JSON.stringify(schema)) + + if (result.oneOf && result.oneOf.length === 2 && result.oneOf.find(s => s.const === null)) { + Object.assign(result, result.oneOf.find(s => s.const !== null)) + delete result.oneOf + } + + if (result.anyOf && result.anyOf.length === 2 && result.anyOf.find(s => s.const === null)) { + Object.assign(result, result.anyOf.find(s => s.const !== null)) + delete result.anyOf + } + + return result +} + function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', name = '', parent = '', property = '', level = 0, summary, descriptions = true, destination, section, enums = true, skipTitleOnce = false } = {}) { - schema = JSON.parse(JSON.stringify(schema)) + schema = sanitize(schema) state.destination = destination state.section = section @@ -340,6 +362,7 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', name schema.anyOf = schema.oneOf } const shape = insertAnyOfMacros(getTemplate(path.join(templateDir, 'anyOf' + suffix)), schema, module, theTitle) + result = result.replace(/\$\{shape\}/g, shape) return insertSchemaMacros(result, schema, module, theTitle, parent, property) } @@ -439,14 +462,18 @@ const isSupportedTuple = schema => { } } -function getSchemaType(schema, module, { destination, templateDir = 'types', link = false, title = false, code = false, asPath = false, event = false, result = false, expandEnums = true, baseUrl = '', namespace = false } = {}) { +function getSchemaType(schema, module, { destination, templateDir = 'types', link = false, code = false, asPath = false, event = false, result = false, expandEnums = true, baseUrl = '', namespace = false } = {}) { const wrap = (str, wrapper) => wrapper + str + wrapper + schema = sanitize(schema) + const suffix = destination && ('.' + destination.split('.').pop()) || '' const namespaceStr = namespace ? getTemplate(path.join(templateDir, 'namespace' + suffix)) : '' const theTitle = insertSchemaMacros(namespaceStr + getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, schema.title || '', '', '', false) const allocatedProxy = event || result + const title = schema.type === "object" || schema.enum ? true : false + if (schema['$ref']) { if (schema['$ref'][0] === '#') { return getSchemaType(getPath(schema['$ref'], module), module, {destination, templateDir, link, title, code, asPath, event, result, expandEnums, baseUrl, namespace })// { link: link, code: code, destination }) @@ -566,6 +593,7 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin if (!schema.anyOf) { schema.anyOf = schema.oneOf } + // todo... we probably shouldn't allow untitled anyOfs, at least not w/out a feature flag const shape = insertAnyOfMacros(getTemplate(path.join(templateDir, 'anyOf' + suffix)), schema, module, theTitle) return insertSchemaMacros(shape, schema, module, theTitle, '', '', false) From c44e9a69062b471df1d2bad8b982e121076ff4b9 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 26 Apr 2023 10:25:43 -0400 Subject: [PATCH 033/137] chore: Copy JS templates to C and create language.config.json --- languages/c/Types.mjs | 78 +++++++++++++++++++ languages/c/language.config.json | 14 ++++ languages/c/src/index.mjs | 19 +++++ languages/c/src/types/CommonCppTypes.mjs | 60 ++++++++++++++ languages/c/src/types/CommonHeaderTypes.mjs | 55 +++++++++++++ languages/c/src/types/CppTypes.mjs | 55 +++++++++++++ languages/c/src/types/HeaderTypes.mjs | 55 +++++++++++++ languages/c/src/types/JSONTypes.mjs | 56 +++++++++++++ languages/c/templates/codeblocks/export.mjs | 1 + .../c/templates/codeblocks/mock-import.mjs | 1 + .../c/templates/codeblocks/mock-parameter.mjs | 1 + languages/c/templates/codeblocks/module.mjs | 11 +++ languages/c/templates/declarations/clear.js | 0 languages/c/templates/declarations/default.js | 4 + languages/c/templates/declarations/listen.js | 0 languages/c/templates/declarations/once.js | 0 .../declarations/polymorphic-reducer.js | 6 ++ languages/c/templates/declarations/provide.js | 0 .../c/templates/declarations/rpc-only.js | 0 languages/c/templates/defaults/default.mjs | 1 + languages/c/templates/defaults/property.mjs | 1 + languages/c/templates/examples/default.md | 6 ++ languages/c/templates/examples/event.md | 5 ++ .../examples/polymorphic-pull-event.md | 9 +++ .../c/templates/examples/polymorphic-pull.md | 6 ++ languages/c/templates/examples/provider.md | 10 +++ languages/c/templates/examples/setter.md | 6 ++ languages/c/templates/examples/subscriber.md | 7 ++ languages/c/templates/examples/synchronous.md | 4 + .../c/templates/examples/temporal-set.md | 13 ++++ .../c/templates/imports/context-event.mjs | 1 + languages/c/templates/imports/event.mjs | 2 + languages/c/templates/imports/property.mjs | 1 + languages/c/templates/imports/provider.mjs | 2 + languages/c/templates/imports/rpc.mjs | 1 + .../c/templates/imports/temporal-set.mjs | 1 + languages/c/templates/imports/x-method.mjs | 1 + .../templates/initializations/deprecated.mjs | 1 + .../c/templates/initializations/event.mjs | 1 + .../c/templates/initializations/provider.mjs | 1 + languages/c/templates/methods/clear.js | 0 languages/c/templates/methods/default.js | 7 ++ languages/c/templates/methods/listen.js | 0 languages/c/templates/methods/once.js | 0 .../templates/methods/polymorphic-reducer.js | 11 +++ languages/c/templates/methods/provide.js | 3 + languages/c/templates/methods/rpc-only.js | 0 .../templates/modules/include/Common/Module.h | 23 ++++++ .../c/templates/modules/include/Module.h | 25 ++++++ .../c/templates/modules/src/JsonData_Module.h | 23 ++++++ languages/c/templates/modules/src/Module.cpp | 29 +++++++ .../c/templates/modules/src/Module_Common.cpp | 26 +++++++ languages/c/templates/parameters/default.js | 1 + languages/c/templates/schemas/default.js | 5 ++ .../templates/schemas/include/Common/Module.h | 25 ++++++ .../c/templates/schemas/include/Module.h | 23 ++++++ .../c/templates/schemas/src/JsonData_Module.h | 23 ++++++ languages/c/templates/schemas/src/Module.cpp | 29 +++++++ .../c/templates/schemas/src/Module_Common.cpp | 26 +++++++ languages/c/templates/sdk/main.cpp | 30 +++++++ .../c/templates/sections/declarations.js | 1 + languages/c/templates/sections/events.js | 1 + languages/c/templates/sections/methods.js | 3 + .../templates/sections/provider-interfaces.js | 11 +++ languages/c/templates/sections/schemas.js | 3 + languages/c/templates/types/enum.mjs | 3 + 66 files changed, 827 insertions(+) create mode 100644 languages/c/Types.mjs create mode 100644 languages/c/language.config.json create mode 100644 languages/c/src/index.mjs create mode 100644 languages/c/src/types/CommonCppTypes.mjs create mode 100644 languages/c/src/types/CommonHeaderTypes.mjs create mode 100644 languages/c/src/types/CppTypes.mjs create mode 100644 languages/c/src/types/HeaderTypes.mjs create mode 100644 languages/c/src/types/JSONTypes.mjs create mode 100644 languages/c/templates/codeblocks/export.mjs create mode 100644 languages/c/templates/codeblocks/mock-import.mjs create mode 100644 languages/c/templates/codeblocks/mock-parameter.mjs create mode 100644 languages/c/templates/codeblocks/module.mjs create mode 100644 languages/c/templates/declarations/clear.js create mode 100644 languages/c/templates/declarations/default.js create mode 100644 languages/c/templates/declarations/listen.js create mode 100644 languages/c/templates/declarations/once.js create mode 100644 languages/c/templates/declarations/polymorphic-reducer.js create mode 100644 languages/c/templates/declarations/provide.js create mode 100644 languages/c/templates/declarations/rpc-only.js create mode 100644 languages/c/templates/defaults/default.mjs create mode 100644 languages/c/templates/defaults/property.mjs create mode 100644 languages/c/templates/examples/default.md create mode 100644 languages/c/templates/examples/event.md create mode 100644 languages/c/templates/examples/polymorphic-pull-event.md create mode 100644 languages/c/templates/examples/polymorphic-pull.md create mode 100644 languages/c/templates/examples/provider.md create mode 100644 languages/c/templates/examples/setter.md create mode 100644 languages/c/templates/examples/subscriber.md create mode 100644 languages/c/templates/examples/synchronous.md create mode 100644 languages/c/templates/examples/temporal-set.md create mode 100644 languages/c/templates/imports/context-event.mjs create mode 100644 languages/c/templates/imports/event.mjs create mode 100644 languages/c/templates/imports/property.mjs create mode 100644 languages/c/templates/imports/provider.mjs create mode 100644 languages/c/templates/imports/rpc.mjs create mode 100644 languages/c/templates/imports/temporal-set.mjs create mode 100644 languages/c/templates/imports/x-method.mjs create mode 100644 languages/c/templates/initializations/deprecated.mjs create mode 100644 languages/c/templates/initializations/event.mjs create mode 100644 languages/c/templates/initializations/provider.mjs create mode 100644 languages/c/templates/methods/clear.js create mode 100644 languages/c/templates/methods/default.js create mode 100644 languages/c/templates/methods/listen.js create mode 100644 languages/c/templates/methods/once.js create mode 100644 languages/c/templates/methods/polymorphic-reducer.js create mode 100644 languages/c/templates/methods/provide.js create mode 100644 languages/c/templates/methods/rpc-only.js create mode 100644 languages/c/templates/modules/include/Common/Module.h create mode 100644 languages/c/templates/modules/include/Module.h create mode 100644 languages/c/templates/modules/src/JsonData_Module.h create mode 100644 languages/c/templates/modules/src/Module.cpp create mode 100644 languages/c/templates/modules/src/Module_Common.cpp create mode 100644 languages/c/templates/parameters/default.js create mode 100644 languages/c/templates/schemas/default.js create mode 100644 languages/c/templates/schemas/include/Common/Module.h create mode 100644 languages/c/templates/schemas/include/Module.h create mode 100644 languages/c/templates/schemas/src/JsonData_Module.h create mode 100644 languages/c/templates/schemas/src/Module.cpp create mode 100644 languages/c/templates/schemas/src/Module_Common.cpp create mode 100644 languages/c/templates/sdk/main.cpp create mode 100644 languages/c/templates/sections/declarations.js create mode 100644 languages/c/templates/sections/events.js create mode 100644 languages/c/templates/sections/methods.js create mode 100644 languages/c/templates/sections/provider-interfaces.js create mode 100644 languages/c/templates/sections/schemas.js create mode 100644 languages/c/templates/types/enum.mjs diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs new file mode 100644 index 00000000..31f48dd1 --- /dev/null +++ b/languages/c/Types.mjs @@ -0,0 +1,78 @@ +/* + * Copyright 2021 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 + */ + +import jsonTypes from './src/types/JSONTypes.mjs' +import commonTypes from './src/types/CommonCppTypes.mjs' +import headerCommonTypes from './src/types/CommonHeaderTypes.mjs' +import headerTypes from './src/types/HeaderTypes.mjs' +import cppTypes from './src/types/CppTypes.mjs' + +import path from "path" + +const isSynchronous = m => !m.tags ? false : m.tags.map(t => t.name).find(s => s === 'synchronous') + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return routeToDestination('getMethodSignature', arguments) +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return routeToDestination('getMethodSignatureParams', arguments) +} + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + return routeToDestination('getSchemaShape', arguments) +} + +function getSchemaType(schema, module, { destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + const value = routeToDestination('getSchemaType', arguments) + return value +} + +function routeToDestination(method, args) { + const destination = args[args.length-1].destination || '' + + if ( path.basename(destination) === 'JsonData_Module.h') { + return jsonTypes[method](...args) + } + else if (path.basename(destination) === 'Module.cpp') { + return cppTypes[method](...args) + } + else if (path.basename(destination) === 'Module_Common.cpp') { + return commonTypes[method](...args) + } + else if (path.basename(destination) === 'Module.h' && path.dirname(destination).endsWith(path.sep + 'Common')) { + return headerCommonTypes[method](...args) + } + else if (path.basename(destination) === 'Module.h') { + return headerTypes[method](...args) + } + + return '' +} + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/language.config.json b/languages/c/language.config.json new file mode 100644 index 00000000..185b0370 --- /dev/null +++ b/languages/c/language.config.json @@ -0,0 +1,14 @@ +{ + "name": "C", + "langcode": "c", + "createModuleDirectories": false, + "templatesPerModule": [ + "/include/Module.h", + "/src/Module.cpp" + ], + "templatesPerSchema": [ + "/include/Common/Module.h", + "/src/Module_Common.cpp", + "/src/JsonData_Module.h" + ] +} \ No newline at end of file diff --git a/languages/c/src/index.mjs b/languages/c/src/index.mjs new file mode 100644 index 00000000..51c547a1 --- /dev/null +++ b/languages/c/src/index.mjs @@ -0,0 +1,19 @@ +/* + * Copyright 2021 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 + */ + +export { default as Transport } from './shared/Transport/index.mjs' \ No newline at end of file diff --git a/languages/c/src/types/CommonCppTypes.mjs b/languages/c/src/types/CommonCppTypes.mjs new file mode 100644 index 00000000..863cd77b --- /dev/null +++ b/languages/c/src/types/CommonCppTypes.mjs @@ -0,0 +1,60 @@ +/* + * Copyright 2021 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 + */ + +// import deepmerge from 'deepmerge' +// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' +// import { getLinkFromRef } from '../../src/shared/markdown.mjs' +// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' + + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return `// Common CPP Signatures for ${module}_${method}` +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return `// Common CPP Signature Params for ${module}_${method}` +} + +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + + return { + dependencies: [], + code: `// Common CPP Schema Shape` + } + return `// Common CPP Schema Shape` +} + +function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + return `// Common CPP Schema Type` +} + + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/src/types/CommonHeaderTypes.mjs b/languages/c/src/types/CommonHeaderTypes.mjs new file mode 100644 index 00000000..9c40c084 --- /dev/null +++ b/languages/c/src/types/CommonHeaderTypes.mjs @@ -0,0 +1,55 @@ +/* + * Copyright 2021 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 + */ + +// import deepmerge from 'deepmerge' +// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' +// import { getLinkFromRef } from '../../src/shared/markdown.mjs' +// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' + + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return `// common .h Signatures for ${module}_${method}` +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return `// common .h Signature Params for ${module}_${method}` +} + +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + return `// common .h Schema Shape` +} + +function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + return `// common .h Schema Type` +} + + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/src/types/CppTypes.mjs b/languages/c/src/types/CppTypes.mjs new file mode 100644 index 00000000..4b6fa6a8 --- /dev/null +++ b/languages/c/src/types/CppTypes.mjs @@ -0,0 +1,55 @@ +/* + * Copyright 2021 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 + */ + +// import deepmerge from 'deepmerge' +// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' +// import { getLinkFromRef } from '../../src/shared/markdown.mjs' +// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' + + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return `// CPP Signatures for ${module}_${method}` +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return `// CPP Signature Params for ${module}_${method}` +} + +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + return `// CPP Schema Shape` +} + +function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + return `// CPP Schema Type` +} + + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/src/types/HeaderTypes.mjs b/languages/c/src/types/HeaderTypes.mjs new file mode 100644 index 00000000..9ce0155e --- /dev/null +++ b/languages/c/src/types/HeaderTypes.mjs @@ -0,0 +1,55 @@ +/* + * Copyright 2021 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 + */ + +// import deepmerge from 'deepmerge' +// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' +// import { getLinkFromRef } from '../../src/shared/markdown.mjs' +// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' + + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return `// .h Signatures for ${module.info.title}_${method.name}` +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return `// .h Signature Params for ${module.info.title}_${method.name}` +} + +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + return `// .h Schema Shape` +} + +function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + return `// .h Schema Type` +} + + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/src/types/JSONTypes.mjs b/languages/c/src/types/JSONTypes.mjs new file mode 100644 index 00000000..d2961794 --- /dev/null +++ b/languages/c/src/types/JSONTypes.mjs @@ -0,0 +1,56 @@ + +/* + * Copyright 2021 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 + */ + +// import deepmerge from 'deepmerge' +// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' +// import { getLinkFromRef } from '../../src/shared/markdown.mjs' +// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' + + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return `// JSON Signatures for ${module}_${method}` +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return `// JSON Signature Params for ${module}_${method}` +} + +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + return `// JSON Schema Shape` +} + +function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + return `// JSON Schema Type` +} + + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/templates/codeblocks/export.mjs b/languages/c/templates/codeblocks/export.mjs new file mode 100644 index 00000000..c98498e4 --- /dev/null +++ b/languages/c/templates/codeblocks/export.mjs @@ -0,0 +1 @@ +export { default as ${info.title} } from './${info.title}/index.mjs' \ No newline at end of file diff --git a/languages/c/templates/codeblocks/mock-import.mjs b/languages/c/templates/codeblocks/mock-import.mjs new file mode 100644 index 00000000..5d22512a --- /dev/null +++ b/languages/c/templates/codeblocks/mock-import.mjs @@ -0,0 +1 @@ +import { default as _${info.title} } from './${info.title}/defaults.mjs' \ No newline at end of file diff --git a/languages/c/templates/codeblocks/mock-parameter.mjs b/languages/c/templates/codeblocks/mock-parameter.mjs new file mode 100644 index 00000000..63e63902 --- /dev/null +++ b/languages/c/templates/codeblocks/mock-parameter.mjs @@ -0,0 +1 @@ + ${info.title}: _${info.title}, \ No newline at end of file diff --git a/languages/c/templates/codeblocks/module.mjs b/languages/c/templates/codeblocks/module.mjs new file mode 100644 index 00000000..48f6d6bc --- /dev/null +++ b/languages/c/templates/codeblocks/module.mjs @@ -0,0 +1,11 @@ +// JEREMY + +export module ${info.title} { + + /* ${SCHEMAS} */ + + /* ${DECLARATIONS} */ + + /* ${PROVIDERS} */ + +} \ No newline at end of file diff --git a/languages/c/templates/declarations/clear.js b/languages/c/templates/declarations/clear.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/declarations/default.js b/languages/c/templates/declarations/default.js new file mode 100644 index 00000000..bd8b6fcf --- /dev/null +++ b/languages/c/templates/declarations/default.js @@ -0,0 +1,4 @@ + /** + * ${method.summary} + ${method.params} */ + ${method.signature} diff --git a/languages/c/templates/declarations/listen.js b/languages/c/templates/declarations/listen.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/declarations/once.js b/languages/c/templates/declarations/once.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/declarations/polymorphic-reducer.js b/languages/c/templates/declarations/polymorphic-reducer.js new file mode 100644 index 00000000..979832b2 --- /dev/null +++ b/languages/c/templates/declarations/polymorphic-reducer.js @@ -0,0 +1,6 @@ + /** + * ${method.summary} + ${method.params} */ + ${method.signature} + +// TODO: generate reducer signature \ No newline at end of file diff --git a/languages/c/templates/declarations/provide.js b/languages/c/templates/declarations/provide.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/declarations/rpc-only.js b/languages/c/templates/declarations/rpc-only.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/defaults/default.mjs b/languages/c/templates/defaults/default.mjs new file mode 100644 index 00000000..e29085d1 --- /dev/null +++ b/languages/c/templates/defaults/default.mjs @@ -0,0 +1 @@ + ${method.name}: ${method.example.value} \ No newline at end of file diff --git a/languages/c/templates/defaults/property.mjs b/languages/c/templates/defaults/property.mjs new file mode 100644 index 00000000..95ef20cf --- /dev/null +++ b/languages/c/templates/defaults/property.mjs @@ -0,0 +1 @@ + ${method.name}: function () { return MockProps.mock('${info.title}', '${method.name}', arguments, ${method.example.value}) } \ No newline at end of file diff --git a/languages/c/templates/examples/default.md b/languages/c/templates/examples/default.md new file mode 100644 index 00000000..ecc979ba --- /dev/null +++ b/languages/c/templates/examples/default.md @@ -0,0 +1,6 @@ +import { ${module} } from '${package.name}' + +${module}.${method.name}(${example.params}) + .then(${method.result.name} => { + console.log(${method.result.name}) + }) \ No newline at end of file diff --git a/languages/c/templates/examples/event.md b/languages/c/templates/examples/event.md new file mode 100644 index 00000000..7b78fe76 --- /dev/null +++ b/languages/c/templates/examples/event.md @@ -0,0 +1,5 @@ +import { ${module} } from '${package.name}' + +${module}.listen('${event.name}', ${method.result.name} => { + console.log(${method.result.name}) +}) \ No newline at end of file diff --git a/languages/c/templates/examples/polymorphic-pull-event.md b/languages/c/templates/examples/polymorphic-pull-event.md new file mode 100644 index 00000000..7bc2baa7 --- /dev/null +++ b/languages/c/templates/examples/polymorphic-pull-event.md @@ -0,0 +1,9 @@ +import { ${module} } from '${package.name}' + +${module}.${method.pulls.for}(function(parameters) { + console.log(parameters.entityId) + console.log(parameters.assetId) + return Promise.resolve(${originator.params[1].example.value}) +}).then(success => { + console.log(success) +}) \ No newline at end of file diff --git a/languages/c/templates/examples/polymorphic-pull.md b/languages/c/templates/examples/polymorphic-pull.md new file mode 100644 index 00000000..7c53080c --- /dev/null +++ b/languages/c/templates/examples/polymorphic-pull.md @@ -0,0 +1,6 @@ +import { ${module} } from '${package.name}' + +${module}.${method.name}(${method.params[1].example.value}) + .then(success => { + console.log(success) + }) \ No newline at end of file diff --git a/languages/c/templates/examples/provider.md b/languages/c/templates/examples/provider.md new file mode 100644 index 00000000..d2d16366 --- /dev/null +++ b/languages/c/templates/examples/provider.md @@ -0,0 +1,10 @@ +import { ${module} } from '${package.name}' + +class MyProvider { + async ${example.providerMethod}(${method.result.name}, responder) { + console.log(JSON.stringify(${method.result.name}, null, 2)) + responder(${example.providerResponse}) + } +} + +${module}.provide(new MyProvider()) \ No newline at end of file diff --git a/languages/c/templates/examples/setter.md b/languages/c/templates/examples/setter.md new file mode 100644 index 00000000..c258314a --- /dev/null +++ b/languages/c/templates/examples/setter.md @@ -0,0 +1,6 @@ +import { ${module} } from '${package.name}' + +${module}.${method.setter.for}(${example.params}) + .then(${method.result.name} => { + console.log(${method.result.name}) + }) \ No newline at end of file diff --git a/languages/c/templates/examples/subscriber.md b/languages/c/templates/examples/subscriber.md new file mode 100644 index 00000000..99c0516f --- /dev/null +++ b/languages/c/templates/examples/subscriber.md @@ -0,0 +1,7 @@ +import { ${module} } from '${package.name}' + +${method.alternative}(value => { + console.log(value) +}).then(listenerId => { + console.log(listenerId) +}) \ No newline at end of file diff --git a/languages/c/templates/examples/synchronous.md b/languages/c/templates/examples/synchronous.md new file mode 100644 index 00000000..6e8e1e82 --- /dev/null +++ b/languages/c/templates/examples/synchronous.md @@ -0,0 +1,4 @@ +import { ${module} } from '${package.name}' + +const ${method.result.name} = ${module}.${method.name}(${example.params}) +console.log(${method.result.name}) \ No newline at end of file diff --git a/languages/c/templates/examples/temporal-set.md b/languages/c/templates/examples/temporal-set.md new file mode 100644 index 00000000..4a8e94ea --- /dev/null +++ b/languages/c/templates/examples/temporal-set.md @@ -0,0 +1,13 @@ +import { ${module} } from '${package.name}' + +const process = ${module}.${method.name}(function(${example.params}${if.params},${end.if.params} + ${method.item} => { + console.log('Added to temporal set:') + console.dir(${method.item}) + }, + ${method.item} => { + console.log('Removed from temporal set:') + console.dir(${method.item}) + }) + +setTimeout( () => process.stop(), 10000) \ No newline at end of file diff --git a/languages/c/templates/imports/context-event.mjs b/languages/c/templates/imports/context-event.mjs new file mode 100644 index 00000000..fcd3186b --- /dev/null +++ b/languages/c/templates/imports/context-event.mjs @@ -0,0 +1 @@ +import { registerEventContext } from '../Events/index.mjs' diff --git a/languages/c/templates/imports/event.mjs b/languages/c/templates/imports/event.mjs new file mode 100644 index 00000000..bc019bca --- /dev/null +++ b/languages/c/templates/imports/event.mjs @@ -0,0 +1,2 @@ +import Events from '../Events/index.mjs' +import { registerEvents } from '../Events/index.mjs' diff --git a/languages/c/templates/imports/property.mjs b/languages/c/templates/imports/property.mjs new file mode 100644 index 00000000..7107a163 --- /dev/null +++ b/languages/c/templates/imports/property.mjs @@ -0,0 +1 @@ +import Prop from '../Prop/index.mjs' diff --git a/languages/c/templates/imports/provider.mjs b/languages/c/templates/imports/provider.mjs new file mode 100644 index 00000000..b3ea7b4f --- /dev/null +++ b/languages/c/templates/imports/provider.mjs @@ -0,0 +1,2 @@ +import ProvideManager from '../ProvideManager/index.mjs' +import { registerProviderInterface } from '../ProvideManager/index.mjs' diff --git a/languages/c/templates/imports/rpc.mjs b/languages/c/templates/imports/rpc.mjs new file mode 100644 index 00000000..af459a1e --- /dev/null +++ b/languages/c/templates/imports/rpc.mjs @@ -0,0 +1 @@ +import Transport from '../Transport/index.mjs' diff --git a/languages/c/templates/imports/temporal-set.mjs b/languages/c/templates/imports/temporal-set.mjs new file mode 100644 index 00000000..089d35b1 --- /dev/null +++ b/languages/c/templates/imports/temporal-set.mjs @@ -0,0 +1 @@ +import TemporalSet from '../TemporalSet/index.mjs' \ No newline at end of file diff --git a/languages/c/templates/imports/x-method.mjs b/languages/c/templates/imports/x-method.mjs new file mode 100644 index 00000000..42453ecb --- /dev/null +++ b/languages/c/templates/imports/x-method.mjs @@ -0,0 +1 @@ +import Results from '../Results/index.mjs' \ No newline at end of file diff --git a/languages/c/templates/initializations/deprecated.mjs b/languages/c/templates/initializations/deprecated.mjs new file mode 100644 index 00000000..737d1c25 --- /dev/null +++ b/languages/c/templates/initializations/deprecated.mjs @@ -0,0 +1 @@ +Transport.registerDeprecatedMethod('${info.title}', '${method.name}', 'Use ${method.alternative} instead.') diff --git a/languages/c/templates/initializations/event.mjs b/languages/c/templates/initializations/event.mjs new file mode 100644 index 00000000..c151f674 --- /dev/null +++ b/languages/c/templates/initializations/event.mjs @@ -0,0 +1 @@ +registerEvents('${info.title}', ${events.array}) diff --git a/languages/c/templates/initializations/provider.mjs b/languages/c/templates/initializations/provider.mjs new file mode 100644 index 00000000..b113d236 --- /dev/null +++ b/languages/c/templates/initializations/provider.mjs @@ -0,0 +1 @@ +registerProviderInterface('${capability}', '${info.title}', ${interface}) diff --git a/languages/c/templates/methods/clear.js b/languages/c/templates/methods/clear.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/methods/default.js b/languages/c/templates/methods/default.js new file mode 100644 index 00000000..0c7f799b --- /dev/null +++ b/languages/c/templates/methods/default.js @@ -0,0 +1,7 @@ + +function ${method.name}(${method.params.list}) { + + const transforms = ${method.transforms} + + return Transport.send('${info.title}', '${method.name}', { ${method.params.list} }, transforms) +} \ No newline at end of file diff --git a/languages/c/templates/methods/listen.js b/languages/c/templates/methods/listen.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/methods/once.js b/languages/c/templates/methods/once.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/methods/polymorphic-reducer.js b/languages/c/templates/methods/polymorphic-reducer.js new file mode 100644 index 00000000..db07747f --- /dev/null +++ b/languages/c/templates/methods/polymorphic-reducer.js @@ -0,0 +1,11 @@ + +function ${method.name}(${method.params.list}) { + const transforms = ${method.transforms} + + if (arguments.length === 1 && Array.isArray(arguments[0])) { + return Transport.send('${info.title}', '${method.name}', arguments[0], transforms) + } + else { + return Transport.send('${info.title}', '${method.name}', { ${method.params.list} }, transforms) + } +} \ No newline at end of file diff --git a/languages/c/templates/methods/provide.js b/languages/c/templates/methods/provide.js new file mode 100644 index 00000000..8cb48885 --- /dev/null +++ b/languages/c/templates/methods/provide.js @@ -0,0 +1,3 @@ +function provide(capability, provider) { + return ProvideManager.provide(capability, provider) +} diff --git a/languages/c/templates/methods/rpc-only.js b/languages/c/templates/methods/rpc-only.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/modules/include/Common/Module.h b/languages/c/templates/modules/include/Common/Module.h new file mode 100644 index 00000000..4cee1781 --- /dev/null +++ b/languages/c/templates/modules/include/Common/Module.h @@ -0,0 +1,23 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${DECLARATIONS} */ + +} diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h new file mode 100644 index 00000000..60a75f5f --- /dev/null +++ b/languages/c/templates/modules/include/Module.h @@ -0,0 +1,25 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${SCHEMAS} */ + + /* ${DECLARATIONS} */ + +} diff --git a/languages/c/templates/modules/src/JsonData_Module.h b/languages/c/templates/modules/src/JsonData_Module.h new file mode 100644 index 00000000..4cee1781 --- /dev/null +++ b/languages/c/templates/modules/src/JsonData_Module.h @@ -0,0 +1,23 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${DECLARATIONS} */ + +} diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp new file mode 100644 index 00000000..26a26050 --- /dev/null +++ b/languages/c/templates/modules/src/Module.cpp @@ -0,0 +1,29 @@ +/* + * 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 + */ + +/* ${IMPORTS} */ + + +namespace FireboltSDK { + + namespace ${info.title} { + + /* ${METHODS} */ + + } +} diff --git a/languages/c/templates/modules/src/Module_Common.cpp b/languages/c/templates/modules/src/Module_Common.cpp new file mode 100644 index 00000000..8460c52a --- /dev/null +++ b/languages/c/templates/modules/src/Module_Common.cpp @@ -0,0 +1,26 @@ +/* + * 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 + */ + +/* ${IMPORTS} */ + + +namespace FireboltSDK { + + /* ${METHODS} */ + +} diff --git a/languages/c/templates/parameters/default.js b/languages/c/templates/parameters/default.js new file mode 100644 index 00000000..916a8adf --- /dev/null +++ b/languages/c/templates/parameters/default.js @@ -0,0 +1 @@ +${method.params.list} \ No newline at end of file diff --git a/languages/c/templates/schemas/default.js b/languages/c/templates/schemas/default.js new file mode 100644 index 00000000..bc9ab873 --- /dev/null +++ b/languages/c/templates/schemas/default.js @@ -0,0 +1,5 @@ + /** + * ${schema.description} + */ + +${schema.shape} diff --git a/languages/c/templates/schemas/include/Common/Module.h b/languages/c/templates/schemas/include/Common/Module.h new file mode 100644 index 00000000..5582d8ea --- /dev/null +++ b/languages/c/templates/schemas/include/Common/Module.h @@ -0,0 +1,25 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${DECLARATIONS} */ + + /* ${SCHEMAS} */ + +} diff --git a/languages/c/templates/schemas/include/Module.h b/languages/c/templates/schemas/include/Module.h new file mode 100644 index 00000000..4cee1781 --- /dev/null +++ b/languages/c/templates/schemas/include/Module.h @@ -0,0 +1,23 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${DECLARATIONS} */ + +} diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/JsonData_Module.h new file mode 100644 index 00000000..4cee1781 --- /dev/null +++ b/languages/c/templates/schemas/src/JsonData_Module.h @@ -0,0 +1,23 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${DECLARATIONS} */ + +} diff --git a/languages/c/templates/schemas/src/Module.cpp b/languages/c/templates/schemas/src/Module.cpp new file mode 100644 index 00000000..26a26050 --- /dev/null +++ b/languages/c/templates/schemas/src/Module.cpp @@ -0,0 +1,29 @@ +/* + * 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 + */ + +/* ${IMPORTS} */ + + +namespace FireboltSDK { + + namespace ${info.title} { + + /* ${METHODS} */ + + } +} diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/Module_Common.cpp new file mode 100644 index 00000000..8460c52a --- /dev/null +++ b/languages/c/templates/schemas/src/Module_Common.cpp @@ -0,0 +1,26 @@ +/* + * 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 + */ + +/* ${IMPORTS} */ + + +namespace FireboltSDK { + + /* ${METHODS} */ + +} diff --git a/languages/c/templates/sdk/main.cpp b/languages/c/templates/sdk/main.cpp new file mode 100644 index 00000000..a9f2f5ca --- /dev/null +++ b/languages/c/templates/sdk/main.cpp @@ -0,0 +1,30 @@ +/* + * Copyright 2021 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 + */ + +import { setMockResponses } from './Transport/MockTransport.mjs' + +/* ${MOCK_IMPORTS} */ + +setMockResponses({ + /* ${MOCK_OBJECTS} */ +}) + +/* ${EXPORTS} */ +export { default as Log } from './Log/index.mjs' +export { default as Events } from './Events/index.mjs' +export { default as Settings } from './Settings/index.mjs' diff --git a/languages/c/templates/sections/declarations.js b/languages/c/templates/sections/declarations.js new file mode 100644 index 00000000..b3ef974d --- /dev/null +++ b/languages/c/templates/sections/declarations.js @@ -0,0 +1 @@ +${declaration.list} diff --git a/languages/c/templates/sections/events.js b/languages/c/templates/sections/events.js new file mode 100644 index 00000000..5be10409 --- /dev/null +++ b/languages/c/templates/sections/events.js @@ -0,0 +1 @@ +${event.list} diff --git a/languages/c/templates/sections/methods.js b/languages/c/templates/sections/methods.js new file mode 100644 index 00000000..3f382a63 --- /dev/null +++ b/languages/c/templates/sections/methods.js @@ -0,0 +1,3 @@ + + // Methods +${method.list} diff --git a/languages/c/templates/sections/provider-interfaces.js b/languages/c/templates/sections/provider-interfaces.js new file mode 100644 index 00000000..418d7abf --- /dev/null +++ b/languages/c/templates/sections/provider-interfaces.js @@ -0,0 +1,11 @@ + // Provider Interfaces + + interface ProviderSession { + correlationId(): string // Returns the correlation id of the current provider session + } + + interface FocusableProviderSession extends ProviderSession { + focus(): Promise // Requests that the provider app be moved into focus to prevent a user experience + } + + ${providers.list} \ No newline at end of file diff --git a/languages/c/templates/sections/schemas.js b/languages/c/templates/sections/schemas.js new file mode 100644 index 00000000..a2d20dbb --- /dev/null +++ b/languages/c/templates/sections/schemas.js @@ -0,0 +1,3 @@ +// Types + +${schema.list} diff --git a/languages/c/templates/types/enum.mjs b/languages/c/templates/types/enum.mjs new file mode 100644 index 00000000..907fb37d --- /dev/null +++ b/languages/c/templates/types/enum.mjs @@ -0,0 +1,3 @@ +${name}: { + ${key}: '${value}', +}, From b61188f16a6f9e3b8aee842afad09ebd26fc46a3 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 26 Apr 2023 14:42:31 -0400 Subject: [PATCH 034/137] feat(languages): Add support for a distinct JSON-type for each schema Also started tweaking C templates and adding a few useful macros. --- languages/c/Types.mjs | 73 ++- languages/c/src/types/NativeHelpers.mjs | 494 ++++++++++++++++++ languages/c/templates/methods/default.c | 24 + languages/c/templates/methods/default.js | 7 - languages/c/templates/methods/property.c | 12 + .../templates/modules/include/Common/Module.h | 15 +- .../c/templates/modules/include/Module.h | 14 +- .../c/templates/modules/src/JsonData_Module.h | 8 +- languages/c/templates/modules/src/Module.cpp | 17 +- .../c/templates/modules/src/Module_Common.cpp | 15 +- languages/c/templates/parameters/default.c | 1 + languages/c/templates/parameters/default.js | 1 - languages/c/templates/parameters/json.c | 3 + .../javascript/templates/methods/property.js | 2 +- src/macrofier/engine.mjs | 33 +- src/macrofier/index.mjs | 3 + src/shared/typescript.mjs | 11 +- 17 files changed, 687 insertions(+), 46 deletions(-) create mode 100644 languages/c/src/types/NativeHelpers.mjs create mode 100644 languages/c/templates/methods/default.c delete mode 100644 languages/c/templates/methods/default.js create mode 100644 languages/c/templates/methods/property.c create mode 100644 languages/c/templates/parameters/default.c delete mode 100644 languages/c/templates/parameters/default.js create mode 100644 languages/c/templates/parameters/json.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 31f48dd1..aa209ad4 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -21,6 +21,8 @@ import commonTypes from './src/types/CommonCppTypes.mjs' import headerCommonTypes from './src/types/CommonHeaderTypes.mjs' import headerTypes from './src/types/HeaderTypes.mjs' import cppTypes from './src/types/CppTypes.mjs' +import typeScriptTypes from '../../src/shared/typescript.mjs' +import { getNativeType } from './src/types/NativeHelpers.mjs' import path from "path" @@ -31,8 +33,13 @@ const isSynchronous = m => !m.tags ? false : m.tags.map(t => t.name).find(s => s // getSchemaType(schema, module, options = { destination: 'file.txt' }) // getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -function getMethodSignature(method, module, { destination = '' } = {}) { - return routeToDestination('getMethodSignature', arguments) +function getMethodSignature(method, module, { destination = '' } = {}) { + const returnType = getNativeType(method.result.schema) + const useHandle = !returnType + const extraParam = useHandle ? '${info.title}_${method.result.type}Handle* ${method.result.name}' : '' + + + return (returnType || 'uint32_t') + ' ${info.title}_Get${method.Name}(' + extraParam + ')' } function getMethodSignatureParams(method, module, { destination = '' } = {}) { @@ -44,8 +51,53 @@ function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', } function getSchemaType(schema, module, { destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - const value = routeToDestination('getSchemaType', arguments) - return value + let type = getNativeType(schema) + + if (!type) { + type = typeScriptTypes.getSchemaType(...arguments) + + const array = type.endsWith('[]') + + if (array) { + type = type.substring(0, type.length-2) + type = `${type}ObjectArrayHandle` + } + + type = `${module.info.title}_${type}` + } + return type +} + +function getJsonType(schema, module, { destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + let type = getSchemaType(...arguments) + + // FireboltSDK::JSON::String&, etc. + // FireboltSDK::::& + // WPEFramework::Core::JSON::Boolean + + const array = type.endsWith('[]') + + if (array) { + type = type.substring(0, type.length-2) + } + + let jsonType + + if (type === 'string') { + jsonType = 'FireboltSDK::JSON::String' + } + else if (type === 'boolean') { + jsonType = 'WPEFramework::Core::JSON::Boolean' + } + else { + jsonType = `FireboltSDK::${module.info.title}::${getSchemaType(...arguments)}` + } + + if (array) { + jsonType = `WPEFramework::Core::JSON::ArrayType<${jsonType}>` + } + + return `${jsonType}&` } function routeToDestination(method, args) { @@ -70,9 +122,22 @@ function routeToDestination(method, args) { return '' } +function getPrimativeType(schema) { + if (schema.type === "boolean") { + return "bool" + } + else if (schema.type === "integer") { + return "uint32_t" + } + else if (schema.type === "number") { + return + } +} + export default { getMethodSignature, getMethodSignatureParams, getSchemaShape, getSchemaType, + getJsonType } \ No newline at end of file diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs new file mode 100644 index 00000000..e51c47d7 --- /dev/null +++ b/languages/c/src/types/NativeHelpers.mjs @@ -0,0 +1,494 @@ +/* + * Copyright 2021 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 + */ + +import helpers from 'crocks/helpers/index.js' +const { compose, getPathOr } = helpers +import safe from 'crocks/Maybe/safe.js' +import pointfree from 'crocks/pointfree/index.js' +const { chain, filter, reduce, option, map } = pointfree +import predicates from 'crocks/predicates/index.js' +import { getPath, getExternalSchemaPaths } from '../../../../src/shared/json-schema.mjs' +import deepmerge from 'deepmerge' + +const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = predicates + +const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' + +const getHeaderText = () => { + + return `/* +* Copyright 2022 Comcast +* +* Auto Generated using firebolt-openrpc tools. DO NOT EDIT. +* +*/ + +` +} + +const getIncludeGuardOpen = (json, prefix=null) => { + prefix = prefix ? `${prefix.toUpperCase()}_` : '' + return ` +#ifndef _${prefix}${getModuleName(json).toUpperCase()}_H +#define _${prefix}${getModuleName(json).toUpperCase()}_H + +` +} + +const getStyleGuardOpen = () => { + return ` +#ifdef __cplusplus +extern "C" { +#endif + +` +} + +const getStyleGuardClose = () => { + return ` + +#ifdef __cplusplus +} +#endif + +` +} + +const getIncludeGuardClose = () => { + return ` +#endif // Header Include Guard +` +} + +const capitalize = str => str[0].toUpperCase() + str.substr(1) +const description = (title, str='') => '/* ' + title + (str.length > 0 ? ' - ' + str : '') + ' */' +const isOptional = (prop, json) => (!json.required || !json.required.includes(prop)) + +const SdkTypesPrefix = 'Firebolt' + +const Indent = ' ' + +const getNativeType = json => { + let type + + if (json.const) { + if (typeof json.const === 'string') { + type = 'char*' + } + else if (typeof json.const === 'number') { + type = 'uint32_t' + if (json.const < 0) + type = 'int32_t' + } else if (typeof json.const === 'boolean'){ + type = 'bool' + } + } + else if (json.type === 'string') { + type = 'char*' + } + else if (json.type === 'number' || json.type === 'integer') { //Lets keep it simple for now + type = 'uint32_t' + if ((json.minimum && json.minimum < 0) + || (json.exclusiveMinimum && json.exclusiveMinimum < 0)) { + type = 'int32_t' + } + } + else if (json.type === 'boolean') { + type = 'bool' + } + return type +} + +const getObjectHandleManagement = varName => { + + let result = `typedef void* ${varName}Handle; +${varName}Handle ${varName}Handle_Create(void); +void ${varName}Handle_Addref(${varName}Handle handle); +void ${varName}Handle_Release(${varName}Handle handle); +bool ${varName}Handle_IsValid(${varName}Handle handle); +` + return result +} + +const getPropertyAccessors = (objName, propertyName, propertyType, options = {level:0, readonly:false, optional:false}) => { + + let result = `${Indent.repeat(options.level)}${propertyType} ${objName}_Get_${propertyName}(${objName}Handle handle);` + '\n' + + if (!options.readonly) { + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${propertyType} ${propertyName.toLowerCase()});` + '\n' + } + + if (options.optional === true) { + result += `${Indent.repeat(options.level)}bool ${objName}_has_${propertyName}(${objName}Handle handle);` + '\n' + result += `${Indent.repeat(options.level)}void ${objName}_clear_${propertyName}(${objName}Handle handle);` + '\n' + } + + return result +} + +const getMapAccessors = (typeName, nativeType, level=0) => { + + let res + + res = `${Indent.repeat(level)}uint32_t ${typeName}_KeysCount(${typeName}Handle handle);` + '\n' + res += `${Indent.repeat(level)}void ${typeName}_AddKey(${typeName}Handle handle, char* key, ${nativeType} value);` + '\n' + res += `${Indent.repeat(level)}void ${typeName}_RemoveKey(${typeName}Handle handle, char* key);` + '\n' + res += `${Indent.repeat(level)}${nativeType} ${typeName}_FindKey(${typeName}Handle handle, char* key);` + '\n' + + return res +} + +const getTypeName = (moduleName, varName, upperCase = false) => { + let mName = upperCase ? moduleName.toUpperCase() : capitalize(moduleName) + let vName = upperCase ? varName.toUpperCase() : capitalize(varName) + + return `${mName}_${vName}` +} + +const getArrayAccessors = (arrayName, valueType) => { + + let res = `uint32_t ${arrayName}_Size(${arrayName}Handle handle);` + '\n' + res += `${valueType} ${arrayName}_Get(${arrayName}Handle handle, uint32_t index);` + '\n' + res += `void ${arrayName}_Add(${arrayName}Handle handle, ${valueType} value);` + '\n' + res += `void ${arrayName}_Clear(${arrayName}Handle handle);` + '\n' + + return res +} + +const enumValue = (val,prefix) => { + const keyName = val.replace(/[\.\-:]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + return ` ${prefix.toUpperCase()}_${keyName.toUpperCase()}` +} + +const generateEnum = (schema, prefix)=> { + if (!schema.enum) { + return '' + } + else { + let str = `typedef enum {\n` + str += schema.enum.map(e => enumValue(e, prefix)).join(',\n') + str += `\n} ${prefix};\n` + return str + } +} + +const getIncludeDefinitions = (json = {}, jsonData = false) => { + return getExternalSchemaPaths(json) + .map(ref => { + const mod = ref.split('#')[0].split('/').pop() + let i = `#include "Common/${capitalize(mod)}.h"` + if(jsonData === true) { + i += '\n' + `#include "JsonData_${capitalize(mod)}.h"` + } + return i + }) + .filter((item, index, arr) => arr.indexOf(item) === index) + .concat([`#include "Firebolt/Types.h"`]) +} + +function getSchemaType(module = {}, json = {}, name = '', schemas = {}, options = {level: 0, descriptions: true, title: false}) { + if (json.schema) { + json = json.schema + } + + let structure = {} + structure["deps"] = new Set() //To avoid duplication of local ref definitions + structure["type"] = [] + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(json['$ref'], module, schemas) + let tName = definition.title || json['$ref'].split('/').pop() + const res = getSchemaType(module, definition, tName, schemas, {descriptions: options.descriptions, level: options.level}) + res.deps.forEach(dep => structure.deps.add(dep)) + structure.type = res.type + return structure + } + else { + // External dependency. + // e.g, "https://meta.comcast.com/firebolt/entertainment#/definitions/ProgramType" + + //Get the module of this definition + const schema = getPath(json['$ref'].split('#')[0], schemas) || module + + //Get the schema of the definition + const definition = getPath(json['$ref'], module, schemas) + let tName = definition.title || json['$ref'].split('/').pop() + const res = getSchemaType(schema, definition, tName, schemas, {descriptions: options.descriptions, level: options.level}) + //We are only interested in the type definition for external modules + structure.type = res.type + return structure + } + } + else if (json.const) { + structure.type = getNativeType(json) + return structure + } + else if (json['x-method']) { + console.log(`WARNING UNHANDLED: x-method in ${name}`) + return structure + //throw "x-methods not supported yet" + } + else if (json.type === 'string' && json.enum) { + //Enum + let typeName = getTypeName(getModuleName(module), name || json.title) + let res = description(capitalize(name || json.title), json.description) + '\n' + generateEnum(json, typeName) + structure.deps.add(res) + structure.type.push(typeName) + return structure + } + else if (Array.isArray(json.type)) { + let type = json.type.find(t => t !== 'null') + console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) + } + else if (json.type === 'array' && json.items) { + let res + if (Array.isArray(json.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(json.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getSchemaType(module, json.items[0],'',schemas) + } + else { + // grab the type for the non-array schema + res = getSchemaType(module, json.items, '', schemas) + } + + res.deps.forEach(dep => structure.deps.add(dep)) + let n = getTypeName(getModuleName(module), name || json.title) + let def = description(name || json.title, json.description) + '\n' + if (options.level === 0) { + def += getObjectHandleManagement(n + 'Array') + '\n' + } + def += getArrayAccessors(n + 'Array', res.type) + structure.deps.add(def) + structure.type.push(n + 'ArrayHandle') + return structure + } + else if (json.allOf) { + let union = deepmerge.all([...json.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)]) + if (json.title) { + union['title'] = json.title + } + else { + union['title'] = name + } + delete union['$ref'] + return getSchemaType(module, union, '',schemas, options) + } + else if (json.oneOf || json.anyOf) { + return structure + //TODO + } + else if (json.type === 'object') { + let res = getSchemaShape(module, json, schemas, json.title || name, {descriptions: options.descriptions, level: 0}) + res.deps.forEach(dep => structure.deps.add(dep)) + res.type.forEach(t => structure.deps.add(t)) + structure.type.push(getTypeName(getModuleName(module), json.title || name) + 'Handle') + return structure + //TODO + } + else if (json.type) { + structure.type = getNativeType(json) + return structure + } + return structure +} + +function getSchemaShape(moduleJson = {}, json = {}, schemas = {}, name = '', options = {level: 0, descriptions: true}) { + json = JSON.parse(JSON.stringify(json)) + let level = options.level + let descriptions = options.descriptions + + let structure = {} + structure["deps"] = new Set() //To avoid duplication of local ref definitions + structure["type"] = [] + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + + const schema = getPath(json['$ref'], module, schemas) + const tname = schema.title || json['$ref'].split('/').pop() + res = getSchemaShape(module, schema, schemas, tname, {descriptions: descriptions, level: level}) + res.deps.forEach(dep => structure.deps.add(dep)) + structure.type = res.type + } + else { + // External dependency. Return only type + // e.g, "https://meta.comcast.com/firebolt/entertainment#/definitions/ProgramType" + + //Get the module of this definition + const schema = getPath(json['$ref'].split('#')[0], schemas) || module + + //Get the schema of the definition + const definition = getPath(json['$ref'], schema, schemas) + const pname = (json.title || name) + (definition.title || json['$ref'].split('/').pop()) + + res = getSchemaShape(schema, definition, schemas, pname,{descriptions: descriptions, level: level}) + //We are only interested in the type definition for external modules + structure.type = res.type + } + } + //If the schema is a const, + else if (json.hasOwnProperty('const')) { + if (level > 0) { + + let t = description(name, json.description) + typeName = getTypeName(getModuleName(moduleJson), name) + t += getPropertyAccessors(typeName, capitalize(name), typeof json.const, {level: level, readonly:true, optional:false}) + structure.type.push(t) + } + } + else if (json.type === 'object') { + + if (json.properties) { + let tName = getTypeName(getModuleName(moduleJson), name) + let t = description(name, json.description) + t += '\n' + getObjectHandleManagement(tName) + Object.entries(json.properties).forEach(([pname, prop]) => { + t += '\n' + description(pname, prop.description) + let res + if (prop.type === 'array') { + if (Array.isArray(prop.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(prop.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getSchemaType(moduleJson, prop.items[0],pname, schemas, {level : options.level, descriptions: options.descriptions, title: true}) + } + else { + // grab the type for the non-array schema + res = getSchemaType(moduleJson, prop.items, pname, schemas, {level : options.level, descriptions: options.descriptions, title: true}) + } + if (res.type && res.type.length > 0) { + let n = tName + '_' + capitalize(pname || prop.title) + let def = getArrayAccessors(n + 'Array', res.type) + t += '\n' + def + } + else { + console.log(`WARNING: Type undetermined for ${name}:${pname}`) + } + } else { + res = getSchemaType(moduleJson, prop, pname,schemas, {descriptions: descriptions, level: level + 1, title: true}) + if (res.type && res.type.length > 0) { + t += '\n' + getPropertyAccessors(tName, capitalize(pname), res.type, {level: level, readonly:false, optional:isOptional(pname, json)}) + } + else { + console.log(`WARNING: Type undetermined for ${name}:${pname}`) + } + } + res.deps.forEach(dep => structure.deps.add(dep)) + }) + structure.type.push(t) + } + else if (json.propertyNames && json.propertyNames.enum) { + //propertyNames in object not handled yet + } + else if (json.additionalProperties && (typeof json.additionalProperties === 'object')) { + //This is a map of string to type in schema + //Get the Type + let type = getSchemaType(moduleJson, json.additionalProperties, name,schemas) + if (type.type && type.type.length > 0) { + let tName = getTypeName(getModuleName(moduleJson), name) + type.deps.forEach(dep => structure.deps.add(dep)) + let t = description(name, json.description) + t += '\n' + getObjectHandleManagement(tName) + '\n' + t += getMapAccessors(getTypeName(getModuleName(moduleJson), name), type.type,{descriptions: descriptions, level: level}) + structure.type.push(t) + } + else { + console.log(`WARNING: Type undetermined for ${name}`) + } + } + else if (json.patternProperties) { + throw "patternProperties are not supported by Firebolt" + } + } + else if (json.anyOf) { + + } + else if (json.oneOf) { + + } + else if (json.allOf) { + let union = deepmerge.all([...json.allOf.map(x => x['$ref'] ? getPath(x['$ref'], moduleJson, schemas) || x : x)], options) + if (json.title) { + union['title'] = json.title + } + else { + union['title'] = name + } + delete union['$ref'] + return getSchemaShape(moduleJson, union, schemas, name, options) + + } + else if (json.type === 'array') { + let res = getSchemaType(moduleJson, json, name, schemas, {level: 0, descriptions: descriptions}) + res.deps.forEach(dep => structure.deps.add(dep)) + } + else { + let res = getSchemaType(moduleJson, json, name, schemas, {level: level, descriptions: descriptions}) + res.deps.forEach(dep => structure.deps.add(dep)) + } + return structure + } + + function getPropertyGetterSignature(method, module, paramType) { + let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` + return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` + } + + function getPropertySetterSignature(method, module, paramType) { + let m = `${capitalize(getModuleName(module))}_Set${capitalize(method.name)}` + return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType} ${method.result.name || method.name} )` + } + + function getPropertyEventCallbackSignature(method, module, paramType) { + return `typedef void (*On${capitalize(method.name)}Changed)(${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType})` + } + + function getPropertyEventSignature(method, module) { + return `${description(method.name, 'Listen to updates')}\n` + `uint32_t ${capitalize(getModuleName(module))}_Listen${capitalize(method.name)}Update(On${capitalize(method.name)}Changed notification, uint16_t* listenerId)` + } + + export { + getHeaderText, + getIncludeGuardOpen, + getStyleGuardOpen, + getStyleGuardClose, + getIncludeGuardClose, + getNativeType, + getSchemaType, + getSchemaShape, + getModuleName, + getIncludeDefinitions, + getPropertyGetterSignature, + getPropertySetterSignature, + getPropertyEventCallbackSignature, + getPropertyEventSignature, + capitalize, + description, + getTypeName + } diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c new file mode 100644 index 00000000..7d10ba97 --- /dev/null +++ b/languages/c/templates/methods/default.c @@ -0,0 +1,24 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.title}_${method.Name}(${method.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { + uint32_t status = FireboltSDKErrorUnavailable; + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + + JsonObject jsonParameters; + + ${if.params} +${method.params.json} + ${end.if.params} + + WPEFramework::Core::JSON::Boolean jsonResult; + status = transport->Invoke("${info.title}.${method.name}", jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + *success = jsonResult.Value(); + } + + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; +} \ No newline at end of file diff --git a/languages/c/templates/methods/default.js b/languages/c/templates/methods/default.js deleted file mode 100644 index 0c7f799b..00000000 --- a/languages/c/templates/methods/default.js +++ /dev/null @@ -1,7 +0,0 @@ - -function ${method.name}(${method.params.list}) { - - const transforms = ${method.transforms} - - return Transport.send('${info.title}', '${method.name}', { ${method.params.list} }, transforms) -} \ No newline at end of file diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c new file mode 100644 index 00000000..8f301bea --- /dev/null +++ b/languages/c/templates/methods/property.c @@ -0,0 +1,12 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.title}_Get${method.Name}(${method.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { + const string method = _T("${info.title}.${method.name}"); + FireboltSDK::${info.title}::${method.result.type} jsonResult; + + uint32_t status = FireboltSDK::Properties::Get(method, jsonResult); + if (status == FireboltSDKErrorNone) { + WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); + *${method.result.name} = static_cast<${info.title}_${method.result.type}Handle>(resultPtr); + } + return status; +} diff --git a/languages/c/templates/modules/include/Common/Module.h b/languages/c/templates/modules/include/Common/Module.h index 4cee1781..22c25143 100644 --- a/languages/c/templates/modules/include/Common/Module.h +++ b/languages/c/templates/modules/include/Common/Module.h @@ -16,8 +16,19 @@ * SPDX-License-Identifier: Apache-2.0 */ -namespace FireboltSDK { +#ifndef _COMMON_${info.TITLE}_H +#define _COMMON_${info.TITLE}_H - /* ${DECLARATIONS} */ +#include "Firebolt.h" +#ifdef __cplusplus +extern "C" { +#endif + + /* ${SCHEMAS} */ + +#ifdef __cplusplus } +#endif + +#endif // Header Include Guard \ No newline at end of file diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h index 60a75f5f..92bab4f7 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/Module.h @@ -16,10 +16,22 @@ * SPDX-License-Identifier: Apache-2.0 */ -namespace FireboltSDK { +#ifndef _${info.TITLE}_H +#define _${info.TITLE}_H + +#include "Firebolt.h" +#include "Common/${info.title}.h" + +#ifdef __cplusplus +extern "C" { +#endif /* ${SCHEMAS} */ /* ${DECLARATIONS} */ +#ifdef __cplusplus } +#endif + +#endif // Header Include Guard \ No newline at end of file diff --git a/languages/c/templates/modules/src/JsonData_Module.h b/languages/c/templates/modules/src/JsonData_Module.h index 4cee1781..2c7ca8c8 100644 --- a/languages/c/templates/modules/src/JsonData_Module.h +++ b/languages/c/templates/modules/src/JsonData_Module.h @@ -16,8 +16,14 @@ * SPDX-License-Identifier: Apache-2.0 */ +#pragma once + +#include "Firebolt.h" + namespace FireboltSDK { + namespace ${info.title} { - /* ${DECLARATIONS} */ + /* ${SCHEMAS}} */ + } } diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 26a26050..2417f708 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -16,14 +16,17 @@ * SPDX-License-Identifier: Apache-2.0 */ -/* ${IMPORTS} */ +#include "FireboltSDK.h" +#include "${info.title}.h" +#include "Common/${info.title}.h" +#include "JsonData_${info.title}.h" +#ifdef __cplusplus +extern "C" { +#endif -namespace FireboltSDK { - - namespace ${info.title} { + /* ${METHODS} */ - /* ${METHODS} */ - - } +#ifdef __cplusplus } +#endif diff --git a/languages/c/templates/modules/src/Module_Common.cpp b/languages/c/templates/modules/src/Module_Common.cpp index 8460c52a..bce775ff 100644 --- a/languages/c/templates/modules/src/Module_Common.cpp +++ b/languages/c/templates/modules/src/Module_Common.cpp @@ -16,11 +16,16 @@ * SPDX-License-Identifier: Apache-2.0 */ -/* ${IMPORTS} */ - - -namespace FireboltSDK { +#include "FireboltSDK.h" +#include "Common/${info.title}.h" +#include "JsonData_${info.title}.h" +} +#ifdef __cplusplus +extern "C" { +#endif - /* ${METHODS} */ + /* ${SCHEMAS}} */ +#ifdef __cplusplus } +#endif \ No newline at end of file diff --git a/languages/c/templates/parameters/default.c b/languages/c/templates/parameters/default.c new file mode 100644 index 00000000..e6e3b8ba --- /dev/null +++ b/languages/c/templates/parameters/default.c @@ -0,0 +1 @@ +${method.param.type} ${method.param.name} \ No newline at end of file diff --git a/languages/c/templates/parameters/default.js b/languages/c/templates/parameters/default.js deleted file mode 100644 index 916a8adf..00000000 --- a/languages/c/templates/parameters/default.js +++ /dev/null @@ -1 +0,0 @@ -${method.params.list} \ No newline at end of file diff --git a/languages/c/templates/parameters/json.c b/languages/c/templates/parameters/json.c new file mode 100644 index 00000000..5ee36bec --- /dev/null +++ b/languages/c/templates/parameters/json.c @@ -0,0 +1,3 @@ + ${json.param.type} ${method.param.Name} = ${method.param.name}; + jsonParameters.Add("_T(${method.param.name})", &${method.param.Name}); + diff --git a/languages/javascript/templates/methods/property.js b/languages/javascript/templates/methods/property.js index df748ecd..0b1e1359 100644 --- a/languages/javascript/templates/methods/property.js +++ b/languages/javascript/templates/methods/property.js @@ -1,4 +1,4 @@ function ${method.name}(${method.params.list}) { const callbackOrValue = arguments[${method.params.count}] - return Prop.prop('${info.title}', '${method.name}', { ${method.params} }, callbackOrValue, ${method.property.immutable}, ${method.property.readonly}, ${method.params.count}) + return Prop.prop('${info.title}', '${method.name}', { ${method.params.list} }, callbackOrValue, ${method.property.immutable}, ${method.property.readonly}, ${method.params.count}) } \ No newline at end of file diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index cc2f9051..77541d85 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -51,7 +51,8 @@ let types = { getMethodSignature: ()=>null, getMethodSignatureParams: ()=>null, getSchemaShape: ()=>null, - getSchemaType: ()=>null + getSchemaType: ()=>null, + getJsonType: ()=>null } let config = { @@ -877,12 +878,15 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { } } + const paramDelimiter = config.operators ? config.operators.paramDelimiter : ', ' + const temporalItemName = isTemporalSetMethod(methodObj) ? methodObj.result.schema.items && methodObj.result.schema.items.title || 'Item' : '' const temporalAddName = isTemporalSetMethod(methodObj) ? `on${temporalItemName}Available` : '' const temporalRemoveName = isTemporalSetMethod(methodObj) ? `on${temporalItemName}Unvailable` : '' - const params = methodObj.params && methodObj.params.length ? getTemplate('/sections/parameters', templates) + methodObj.params.map(p => insertParameterMacros(getTemplate('/parameters/default', templates), p, methodObj, json)).join('') : '' + const params = methodObj.params && methodObj.params.length ? getTemplate('/sections/parameters', templates) + methodObj.params.map(p => insertParameterMacros(getTemplate('/parameters/default', templates), p, methodObj, json)).join(paramDelimiter) : '' const paramsRows = methodObj.params && methodObj.params.length ? methodObj.params.map(p => insertParameterMacros(getTemplate('/parameters/default', templates), p, methodObj, json)).join('') : '' const paramsAnnotations = methodObj.params && methodObj.params.length ? methodObj.params.map(p => insertParameterMacros(getTemplate('/parameters/annotations', templates), p, methodObj, json)).join('') : '' + const paramsJson = methodObj.params && methodObj.params.length ? methodObj.params.map(p => insertParameterMacros(getTemplate('/parameters/json', templates), p, methodObj, json)).join('') : '' const deprecated = methodObj.tags && methodObj.tags.find(t => t.name === 'deprecated') const deprecation = deprecated ? deprecated['x-since'] ? `since version ${deprecated['x-since']}` : '' : '' @@ -945,10 +949,11 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{method\.params\}/g, params) .replace(/\$\{method\.params\.table\.rows\}/g, paramsRows) .replace(/\$\{method\.params\.annotations\}/g, paramsAnnotations) + .replace(/\$\{method\.params\.json\}/g, paramsJson) .replace(/\$\{method\.params\.list\}/g, method.params) .replace(/\$\{method\.params\.array\}/g, JSON.stringify(methodObj.params.map(p => p.name))) .replace(/\$\{method\.params\.count}/g, methodObj.params ? methodObj.params.length : 0) - .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/g, method.params.length ? '$1' : '') + .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/gms, method.params.length ? '$1' : '') .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event.params.length ? '$1' : '') // Typed signature stuff .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination })) @@ -962,6 +967,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{event\.params\.table\.rows\}/g, eventParamsRows) .replace(/\$\{event\.signature\.params\}/g, types.getMethodSignatureParams(event, json, { destination: state.destination })) .replace(/\$\{info\.title\}/g, info.title) + .replace(/\$\{info\.TITLE\}/g, info.title.toUpperCase()) .replace(/\$\{method\.property\.immutable\}/g, hasTag(methodObj, 'property:immutable')) .replace(/\$\{method\.property\.readonly\}/g, !getSetterFor(methodObj.name, json)) .replace(/\$\{method\.temporalset\.add\}/g, temporalAddName) @@ -974,8 +980,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{method\.result\.name\}/g, result.name) .replace(/\$\{method\.result\.summary\}/g, result.summary) .replace(/\$\{method\.result\.link\}/g, getLinkForSchema(result, json)) //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result, json, {title: true, asPath: false, destination: state.destination })) //, baseUrl: options.baseUrl - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result, json, { destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result.schema, json, {title: true, asPath: false, destination: state.destination })) //, baseUrl: options.baseUrl + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates)) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) @@ -1153,20 +1159,23 @@ 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, module, { destination: state.destination, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl + let type = types.getSchemaType(param.schema, module, { destination: state.destination, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl let typeLink = getLinkForSchema(param, module) + let jsonType = types.getJsonType(param.schema, module, { destination: state.destination, code: false, link: false, title: true, asPath: false, expandEnums: false }) if (constraints && type) { constraints = '
' + constraints } return template - .replace(/\$\{method.param.name\}/, param.name) - .replace(/\$\{method.param.summary\}/, param.summary || '') - .replace(/\$\{method.param.required\}/, param.required || 'false') - .replace(/\$\{method.param.type\}/, type) //getType(param)) - .replace(/\$\{method.param.link\}/, getLinkForSchema(param, module)) //getType(param)) - .replace(/\$\{method.param.constraints\}/, constraints) //getType(param)) + .replace(/\$\{method.param.name\}/g, param.name) + .replace(/\$\{method.param.Name\}/g, param.name[0].toUpperCase() + param.name.substring(1)) + .replace(/\$\{method.param.summary\}/g, param.summary || '') + .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, module)) //getType(param)) + .replace(/\$\{method.param.constraints\}/g, constraints) //getType(param)) } function insertCapabilityMacros(template, capabilities, method, module) { diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 89c194e2..29cf7ba4 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -68,10 +68,13 @@ const macrofy = async ( let typer try { + console.log(path.join(sharedTemplates, '..', 'Types.mjs')) const typerModule = await import(path.join(sharedTemplates, '..', 'Types.mjs')) typer = typerModule.default } catch (_) { + console.log("Using default Typer") + console.dir(_) typer = (await import('../shared/typescript.mjs')).default } diff --git a/src/shared/typescript.mjs b/src/shared/typescript.mjs index aa6e21f5..e53747cd 100644 --- a/src/shared/typescript.mjs +++ b/src/shared/typescript.mjs @@ -199,10 +199,6 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, } function getSchemaType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - if (schema.schema) { - schema = schema.schema - } - const wrap = (str, wrapper) => wrapper + str + wrapper if (schema['$ref']) { @@ -327,6 +323,10 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, return wrap('void', code ? '`' : '') } } + + function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + return '' + } function getTypeScriptType(jsonType) { if (jsonType === 'integer') { @@ -350,5 +350,6 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, getMethodSignature, getMethodSignatureParams, getSchemaShape, - getSchemaType + getSchemaType, + getJsonType } \ No newline at end of file From 02e2e7371e40eeff21bdbcc6b8e57f1b44d4b671 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 26 Apr 2023 14:43:51 -0400 Subject: [PATCH 035/137] chore: Dropped debug logs --- src/macrofier/index.mjs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 29cf7ba4..89c194e2 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -68,13 +68,10 @@ const macrofy = async ( let typer try { - console.log(path.join(sharedTemplates, '..', 'Types.mjs')) const typerModule = await import(path.join(sharedTemplates, '..', 'Types.mjs')) typer = typerModule.default } catch (_) { - console.log("Using default Typer") - console.dir(_) typer = (await import('../shared/typescript.mjs')).default } From 5814d9d975b3fad65d098b960cafee4f0d48cd02 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 26 Apr 2023 14:49:28 -0400 Subject: [PATCH 036/137] fix: Stop passing non-schemas in to getSchemaType --- src/macrofier/engine.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 77541d85..6404a059 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -1007,7 +1007,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const matches = [...template.matchAll(/\$\{method\.params\[([0-9]+)\]\.type\}/g)] matches.forEach(match => { const index = parseInt(match[1]) - template = template.replace(/\$\{method\.params\[([0-9]+)\]\.type\}/g, types.getSchemaType(methodObj.params[index], json, { destination: state.destination })) + template = template.replace(/\$\{method\.params\[([0-9]+)\]\.type\}/g, types.getSchemaType(methodObj.params[index].schema, json, { destination: state.destination })) template = template.replace(/\$\{method\.params\[([0-9]+)\]\.name\}/g, methodObj.params[index].name) }) From c1ba6ae6b26ee9ac0c99bea78cd6e6a3b3ae0905 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Fri, 28 Apr 2023 12:44:35 -0400 Subject: [PATCH 037/137] feat(accessors): New macro section for schema property accessors --- languages/c/Types.mjs | 397 ++++++-- languages/c/src/types/CommonCppTypes.mjs | 60 -- languages/c/src/types/CommonHeaderTypes.mjs | 55 -- languages/c/src/types/CppTypes.mjs | 55 -- languages/c/src/types/HeaderTypes.mjs | 55 -- languages/c/src/types/ImplHelpers.mjs | 294 ++++++ languages/c/src/types/JSONHelpers.mjs | 61 ++ languages/c/src/types/JSONTypes.mjs | 56 -- languages/c/src/types/NativeHelpers.mjs | 264 +----- .../codeblocks/{export.mjs => export.c} | 0 .../{mock-import.mjs => mock-import.c} | 0 .../{mock-parameter.mjs => mock-parameter.c} | 0 .../clear.js => codeblocks/module.c} | 0 languages/c/templates/codeblocks/module.mjs | 11 - .../declarations/{listen.js => clear.c} | 0 .../declarations/{default.js => default.c} | 2 +- .../declarations/{once.js => listen.c} | 0 .../declarations/{provide.js => once.c} | 0 ...rphic-reducer.js => polymorphic-reducer.c} | 0 .../declarations/{rpc-only.js => provide.c} | 0 .../listen.js => declarations/rpc-only.c} | 0 .../defaults/{default.mjs => default.c} | 0 .../defaults/{property.mjs => property.c} | 0 languages/c/templates/examples/default.md | 6 - languages/c/templates/examples/event.md | 5 - .../examples/polymorphic-pull-event.md | 9 - .../c/templates/examples/polymorphic-pull.md | 6 - languages/c/templates/examples/provider.md | 10 - languages/c/templates/examples/setter.md | 6 - languages/c/templates/examples/subscriber.md | 7 - languages/c/templates/examples/synchronous.md | 4 - .../c/templates/examples/temporal-set.md | 13 - .../c/templates/imports/context-event.mjs | 1 - languages/c/templates/imports/default.c | 1 + languages/c/templates/imports/event.mjs | 2 - languages/c/templates/imports/property.mjs | 1 - languages/c/templates/imports/provider.mjs | 2 - languages/c/templates/imports/rpc.mjs | 1 - .../c/templates/imports/temporal-set.mjs | 1 - languages/c/templates/imports/x-method.mjs | 1 - .../templates/initializations/deprecated.mjs | 1 - .../c/templates/initializations/event.mjs | 1 - .../c/templates/initializations/provider.mjs | 1 - languages/c/templates/methods/default.c | 2 +- .../c/templates/methods/{once.js => listen.c} | 0 .../templates/methods/{rpc-only.js => once.c} | 0 ...rphic-reducer.js => polymorphic-reducer.c} | 0 .../methods/{provide.js => provide.c} | 0 languages/c/templates/methods/rpc-only.c | 0 .../templates/modules/include/Common/Module.h | 6 + .../c/templates/modules/include/Module.h | 3 +- languages/c/templates/modules/src/Module.cpp | 11 +- .../schemas/{default.js => default.c} | 0 .../templates/schemas/include/Common/Module.h | 21 +- .../c/templates/schemas/src/Module_Common.cpp | 14 +- languages/c/templates/sdk/CMakeLists.txt | 49 + .../c/templates/sdk/build/CMakeCache.txt | 407 ++++++++ .../CMakeFiles/3.25.3/CMakeCCompiler.cmake | 72 ++ .../CMakeFiles/3.25.3/CMakeCXXCompiler.cmake | 83 ++ .../3.25.3/CMakeDetermineCompilerABI_C.bin | Bin 0 -> 16999 bytes .../3.25.3/CMakeDetermineCompilerABI_CXX.bin | Bin 0 -> 16983 bytes .../build/CMakeFiles/3.25.3/CMakeSystem.cmake | 15 + .../3.25.3/CompilerIdC/CMakeCCompilerId.c | 868 +++++++++++++++++ .../3.25.3/CompilerIdC/CMakeCCompilerId.o | Bin 0 -> 1712 bytes .../CompilerIdCXX/CMakeCXXCompilerId.cpp | 857 +++++++++++++++++ .../3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o | Bin 0 -> 1712 bytes .../sdk/build/CMakeFiles/CMakeError.log | 0 .../sdk/build/CMakeFiles/CMakeOutput.log | 266 ++++++ .../sdk/build/CMakeFiles/cmake.check_cache | 1 + .../c/templates/sdk/cmake/CopySymlink.cmake | 17 + .../templates/sdk/cmake/HelperFunctions.cmake | 139 +++ .../c/templates/sdk/cmake/project.cmake.in | 30 + languages/c/templates/sdk/include/Error.h | 41 + languages/c/templates/sdk/include/Types.h | 43 + languages/c/templates/sdk/scripts/install.js | 32 + .../c/templates/sdk/src/Accessor/Accessor.cpp | 134 +++ .../c/templates/sdk/src/Accessor/Accessor.h | 79 ++ .../c/templates/sdk/src/Accessor/Config.h | 41 + .../c/templates/sdk/src/Accessor/WorkerPool.h | 72 ++ languages/c/templates/sdk/src/CMakeLists.txt | 93 ++ languages/c/templates/sdk/src/Config.cmake | 34 + languages/c/templates/sdk/src/Event/Event.cpp | 148 +++ languages/c/templates/sdk/src/Event/Event.h | 154 +++ languages/c/templates/sdk/src/Firebolt.h | 25 + .../c/templates/sdk/src/FireboltSDK.conf.in | 3 + .../c/templates/sdk/src/Logger/Logger.cpp | 84 ++ languages/c/templates/sdk/src/Logger/Logger.h | 85 ++ .../templates/{schemas => sdk}/src/Module.cpp | 12 +- .../templates/sdk/{main.cpp => src/Module.h} | 21 +- languages/c/templates/sdk/src/Params.config | 3 + .../templates/sdk/src/Properties/Properties.h | 90 ++ .../src/Transport/Transport.cpp} | 5 +- .../c/templates/sdk/src/Transport/Transport.h | 897 ++++++++++++++++++ languages/c/templates/sdk/src/Types.cpp | 41 + languages/c/templates/sdk/src/TypesPriv.h | 55 ++ .../templates/sdk/src/cmake/CopySymlink.cmake | 1 + languages/c/templates/sdk/test/CMakeLists.txt | 86 ++ languages/c/templates/sdk/test/Main.c | 44 + languages/c/templates/sdk/test/Module.cpp | 21 + .../Module_Common.cpp => sdk/test/Module.h} | 18 +- .../c/templates/sdk/test/OpenRPCCTests.h | 42 + .../c/templates/sdk/test/OpenRPCTests.cpp | 385 ++++++++ languages/c/templates/sdk/test/OpenRPCTests.h | 99 ++ languages/c/templates/sdk/test/TestUtils.h | 38 + languages/c/templates/sections/accessors.c | 3 + .../{declarations.js => declarations.c} | 0 .../sections/{events.js => events.c} | 0 .../sections/{methods.js => methods.c} | 0 ...er-interfaces.js => provider-interfaces.c} | 0 languages/c/templates/sections/schemas.c | 3 + .../sections/{schemas.js => types.c} | 0 languages/c/templates/types/enum.c | 3 + languages/c/templates/types/enum.mjs | 3 - src/macrofier/engine.mjs | 73 +- 114 files changed, 6485 insertions(+), 776 deletions(-) delete mode 100644 languages/c/src/types/CommonCppTypes.mjs delete mode 100644 languages/c/src/types/CommonHeaderTypes.mjs delete mode 100644 languages/c/src/types/CppTypes.mjs delete mode 100644 languages/c/src/types/HeaderTypes.mjs create mode 100644 languages/c/src/types/ImplHelpers.mjs create mode 100644 languages/c/src/types/JSONHelpers.mjs delete mode 100644 languages/c/src/types/JSONTypes.mjs rename languages/c/templates/codeblocks/{export.mjs => export.c} (100%) rename languages/c/templates/codeblocks/{mock-import.mjs => mock-import.c} (100%) rename languages/c/templates/codeblocks/{mock-parameter.mjs => mock-parameter.c} (100%) rename languages/c/templates/{declarations/clear.js => codeblocks/module.c} (100%) delete mode 100644 languages/c/templates/codeblocks/module.mjs rename languages/c/templates/declarations/{listen.js => clear.c} (100%) rename languages/c/templates/declarations/{default.js => default.c} (68%) rename languages/c/templates/declarations/{once.js => listen.c} (100%) rename languages/c/templates/declarations/{provide.js => once.c} (100%) rename languages/c/templates/declarations/{polymorphic-reducer.js => polymorphic-reducer.c} (100%) rename languages/c/templates/declarations/{rpc-only.js => provide.c} (100%) rename languages/c/templates/{methods/listen.js => declarations/rpc-only.c} (100%) rename languages/c/templates/defaults/{default.mjs => default.c} (100%) rename languages/c/templates/defaults/{property.mjs => property.c} (100%) delete mode 100644 languages/c/templates/examples/default.md delete mode 100644 languages/c/templates/examples/event.md delete mode 100644 languages/c/templates/examples/polymorphic-pull-event.md delete mode 100644 languages/c/templates/examples/polymorphic-pull.md delete mode 100644 languages/c/templates/examples/provider.md delete mode 100644 languages/c/templates/examples/setter.md delete mode 100644 languages/c/templates/examples/subscriber.md delete mode 100644 languages/c/templates/examples/synchronous.md delete mode 100644 languages/c/templates/examples/temporal-set.md delete mode 100644 languages/c/templates/imports/context-event.mjs create mode 100644 languages/c/templates/imports/default.c delete mode 100644 languages/c/templates/imports/event.mjs delete mode 100644 languages/c/templates/imports/property.mjs delete mode 100644 languages/c/templates/imports/provider.mjs delete mode 100644 languages/c/templates/imports/rpc.mjs delete mode 100644 languages/c/templates/imports/temporal-set.mjs delete mode 100644 languages/c/templates/imports/x-method.mjs delete mode 100644 languages/c/templates/initializations/deprecated.mjs delete mode 100644 languages/c/templates/initializations/event.mjs delete mode 100644 languages/c/templates/initializations/provider.mjs rename languages/c/templates/methods/{once.js => listen.c} (100%) rename languages/c/templates/methods/{rpc-only.js => once.c} (100%) rename languages/c/templates/methods/{polymorphic-reducer.js => polymorphic-reducer.c} (100%) rename languages/c/templates/methods/{provide.js => provide.c} (100%) create mode 100644 languages/c/templates/methods/rpc-only.c rename languages/c/templates/schemas/{default.js => default.c} (100%) create mode 100644 languages/c/templates/sdk/CMakeLists.txt create mode 100644 languages/c/templates/sdk/build/CMakeCache.txt create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake create mode 100755 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin create mode 100755 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_CXX.bin create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeSystem.cmake create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.c create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.cpp create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o create mode 100644 languages/c/templates/sdk/build/CMakeFiles/CMakeError.log create mode 100644 languages/c/templates/sdk/build/CMakeFiles/CMakeOutput.log create mode 100644 languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache create mode 100644 languages/c/templates/sdk/cmake/CopySymlink.cmake create mode 100644 languages/c/templates/sdk/cmake/HelperFunctions.cmake create mode 100644 languages/c/templates/sdk/cmake/project.cmake.in create mode 100644 languages/c/templates/sdk/include/Error.h create mode 100644 languages/c/templates/sdk/include/Types.h create mode 100644 languages/c/templates/sdk/scripts/install.js create mode 100644 languages/c/templates/sdk/src/Accessor/Accessor.cpp create mode 100644 languages/c/templates/sdk/src/Accessor/Accessor.h create mode 100644 languages/c/templates/sdk/src/Accessor/Config.h create mode 100644 languages/c/templates/sdk/src/Accessor/WorkerPool.h create mode 100644 languages/c/templates/sdk/src/CMakeLists.txt create mode 100644 languages/c/templates/sdk/src/Config.cmake create mode 100644 languages/c/templates/sdk/src/Event/Event.cpp create mode 100644 languages/c/templates/sdk/src/Event/Event.h create mode 100644 languages/c/templates/sdk/src/Firebolt.h create mode 100644 languages/c/templates/sdk/src/FireboltSDK.conf.in create mode 100644 languages/c/templates/sdk/src/Logger/Logger.cpp create mode 100644 languages/c/templates/sdk/src/Logger/Logger.h rename languages/c/templates/{schemas => sdk}/src/Module.cpp (85%) rename languages/c/templates/sdk/{main.cpp => src/Module.h} (61%) create mode 100644 languages/c/templates/sdk/src/Params.config create mode 100644 languages/c/templates/sdk/src/Properties/Properties.h rename languages/c/templates/{schemas/include/Module.h => sdk/src/Transport/Transport.cpp} (96%) create mode 100644 languages/c/templates/sdk/src/Transport/Transport.h create mode 100644 languages/c/templates/sdk/src/Types.cpp create mode 100644 languages/c/templates/sdk/src/TypesPriv.h create mode 100644 languages/c/templates/sdk/src/cmake/CopySymlink.cmake create mode 100644 languages/c/templates/sdk/test/CMakeLists.txt create mode 100644 languages/c/templates/sdk/test/Main.c create mode 100644 languages/c/templates/sdk/test/Module.cpp rename languages/c/templates/{modules/src/Module_Common.cpp => sdk/test/Module.h} (79%) create mode 100644 languages/c/templates/sdk/test/OpenRPCCTests.h create mode 100644 languages/c/templates/sdk/test/OpenRPCTests.cpp create mode 100644 languages/c/templates/sdk/test/OpenRPCTests.h create mode 100644 languages/c/templates/sdk/test/TestUtils.h create mode 100644 languages/c/templates/sections/accessors.c rename languages/c/templates/sections/{declarations.js => declarations.c} (100%) rename languages/c/templates/sections/{events.js => events.c} (100%) rename languages/c/templates/sections/{methods.js => methods.c} (100%) rename languages/c/templates/sections/{provider-interfaces.js => provider-interfaces.c} (100%) create mode 100644 languages/c/templates/sections/schemas.c rename languages/c/templates/sections/{schemas.js => types.c} (100%) create mode 100644 languages/c/templates/types/enum.c delete mode 100644 languages/c/templates/types/enum.mjs diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index aa209ad4..e44b4a78 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -16,122 +16,367 @@ * SPDX-License-Identifier: Apache-2.0 */ -import jsonTypes from './src/types/JSONTypes.mjs' -import commonTypes from './src/types/CommonCppTypes.mjs' -import headerCommonTypes from './src/types/CommonHeaderTypes.mjs' -import headerTypes from './src/types/HeaderTypes.mjs' -import cppTypes from './src/types/CppTypes.mjs' -import typeScriptTypes from '../../src/shared/typescript.mjs' -import { getNativeType } from './src/types/NativeHelpers.mjs' - -import path from "path" - -const isSynchronous = m => !m.tags ? false : m.tags.map(t => t.name).find(s => s === 'synchronous') - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) - -function getMethodSignature(method, module, { destination = '' } = {}) { - const returnType = getNativeType(method.result.schema) - const useHandle = !returnType - const extraParam = useHandle ? '${info.title}_${method.result.type}Handle* ${method.result.name}' : '' - - - return (returnType || 'uint32_t') + ' ${info.title}_Get${method.Name}(' + extraParam + ')' -} +import deepmerge from 'deepmerge' +import { getPath } from '../../src/shared/json-schema.mjs' +import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors } from './src/types/NativeHelpers.mjs' +import { getObjectHandleManagementImpl, getPropertyAccessorsImpl } from './src/types/ImplHelpers.mjs' +import { getJsonContainerDefinition } from './src/types/JSONHelpers.mjs' + +function getMethodSignature(method, module, { destination, isInterface = false }) { + const extraParam = '${method.result.type}* ${method.result.name}' -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return routeToDestination('getMethodSignatureParams', arguments) + const prefix = method.tags.find(t => t.name.split(":")[0] === "property") ? "Get" : "" + + return 'uint32_t ${info.title}_' + prefix + '${method.Name}(' + extraParam + ')' } -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - return routeToDestination('getSchemaShape', arguments) +function getMethodSignatureParams(method, module, { destination }) { + return method.params.map(param => param.name + (!param.required ? '?' : '') + ': ' + getSchemaType(param.schema, module, { title: true, destination })).join(', ') } -function getSchemaType(schema, module, { destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - let type = getNativeType(schema) +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaType(schema, module, { name, destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + let type = '' + let theTitle = schema.title || name || ('UnamedSchema' + (Math.floor(Math.random() * 100))) - if (!type) { - type = typeScriptTypes.getSchemaType(...arguments) + if (schema['x-method']) { + console.log(`WARNING UNHANDLED: x-method in ${theTitle}`) + //throw "x-methods not supported yet" + } - const array = type.endsWith('[]') + if (schema['$ref']) { + if (schema['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(schema['$ref'], module) + let tName = definition.title || schema['$ref'].split('/').pop() + return getSchemaType(definition, module, { name: tName, destination, link, title, code, asPath, event, expandEnums, baseUrl }) + } + } + else if (schema.const) { + type = getNativeType(schema) + return type + } + else if (schema.type === 'string' && schema.enum) { + //Enum + let typeName = getTypeName(getModuleName(module), theTitle) + return typeName + } + else if (Array.isArray(schema.type)) { + let type = schema.type.find(t => t !== 'null') + console.log(`WARNING UNHANDLED: type is an array containing ${schema.type}`) + } + else if (schema.type === 'array' && schema.items) { + let res + if (Array.isArray(schema.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(schema.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getSchemaType(schema.items[0], module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) + } + else { + // grab the type for the non-array schema + res = getSchemaType(schema.items, module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) + } - if (array) { - type = type.substring(0, type.length-2) - type = `${type}ObjectArrayHandle` + if (!schema.title && !name) { + console.log(`WARNING: generated name for ${module.info.title} schema w/ no title: ${theTitle}`) + console.dir(schema) } - type = `${module.info.title}_${type}` + let n = getTypeName(getModuleName(module), theTitle) + return n + 'ArrayHandle' + } + else if (schema.allOf) { + let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x)]) + if (theTitle) { + union['title'] = theTitle + } + delete union['$ref'] + return getSchemaType(union, module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) + } + else if (schema.oneOf || schema.anyOf) { + return type + //TODO + } + else if (schema.type === 'object') { + if (!schema.title && !name) { + console.log(`WARNING: generated name for ${module.info.title} schema w/ no title: ${theTitle}`) + console.dir(schema) + } + return getTypeName(getModuleName(module), theTitle) + 'Handle' + //TODO + } + else if (schema.type) { + type = getNativeType(schema) + return type } + + // TODO: deal with dependencies return type } -function getJsonType(schema, module, { destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - let type = getSchemaType(...arguments) +//function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, summary, descriptions = true, destination, enums = true } = {}) +// function getSchemaType() +function getSchemaShape(schema, module, { name = '', level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { + const isHeader = destination.endsWith(".h") + const isCPP = (destination.endsWith(".cpp") && section !== 'accessors') + + schema = JSON.parse(JSON.stringify(schema)) - // FireboltSDK::JSON::String&, etc. - // FireboltSDK::::& - // WPEFramework::Core::JSON::Boolean + let shape = '' - const array = type.endsWith('[]') + name = schema.title || name - if (array) { - type = type.substring(0, type.length-2) + if (!name) { + console.log(`WARNING: schema without a name in ${module.info.title}`) + return shape } - let jsonType + if (schema['$ref']) { + if (schema['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType - if (type === 'string') { - jsonType = 'FireboltSDK::JSON::String' + const schema = getPath(schema['$ref'], module) + const tname = name || schema['$ref'].split('/').pop() + return getSchemaShape(schema, module, { name: tname, descriptions: descriptions, level: level }) + } } - else if (type === 'boolean') { - jsonType = 'WPEFramework::Core::JSON::Boolean' + //If the schema is a const, + else if (schema.hasOwnProperty('const') && !isCPP) { + if (level > 0) { + + let t = description(name, schema.description) + typeName = getTypeName(getModuleName(module), name) + t += (isHeader ? getPropertyAccessors(typeName, capitalize(name), typeof schema.const, { level: level, readonly: true, optional: false }) : getPropertyAccessorsImpl(typeName, capitalize(name), getJsonType(schema, module, { level, name }), typeof schema.const, { level: level, readonly: true, optional: false })) + shape += '\n' + t + } } - else { - jsonType = `FireboltSDK::${module.info.title}::${getSchemaType(...arguments)}` + else if (schema.type === 'object') { + if (!name) { + console.log(`WARNING: unnamed schema in ${module.info.title}.`) + console.dir(schema) + shape = '' + } + else if (schema.properties) { + let tName = getTypeName(getModuleName(module), name) + let c_shape = description(name, schema.description) + let cpp_shape = '' + c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(schema, module, { name }))) + Object.entries(schema.properties).forEach(([pname, prop]) => { + c_shape += '\n' + description(pname, prop.description) + let res + if (prop.type === 'array') { + if (Array.isArray(prop.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(prop.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getSchemaType(prop.items[0], module, { name: pname, level: level, descriptions: descriptions, title: true }) + } + else { + // grab the type for the non-array schema + res = getSchemaType(prop.items, module, { name: pname, level: level, descriptions: descriptions, title: true }) + } + if (res && res.length > 0) { + let n = tName + '_' + capitalize(pname || prop.title) + let def = getArrayAccessors(n + 'Array', res) + c_shape += '\n' + def + } + else { + console.log(`a. WARNING: Type undetermined for ${name}:${pname}`) + } + } else { + res = getSchemaType(prop, module, { name: pname, descriptions: descriptions, level: level + 1, title: true }) + if (res && res.length > 0) { + c_shape += '\n' + (isHeader ? getPropertyAccessors(tName, capitalize(pname), res, { level: level, readonly: false, optional: isOptional(pname, schema) }) : getPropertyAccessorsImpl(tName, capitalize(pname), getJsonType(prop, module, { level, name }), res, { level: level, readonly: false, optional: isOptional(pname, schema) })) + } + else { + console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) + } + } + }) + cpp_shape += getJsonContainerDefinition(tName, Object.entries(schema.properties).map(([name, prop]) => ({ name, type: getJsonType(prop, module) }))) + + if (isCPP) { + shape += '\n' + cpp_shape + } + else { + shape += '\n' + c_shape + } + } + else if (schema.propertyNames && schema.propertyNames.enum) { + //propertyNames in object not handled yet + } + else if (schema.additionalProperties && (typeof schema.additionalProperties === 'object') && !isCPP) { + //This is a map of string to type in schema + //Get the Type + let type = getSchemaType(schema.additionalProperties, module, { name: name }) + if (type && type.length > 0) { + let tName = getTypeName(getModuleName(module), name) + // type.deps.forEach(dep => structure.deps.add(dep)) + let t = description(name, schema.description) + t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(schema, module, { name }))) + t += getMapAccessors(getTypeName(getModuleName(module), name), type, { descriptions: descriptions, level: level }) + shape += '\n' + t + } + else { + console.log(`c. WARNING: Type undetermined for ${name}`) + } + } + else if (schema.patternProperties) { + console.log(`WARNING: patternProperties not supported yet...`) + // throw "patternProperties are not supported by Firebolt" + } + } + else if (schema.anyOf) { + } + else if (schema.oneOf) { - if (array) { - jsonType = `WPEFramework::Core::JSON::ArrayType<${jsonType}>` } + else if (schema.allOf) { + let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x)]) + if (name) { + union['title'] = name + } + delete union['$ref'] + return getSchemaShape(union, module, { name, level, title, summary, descriptions, destination, section, enums }) + + } + else if (schema.type === 'array') { + let res = getSchemaType(schema, module, { name, level: 0, descriptions: descriptions }) + // res.deps.forEach(dep => structure.deps.add(dep)) + } + else { + let res = getSchemaType(schema, module, { name, level: level, descriptions: descriptions }) + // res.deps.forEach(dep => structure.deps.add(dep)) + } + // console.dir(structure.deps) + return shape +} + +// function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - return `${jsonType}&` +const getJsonDataStructName = (modName, name) => `${capitalize(modName)}::${capitalize(name)}` + +const getJsonNativeType = json => { + let type + let jsonType = json.const ? typeof json.const : json.type + + if (jsonType === 'string') { + type = 'WPEFramework::Core::JSON::String' + } + else if (jsonType === 'number' || json.type === 'integer') { //Lets keep it simple for now + type = 'WPEFramework::Core::JSON::Number' + } + else if (jsonType === 'boolean') { + type = 'WPEFramework::Core::JSON::Boolean' + } + else { + throw 'Unknown JSON Native Type !!!' + } + return type } -function routeToDestination(method, args) { - const destination = args[args.length-1].destination || '' +function getJsonType(schema = {}, module = {}, { name = '', descriptions = false, level = 0 } = {}) { - if ( path.basename(destination) === 'JsonData_Module.h') { - return jsonTypes[method](...args) + let type = '' + + if (schema['$ref']) { + if (schema['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(schema['$ref'], module) + let tName = definition.title || schema['$ref'].split('/').pop() + return getJsonType(definition, module, { name: tName, descriptions: descriptions, level: level }) + } } - else if (path.basename(destination) === 'Module.cpp') { - return cppTypes[method](...args) + else if (schema.const) { + return getJsonNativeType(schema) } - else if (path.basename(destination) === 'Module_Common.cpp') { - return commonTypes[method](...args) + else if (schema['x-method']) { + console.log(`WARNING: x-methods are not supported yet...`) + return type + //throw "x-methods not supported yet" } - else if (path.basename(destination) === 'Module.h' && path.dirname(destination).endsWith(path.sep + 'Common')) { - return headerCommonTypes[method](...args) + else if (schema.type === 'string' && schema.enum) { + //Enum + let t = getSchemaType(schema, module, { name }) + return 'WPEFramework::Core::JSON::EnumType<::' + t + '>' } - else if (path.basename(destination) === 'Module.h') { - return headerTypes[method](...args) + else if (Array.isArray(schema.type)) { + let type = schema.type.find(t => t !== 'null') + console.log(`WARNING UNHANDLED: type is an array containing ${schema.type}`) } + else if (schema.type === 'array' && schema.items) { + let res + if (Array.isArray(schema.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(schema.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getJsonType(schema.items[0], module, { name: '' }) + } + else { + // grab the type for the non-array schema + res = getJsonType(schema.items, module, { name: '' }) + } - return '' + return `WPEFramework::Core::JSON::ArrayType<${res}>` + } + else if (schema.allOf) { + let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)]) + if (schema.title) { + union['title'] = schema.title + } + else { + union['title'] = name + } + delete union['$ref'] + return getJsonType(union, module, { name: '', level, descriptions }) + } + else if (schema.oneOf || schema.anyOf) { + return type + //TODO + } + else if (schema.type === 'object') { + if (!schema.title && !name) { + console.log(`WARNING: schema with no name`) + console.dir(schema) + return 'Unknown' + } + return getJsonDataStructName(getModuleName(module), schema.title || name) + //TODO + } + else if (schema.type) { + return getJsonNativeType(schema) + } + return type } -function getPrimativeType(schema) { - if (schema.type === "boolean") { - return "bool" +function getTypeScriptType(jsonType) { + if (jsonType === 'integer') { + return 'number' } - else if (schema.type === "integer") { - return "uint32_t" + else { + return jsonType } - else if (schema.type === "number") { - return +} + +const enumReducer = (acc, val, i, arr) => { + const keyName = val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + acc = acc + ` ${keyName} = '${val}'` + if (i < arr.length - 1) { + acc = acc.concat(',\n') } + return acc } export default { diff --git a/languages/c/src/types/CommonCppTypes.mjs b/languages/c/src/types/CommonCppTypes.mjs deleted file mode 100644 index 863cd77b..00000000 --- a/languages/c/src/types/CommonCppTypes.mjs +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2021 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 - */ - -// import deepmerge from 'deepmerge' -// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' -// import { getLinkFromRef } from '../../src/shared/markdown.mjs' -// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' - - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) - -function getMethodSignature(method, module, { destination = '' } = {}) { - return `// Common CPP Signatures for ${module}_${method}` -} - -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return `// Common CPP Signature Params for ${module}_${method}` -} - -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - - return { - dependencies: [], - code: `// Common CPP Schema Shape` - } - return `// Common CPP Schema Shape` -} - -function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - return `// Common CPP Schema Type` -} - - -export default { - getMethodSignature, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, -} \ No newline at end of file diff --git a/languages/c/src/types/CommonHeaderTypes.mjs b/languages/c/src/types/CommonHeaderTypes.mjs deleted file mode 100644 index 9c40c084..00000000 --- a/languages/c/src/types/CommonHeaderTypes.mjs +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2021 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 - */ - -// import deepmerge from 'deepmerge' -// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' -// import { getLinkFromRef } from '../../src/shared/markdown.mjs' -// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' - - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) - -function getMethodSignature(method, module, { destination = '' } = {}) { - return `// common .h Signatures for ${module}_${method}` -} - -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return `// common .h Signature Params for ${module}_${method}` -} - -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - return `// common .h Schema Shape` -} - -function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - return `// common .h Schema Type` -} - - -export default { - getMethodSignature, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, -} \ No newline at end of file diff --git a/languages/c/src/types/CppTypes.mjs b/languages/c/src/types/CppTypes.mjs deleted file mode 100644 index 4b6fa6a8..00000000 --- a/languages/c/src/types/CppTypes.mjs +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2021 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 - */ - -// import deepmerge from 'deepmerge' -// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' -// import { getLinkFromRef } from '../../src/shared/markdown.mjs' -// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' - - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) - -function getMethodSignature(method, module, { destination = '' } = {}) { - return `// CPP Signatures for ${module}_${method}` -} - -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return `// CPP Signature Params for ${module}_${method}` -} - -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - return `// CPP Schema Shape` -} - -function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - return `// CPP Schema Type` -} - - -export default { - getMethodSignature, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, -} \ No newline at end of file diff --git a/languages/c/src/types/HeaderTypes.mjs b/languages/c/src/types/HeaderTypes.mjs deleted file mode 100644 index 9ce0155e..00000000 --- a/languages/c/src/types/HeaderTypes.mjs +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2021 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 - */ - -// import deepmerge from 'deepmerge' -// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' -// import { getLinkFromRef } from '../../src/shared/markdown.mjs' -// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' - - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) - -function getMethodSignature(method, module, { destination = '' } = {}) { - return `// .h Signatures for ${module.info.title}_${method.name}` -} - -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return `// .h Signature Params for ${module.info.title}_${method.name}` -} - -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - return `// .h Schema Shape` -} - -function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - return `// .h Schema Type` -} - - -export default { - getMethodSignature, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, -} \ No newline at end of file diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs new file mode 100644 index 00000000..f3b39cbf --- /dev/null +++ b/languages/c/src/types/ImplHelpers.mjs @@ -0,0 +1,294 @@ +const Indent = '\t' + +const getObjectHandleManagementImpl = (varName, jsonDataName) => { + + let result = ` +${varName}Handle ${varName}Handle_Create(void) { + WPEFramework::Core::ProxyType<${jsonDataName}>* type = new WPEFramework::Core::ProxyType<${jsonDataName}>(); + *type = WPEFramework::Core::ProxyType<${jsonDataName}>::Create(); + return (static_cast<${varName}Handle>(type)); +} +void ${varName}Handle_Addref(${varName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + var->AddRef(); +} +void ${varName}Handle_Release(${varName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + var->Release(); + if(var->IsValid() != true) { + delete var; + } +} +bool ${varName}Handle_IsValid(${varName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + return var->IsValid(); +} +` + return result +} + +const getPropertyAccessorsImpl = (objName, propertyName, jsonDataName, propertyType, json = {}, options = {readonly:false, optional:false}) => { + + let result + if (json.type === 'object') { + result += `${objName}_${propertyName}Handle ${objName}_Get_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyName}>(); + *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); + *(*object) = (*var)->${propertyName}; + return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' + } else if (json.type === 'array') { + result += `${objName}_${propertyName}ArrayHandle ${objName}_Get_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + WPEFramework::Core::ProxyType>* object = new WPEFramework::Core::ProxyType>(); + *object = WPEFramework::Core::ProxyType>::Create(); + *(*object) = (*var)->${propertyName}.Element(); + return (static_cast<${objName}_${propertyType}ArrayHandle>(object));` + '\n' + } else if (json.enum) { + result += `${objName}_${propertyName} ${objName}_Get_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + return static_cast<${propertyType}>((*var)->${propertyName}.Value());` + '\n' + } else { + result += `${propertyType} ${objName}_Get_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid());` + '\n' + if (json.type === 'string') { + result += ` + return static_cast<${propertyType}>((*var)->${propertyName}.Value().c_str());` + '\n' + } else { + result += ` + return static_cast<${propertyType}>((*var)->${propertyName}.Value());` + '\n' + } + } + result += ` +}` + '\n' + if (!options.readonly) { + if (json.type === 'object') { + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName}Handle ${propertyName.toLowerCase()}) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* object = static_cast*>(${propertyName.toLowerCase()}); + (*var)->${propertyName} = *(*object);` + '\n' + } + if (json.type === 'array') { + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName}ArrayHandle ${propertyName.toLowerCase()}) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + WPEFramework::Core::ProxyType>* object = static_cast>*>(${propertyName.toLowerCase()}).Element(); + (*var)->${propertyName} = *(*object);` + '\n' + } if (json.enum) { + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName} ${propertyName.toLowerCase()}) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + (*var)->${propertyName} = static_cast<${propertyType}>(${propertyName.toLowerCase()});` + '\n' + } + else { + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${propertyType} ${propertyName.toLowerCase()}) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + (*var)->${propertyName} = static_cast<${propertyType}>(${propertyName.toLowerCase()});` + '\n' + } +result += `}` + '\n' + } + + if (options.optional === true) { + result += `${Indent.repeat(options.level)}bool ${objName}_has_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + return ((*var)->${propertyName}.IsSet()); +}` + '\n' + result += `${Indent.repeat(options.level)}void ${objName}_clear_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + ((*var)->${propertyName}.Clear()); +}` + '\n' + } + return result +} + +const getArrayAccessors = (objName, propertyName, propertyType, json = {}, options = {readonly:false, optional:false}) => { + let result = ` +uint32_t ${objName}_${propertyName}Array_Size(${objName}::${propertyName}ArrayHandle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + return ((*var)->Length()); +}` + '\n' + + if (json.type === 'object') { +result += `${objName}_${propertyType}Handle ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid()); + WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyType}>(); + *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); + *(*object) = (*var)->Get(index); + return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' + } else if (json.enum) { + result += `${objName}_${propertyType} ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid()); + + return (static_cast<${propertyType}>((*var)->Get(index)));` + '\n' + } else { + result += `${propertyType} ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid());` + '\n' + + if (json.type === 'string') { + result += `return (static_cast<${propertyType}>((*var)->Get(index).Value().c_str()));` + '\n' + } else { + result += `return (static_cast<${propertyType}>((*var)->Get(index)));` + '\n' + } + + } + result += `}` + '\n' + + if (json.type === 'object') { + result += `void ${objName}_${propertyName}Array_Add(${objName}_${propertyName}ArrayHandle handle, ${objName}_${propertyType}Handle value) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid()); + WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = static_cast*>(value); + + (*var)->Add(*(*object));` + '\n' + } else { + result += `void ${objName}_${propertyName}Array_Add(${objName}_${propertyName}ArrayHandle handle, ${propertyType} value) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid());` + '\n' + if (json.type === 'string') { + result += `WPEFramework::Core::JSON::String element(value);` + '\n' + } else if (json.type === 'number') { + result += `WPEFramework::Core::JSON::Number element(value);` + '\n' + } else if (json.enum) { + result += `WPEFramework::Core::JSON::EnumType<${propertyType}> element(value);` + '\n' + } + result += `(*var)->Add(element);` + '\n' + } + result += `}` + '\n' + + result += `void ${objName}_${propertyName}Array_Clear(${objName}_${propertyName}ArrayHandle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid()); + (*var)->Clear(); +}` + '\n' + + return result +} + +const getMapAccessors = (objName, propertyName, propertyType, json = {}, options = {readonly:false, optional:false}) => { + let result = `uint32_t ${objName}_${propertyName}_KeysCount(${objName}_${propertyName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + return (*var)->Size()); + + }` + '\n' + result += `void ${objName}_${propertyName}_AddKey(${objName}_${propertyName}Handle handle, char* key, ${propertyType} value) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid());` + '\n' + + if (json.type === 'object') { + result += ` + (*var)->Add(key, value);` + '\n' + } else if (json.type === 'boolean') { + result += ` + WPEFramework::Core::JSON::Boolean element(value);` + } else if (json.type === 'string') { + result += ` + WPEFramework::Core::JSON::String element(value);` + } else if (json.type === 'number') { + result += ` + WPEFramework::Core::JSON::Number element(value);` + } else if (json.type === 'array') { + result += ` + WPEFramework::Core::JSON::ArrayType element(value);` + } else if (json.enum) { + result += ` + WPEFramework::Core::JSON::EnumType element(value); + (*var)->Add(key, element);` + '\n' + } + result += ` + }` + '\n' + result += `void ${objName}_${propertyName}_RemoveKey(${objName}_${propertyName}Handle handle, char* key) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + (*var)->Remove(key); + }` + '\n' + + if (json.type === 'object') { + result += `${objName}_${propertyType}Handle ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyType}>(); + *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); + *(*object) = (*var)->Find(key); + return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' + + } else if (json.type === 'array') { + result += `${objName}_${propertyType}ArrayHandle ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + WPEFramework::Core::ProxyType>* object = new WPEFramework::Core::ProxyType>(); + *object = WPEFramework::Core::ProxyType>::Create(); + *(*object) = (*var)->Find(key); + return (static_cast<${objName}_${propertyType}ArrayHandle>(object));` + '\n' + + } else { + result += `${propertyType} ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid());` + '\n' + + if (json.type === 'string') { + result += ` + return (static_cast<${propertyType}>((*var)->(Find(key).Value().c_str())));` + '\n' + } else { + result += ` + return (static_cast<${propertyType}>((*var)->(Find(key).Value())));` + '\n' + } + } + result += ` +}` + '\n' + + return result +} + +export { + getObjectHandleManagementImpl, + getPropertyAccessorsImpl +} diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs new file mode 100644 index 00000000..25d1ad3b --- /dev/null +++ b/languages/c/src/types/JSONHelpers.mjs @@ -0,0 +1,61 @@ +const capitalize = str => str[0].toUpperCase() + str.substr(1) + +function getJsonContainerDefinition (name, props) { + name = capitalize(name) + let c = ` class ${name}: public Core::JSON::Container { + public: + ${name}(const ${name}&) = delete; + ${name}& operator=(const ${name}&) = delete; + ~${name}() override = default; + + public: + ${name}() + : Core::JSON::Container() + {` + + props.forEach(prop => { + c += `\n Add(_T("${prop.name}"), &${capitalize(prop.name)});` + }) + + c += `\n }\n\n public:` + + props.forEach(prop => { + c += `\n ${prop.type} ${capitalize(prop.name)};` + }) + + c += '\n };' + return c + } + +/* + +ENUM_CONVERSION_BEGIN(Advertising_SkipRestriction) + { ADVERTISING_SKIPRESTRICTION_NONE, _T("none") }, + { ADVERTISING_SKIPRESTRICTION_ADS_UNWATCHED, _T("adsUnwatched") }, + { ADVERTISING_SKIPRESTRICTION_ADS_ALL, _T("adsAll") }, + { ADVERTISING_SKIPRESTRICTION_ALL, _T("all") }, +ENUM_CONVERSION_END(Advertising_SkipRestriction) + + +*/ + +// TODO - this should be a global function in the main /src/ directory... not part of a language pack +const keyName = val => val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + +function getJsonEnumConversion(schema, module, { name }) { + name = capitalize(schema.title || name) + let e = `ENUM_CONVERSION_BEGIN(${module.info.title}_${name})\n` + + schema.enum.forEach(value => { + e += `{ ${module.info.title.toUpperCase()}_${name.toUpperCase()}_${keyName(value)}, _T("${value}") },` + }) + + e += `ENUM_CONVERSION_END(${module.info.title}_${name})` + + return e +} + +export { + getJsonContainerDefinition, + getJsonEnumConversion +} diff --git a/languages/c/src/types/JSONTypes.mjs b/languages/c/src/types/JSONTypes.mjs deleted file mode 100644 index d2961794..00000000 --- a/languages/c/src/types/JSONTypes.mjs +++ /dev/null @@ -1,56 +0,0 @@ - -/* - * Copyright 2021 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 - */ - -// import deepmerge from 'deepmerge' -// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' -// import { getLinkFromRef } from '../../src/shared/markdown.mjs' -// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' - - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) - -function getMethodSignature(method, module, { destination = '' } = {}) { - return `// JSON Signatures for ${module}_${method}` -} - -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return `// JSON Signature Params for ${module}_${method}` -} - -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - return `// JSON Schema Shape` -} - -function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - return `// JSON Schema Type` -} - - -export default { - getMethodSignature, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, -} \ No newline at end of file diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index e51c47d7..79242d1f 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -201,260 +201,6 @@ const getIncludeDefinitions = (json = {}, jsonData = false) => { .concat([`#include "Firebolt/Types.h"`]) } -function getSchemaType(module = {}, json = {}, name = '', schemas = {}, options = {level: 0, descriptions: true, title: false}) { - if (json.schema) { - json = json.schema - } - - let structure = {} - structure["deps"] = new Set() //To avoid duplication of local ref definitions - structure["type"] = [] - - if (json['$ref']) { - if (json['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType - let definition = getPath(json['$ref'], module, schemas) - let tName = definition.title || json['$ref'].split('/').pop() - const res = getSchemaType(module, definition, tName, schemas, {descriptions: options.descriptions, level: options.level}) - res.deps.forEach(dep => structure.deps.add(dep)) - structure.type = res.type - return structure - } - else { - // External dependency. - // e.g, "https://meta.comcast.com/firebolt/entertainment#/definitions/ProgramType" - - //Get the module of this definition - const schema = getPath(json['$ref'].split('#')[0], schemas) || module - - //Get the schema of the definition - const definition = getPath(json['$ref'], module, schemas) - let tName = definition.title || json['$ref'].split('/').pop() - const res = getSchemaType(schema, definition, tName, schemas, {descriptions: options.descriptions, level: options.level}) - //We are only interested in the type definition for external modules - structure.type = res.type - return structure - } - } - else if (json.const) { - structure.type = getNativeType(json) - return structure - } - else if (json['x-method']) { - console.log(`WARNING UNHANDLED: x-method in ${name}`) - return structure - //throw "x-methods not supported yet" - } - else if (json.type === 'string' && json.enum) { - //Enum - let typeName = getTypeName(getModuleName(module), name || json.title) - let res = description(capitalize(name || json.title), json.description) + '\n' + generateEnum(json, typeName) - structure.deps.add(res) - structure.type.push(typeName) - return structure - } - else if (Array.isArray(json.type)) { - let type = json.type.find(t => t !== 'null') - console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) - } - else if (json.type === 'array' && json.items) { - let res - if (Array.isArray(json.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(json.items)) { - throw 'Heterogenous Arrays not supported yet' - } - res = getSchemaType(module, json.items[0],'',schemas) - } - else { - // grab the type for the non-array schema - res = getSchemaType(module, json.items, '', schemas) - } - - res.deps.forEach(dep => structure.deps.add(dep)) - let n = getTypeName(getModuleName(module), name || json.title) - let def = description(name || json.title, json.description) + '\n' - if (options.level === 0) { - def += getObjectHandleManagement(n + 'Array') + '\n' - } - def += getArrayAccessors(n + 'Array', res.type) - structure.deps.add(def) - structure.type.push(n + 'ArrayHandle') - return structure - } - else if (json.allOf) { - let union = deepmerge.all([...json.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)]) - if (json.title) { - union['title'] = json.title - } - else { - union['title'] = name - } - delete union['$ref'] - return getSchemaType(module, union, '',schemas, options) - } - else if (json.oneOf || json.anyOf) { - return structure - //TODO - } - else if (json.type === 'object') { - let res = getSchemaShape(module, json, schemas, json.title || name, {descriptions: options.descriptions, level: 0}) - res.deps.forEach(dep => structure.deps.add(dep)) - res.type.forEach(t => structure.deps.add(t)) - structure.type.push(getTypeName(getModuleName(module), json.title || name) + 'Handle') - return structure - //TODO - } - else if (json.type) { - structure.type = getNativeType(json) - return structure - } - return structure -} - -function getSchemaShape(moduleJson = {}, json = {}, schemas = {}, name = '', options = {level: 0, descriptions: true}) { - json = JSON.parse(JSON.stringify(json)) - let level = options.level - let descriptions = options.descriptions - - let structure = {} - structure["deps"] = new Set() //To avoid duplication of local ref definitions - structure["type"] = [] - - if (json['$ref']) { - if (json['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType - - const schema = getPath(json['$ref'], module, schemas) - const tname = schema.title || json['$ref'].split('/').pop() - res = getSchemaShape(module, schema, schemas, tname, {descriptions: descriptions, level: level}) - res.deps.forEach(dep => structure.deps.add(dep)) - structure.type = res.type - } - else { - // External dependency. Return only type - // e.g, "https://meta.comcast.com/firebolt/entertainment#/definitions/ProgramType" - - //Get the module of this definition - const schema = getPath(json['$ref'].split('#')[0], schemas) || module - - //Get the schema of the definition - const definition = getPath(json['$ref'], schema, schemas) - const pname = (json.title || name) + (definition.title || json['$ref'].split('/').pop()) - - res = getSchemaShape(schema, definition, schemas, pname,{descriptions: descriptions, level: level}) - //We are only interested in the type definition for external modules - structure.type = res.type - } - } - //If the schema is a const, - else if (json.hasOwnProperty('const')) { - if (level > 0) { - - let t = description(name, json.description) - typeName = getTypeName(getModuleName(moduleJson), name) - t += getPropertyAccessors(typeName, capitalize(name), typeof json.const, {level: level, readonly:true, optional:false}) - structure.type.push(t) - } - } - else if (json.type === 'object') { - - if (json.properties) { - let tName = getTypeName(getModuleName(moduleJson), name) - let t = description(name, json.description) - t += '\n' + getObjectHandleManagement(tName) - Object.entries(json.properties).forEach(([pname, prop]) => { - t += '\n' + description(pname, prop.description) - let res - if (prop.type === 'array') { - if (Array.isArray(prop.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(prop.items)) { - throw 'Heterogenous Arrays not supported yet' - } - res = getSchemaType(moduleJson, prop.items[0],pname, schemas, {level : options.level, descriptions: options.descriptions, title: true}) - } - else { - // grab the type for the non-array schema - res = getSchemaType(moduleJson, prop.items, pname, schemas, {level : options.level, descriptions: options.descriptions, title: true}) - } - if (res.type && res.type.length > 0) { - let n = tName + '_' + capitalize(pname || prop.title) - let def = getArrayAccessors(n + 'Array', res.type) - t += '\n' + def - } - else { - console.log(`WARNING: Type undetermined for ${name}:${pname}`) - } - } else { - res = getSchemaType(moduleJson, prop, pname,schemas, {descriptions: descriptions, level: level + 1, title: true}) - if (res.type && res.type.length > 0) { - t += '\n' + getPropertyAccessors(tName, capitalize(pname), res.type, {level: level, readonly:false, optional:isOptional(pname, json)}) - } - else { - console.log(`WARNING: Type undetermined for ${name}:${pname}`) - } - } - res.deps.forEach(dep => structure.deps.add(dep)) - }) - structure.type.push(t) - } - else if (json.propertyNames && json.propertyNames.enum) { - //propertyNames in object not handled yet - } - else if (json.additionalProperties && (typeof json.additionalProperties === 'object')) { - //This is a map of string to type in schema - //Get the Type - let type = getSchemaType(moduleJson, json.additionalProperties, name,schemas) - if (type.type && type.type.length > 0) { - let tName = getTypeName(getModuleName(moduleJson), name) - type.deps.forEach(dep => structure.deps.add(dep)) - let t = description(name, json.description) - t += '\n' + getObjectHandleManagement(tName) + '\n' - t += getMapAccessors(getTypeName(getModuleName(moduleJson), name), type.type,{descriptions: descriptions, level: level}) - structure.type.push(t) - } - else { - console.log(`WARNING: Type undetermined for ${name}`) - } - } - else if (json.patternProperties) { - throw "patternProperties are not supported by Firebolt" - } - } - else if (json.anyOf) { - - } - else if (json.oneOf) { - - } - else if (json.allOf) { - let union = deepmerge.all([...json.allOf.map(x => x['$ref'] ? getPath(x['$ref'], moduleJson, schemas) || x : x)], options) - if (json.title) { - union['title'] = json.title - } - else { - union['title'] = name - } - delete union['$ref'] - return getSchemaShape(moduleJson, union, schemas, name, options) - - } - else if (json.type === 'array') { - let res = getSchemaType(moduleJson, json, name, schemas, {level: 0, descriptions: descriptions}) - res.deps.forEach(dep => structure.deps.add(dep)) - } - else { - let res = getSchemaType(moduleJson, json, name, schemas, {level: level, descriptions: descriptions}) - res.deps.forEach(dep => structure.deps.add(dep)) - } - return structure - } - function getPropertyGetterSignature(method, module, paramType) { let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` @@ -480,15 +226,19 @@ function getSchemaShape(moduleJson = {}, json = {}, schemas = {}, name = '', opt getStyleGuardClose, getIncludeGuardClose, getNativeType, - getSchemaType, - getSchemaShape, getModuleName, getIncludeDefinitions, getPropertyGetterSignature, getPropertySetterSignature, getPropertyEventCallbackSignature, getPropertyEventSignature, + getMapAccessors, + getArrayAccessors, capitalize, description, - getTypeName + getTypeName, + getObjectHandleManagement, + getPropertyAccessors, + isOptional, + generateEnum } diff --git a/languages/c/templates/codeblocks/export.mjs b/languages/c/templates/codeblocks/export.c similarity index 100% rename from languages/c/templates/codeblocks/export.mjs rename to languages/c/templates/codeblocks/export.c diff --git a/languages/c/templates/codeblocks/mock-import.mjs b/languages/c/templates/codeblocks/mock-import.c similarity index 100% rename from languages/c/templates/codeblocks/mock-import.mjs rename to languages/c/templates/codeblocks/mock-import.c diff --git a/languages/c/templates/codeblocks/mock-parameter.mjs b/languages/c/templates/codeblocks/mock-parameter.c similarity index 100% rename from languages/c/templates/codeblocks/mock-parameter.mjs rename to languages/c/templates/codeblocks/mock-parameter.c diff --git a/languages/c/templates/declarations/clear.js b/languages/c/templates/codeblocks/module.c similarity index 100% rename from languages/c/templates/declarations/clear.js rename to languages/c/templates/codeblocks/module.c diff --git a/languages/c/templates/codeblocks/module.mjs b/languages/c/templates/codeblocks/module.mjs deleted file mode 100644 index 48f6d6bc..00000000 --- a/languages/c/templates/codeblocks/module.mjs +++ /dev/null @@ -1,11 +0,0 @@ -// JEREMY - -export module ${info.title} { - - /* ${SCHEMAS} */ - - /* ${DECLARATIONS} */ - - /* ${PROVIDERS} */ - -} \ No newline at end of file diff --git a/languages/c/templates/declarations/listen.js b/languages/c/templates/declarations/clear.c similarity index 100% rename from languages/c/templates/declarations/listen.js rename to languages/c/templates/declarations/clear.c diff --git a/languages/c/templates/declarations/default.js b/languages/c/templates/declarations/default.c similarity index 68% rename from languages/c/templates/declarations/default.js rename to languages/c/templates/declarations/default.c index bd8b6fcf..72fbf14f 100644 --- a/languages/c/templates/declarations/default.js +++ b/languages/c/templates/declarations/default.c @@ -1,4 +1,4 @@ /** * ${method.summary} ${method.params} */ - ${method.signature} + ${method.signature}; diff --git a/languages/c/templates/declarations/once.js b/languages/c/templates/declarations/listen.c similarity index 100% rename from languages/c/templates/declarations/once.js rename to languages/c/templates/declarations/listen.c diff --git a/languages/c/templates/declarations/provide.js b/languages/c/templates/declarations/once.c similarity index 100% rename from languages/c/templates/declarations/provide.js rename to languages/c/templates/declarations/once.c diff --git a/languages/c/templates/declarations/polymorphic-reducer.js b/languages/c/templates/declarations/polymorphic-reducer.c similarity index 100% rename from languages/c/templates/declarations/polymorphic-reducer.js rename to languages/c/templates/declarations/polymorphic-reducer.c diff --git a/languages/c/templates/declarations/rpc-only.js b/languages/c/templates/declarations/provide.c similarity index 100% rename from languages/c/templates/declarations/rpc-only.js rename to languages/c/templates/declarations/provide.c diff --git a/languages/c/templates/methods/listen.js b/languages/c/templates/declarations/rpc-only.c similarity index 100% rename from languages/c/templates/methods/listen.js rename to languages/c/templates/declarations/rpc-only.c diff --git a/languages/c/templates/defaults/default.mjs b/languages/c/templates/defaults/default.c similarity index 100% rename from languages/c/templates/defaults/default.mjs rename to languages/c/templates/defaults/default.c diff --git a/languages/c/templates/defaults/property.mjs b/languages/c/templates/defaults/property.c similarity index 100% rename from languages/c/templates/defaults/property.mjs rename to languages/c/templates/defaults/property.c diff --git a/languages/c/templates/examples/default.md b/languages/c/templates/examples/default.md deleted file mode 100644 index ecc979ba..00000000 --- a/languages/c/templates/examples/default.md +++ /dev/null @@ -1,6 +0,0 @@ -import { ${module} } from '${package.name}' - -${module}.${method.name}(${example.params}) - .then(${method.result.name} => { - console.log(${method.result.name}) - }) \ No newline at end of file diff --git a/languages/c/templates/examples/event.md b/languages/c/templates/examples/event.md deleted file mode 100644 index 7b78fe76..00000000 --- a/languages/c/templates/examples/event.md +++ /dev/null @@ -1,5 +0,0 @@ -import { ${module} } from '${package.name}' - -${module}.listen('${event.name}', ${method.result.name} => { - console.log(${method.result.name}) -}) \ No newline at end of file diff --git a/languages/c/templates/examples/polymorphic-pull-event.md b/languages/c/templates/examples/polymorphic-pull-event.md deleted file mode 100644 index 7bc2baa7..00000000 --- a/languages/c/templates/examples/polymorphic-pull-event.md +++ /dev/null @@ -1,9 +0,0 @@ -import { ${module} } from '${package.name}' - -${module}.${method.pulls.for}(function(parameters) { - console.log(parameters.entityId) - console.log(parameters.assetId) - return Promise.resolve(${originator.params[1].example.value}) -}).then(success => { - console.log(success) -}) \ No newline at end of file diff --git a/languages/c/templates/examples/polymorphic-pull.md b/languages/c/templates/examples/polymorphic-pull.md deleted file mode 100644 index 7c53080c..00000000 --- a/languages/c/templates/examples/polymorphic-pull.md +++ /dev/null @@ -1,6 +0,0 @@ -import { ${module} } from '${package.name}' - -${module}.${method.name}(${method.params[1].example.value}) - .then(success => { - console.log(success) - }) \ No newline at end of file diff --git a/languages/c/templates/examples/provider.md b/languages/c/templates/examples/provider.md deleted file mode 100644 index d2d16366..00000000 --- a/languages/c/templates/examples/provider.md +++ /dev/null @@ -1,10 +0,0 @@ -import { ${module} } from '${package.name}' - -class MyProvider { - async ${example.providerMethod}(${method.result.name}, responder) { - console.log(JSON.stringify(${method.result.name}, null, 2)) - responder(${example.providerResponse}) - } -} - -${module}.provide(new MyProvider()) \ No newline at end of file diff --git a/languages/c/templates/examples/setter.md b/languages/c/templates/examples/setter.md deleted file mode 100644 index c258314a..00000000 --- a/languages/c/templates/examples/setter.md +++ /dev/null @@ -1,6 +0,0 @@ -import { ${module} } from '${package.name}' - -${module}.${method.setter.for}(${example.params}) - .then(${method.result.name} => { - console.log(${method.result.name}) - }) \ No newline at end of file diff --git a/languages/c/templates/examples/subscriber.md b/languages/c/templates/examples/subscriber.md deleted file mode 100644 index 99c0516f..00000000 --- a/languages/c/templates/examples/subscriber.md +++ /dev/null @@ -1,7 +0,0 @@ -import { ${module} } from '${package.name}' - -${method.alternative}(value => { - console.log(value) -}).then(listenerId => { - console.log(listenerId) -}) \ No newline at end of file diff --git a/languages/c/templates/examples/synchronous.md b/languages/c/templates/examples/synchronous.md deleted file mode 100644 index 6e8e1e82..00000000 --- a/languages/c/templates/examples/synchronous.md +++ /dev/null @@ -1,4 +0,0 @@ -import { ${module} } from '${package.name}' - -const ${method.result.name} = ${module}.${method.name}(${example.params}) -console.log(${method.result.name}) \ No newline at end of file diff --git a/languages/c/templates/examples/temporal-set.md b/languages/c/templates/examples/temporal-set.md deleted file mode 100644 index 4a8e94ea..00000000 --- a/languages/c/templates/examples/temporal-set.md +++ /dev/null @@ -1,13 +0,0 @@ -import { ${module} } from '${package.name}' - -const process = ${module}.${method.name}(function(${example.params}${if.params},${end.if.params} - ${method.item} => { - console.log('Added to temporal set:') - console.dir(${method.item}) - }, - ${method.item} => { - console.log('Removed from temporal set:') - console.dir(${method.item}) - }) - -setTimeout( () => process.stop(), 10000) \ No newline at end of file diff --git a/languages/c/templates/imports/context-event.mjs b/languages/c/templates/imports/context-event.mjs deleted file mode 100644 index fcd3186b..00000000 --- a/languages/c/templates/imports/context-event.mjs +++ /dev/null @@ -1 +0,0 @@ -import { registerEventContext } from '../Events/index.mjs' diff --git a/languages/c/templates/imports/default.c b/languages/c/templates/imports/default.c new file mode 100644 index 00000000..a38b58ef --- /dev/null +++ b/languages/c/templates/imports/default.c @@ -0,0 +1 @@ +#include "Common/${info.title}.h" diff --git a/languages/c/templates/imports/event.mjs b/languages/c/templates/imports/event.mjs deleted file mode 100644 index bc019bca..00000000 --- a/languages/c/templates/imports/event.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import Events from '../Events/index.mjs' -import { registerEvents } from '../Events/index.mjs' diff --git a/languages/c/templates/imports/property.mjs b/languages/c/templates/imports/property.mjs deleted file mode 100644 index 7107a163..00000000 --- a/languages/c/templates/imports/property.mjs +++ /dev/null @@ -1 +0,0 @@ -import Prop from '../Prop/index.mjs' diff --git a/languages/c/templates/imports/provider.mjs b/languages/c/templates/imports/provider.mjs deleted file mode 100644 index b3ea7b4f..00000000 --- a/languages/c/templates/imports/provider.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import ProvideManager from '../ProvideManager/index.mjs' -import { registerProviderInterface } from '../ProvideManager/index.mjs' diff --git a/languages/c/templates/imports/rpc.mjs b/languages/c/templates/imports/rpc.mjs deleted file mode 100644 index af459a1e..00000000 --- a/languages/c/templates/imports/rpc.mjs +++ /dev/null @@ -1 +0,0 @@ -import Transport from '../Transport/index.mjs' diff --git a/languages/c/templates/imports/temporal-set.mjs b/languages/c/templates/imports/temporal-set.mjs deleted file mode 100644 index 089d35b1..00000000 --- a/languages/c/templates/imports/temporal-set.mjs +++ /dev/null @@ -1 +0,0 @@ -import TemporalSet from '../TemporalSet/index.mjs' \ No newline at end of file diff --git a/languages/c/templates/imports/x-method.mjs b/languages/c/templates/imports/x-method.mjs deleted file mode 100644 index 42453ecb..00000000 --- a/languages/c/templates/imports/x-method.mjs +++ /dev/null @@ -1 +0,0 @@ -import Results from '../Results/index.mjs' \ No newline at end of file diff --git a/languages/c/templates/initializations/deprecated.mjs b/languages/c/templates/initializations/deprecated.mjs deleted file mode 100644 index 737d1c25..00000000 --- a/languages/c/templates/initializations/deprecated.mjs +++ /dev/null @@ -1 +0,0 @@ -Transport.registerDeprecatedMethod('${info.title}', '${method.name}', 'Use ${method.alternative} instead.') diff --git a/languages/c/templates/initializations/event.mjs b/languages/c/templates/initializations/event.mjs deleted file mode 100644 index c151f674..00000000 --- a/languages/c/templates/initializations/event.mjs +++ /dev/null @@ -1 +0,0 @@ -registerEvents('${info.title}', ${events.array}) diff --git a/languages/c/templates/initializations/provider.mjs b/languages/c/templates/initializations/provider.mjs deleted file mode 100644 index b113d236..00000000 --- a/languages/c/templates/initializations/provider.mjs +++ /dev/null @@ -1 +0,0 @@ -registerProviderInterface('${capability}', '${info.title}', ${interface}) diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 7d10ba97..49f76ce1 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -1,5 +1,5 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_${method.Name}(${method.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { +uint32_t ${info.title}_${method.Name}(${method.params.list}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { uint32_t status = FireboltSDKErrorUnavailable; FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { diff --git a/languages/c/templates/methods/once.js b/languages/c/templates/methods/listen.c similarity index 100% rename from languages/c/templates/methods/once.js rename to languages/c/templates/methods/listen.c diff --git a/languages/c/templates/methods/rpc-only.js b/languages/c/templates/methods/once.c similarity index 100% rename from languages/c/templates/methods/rpc-only.js rename to languages/c/templates/methods/once.c diff --git a/languages/c/templates/methods/polymorphic-reducer.js b/languages/c/templates/methods/polymorphic-reducer.c similarity index 100% rename from languages/c/templates/methods/polymorphic-reducer.js rename to languages/c/templates/methods/polymorphic-reducer.c diff --git a/languages/c/templates/methods/provide.js b/languages/c/templates/methods/provide.c similarity index 100% rename from languages/c/templates/methods/provide.js rename to languages/c/templates/methods/provide.c diff --git a/languages/c/templates/methods/rpc-only.c b/languages/c/templates/methods/rpc-only.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/modules/include/Common/Module.h b/languages/c/templates/modules/include/Common/Module.h index 22c25143..2834b997 100644 --- a/languages/c/templates/modules/include/Common/Module.h +++ b/languages/c/templates/modules/include/Common/Module.h @@ -25,6 +25,12 @@ extern "C" { #endif + // Enums + + /* ${ENUMS}} */ + + // Schemas + /* ${SCHEMAS} */ #ifdef __cplusplus diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h index 92bab4f7..e24c869f 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/Module.h @@ -20,7 +20,7 @@ #define _${info.TITLE}_H #include "Firebolt.h" -#include "Common/${info.title}.h" +/* ${IMPORTS} */ #ifdef __cplusplus extern "C" { @@ -28,6 +28,7 @@ extern "C" { /* ${SCHEMAS} */ + /* ${ACCESSORS} */ /* ${DECLARATIONS} */ #ifdef __cplusplus diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 2417f708..0783b416 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -16,17 +16,22 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "FireboltSDK.h" +#include "Firebolt.h" #include "${info.title}.h" -#include "Common/${info.title}.h" #include "JsonData_${info.title}.h" +/* ${IMPORTS} */ + + #ifdef __cplusplus extern "C" { #endif - /* ${METHODS} */ +/* ${TYPES} */ #ifdef __cplusplus } #endif + +/* ${ACCESSORS} */ +/* ${METHODS} */ diff --git a/languages/c/templates/schemas/default.js b/languages/c/templates/schemas/default.c similarity index 100% rename from languages/c/templates/schemas/default.js rename to languages/c/templates/schemas/default.c diff --git a/languages/c/templates/schemas/include/Common/Module.h b/languages/c/templates/schemas/include/Common/Module.h index 5582d8ea..50ef1fd9 100644 --- a/languages/c/templates/schemas/include/Common/Module.h +++ b/languages/c/templates/schemas/include/Common/Module.h @@ -16,10 +16,25 @@ * SPDX-License-Identifier: Apache-2.0 */ -namespace FireboltSDK { +#ifndef _COMMON_${info.TITLE}_H +#define _COMMON_${info.TITLE}_H - /* ${DECLARATIONS} */ +#include "Firebolt.h" - /* ${SCHEMAS} */ +#ifdef __cplusplus +extern "C" { +#endif + // Enums + + /* ${ENUMS} */ + + // Types + + /* ${TYPES} */ + +#ifdef __cplusplus } +#endif + +#endif // Header Include Guard \ No newline at end of file diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/Module_Common.cpp index 8460c52a..632f38d6 100644 --- a/languages/c/templates/schemas/src/Module_Common.cpp +++ b/languages/c/templates/schemas/src/Module_Common.cpp @@ -16,11 +16,19 @@ * SPDX-License-Identifier: Apache-2.0 */ -/* ${IMPORTS} */ +#include "Firebolt.h" +#include "${info.title}.h" +#include "Common/${info.title}.h" +#include "JsonData_${info.title}.h" +#ifdef __cplusplus +extern "C" { +#endif -namespace FireboltSDK { - + /* ${TYPES} */ + /* ${ACCESSORS} */ /* ${METHODS} */ +#ifdef __cplusplus } +#endif diff --git a/languages/c/templates/sdk/CMakeLists.txt b/languages/c/templates/sdk/CMakeLists.txt new file mode 100644 index 00000000..a29658f7 --- /dev/null +++ b/languages/c/templates/sdk/CMakeLists.txt @@ -0,0 +1,49 @@ +# 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 + +cmake_minimum_required(VERSION 3.3) + +project(Firebolt) + +set(FIREBOLT_TRANSPORT_WAITTIME 1000 CACHE STRING "Maximum time to wait for Transport layer to get response") +set(FIREBOLT_LOGLEVEL "Info" CACHE STRING "Log level to be enabled") + +option(ENABLE_TESTS "Build openrpc native test" OFF) + +list(APPEND CMAKE_MODULE_PATH + "${CMAKE_SOURCE_DIR}/cmake" + "${SYSROOT_PATH}/usr/lib/cmake" + "${SYSROOT_PATH}/tools/cmake") +include(HelperFunctions) + +if (NOT DEFINED CMAKE_PREFIX_PATH) + set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) +endif() + +set(FIREBOLT_NAMESPACE ${PROJECT_NAME} CACHE STRING "Namespace of the project") + +find_package(WPEFramework CONFIG REQUIRED) + +add_subdirectory(src) + +if (ENABLE_TESTS) + add_subdirectory(test) +endif() + +# make sure others can make use cmake settings of Firebolt OpenRPC +configure_file( "${CMAKE_SOURCE_DIR}/cmake/project.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake" + @ONLY) diff --git a/languages/c/templates/sdk/build/CMakeCache.txt b/languages/c/templates/sdk/build/CMakeCache.txt new file mode 100644 index 00000000..f10d476d --- /dev/null +++ b/languages/c/templates/sdk/build/CMakeCache.txt @@ -0,0 +1,407 @@ +# This is the CMakeCache file. +# For build in directory: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build +# It was generated by CMake: /opt/homebrew/Cellar/cmake/3.25.3/bin/cmake +# You can edit this file to change values found and used by cmake. +# If you do not want to change any of the values, simply exit the editor. +# If you do want to change a value, simply edit, save, and exit the editor. +# The syntax for the file is as follows: +# KEY:TYPE=VALUE +# KEY is the name of a variable in the cache. +# TYPE is a hint to GUIs for the type of VALUE, DO NOT EDIT TYPE!. +# VALUE is the current value for the KEY. + +######################## +# EXTERNAL cache entries +######################## + +//Path to a program. +CMAKE_ADDR2LINE:FILEPATH=CMAKE_ADDR2LINE-NOTFOUND + +//Path to a program. +CMAKE_AR:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ar + +//Choose the type of build, options are: None Debug Release RelWithDebInfo +// MinSizeRel ... +CMAKE_BUILD_TYPE:STRING=Release + +//Enable/Disable color output during build. +CMAKE_COLOR_MAKEFILE:BOOL=ON + +//CXX compiler +CMAKE_CXX_COMPILER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/c++ + +//Flags used by the CXX compiler during all build types. +CMAKE_CXX_FLAGS:STRING=-D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION + +//Flags used by the CXX compiler during DEBUG builds. +CMAKE_CXX_FLAGS_DEBUG:STRING=-g + +//Flags used by the CXX compiler during MINSIZEREL builds. +CMAKE_CXX_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG + +//Flags used by the CXX compiler during RELEASE builds. +CMAKE_CXX_FLAGS_RELEASE:STRING=-O3 -DNDEBUG + +//Flags used by the CXX compiler during RELWITHDEBINFO builds. +CMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG + +//C compiler +CMAKE_C_COMPILER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/cc + +//Flags used by the C compiler during all build types. +CMAKE_C_FLAGS:STRING= + +//Flags used by the C compiler during DEBUG builds. +CMAKE_C_FLAGS_DEBUG:STRING=-g + +//Flags used by the C compiler during MINSIZEREL builds. +CMAKE_C_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG + +//Flags used by the C compiler during RELEASE builds. +CMAKE_C_FLAGS_RELEASE:STRING=-O3 -DNDEBUG + +//Flags used by the C compiler during RELWITHDEBINFO builds. +CMAKE_C_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG + +//Path to a program. +CMAKE_DLLTOOL:FILEPATH=CMAKE_DLLTOOL-NOTFOUND + +//Flags used by the linker during all build types. +CMAKE_EXE_LINKER_FLAGS:STRING= + +//Flags used by the linker during DEBUG builds. +CMAKE_EXE_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during MINSIZEREL builds. +CMAKE_EXE_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during RELEASE builds. +CMAKE_EXE_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during RELWITHDEBINFO builds. +CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//Enable/Disable output of compile commands during generation. +CMAKE_EXPORT_COMPILE_COMMANDS:BOOL= + +//Value Computed by CMake. +CMAKE_FIND_PACKAGE_REDIRECTS_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/pkgRedirects + +//Path to a program. +CMAKE_INSTALL_NAME_TOOL:FILEPATH=/usr/bin/install_name_tool + +//Install path prefix, prepended onto install directories. +CMAKE_INSTALL_PREFIX:PATH=/usr + +//No help, variable specified on the command line. +CMAKE_JS_INC:UNINITIALIZED=/Users/JLaciv000/.cmake-js/node-arm64/v19.6.1/include/node + +//No help, variable specified on the command line. +CMAKE_JS_SRC:UNINITIALIZED= + +//No help, variable specified on the command line. +CMAKE_JS_VERSION:UNINITIALIZED=undefined + +//No help, variable specified on the command line. +CMAKE_LIBRARY_OUTPUT_DIRECTORY:UNINITIALIZED=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/Release + +//Path to a program. +CMAKE_LINKER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ld + +//Path to a program. +CMAKE_MAKE_PROGRAM:FILEPATH=/usr/bin/make + +//Flags used by the linker during the creation of modules during +// all build types. +CMAKE_MODULE_LINKER_FLAGS:STRING= + +//Flags used by the linker during the creation of modules during +// DEBUG builds. +CMAKE_MODULE_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during the creation of modules during +// MINSIZEREL builds. +CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during the creation of modules during +// RELEASE builds. +CMAKE_MODULE_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during the creation of modules during +// RELWITHDEBINFO builds. +CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//No help, variable specified on the command line. +CMAKE_MSVC_RUNTIME_LIBRARY:UNINITIALIZED=MultiThreaded$<$:Debug> + +//Path to a program. +CMAKE_NM:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/nm + +//Path to a program. +CMAKE_OBJCOPY:FILEPATH=CMAKE_OBJCOPY-NOTFOUND + +//Path to a program. +CMAKE_OBJDUMP:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/objdump + +//Build architectures for OSX +CMAKE_OSX_ARCHITECTURES:STRING=arm64 + +//Minimum OS X version to target for deployment (at runtime); newer +// APIs weak linked. Set to empty string for default value. +CMAKE_OSX_DEPLOYMENT_TARGET:STRING= + +//The product will be built against the headers and libraries located +// inside the indicated SDK. +CMAKE_OSX_SYSROOT:PATH=/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk + +//Value Computed by CMake +CMAKE_PROJECT_DESCRIPTION:STATIC= + +//Value Computed by CMake +CMAKE_PROJECT_HOMEPAGE_URL:STATIC= + +//Value Computed by CMake +CMAKE_PROJECT_NAME:STATIC=Firebolt + +//Path to a program. +CMAKE_RANLIB:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ranlib + +//Path to a program. +CMAKE_READELF:FILEPATH=CMAKE_READELF-NOTFOUND + +//Flags used by the linker during the creation of shared libraries +// during all build types. +CMAKE_SHARED_LINKER_FLAGS:STRING=-undefined dynamic_lookup + +//Flags used by the linker during the creation of shared libraries +// during DEBUG builds. +CMAKE_SHARED_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during the creation of shared libraries +// during MINSIZEREL builds. +CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during the creation of shared libraries +// during RELEASE builds. +CMAKE_SHARED_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during the creation of shared libraries +// during RELWITHDEBINFO builds. +CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//If set, runtime paths are not added when installing shared libraries, +// but are added when building. +CMAKE_SKIP_INSTALL_RPATH:BOOL=NO + +//If set, runtime paths are not added when using shared libraries. +CMAKE_SKIP_RPATH:BOOL=NO + +//Flags used by the linker during the creation of static libraries +// during all build types. +CMAKE_STATIC_LINKER_FLAGS:STRING= + +//Flags used by the linker during the creation of static libraries +// during DEBUG builds. +CMAKE_STATIC_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during the creation of static libraries +// during MINSIZEREL builds. +CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during the creation of static libraries +// during RELEASE builds. +CMAKE_STATIC_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during the creation of static libraries +// during RELWITHDEBINFO builds. +CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//Path to a program. +CMAKE_STRIP:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/strip + +//If this value is on, makefiles will be generated without the +// .SILENT directive, and all commands will be echoed to the console +// during the make. This is useful for debugging only. With Visual +// Studio IDE projects all commands are done without /nologo. +CMAKE_VERBOSE_MAKEFILE:BOOL=FALSE + +//Build openrpc native test +ENABLE_TESTS:BOOL=OFF + +//Log level to be enabled +FIREBOLT_LOGLEVEL:STRING=Info + +//Namespace of the project +FIREBOLT_NAMESPACE:STRING=Firebolt + +//Maximum time to wait for Transport layer to get response +FIREBOLT_TRANSPORT_WAITTIME:STRING=1000 + +//Value Computed by CMake +Firebolt_BINARY_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build + +//Value Computed by CMake +Firebolt_IS_TOP_LEVEL:STATIC=ON + +//Value Computed by CMake +Firebolt_SOURCE_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native + +//No help, variable specified on the command line. +GENERATED_CODE_PATH:UNINITIALIZED=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/build/sdk/native-c + +//No help, variable specified on the command line. +NODE_ARCH:UNINITIALIZED=arm64 + +//No help, variable specified on the command line. +NODE_RUNTIME:UNINITIALIZED=node + +//No help, variable specified on the command line. +NODE_RUNTIMEVERSION:UNINITIALIZED=19.6.1 + +//The directory containing a CMake configuration file for WPEFramework. +WPEFramework_DIR:PATH=WPEFramework_DIR-NOTFOUND + + +######################## +# INTERNAL cache entries +######################## + +//ADVANCED property for variable: CMAKE_ADDR2LINE +CMAKE_ADDR2LINE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_AR +CMAKE_AR-ADVANCED:INTERNAL=1 +//This is the directory where this CMakeCache.txt was created +CMAKE_CACHEFILE_DIR:INTERNAL=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build +//Major version of cmake used to create the current loaded cache +CMAKE_CACHE_MAJOR_VERSION:INTERNAL=3 +//Minor version of cmake used to create the current loaded cache +CMAKE_CACHE_MINOR_VERSION:INTERNAL=25 +//Patch version of cmake used to create the current loaded cache +CMAKE_CACHE_PATCH_VERSION:INTERNAL=3 +//ADVANCED property for variable: CMAKE_COLOR_MAKEFILE +CMAKE_COLOR_MAKEFILE-ADVANCED:INTERNAL=1 +//Path to CMake executable. +CMAKE_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake +//Path to cpack program executable. +CMAKE_CPACK_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/cpack +//Path to ctest program executable. +CMAKE_CTEST_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/ctest +//ADVANCED property for variable: CMAKE_CXX_COMPILER +CMAKE_CXX_COMPILER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS +CMAKE_CXX_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_DEBUG +CMAKE_CXX_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_MINSIZEREL +CMAKE_CXX_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELEASE +CMAKE_CXX_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELWITHDEBINFO +CMAKE_CXX_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_COMPILER +CMAKE_C_COMPILER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS +CMAKE_C_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_DEBUG +CMAKE_C_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_MINSIZEREL +CMAKE_C_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_RELEASE +CMAKE_C_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_RELWITHDEBINFO +CMAKE_C_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_DLLTOOL +CMAKE_DLLTOOL-ADVANCED:INTERNAL=1 +//Path to cache edit program executable. +CMAKE_EDIT_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/ccmake +//Executable file format +CMAKE_EXECUTABLE_FORMAT:INTERNAL=MACHO +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS +CMAKE_EXE_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_DEBUG +CMAKE_EXE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_MINSIZEREL +CMAKE_EXE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELEASE +CMAKE_EXE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXPORT_COMPILE_COMMANDS +CMAKE_EXPORT_COMPILE_COMMANDS-ADVANCED:INTERNAL=1 +//Name of external makefile project generator. +CMAKE_EXTRA_GENERATOR:INTERNAL= +//Name of generator. +CMAKE_GENERATOR:INTERNAL=Unix Makefiles +//Generator instance identifier. +CMAKE_GENERATOR_INSTANCE:INTERNAL= +//Name of generator platform. +CMAKE_GENERATOR_PLATFORM:INTERNAL= +//Name of generator toolset. +CMAKE_GENERATOR_TOOLSET:INTERNAL= +//Source directory with the top level CMakeLists.txt file for this +// project +CMAKE_HOME_DIRECTORY:INTERNAL=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native +//ADVANCED property for variable: CMAKE_INSTALL_NAME_TOOL +CMAKE_INSTALL_NAME_TOOL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_LINKER +CMAKE_LINKER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MAKE_PROGRAM +CMAKE_MAKE_PROGRAM-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS +CMAKE_MODULE_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_DEBUG +CMAKE_MODULE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL +CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELEASE +CMAKE_MODULE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_NM +CMAKE_NM-ADVANCED:INTERNAL=1 +//number of local generators +CMAKE_NUMBER_OF_MAKEFILES:INTERNAL=1 +//ADVANCED property for variable: CMAKE_OBJCOPY +CMAKE_OBJCOPY-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_OBJDUMP +CMAKE_OBJDUMP-ADVANCED:INTERNAL=1 +//Platform information initialized +CMAKE_PLATFORM_INFO_INITIALIZED:INTERNAL=1 +CMAKE_PREFIX_PATH:INTERNAL=/usr/lib/cmake +//ADVANCED property for variable: CMAKE_RANLIB +CMAKE_RANLIB-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_READELF +CMAKE_READELF-ADVANCED:INTERNAL=1 +//Path to CMake installation. +CMAKE_ROOT:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/share/cmake +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS +CMAKE_SHARED_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_DEBUG +CMAKE_SHARED_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL +CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELEASE +CMAKE_SHARED_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SKIP_INSTALL_RPATH +CMAKE_SKIP_INSTALL_RPATH-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SKIP_RPATH +CMAKE_SKIP_RPATH-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS +CMAKE_STATIC_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_DEBUG +CMAKE_STATIC_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL +CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELEASE +CMAKE_STATIC_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STRIP +CMAKE_STRIP-ADVANCED:INTERNAL=1 +//uname command +CMAKE_UNAME:INTERNAL=/usr/bin/uname +//ADVANCED property for variable: CMAKE_VERBOSE_MAKEFILE +CMAKE_VERBOSE_MAKEFILE-ADVANCED:INTERNAL=1 + diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake new file mode 100644 index 00000000..dc7a67f2 --- /dev/null +++ b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake @@ -0,0 +1,72 @@ +set(CMAKE_C_COMPILER "/Library/Developer/CommandLineTools/usr/bin/cc") +set(CMAKE_C_COMPILER_ARG1 "") +set(CMAKE_C_COMPILER_ID "AppleClang") +set(CMAKE_C_COMPILER_VERSION "13.1.6.13160021") +set(CMAKE_C_COMPILER_VERSION_INTERNAL "") +set(CMAKE_C_COMPILER_WRAPPER "") +set(CMAKE_C_STANDARD_COMPUTED_DEFAULT "17") +set(CMAKE_C_EXTENSIONS_COMPUTED_DEFAULT "ON") +set(CMAKE_C_COMPILE_FEATURES "c_std_90;c_function_prototypes;c_std_99;c_restrict;c_variadic_macros;c_std_11;c_static_assert;c_std_17;c_std_23") +set(CMAKE_C90_COMPILE_FEATURES "c_std_90;c_function_prototypes") +set(CMAKE_C99_COMPILE_FEATURES "c_std_99;c_restrict;c_variadic_macros") +set(CMAKE_C11_COMPILE_FEATURES "c_std_11;c_static_assert") +set(CMAKE_C17_COMPILE_FEATURES "c_std_17") +set(CMAKE_C23_COMPILE_FEATURES "c_std_23") + +set(CMAKE_C_PLATFORM_ID "Darwin") +set(CMAKE_C_SIMULATE_ID "") +set(CMAKE_C_COMPILER_FRONTEND_VARIANT "") +set(CMAKE_C_SIMULATE_VERSION "") + + + + +set(CMAKE_AR "/Library/Developer/CommandLineTools/usr/bin/ar") +set(CMAKE_C_COMPILER_AR "") +set(CMAKE_RANLIB "/Library/Developer/CommandLineTools/usr/bin/ranlib") +set(CMAKE_C_COMPILER_RANLIB "") +set(CMAKE_LINKER "/Library/Developer/CommandLineTools/usr/bin/ld") +set(CMAKE_MT "") +set(CMAKE_COMPILER_IS_GNUCC ) +set(CMAKE_C_COMPILER_LOADED 1) +set(CMAKE_C_COMPILER_WORKS TRUE) +set(CMAKE_C_ABI_COMPILED TRUE) + +set(CMAKE_C_COMPILER_ENV_VAR "CC") + +set(CMAKE_C_COMPILER_ID_RUN 1) +set(CMAKE_C_SOURCE_FILE_EXTENSIONS c;m) +set(CMAKE_C_IGNORE_EXTENSIONS h;H;o;O;obj;OBJ;def;DEF;rc;RC) +set(CMAKE_C_LINKER_PREFERENCE 10) + +# Save compiler ABI information. +set(CMAKE_C_SIZEOF_DATA_PTR "8") +set(CMAKE_C_COMPILER_ABI "") +set(CMAKE_C_BYTE_ORDER "LITTLE_ENDIAN") +set(CMAKE_C_LIBRARY_ARCHITECTURE "") + +if(CMAKE_C_SIZEOF_DATA_PTR) + set(CMAKE_SIZEOF_VOID_P "${CMAKE_C_SIZEOF_DATA_PTR}") +endif() + +if(CMAKE_C_COMPILER_ABI) + set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_C_COMPILER_ABI}") +endif() + +if(CMAKE_C_LIBRARY_ARCHITECTURE) + set(CMAKE_LIBRARY_ARCHITECTURE "") +endif() + +set(CMAKE_C_CL_SHOWINCLUDES_PREFIX "") +if(CMAKE_C_CL_SHOWINCLUDES_PREFIX) + set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_C_CL_SHOWINCLUDES_PREFIX}") +endif() + + + + + +set(CMAKE_C_IMPLICIT_INCLUDE_DIRECTORIES "/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include") +set(CMAKE_C_IMPLICIT_LINK_LIBRARIES "") +set(CMAKE_C_IMPLICIT_LINK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib") +set(CMAKE_C_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks") diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake new file mode 100644 index 00000000..67dc227a --- /dev/null +++ b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake @@ -0,0 +1,83 @@ +set(CMAKE_CXX_COMPILER "/Library/Developer/CommandLineTools/usr/bin/c++") +set(CMAKE_CXX_COMPILER_ARG1 "") +set(CMAKE_CXX_COMPILER_ID "AppleClang") +set(CMAKE_CXX_COMPILER_VERSION "13.1.6.13160021") +set(CMAKE_CXX_COMPILER_VERSION_INTERNAL "") +set(CMAKE_CXX_COMPILER_WRAPPER "") +set(CMAKE_CXX_STANDARD_COMPUTED_DEFAULT "98") +set(CMAKE_CXX_EXTENSIONS_COMPUTED_DEFAULT "ON") +set(CMAKE_CXX_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters;cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates;cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates;cxx_std_17;cxx_std_20;cxx_std_23") +set(CMAKE_CXX98_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters") +set(CMAKE_CXX11_COMPILE_FEATURES "cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates") +set(CMAKE_CXX14_COMPILE_FEATURES "cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates") +set(CMAKE_CXX17_COMPILE_FEATURES "cxx_std_17") +set(CMAKE_CXX20_COMPILE_FEATURES "cxx_std_20") +set(CMAKE_CXX23_COMPILE_FEATURES "cxx_std_23") + +set(CMAKE_CXX_PLATFORM_ID "Darwin") +set(CMAKE_CXX_SIMULATE_ID "") +set(CMAKE_CXX_COMPILER_FRONTEND_VARIANT "") +set(CMAKE_CXX_SIMULATE_VERSION "") + + + + +set(CMAKE_AR "/Library/Developer/CommandLineTools/usr/bin/ar") +set(CMAKE_CXX_COMPILER_AR "") +set(CMAKE_RANLIB "/Library/Developer/CommandLineTools/usr/bin/ranlib") +set(CMAKE_CXX_COMPILER_RANLIB "") +set(CMAKE_LINKER "/Library/Developer/CommandLineTools/usr/bin/ld") +set(CMAKE_MT "") +set(CMAKE_COMPILER_IS_GNUCXX ) +set(CMAKE_CXX_COMPILER_LOADED 1) +set(CMAKE_CXX_COMPILER_WORKS TRUE) +set(CMAKE_CXX_ABI_COMPILED TRUE) + +set(CMAKE_CXX_COMPILER_ENV_VAR "CXX") + +set(CMAKE_CXX_COMPILER_ID_RUN 1) +set(CMAKE_CXX_SOURCE_FILE_EXTENSIONS C;M;c++;cc;cpp;cxx;m;mm;mpp;CPP;ixx;cppm) +set(CMAKE_CXX_IGNORE_EXTENSIONS inl;h;hpp;HPP;H;o;O;obj;OBJ;def;DEF;rc;RC) + +foreach (lang C OBJC OBJCXX) + if (CMAKE_${lang}_COMPILER_ID_RUN) + foreach(extension IN LISTS CMAKE_${lang}_SOURCE_FILE_EXTENSIONS) + list(REMOVE_ITEM CMAKE_CXX_SOURCE_FILE_EXTENSIONS ${extension}) + endforeach() + endif() +endforeach() + +set(CMAKE_CXX_LINKER_PREFERENCE 30) +set(CMAKE_CXX_LINKER_PREFERENCE_PROPAGATES 1) + +# Save compiler ABI information. +set(CMAKE_CXX_SIZEOF_DATA_PTR "8") +set(CMAKE_CXX_COMPILER_ABI "") +set(CMAKE_CXX_BYTE_ORDER "LITTLE_ENDIAN") +set(CMAKE_CXX_LIBRARY_ARCHITECTURE "") + +if(CMAKE_CXX_SIZEOF_DATA_PTR) + set(CMAKE_SIZEOF_VOID_P "${CMAKE_CXX_SIZEOF_DATA_PTR}") +endif() + +if(CMAKE_CXX_COMPILER_ABI) + set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_CXX_COMPILER_ABI}") +endif() + +if(CMAKE_CXX_LIBRARY_ARCHITECTURE) + set(CMAKE_LIBRARY_ARCHITECTURE "") +endif() + +set(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX "") +if(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX) + set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_CXX_CL_SHOWINCLUDES_PREFIX}") +endif() + + + + + +set(CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1;/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include") +set(CMAKE_CXX_IMPLICIT_LINK_LIBRARIES "c++") +set(CMAKE_CXX_IMPLICIT_LINK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib") +set(CMAKE_CXX_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks") diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin new file mode 100755 index 0000000000000000000000000000000000000000..9b3e67d1d3825990645b4978d3a1e9da0ed43128 GIT binary patch literal 16999 zcmeI3Uuau(6vt1J4mw-bDPw=A+wvq%M%!73vA8vv&DOh>G+QHv1^Joe-nN%DNljAM zl(`jkY7xOI!Vn*PvJ@tW2r~~t@nOEH-NO_gw8E4Y8SKRe>sb7r-@Ug@j7;$P960yf zbI$K~a?a=G^?bX2`(8Vdk05^Nc4#O-beV#9BiaKUgenz}oQR%{o*Cw7qv*?xp(c;( zgm6%)L^PRbOzZpM#u&N&7KB;Rk`|@P)^yo*VE$R}&QWI=?+E)m*M_vv?8ZA@l*$(J zCGT`|J+t4b=e6wl^)>3>m72<*xAUg5^P>e_zj59#+QD&^VNZ&#>~h z;4}Y6w&79`ivJvSPnC+@6LzNCtW22jSvsNI$NH7x4Rex!tKWiOSUF)2!VyE|=*7+mzTkW;b zYDc)*>f743TAy1(u3}IBYc74XDYt?e_^tV+fVyeKjt}>h>=~;ts?5o9G1U`#o+xGv zAJ6oaE6OSsEHhO!j;Rx|s4)CVfjdF!HA3a*weJh$P*jJqFy()F*nK40$e zIUC+Q`%d-|^!D+w?~S}OJLiMg>~HQ(Z{;_1rF6GWd=t0I*kj7dn|3-+O}PoXT%NGJ zG=8gI)_-bW0>NE~aT_c<5JRWF0Qp;Z>6}N&LX(_?VE;T45Bl{=yc4VM6Pqn++5DY9SA;OK&E`)@a62ozG~Gg3vqrwOy?1(}Yo+U07k`F$ z7?Bt+1c@g+5Q2z4kcE(VVk9IUWCXE^ga;BL=A8RyyHz3a>YU`pZ)-|0EOudnCf zw+}yx7_%`DJ7_Uz)WO(6Ccuud$)NS1oHx4HdYU~O8t^n*w9DB?ITq$|K_KUTPr#q; z*6xehXUwoi!7(b7qzUIKr6Xk+u>6|u<4V05GX!nyYgqDF*YF-ToJSJzHZwXmpS()X zXO?W*)*RM7=k4*GYFy@Oyd|OK&+hl8kq?=opq*8pemwjg;qR4v>pgXnS%_#n8myWa zYm<=-nOfgv5o2BBFc9Kgu+$i~3+yVe@!BNN?O-GCURXO|Ed*@@MZq^f#aN8_7a0qe z1W@?TvC8(gWMxbZSIX&_3^qy`DAwVeb!t!?td8y9F?eTu;g@JNoC%I$f4{hdd)E zeq*{VrL>Y5g-CY zfCvx)B0vO)01+SpM1Tko0U|&IhyW2F0z`la5CI}U1c(3;AOb{y2oM1xKm>>Y5g-CY zfCvx)B0vO)01+SpM1Tko0U|&IhyW2F0z}}yA~1A-^$pEnnf@}Cd0EK54mnw7psXtc zGrC9fdsg%mr~|HdPBD{jD=2(t^$mb8t#xUfhTRpuF{#5dIGs{>A}K4$pjYzyy&mrI z)k$t2_;F--s_}Bx6=#}p<{9R_HC14~90hHhmBy**aoTM#1bqZrfGy5MqoP>Hk@fj% z{XFYy<1hnm=dDq$bSRN_C^V{spi(xoHKfMbY%IjVKJGRynH#KiEcnbhdYD7k>`u#^ zJ^D`=Hl}gfa8g>YYl3F$Jz|{#Oz`K{z_l7UZ}u)+f`j>_B0ZR-(lxt1=jV$0r_me)L)enUEBe|6e9e#*%eORpTb7ZmQE>poLc zH~P}0y%($?}6|C|5qI)^f8eSKp>24 & 0x00FF) +# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) +# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) + +#elif defined(__BORLANDC__) +# define COMPILER_ID "Borland" + /* __BORLANDC__ = 0xVRR */ +# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) +# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) + +#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 +# define COMPILER_ID "Watcom" + /* __WATCOMC__ = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__WATCOMC__) +# define COMPILER_ID "OpenWatcom" + /* __WATCOMC__ = VVRP + 1100 */ +# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__SUNPRO_C) +# define COMPILER_ID "SunPro" +# if __SUNPRO_C >= 0x5100 + /* __SUNPRO_C = 0xVRRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>12) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xFF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) +# else + /* __SUNPRO_CC = 0xVRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>8) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) +# endif + +#elif defined(__HP_cc) +# define COMPILER_ID "HP" + /* __HP_cc = VVRRPP */ +# define COMPILER_VERSION_MAJOR DEC(__HP_cc/10000) +# define COMPILER_VERSION_MINOR DEC(__HP_cc/100 % 100) +# define COMPILER_VERSION_PATCH DEC(__HP_cc % 100) + +#elif defined(__DECC) +# define COMPILER_ID "Compaq" + /* __DECC_VER = VVRRTPPPP */ +# define COMPILER_VERSION_MAJOR DEC(__DECC_VER/10000000) +# define COMPILER_VERSION_MINOR DEC(__DECC_VER/100000 % 100) +# define COMPILER_VERSION_PATCH DEC(__DECC_VER % 10000) + +#elif defined(__IBMC__) && defined(__COMPILER_VER__) +# define COMPILER_ID "zOS" + /* __IBMC__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) + +#elif defined(__open_xl__) && defined(__clang__) +# define COMPILER_ID "IBMClang" +# define COMPILER_VERSION_MAJOR DEC(__open_xl_version__) +# define COMPILER_VERSION_MINOR DEC(__open_xl_release__) +# define COMPILER_VERSION_PATCH DEC(__open_xl_modification__) +# define COMPILER_VERSION_TWEAK DEC(__open_xl_ptf_fix_level__) + + +#elif defined(__ibmxl__) && defined(__clang__) +# define COMPILER_ID "XLClang" +# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) +# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) +# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) +# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) + + +#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ >= 800 +# define COMPILER_ID "XL" + /* __IBMC__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) + +#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ < 800 +# define COMPILER_ID "VisualAge" + /* __IBMC__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) + +#elif defined(__NVCOMPILER) +# define COMPILER_ID "NVHPC" +# define COMPILER_VERSION_MAJOR DEC(__NVCOMPILER_MAJOR__) +# define COMPILER_VERSION_MINOR DEC(__NVCOMPILER_MINOR__) +# if defined(__NVCOMPILER_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__NVCOMPILER_PATCHLEVEL__) +# endif + +#elif defined(__PGI) +# define COMPILER_ID "PGI" +# define COMPILER_VERSION_MAJOR DEC(__PGIC__) +# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) +# if defined(__PGIC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) +# endif + +#elif defined(_CRAYC) +# define COMPILER_ID "Cray" +# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) +# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) + +#elif defined(__TI_COMPILER_VERSION__) +# define COMPILER_ID "TI" + /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ +# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) +# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) +# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) + +#elif defined(__CLANG_FUJITSU) +# define COMPILER_ID "FujitsuClang" +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# define COMPILER_VERSION_INTERNAL_STR __clang_version__ + + +#elif defined(__FUJITSU) +# define COMPILER_ID "Fujitsu" +# if defined(__FCC_version__) +# define COMPILER_VERSION __FCC_version__ +# elif defined(__FCC_major__) +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# endif +# if defined(__fcc_version) +# define COMPILER_VERSION_INTERNAL DEC(__fcc_version) +# elif defined(__FCC_VERSION) +# define COMPILER_VERSION_INTERNAL DEC(__FCC_VERSION) +# endif + + +#elif defined(__ghs__) +# define COMPILER_ID "GHS" +/* __GHS_VERSION_NUMBER = VVVVRP */ +# ifdef __GHS_VERSION_NUMBER +# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) +# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) +# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) +# endif + +#elif defined(__TASKING__) +# define COMPILER_ID "Tasking" + # define COMPILER_VERSION_MAJOR DEC(__VERSION__/1000) + # define COMPILER_VERSION_MINOR DEC(__VERSION__ % 100) +# define COMPILER_VERSION_INTERNAL DEC(__VERSION__) + +#elif defined(__TINYC__) +# define COMPILER_ID "TinyCC" + +#elif defined(__BCC__) +# define COMPILER_ID "Bruce" + +#elif defined(__SCO_VERSION__) +# define COMPILER_ID "SCO" + +#elif defined(__ARMCC_VERSION) && !defined(__clang__) +# define COMPILER_ID "ARMCC" +#if __ARMCC_VERSION >= 1000000 + /* __ARMCC_VERSION = VRRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#else + /* __ARMCC_VERSION = VRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#endif + + +#elif defined(__clang__) && defined(__apple_build_version__) +# define COMPILER_ID "AppleClang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif +# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) + +#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) +# define COMPILER_ID "ARMClang" + # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) +# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) + +#elif defined(__clang__) +# define COMPILER_ID "Clang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif + +#elif defined(__LCC__) && (defined(__GNUC__) || defined(__GNUG__) || defined(__MCST__)) +# define COMPILER_ID "LCC" +# define COMPILER_VERSION_MAJOR DEC(1) +# if defined(__LCC__) +# define COMPILER_VERSION_MINOR DEC(__LCC__- 100) +# endif +# if defined(__LCC_MINOR__) +# define COMPILER_VERSION_PATCH DEC(__LCC_MINOR__) +# endif +# if defined(__GNUC__) && defined(__GNUC_MINOR__) +# define SIMULATE_ID "GNU" +# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) +# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) +# if defined(__GNUC_PATCHLEVEL__) +# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif +# endif + +#elif defined(__GNUC__) +# define COMPILER_ID "GNU" +# define COMPILER_VERSION_MAJOR DEC(__GNUC__) +# if defined(__GNUC_MINOR__) +# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) +# endif +# if defined(__GNUC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif + +#elif defined(_MSC_VER) +# define COMPILER_ID "MSVC" + /* _MSC_VER = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) +# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) +# if defined(_MSC_FULL_VER) +# if _MSC_VER >= 1400 + /* _MSC_FULL_VER = VVRRPPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) +# else + /* _MSC_FULL_VER = VVRRPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) +# endif +# endif +# if defined(_MSC_BUILD) +# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) +# endif + +#elif defined(_ADI_COMPILER) +# define COMPILER_ID "ADSP" +#if defined(__VERSIONNUM__) + /* __VERSIONNUM__ = 0xVVRRPPTT */ +# define COMPILER_VERSION_MAJOR DEC(__VERSIONNUM__ >> 24 & 0xFF) +# define COMPILER_VERSION_MINOR DEC(__VERSIONNUM__ >> 16 & 0xFF) +# define COMPILER_VERSION_PATCH DEC(__VERSIONNUM__ >> 8 & 0xFF) +# define COMPILER_VERSION_TWEAK DEC(__VERSIONNUM__ & 0xFF) +#endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# define COMPILER_ID "IAR" +# if defined(__VER__) && defined(__ICCARM__) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) +# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) +# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__) || defined(__ICCSTM8__)) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) +# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) +# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# endif + +#elif defined(__SDCC_VERSION_MAJOR) || defined(SDCC) +# define COMPILER_ID "SDCC" +# if defined(__SDCC_VERSION_MAJOR) +# define COMPILER_VERSION_MAJOR DEC(__SDCC_VERSION_MAJOR) +# define COMPILER_VERSION_MINOR DEC(__SDCC_VERSION_MINOR) +# define COMPILER_VERSION_PATCH DEC(__SDCC_VERSION_PATCH) +# else + /* SDCC = VRP */ +# define COMPILER_VERSION_MAJOR DEC(SDCC/100) +# define COMPILER_VERSION_MINOR DEC(SDCC/10 % 10) +# define COMPILER_VERSION_PATCH DEC(SDCC % 10) +# endif + + +/* These compilers are either not known or too old to define an + identification macro. Try to identify the platform and guess that + it is the native compiler. */ +#elif defined(__hpux) || defined(__hpua) +# define COMPILER_ID "HP" + +#else /* unknown compiler */ +# define COMPILER_ID "" +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; +#ifdef SIMULATE_ID +char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; +#endif + +#ifdef __QNXNTO__ +char const* qnxnto = "INFO" ":" "qnxnto[]"; +#endif + +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) +char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; +#endif + +#define STRINGIFY_HELPER(X) #X +#define STRINGIFY(X) STRINGIFY_HELPER(X) + +/* Identify known platforms by name. */ +#if defined(__linux) || defined(__linux__) || defined(linux) +# define PLATFORM_ID "Linux" + +#elif defined(__MSYS__) +# define PLATFORM_ID "MSYS" + +#elif defined(__CYGWIN__) +# define PLATFORM_ID "Cygwin" + +#elif defined(__MINGW32__) +# define PLATFORM_ID "MinGW" + +#elif defined(__APPLE__) +# define PLATFORM_ID "Darwin" + +#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) +# define PLATFORM_ID "Windows" + +#elif defined(__FreeBSD__) || defined(__FreeBSD) +# define PLATFORM_ID "FreeBSD" + +#elif defined(__NetBSD__) || defined(__NetBSD) +# define PLATFORM_ID "NetBSD" + +#elif defined(__OpenBSD__) || defined(__OPENBSD) +# define PLATFORM_ID "OpenBSD" + +#elif defined(__sun) || defined(sun) +# define PLATFORM_ID "SunOS" + +#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) +# define PLATFORM_ID "AIX" + +#elif defined(__hpux) || defined(__hpux__) +# define PLATFORM_ID "HP-UX" + +#elif defined(__HAIKU__) +# define PLATFORM_ID "Haiku" + +#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) +# define PLATFORM_ID "BeOS" + +#elif defined(__QNX__) || defined(__QNXNTO__) +# define PLATFORM_ID "QNX" + +#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) +# define PLATFORM_ID "Tru64" + +#elif defined(__riscos) || defined(__riscos__) +# define PLATFORM_ID "RISCos" + +#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) +# define PLATFORM_ID "SINIX" + +#elif defined(__UNIX_SV__) +# define PLATFORM_ID "UNIX_SV" + +#elif defined(__bsdos__) +# define PLATFORM_ID "BSDOS" + +#elif defined(_MPRAS) || defined(MPRAS) +# define PLATFORM_ID "MP-RAS" + +#elif defined(__osf) || defined(__osf__) +# define PLATFORM_ID "OSF1" + +#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) +# define PLATFORM_ID "SCO_SV" + +#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) +# define PLATFORM_ID "ULTRIX" + +#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) +# define PLATFORM_ID "Xenix" + +#elif defined(__WATCOMC__) +# if defined(__LINUX__) +# define PLATFORM_ID "Linux" + +# elif defined(__DOS__) +# define PLATFORM_ID "DOS" + +# elif defined(__OS2__) +# define PLATFORM_ID "OS2" + +# elif defined(__WINDOWS__) +# define PLATFORM_ID "Windows3x" + +# elif defined(__VXWORKS__) +# define PLATFORM_ID "VxWorks" + +# else /* unknown platform */ +# define PLATFORM_ID +# endif + +#elif defined(__INTEGRITY) +# if defined(INT_178B) +# define PLATFORM_ID "Integrity178" + +# else /* regular Integrity */ +# define PLATFORM_ID "Integrity" +# endif + +# elif defined(_ADI_COMPILER) +# define PLATFORM_ID "ADSP" + +#else /* unknown platform */ +# define PLATFORM_ID + +#endif + +/* For windows compilers MSVC and Intel we can determine + the architecture of the compiler being used. This is because + the compilers do not have flags that can change the architecture, + but rather depend on which compiler is being used +*/ +#if defined(_WIN32) && defined(_MSC_VER) +# if defined(_M_IA64) +# define ARCHITECTURE_ID "IA64" + +# elif defined(_M_ARM64EC) +# define ARCHITECTURE_ID "ARM64EC" + +# elif defined(_M_X64) || defined(_M_AMD64) +# define ARCHITECTURE_ID "x64" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# elif defined(_M_ARM64) +# define ARCHITECTURE_ID "ARM64" + +# elif defined(_M_ARM) +# if _M_ARM == 4 +# define ARCHITECTURE_ID "ARMV4I" +# elif _M_ARM == 5 +# define ARCHITECTURE_ID "ARMV5I" +# else +# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) +# endif + +# elif defined(_M_MIPS) +# define ARCHITECTURE_ID "MIPS" + +# elif defined(_M_SH) +# define ARCHITECTURE_ID "SHx" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__WATCOMC__) +# if defined(_M_I86) +# define ARCHITECTURE_ID "I86" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# if defined(__ICCARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__ICCRX__) +# define ARCHITECTURE_ID "RX" + +# elif defined(__ICCRH850__) +# define ARCHITECTURE_ID "RH850" + +# elif defined(__ICCRL78__) +# define ARCHITECTURE_ID "RL78" + +# elif defined(__ICCRISCV__) +# define ARCHITECTURE_ID "RISCV" + +# elif defined(__ICCAVR__) +# define ARCHITECTURE_ID "AVR" + +# elif defined(__ICC430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__ICCV850__) +# define ARCHITECTURE_ID "V850" + +# elif defined(__ICC8051__) +# define ARCHITECTURE_ID "8051" + +# elif defined(__ICCSTM8__) +# define ARCHITECTURE_ID "STM8" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__ghs__) +# if defined(__PPC64__) +# define ARCHITECTURE_ID "PPC64" + +# elif defined(__ppc__) +# define ARCHITECTURE_ID "PPC" + +# elif defined(__ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__x86_64__) +# define ARCHITECTURE_ID "x64" + +# elif defined(__i386__) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__TI_COMPILER_VERSION__) +# if defined(__TI_ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__MSP430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__TMS320C28XX__) +# define ARCHITECTURE_ID "TMS320C28x" + +# elif defined(__TMS320C6X__) || defined(_TMS320C6X) +# define ARCHITECTURE_ID "TMS320C6x" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +# elif defined(__ADSPSHARC__) +# define ARCHITECTURE_ID "SHARC" + +# elif defined(__ADSPBLACKFIN__) +# define ARCHITECTURE_ID "Blackfin" + +#elif defined(__TASKING__) + +# if defined(__CTC__) || defined(__CPTC__) +# define ARCHITECTURE_ID "TriCore" + +# elif defined(__CMCS__) +# define ARCHITECTURE_ID "MCS" + +# elif defined(__CARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__CARC__) +# define ARCHITECTURE_ID "ARC" + +# elif defined(__C51__) +# define ARCHITECTURE_ID "8051" + +# elif defined(__CPCP__) +# define ARCHITECTURE_ID "PCP" + +# else +# define ARCHITECTURE_ID "" +# endif + +#else +# define ARCHITECTURE_ID +#endif + +/* Convert integer to decimal digit literals. */ +#define DEC(n) \ + ('0' + (((n) / 10000000)%10)), \ + ('0' + (((n) / 1000000)%10)), \ + ('0' + (((n) / 100000)%10)), \ + ('0' + (((n) / 10000)%10)), \ + ('0' + (((n) / 1000)%10)), \ + ('0' + (((n) / 100)%10)), \ + ('0' + (((n) / 10)%10)), \ + ('0' + ((n) % 10)) + +/* Convert integer to hex digit literals. */ +#define HEX(n) \ + ('0' + ((n)>>28 & 0xF)), \ + ('0' + ((n)>>24 & 0xF)), \ + ('0' + ((n)>>20 & 0xF)), \ + ('0' + ((n)>>16 & 0xF)), \ + ('0' + ((n)>>12 & 0xF)), \ + ('0' + ((n)>>8 & 0xF)), \ + ('0' + ((n)>>4 & 0xF)), \ + ('0' + ((n) & 0xF)) + +/* Construct a string literal encoding the version number. */ +#ifdef COMPILER_VERSION +char const* info_version = "INFO" ":" "compiler_version[" COMPILER_VERSION "]"; + +/* Construct a string literal encoding the version number components. */ +#elif defined(COMPILER_VERSION_MAJOR) +char const info_version[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', + COMPILER_VERSION_MAJOR, +# ifdef COMPILER_VERSION_MINOR + '.', COMPILER_VERSION_MINOR, +# ifdef COMPILER_VERSION_PATCH + '.', COMPILER_VERSION_PATCH, +# ifdef COMPILER_VERSION_TWEAK + '.', COMPILER_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct a string literal encoding the internal version number. */ +#ifdef COMPILER_VERSION_INTERNAL +char const info_version_internal[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', + 'i','n','t','e','r','n','a','l','[', + COMPILER_VERSION_INTERNAL,']','\0'}; +#elif defined(COMPILER_VERSION_INTERNAL_STR) +char const* info_version_internal = "INFO" ":" "compiler_version_internal[" COMPILER_VERSION_INTERNAL_STR "]"; +#endif + +/* Construct a string literal encoding the version number components. */ +#ifdef SIMULATE_VERSION_MAJOR +char const info_simulate_version[] = { + 'I', 'N', 'F', 'O', ':', + 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', + SIMULATE_VERSION_MAJOR, +# ifdef SIMULATE_VERSION_MINOR + '.', SIMULATE_VERSION_MINOR, +# ifdef SIMULATE_VERSION_PATCH + '.', SIMULATE_VERSION_PATCH, +# ifdef SIMULATE_VERSION_TWEAK + '.', SIMULATE_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; +char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; + + + +#if !defined(__STDC__) && !defined(__clang__) +# if defined(_MSC_VER) || defined(__ibmxl__) || defined(__IBMC__) +# define C_VERSION "90" +# else +# define C_VERSION +# endif +#elif __STDC_VERSION__ > 201710L +# define C_VERSION "23" +#elif __STDC_VERSION__ >= 201710L +# define C_VERSION "17" +#elif __STDC_VERSION__ >= 201000L +# define C_VERSION "11" +#elif __STDC_VERSION__ >= 199901L +# define C_VERSION "99" +#else +# define C_VERSION "90" +#endif +const char* info_language_standard_default = + "INFO" ":" "standard_default[" C_VERSION "]"; + +const char* info_language_extensions_default = "INFO" ":" "extensions_default[" +#if (defined(__clang__) || defined(__GNUC__) || defined(__xlC__) || \ + defined(__TI_COMPILER_VERSION__)) && \ + !defined(__STRICT_ANSI__) + "ON" +#else + "OFF" +#endif +"]"; + +/*--------------------------------------------------------------------------*/ + +#ifdef ID_VOID_MAIN +void main() {} +#else +# if defined(__CLASSIC_C__) +int main(argc, argv) int argc; char *argv[]; +# else +int main(int argc, char* argv[]) +# endif +{ + int require = 0; + require += info_compiler[argc]; + require += info_platform[argc]; + require += info_arch[argc]; +#ifdef COMPILER_VERSION_MAJOR + require += info_version[argc]; +#endif +#ifdef COMPILER_VERSION_INTERNAL + require += info_version_internal[argc]; +#endif +#ifdef SIMULATE_ID + require += info_simulate[argc]; +#endif +#ifdef SIMULATE_VERSION_MAJOR + require += info_simulate_version[argc]; +#endif +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) + require += info_cray[argc]; +#endif + require += info_language_standard_default[argc]; + require += info_language_extensions_default[argc]; + (void)argv; + return require; +} +#endif diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o new file mode 100644 index 0000000000000000000000000000000000000000..537fbf261a76f93972038901b25169a2bbc47274 GIT binary patch literal 1712 zcmb_cJ!n%=6uz;wrbZJ52c@6^7pIWdlqyOfp;1&q+aW_FlnbM8Iw+;_kGKK=Uf`-Bi7 z0i(w>M)3$9aSYfwjIS!I=z&L%dbCZ%s}_<rdz)YvA0HYv+3-?QBs2c#UYr|Wo}&rIo+0dl*8pp+HUHwP5`=CXzCkY{+GmpJqe z^{C`F`qO(H&ZhmA8*Xd3;mQ8ix!yHi)SKvUv=;ePuiiAvzHGbqZMPz2J~uk&HP?%C zFpj>cWEaS(u`SOdcNQbasV}Tn(j%)}% za%=g<%2hfV+p)Y-w%K&7CC7AYYeHq3j_Fq$UcHnvJscZHO|QIOV!!2^ZpHK}vSL-u zw&RzK%bdY|vD}so84YqP%WHr6vB&z8_biVJmXgYhR3dPahISScM#@-BCg+Wb7peOc zS66bZgO^}XPkuYV^b_Do@J9iro4^>j6JVM&1pVam0j3v#QSfAdY0@6FmOm3y4i@8<*X7~Z$a`P`qk_SaKIb%|g!jTF5YI&NLI#U*ukag2`Ii@wwl*BF^ czusKnN(nfiDNW&k&T9$>)X)?TD9J>24 & 0x00FF) +# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) +# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) + +#elif defined(__BORLANDC__) +# define COMPILER_ID "Borland" + /* __BORLANDC__ = 0xVRR */ +# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) +# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) + +#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 +# define COMPILER_ID "Watcom" + /* __WATCOMC__ = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__WATCOMC__) +# define COMPILER_ID "OpenWatcom" + /* __WATCOMC__ = VVRP + 1100 */ +# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__SUNPRO_CC) +# define COMPILER_ID "SunPro" +# if __SUNPRO_CC >= 0x5100 + /* __SUNPRO_CC = 0xVRRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>12) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xFF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) +# else + /* __SUNPRO_CC = 0xVRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>8) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) +# endif + +#elif defined(__HP_aCC) +# define COMPILER_ID "HP" + /* __HP_aCC = VVRRPP */ +# define COMPILER_VERSION_MAJOR DEC(__HP_aCC/10000) +# define COMPILER_VERSION_MINOR DEC(__HP_aCC/100 % 100) +# define COMPILER_VERSION_PATCH DEC(__HP_aCC % 100) + +#elif defined(__DECCXX) +# define COMPILER_ID "Compaq" + /* __DECCXX_VER = VVRRTPPPP */ +# define COMPILER_VERSION_MAJOR DEC(__DECCXX_VER/10000000) +# define COMPILER_VERSION_MINOR DEC(__DECCXX_VER/100000 % 100) +# define COMPILER_VERSION_PATCH DEC(__DECCXX_VER % 10000) + +#elif defined(__IBMCPP__) && defined(__COMPILER_VER__) +# define COMPILER_ID "zOS" + /* __IBMCPP__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) + +#elif defined(__open_xl__) && defined(__clang__) +# define COMPILER_ID "IBMClang" +# define COMPILER_VERSION_MAJOR DEC(__open_xl_version__) +# define COMPILER_VERSION_MINOR DEC(__open_xl_release__) +# define COMPILER_VERSION_PATCH DEC(__open_xl_modification__) +# define COMPILER_VERSION_TWEAK DEC(__open_xl_ptf_fix_level__) + + +#elif defined(__ibmxl__) && defined(__clang__) +# define COMPILER_ID "XLClang" +# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) +# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) +# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) +# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) + + +#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ >= 800 +# define COMPILER_ID "XL" + /* __IBMCPP__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) + +#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ < 800 +# define COMPILER_ID "VisualAge" + /* __IBMCPP__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) + +#elif defined(__NVCOMPILER) +# define COMPILER_ID "NVHPC" +# define COMPILER_VERSION_MAJOR DEC(__NVCOMPILER_MAJOR__) +# define COMPILER_VERSION_MINOR DEC(__NVCOMPILER_MINOR__) +# if defined(__NVCOMPILER_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__NVCOMPILER_PATCHLEVEL__) +# endif + +#elif defined(__PGI) +# define COMPILER_ID "PGI" +# define COMPILER_VERSION_MAJOR DEC(__PGIC__) +# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) +# if defined(__PGIC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) +# endif + +#elif defined(_CRAYC) +# define COMPILER_ID "Cray" +# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) +# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) + +#elif defined(__TI_COMPILER_VERSION__) +# define COMPILER_ID "TI" + /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ +# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) +# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) +# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) + +#elif defined(__CLANG_FUJITSU) +# define COMPILER_ID "FujitsuClang" +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# define COMPILER_VERSION_INTERNAL_STR __clang_version__ + + +#elif defined(__FUJITSU) +# define COMPILER_ID "Fujitsu" +# if defined(__FCC_version__) +# define COMPILER_VERSION __FCC_version__ +# elif defined(__FCC_major__) +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# endif +# if defined(__fcc_version) +# define COMPILER_VERSION_INTERNAL DEC(__fcc_version) +# elif defined(__FCC_VERSION) +# define COMPILER_VERSION_INTERNAL DEC(__FCC_VERSION) +# endif + + +#elif defined(__ghs__) +# define COMPILER_ID "GHS" +/* __GHS_VERSION_NUMBER = VVVVRP */ +# ifdef __GHS_VERSION_NUMBER +# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) +# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) +# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) +# endif + +#elif defined(__TASKING__) +# define COMPILER_ID "Tasking" + # define COMPILER_VERSION_MAJOR DEC(__VERSION__/1000) + # define COMPILER_VERSION_MINOR DEC(__VERSION__ % 100) +# define COMPILER_VERSION_INTERNAL DEC(__VERSION__) + +#elif defined(__SCO_VERSION__) +# define COMPILER_ID "SCO" + +#elif defined(__ARMCC_VERSION) && !defined(__clang__) +# define COMPILER_ID "ARMCC" +#if __ARMCC_VERSION >= 1000000 + /* __ARMCC_VERSION = VRRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#else + /* __ARMCC_VERSION = VRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#endif + + +#elif defined(__clang__) && defined(__apple_build_version__) +# define COMPILER_ID "AppleClang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif +# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) + +#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) +# define COMPILER_ID "ARMClang" + # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) +# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) + +#elif defined(__clang__) +# define COMPILER_ID "Clang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif + +#elif defined(__LCC__) && (defined(__GNUC__) || defined(__GNUG__) || defined(__MCST__)) +# define COMPILER_ID "LCC" +# define COMPILER_VERSION_MAJOR DEC(1) +# if defined(__LCC__) +# define COMPILER_VERSION_MINOR DEC(__LCC__- 100) +# endif +# if defined(__LCC_MINOR__) +# define COMPILER_VERSION_PATCH DEC(__LCC_MINOR__) +# endif +# if defined(__GNUC__) && defined(__GNUC_MINOR__) +# define SIMULATE_ID "GNU" +# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) +# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) +# if defined(__GNUC_PATCHLEVEL__) +# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif +# endif + +#elif defined(__GNUC__) || defined(__GNUG__) +# define COMPILER_ID "GNU" +# if defined(__GNUC__) +# define COMPILER_VERSION_MAJOR DEC(__GNUC__) +# else +# define COMPILER_VERSION_MAJOR DEC(__GNUG__) +# endif +# if defined(__GNUC_MINOR__) +# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) +# endif +# if defined(__GNUC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif + +#elif defined(_MSC_VER) +# define COMPILER_ID "MSVC" + /* _MSC_VER = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) +# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) +# if defined(_MSC_FULL_VER) +# if _MSC_VER >= 1400 + /* _MSC_FULL_VER = VVRRPPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) +# else + /* _MSC_FULL_VER = VVRRPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) +# endif +# endif +# if defined(_MSC_BUILD) +# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) +# endif + +#elif defined(_ADI_COMPILER) +# define COMPILER_ID "ADSP" +#if defined(__VERSIONNUM__) + /* __VERSIONNUM__ = 0xVVRRPPTT */ +# define COMPILER_VERSION_MAJOR DEC(__VERSIONNUM__ >> 24 & 0xFF) +# define COMPILER_VERSION_MINOR DEC(__VERSIONNUM__ >> 16 & 0xFF) +# define COMPILER_VERSION_PATCH DEC(__VERSIONNUM__ >> 8 & 0xFF) +# define COMPILER_VERSION_TWEAK DEC(__VERSIONNUM__ & 0xFF) +#endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# define COMPILER_ID "IAR" +# if defined(__VER__) && defined(__ICCARM__) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) +# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) +# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__) || defined(__ICCSTM8__)) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) +# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) +# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# endif + + +/* These compilers are either not known or too old to define an + identification macro. Try to identify the platform and guess that + it is the native compiler. */ +#elif defined(__hpux) || defined(__hpua) +# define COMPILER_ID "HP" + +#else /* unknown compiler */ +# define COMPILER_ID "" +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; +#ifdef SIMULATE_ID +char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; +#endif + +#ifdef __QNXNTO__ +char const* qnxnto = "INFO" ":" "qnxnto[]"; +#endif + +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) +char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; +#endif + +#define STRINGIFY_HELPER(X) #X +#define STRINGIFY(X) STRINGIFY_HELPER(X) + +/* Identify known platforms by name. */ +#if defined(__linux) || defined(__linux__) || defined(linux) +# define PLATFORM_ID "Linux" + +#elif defined(__MSYS__) +# define PLATFORM_ID "MSYS" + +#elif defined(__CYGWIN__) +# define PLATFORM_ID "Cygwin" + +#elif defined(__MINGW32__) +# define PLATFORM_ID "MinGW" + +#elif defined(__APPLE__) +# define PLATFORM_ID "Darwin" + +#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) +# define PLATFORM_ID "Windows" + +#elif defined(__FreeBSD__) || defined(__FreeBSD) +# define PLATFORM_ID "FreeBSD" + +#elif defined(__NetBSD__) || defined(__NetBSD) +# define PLATFORM_ID "NetBSD" + +#elif defined(__OpenBSD__) || defined(__OPENBSD) +# define PLATFORM_ID "OpenBSD" + +#elif defined(__sun) || defined(sun) +# define PLATFORM_ID "SunOS" + +#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) +# define PLATFORM_ID "AIX" + +#elif defined(__hpux) || defined(__hpux__) +# define PLATFORM_ID "HP-UX" + +#elif defined(__HAIKU__) +# define PLATFORM_ID "Haiku" + +#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) +# define PLATFORM_ID "BeOS" + +#elif defined(__QNX__) || defined(__QNXNTO__) +# define PLATFORM_ID "QNX" + +#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) +# define PLATFORM_ID "Tru64" + +#elif defined(__riscos) || defined(__riscos__) +# define PLATFORM_ID "RISCos" + +#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) +# define PLATFORM_ID "SINIX" + +#elif defined(__UNIX_SV__) +# define PLATFORM_ID "UNIX_SV" + +#elif defined(__bsdos__) +# define PLATFORM_ID "BSDOS" + +#elif defined(_MPRAS) || defined(MPRAS) +# define PLATFORM_ID "MP-RAS" + +#elif defined(__osf) || defined(__osf__) +# define PLATFORM_ID "OSF1" + +#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) +# define PLATFORM_ID "SCO_SV" + +#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) +# define PLATFORM_ID "ULTRIX" + +#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) +# define PLATFORM_ID "Xenix" + +#elif defined(__WATCOMC__) +# if defined(__LINUX__) +# define PLATFORM_ID "Linux" + +# elif defined(__DOS__) +# define PLATFORM_ID "DOS" + +# elif defined(__OS2__) +# define PLATFORM_ID "OS2" + +# elif defined(__WINDOWS__) +# define PLATFORM_ID "Windows3x" + +# elif defined(__VXWORKS__) +# define PLATFORM_ID "VxWorks" + +# else /* unknown platform */ +# define PLATFORM_ID +# endif + +#elif defined(__INTEGRITY) +# if defined(INT_178B) +# define PLATFORM_ID "Integrity178" + +# else /* regular Integrity */ +# define PLATFORM_ID "Integrity" +# endif + +# elif defined(_ADI_COMPILER) +# define PLATFORM_ID "ADSP" + +#else /* unknown platform */ +# define PLATFORM_ID + +#endif + +/* For windows compilers MSVC and Intel we can determine + the architecture of the compiler being used. This is because + the compilers do not have flags that can change the architecture, + but rather depend on which compiler is being used +*/ +#if defined(_WIN32) && defined(_MSC_VER) +# if defined(_M_IA64) +# define ARCHITECTURE_ID "IA64" + +# elif defined(_M_ARM64EC) +# define ARCHITECTURE_ID "ARM64EC" + +# elif defined(_M_X64) || defined(_M_AMD64) +# define ARCHITECTURE_ID "x64" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# elif defined(_M_ARM64) +# define ARCHITECTURE_ID "ARM64" + +# elif defined(_M_ARM) +# if _M_ARM == 4 +# define ARCHITECTURE_ID "ARMV4I" +# elif _M_ARM == 5 +# define ARCHITECTURE_ID "ARMV5I" +# else +# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) +# endif + +# elif defined(_M_MIPS) +# define ARCHITECTURE_ID "MIPS" + +# elif defined(_M_SH) +# define ARCHITECTURE_ID "SHx" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__WATCOMC__) +# if defined(_M_I86) +# define ARCHITECTURE_ID "I86" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# if defined(__ICCARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__ICCRX__) +# define ARCHITECTURE_ID "RX" + +# elif defined(__ICCRH850__) +# define ARCHITECTURE_ID "RH850" + +# elif defined(__ICCRL78__) +# define ARCHITECTURE_ID "RL78" + +# elif defined(__ICCRISCV__) +# define ARCHITECTURE_ID "RISCV" + +# elif defined(__ICCAVR__) +# define ARCHITECTURE_ID "AVR" + +# elif defined(__ICC430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__ICCV850__) +# define ARCHITECTURE_ID "V850" + +# elif defined(__ICC8051__) +# define ARCHITECTURE_ID "8051" + +# elif defined(__ICCSTM8__) +# define ARCHITECTURE_ID "STM8" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__ghs__) +# if defined(__PPC64__) +# define ARCHITECTURE_ID "PPC64" + +# elif defined(__ppc__) +# define ARCHITECTURE_ID "PPC" + +# elif defined(__ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__x86_64__) +# define ARCHITECTURE_ID "x64" + +# elif defined(__i386__) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__TI_COMPILER_VERSION__) +# if defined(__TI_ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__MSP430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__TMS320C28XX__) +# define ARCHITECTURE_ID "TMS320C28x" + +# elif defined(__TMS320C6X__) || defined(_TMS320C6X) +# define ARCHITECTURE_ID "TMS320C6x" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +# elif defined(__ADSPSHARC__) +# define ARCHITECTURE_ID "SHARC" + +# elif defined(__ADSPBLACKFIN__) +# define ARCHITECTURE_ID "Blackfin" + +#elif defined(__TASKING__) + +# if defined(__CTC__) || defined(__CPTC__) +# define ARCHITECTURE_ID "TriCore" + +# elif defined(__CMCS__) +# define ARCHITECTURE_ID "MCS" + +# elif defined(__CARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__CARC__) +# define ARCHITECTURE_ID "ARC" + +# elif defined(__C51__) +# define ARCHITECTURE_ID "8051" + +# elif defined(__CPCP__) +# define ARCHITECTURE_ID "PCP" + +# else +# define ARCHITECTURE_ID "" +# endif + +#else +# define ARCHITECTURE_ID +#endif + +/* Convert integer to decimal digit literals. */ +#define DEC(n) \ + ('0' + (((n) / 10000000)%10)), \ + ('0' + (((n) / 1000000)%10)), \ + ('0' + (((n) / 100000)%10)), \ + ('0' + (((n) / 10000)%10)), \ + ('0' + (((n) / 1000)%10)), \ + ('0' + (((n) / 100)%10)), \ + ('0' + (((n) / 10)%10)), \ + ('0' + ((n) % 10)) + +/* Convert integer to hex digit literals. */ +#define HEX(n) \ + ('0' + ((n)>>28 & 0xF)), \ + ('0' + ((n)>>24 & 0xF)), \ + ('0' + ((n)>>20 & 0xF)), \ + ('0' + ((n)>>16 & 0xF)), \ + ('0' + ((n)>>12 & 0xF)), \ + ('0' + ((n)>>8 & 0xF)), \ + ('0' + ((n)>>4 & 0xF)), \ + ('0' + ((n) & 0xF)) + +/* Construct a string literal encoding the version number. */ +#ifdef COMPILER_VERSION +char const* info_version = "INFO" ":" "compiler_version[" COMPILER_VERSION "]"; + +/* Construct a string literal encoding the version number components. */ +#elif defined(COMPILER_VERSION_MAJOR) +char const info_version[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', + COMPILER_VERSION_MAJOR, +# ifdef COMPILER_VERSION_MINOR + '.', COMPILER_VERSION_MINOR, +# ifdef COMPILER_VERSION_PATCH + '.', COMPILER_VERSION_PATCH, +# ifdef COMPILER_VERSION_TWEAK + '.', COMPILER_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct a string literal encoding the internal version number. */ +#ifdef COMPILER_VERSION_INTERNAL +char const info_version_internal[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', + 'i','n','t','e','r','n','a','l','[', + COMPILER_VERSION_INTERNAL,']','\0'}; +#elif defined(COMPILER_VERSION_INTERNAL_STR) +char const* info_version_internal = "INFO" ":" "compiler_version_internal[" COMPILER_VERSION_INTERNAL_STR "]"; +#endif + +/* Construct a string literal encoding the version number components. */ +#ifdef SIMULATE_VERSION_MAJOR +char const info_simulate_version[] = { + 'I', 'N', 'F', 'O', ':', + 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', + SIMULATE_VERSION_MAJOR, +# ifdef SIMULATE_VERSION_MINOR + '.', SIMULATE_VERSION_MINOR, +# ifdef SIMULATE_VERSION_PATCH + '.', SIMULATE_VERSION_PATCH, +# ifdef SIMULATE_VERSION_TWEAK + '.', SIMULATE_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; +char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; + + + +#if defined(__INTEL_COMPILER) && defined(_MSVC_LANG) && _MSVC_LANG < 201403L +# if defined(__INTEL_CXX11_MODE__) +# if defined(__cpp_aggregate_nsdmi) +# define CXX_STD 201402L +# else +# define CXX_STD 201103L +# endif +# else +# define CXX_STD 199711L +# endif +#elif defined(_MSC_VER) && defined(_MSVC_LANG) +# define CXX_STD _MSVC_LANG +#else +# define CXX_STD __cplusplus +#endif + +const char* info_language_standard_default = "INFO" ":" "standard_default[" +#if CXX_STD > 202002L + "23" +#elif CXX_STD > 201703L + "20" +#elif CXX_STD >= 201703L + "17" +#elif CXX_STD >= 201402L + "14" +#elif CXX_STD >= 201103L + "11" +#else + "98" +#endif +"]"; + +const char* info_language_extensions_default = "INFO" ":" "extensions_default[" +#if (defined(__clang__) || defined(__GNUC__) || defined(__xlC__) || \ + defined(__TI_COMPILER_VERSION__)) && \ + !defined(__STRICT_ANSI__) + "ON" +#else + "OFF" +#endif +"]"; + +/*--------------------------------------------------------------------------*/ + +int main(int argc, char* argv[]) +{ + int require = 0; + require += info_compiler[argc]; + require += info_platform[argc]; + require += info_arch[argc]; +#ifdef COMPILER_VERSION_MAJOR + require += info_version[argc]; +#endif +#ifdef COMPILER_VERSION_INTERNAL + require += info_version_internal[argc]; +#endif +#ifdef SIMULATE_ID + require += info_simulate[argc]; +#endif +#ifdef SIMULATE_VERSION_MAJOR + require += info_simulate_version[argc]; +#endif +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) + require += info_cray[argc]; +#endif + require += info_language_standard_default[argc]; + require += info_language_extensions_default[argc]; + (void)argv; + return require; +} diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o new file mode 100644 index 0000000000000000000000000000000000000000..aacee10dfddc5e3114bb159eee743a03c1b12206 GIT binary patch literal 1712 zcmb_cJ#5oZ5PqShqzWV;F@P#TBo?M9PO7SaA|+}-fULGdhCoz3ti(wzIgaHx(6I;x z1_sK?QX~e%#7HI>vr!hr7?|3DoiY%1^Z6O|W@vfbVNlAN;TuDUd5eWoVTAL%&&wQohkn#@ z7xSq-j;d+D)t1v9ZFqXVP40J%U+PcIH{OeU>eqCQsxLdv1IwvNsTapLka_697F8IR1n^Z*cJ-l}YwvWy2!N#ELP!jS<=b%*cH!^r6J`FC4Zht{^ zzsAJjAR)R@A)ZAe`NM;S?e4sFu)LqhccYQ{*#1A{s8`rm?EJ5ueawaVcRtL>&$m`@ ztX-vFW7(!xDY&j}uGogt*bqU+wGF@C@|u;R;o-M&)bOgC753Y{;nWPTCTnKh=-7Vc z$}(qgUQDNLfkwmJ+Umw1e(Z_)ySp2^@ z#c`j+Ps4(Dam47{VX1)UfyFv=G-sR%Pq{mU!DV&cx`aV;sv}u}j^j6kad6amf6w`E zuq1DxRR1GDLcC-=%WFPoe1Y)`!ei?{C5*wsqwOppCjtl9ou4RJe%qk(9hUIXb hB0fW6ys-VIyU6WQZ~(Ik!U4=E2nSG85Dp-5 search starts here: + /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include + /Library/Developer/CommandLineTools/usr/include + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory) +End of search list. +Linking C executable cmTC_5913a +/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_5913a.dir/link.txt --verbose=1 +/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names -v -Wl,-v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -o cmTC_5913a +Apple clang version 13.1.6 (clang-1316.0.21.2.5) +Target: arm64-apple-darwin21.6.0 +Thread model: posix +InstalledDir: /Library/Developer/CommandLineTools/usr/bin + "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_5913a -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a +@(#)PROGRAM:ld PROJECT:ld64-764 +BUILD 11:22:55 Apr 28 2022 +configured to support archs: armv6 armv7 armv7s arm64 arm64e arm64_32 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em +Library search paths: + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib +Framework search paths: + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/ + + + +Parsed C implicit include dir info from above output: rv=done + found start of include info + found start of implicit include info + add: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + add: [/Library/Developer/CommandLineTools/usr/include] + end of search list found + collapse include dir [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] ==> [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + collapse include dir [/Library/Developer/CommandLineTools/usr/include] ==> [/Library/Developer/CommandLineTools/usr/include] + implicit include dirs: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include] + + +Parsed C implicit link information from above output: + link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] + ignore line: [Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-LcrFWX] + ignore line: [] + ignore line: [Run Build Command(s):/usr/bin/make -f Makefile cmTC_5913a/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_5913a.dir/build.make CMakeFiles/cmTC_5913a.dir/build] + ignore line: [Building C object CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o] + ignore line: [/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl -v -MD -MT CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -MF CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o.d -o CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCCompilerABI.c] + ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] + ignore line: [Target: arm64-apple-darwin21.6.0] + ignore line: [Thread model: posix] + ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] + ignore line: [clang: warning: -Wl -v: 'linker' input unused [-Wunused-command-line-argument]] + ignore line: [ "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCCompilerABI.c -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-LcrFWX -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -x c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCCompilerABI.c] + ignore line: [clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0] + ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include"] + ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks"] + ignore line: [#include "..." search starts here:] + ignore line: [#include <...> search starts here:] + ignore line: [ /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + ignore line: [ /Library/Developer/CommandLineTools/usr/include] + ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory)] + ignore line: [End of search list.] + ignore line: [Linking C executable cmTC_5913a] + ignore line: [/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_5913a.dir/link.txt --verbose=1] + ignore line: [/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl -search_paths_first -Wl -headerpad_max_install_names -v -Wl -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -o cmTC_5913a ] + ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] + ignore line: [Target: arm64-apple-darwin21.6.0] + ignore line: [Thread model: posix] + ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] + link line: [ "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_5913a -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + arg [/Library/Developer/CommandLineTools/usr/bin/ld] ==> ignore + arg [-demangle] ==> ignore + arg [-lto_library] ==> ignore, skip following value + arg [/Library/Developer/CommandLineTools/usr/lib/libLTO.dylib] ==> skip value of -lto_library + arg [-dynamic] ==> ignore + arg [-arch] ==> ignore + arg [arm64] ==> ignore + arg [-platform_version] ==> ignore + arg [macos] ==> ignore + arg [12.0.0] ==> ignore + arg [12.3] ==> ignore + arg [-syslibroot] ==> ignore + arg [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk] ==> ignore + arg [-o] ==> ignore + arg [cmTC_5913a] ==> ignore + arg [-search_paths_first] ==> ignore + arg [-headerpad_max_install_names] ==> ignore + arg [-v] ==> ignore + arg [CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o] ==> ignore + arg [-lSystem] ==> lib [System] + arg [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] ==> lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + Library search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + Framework search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] + remove lib [System] + remove lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + collapse library dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + collapse framework dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] + implicit libs: [] + implicit objs: [] + implicit dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + implicit fwks: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] + + +Detecting CXX compiler ABI info compiled with the following output: +Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C + +Run Build Command(s):/usr/bin/make -f Makefile cmTC_48750/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_48750.dir/build.make CMakeFiles/cmTC_48750.dir/build +Building CXX object CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o +/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl,-v -MD -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -MF CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp +Apple clang version 13.1.6 (clang-1316.0.21.2.5) +Target: arm64-apple-darwin21.6.0 +Thread model: posix +InstalledDir: /Library/Developer/CommandLineTools/usr/bin +clang: warning: -Wl,-v: 'linker' input unused [-Wunused-command-line-argument] + "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -D _DARWIN_USE_64_BIT_INODE=1 -D _LARGEFILE_SOURCE -D _FILE_OFFSET_BITS=64 -D BUILDING_NODE_EXTENSION -stdlib=libc++ -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdeprecated-macro -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fno-cxx-modules -fcxx-exceptions -fexceptions -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -x c++ /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp +clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0 +ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include" +ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks" +#include "..." search starts here: +#include <...> search starts here: + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 + /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include + /Library/Developer/CommandLineTools/usr/include + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory) +End of search list. +Linking CXX executable cmTC_48750 +/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_48750.dir/link.txt --verbose=1 +/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names -v -Wl,-v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_48750 +Apple clang version 13.1.6 (clang-1316.0.21.2.5) +Target: arm64-apple-darwin21.6.0 +Thread model: posix +InstalledDir: /Library/Developer/CommandLineTools/usr/bin + "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_48750 -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -lc++ -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a +@(#)PROGRAM:ld PROJECT:ld64-764 +BUILD 11:22:55 Apr 28 2022 +configured to support archs: armv6 armv7 armv7s arm64 arm64e arm64_32 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em +Library search paths: + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib +Framework search paths: + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/ + + + +Parsed CXX implicit include dir info from above output: rv=done + found start of include info + found start of implicit include info + add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] + add: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + add: [/Library/Developer/CommandLineTools/usr/include] + end of search list found + collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] + collapse include dir [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] ==> [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + collapse include dir [/Library/Developer/CommandLineTools/usr/include] ==> [/Library/Developer/CommandLineTools/usr/include] + implicit include dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1;/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include] + + +Parsed CXX implicit link information from above output: + link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] + ignore line: [Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C] + ignore line: [] + ignore line: [Run Build Command(s):/usr/bin/make -f Makefile cmTC_48750/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_48750.dir/build.make CMakeFiles/cmTC_48750.dir/build] + ignore line: [Building CXX object CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o] + ignore line: [/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl -v -MD -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -MF CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp] + ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] + ignore line: [Target: arm64-apple-darwin21.6.0] + ignore line: [Thread model: posix] + ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] + ignore line: [clang: warning: -Wl -v: 'linker' input unused [-Wunused-command-line-argument]] + ignore line: [ "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -D _DARWIN_USE_64_BIT_INODE=1 -D _LARGEFILE_SOURCE -D _FILE_OFFSET_BITS=64 -D BUILDING_NODE_EXTENSION -stdlib=libc++ -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdeprecated-macro -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fno-cxx-modules -fcxx-exceptions -fexceptions -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -x c++ /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp] + ignore line: [clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0] + ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include"] + ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks"] + ignore line: [#include "..." search starts here:] + ignore line: [#include <...> search starts here:] + ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] + ignore line: [ /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + ignore line: [ /Library/Developer/CommandLineTools/usr/include] + ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory)] + ignore line: [End of search list.] + ignore line: [Linking CXX executable cmTC_48750] + ignore line: [/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_48750.dir/link.txt --verbose=1] + ignore line: [/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl -search_paths_first -Wl -headerpad_max_install_names -v -Wl -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_48750 ] + ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] + ignore line: [Target: arm64-apple-darwin21.6.0] + ignore line: [Thread model: posix] + ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] + link line: [ "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_48750 -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -lc++ -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + arg [/Library/Developer/CommandLineTools/usr/bin/ld] ==> ignore + arg [-demangle] ==> ignore + arg [-lto_library] ==> ignore, skip following value + arg [/Library/Developer/CommandLineTools/usr/lib/libLTO.dylib] ==> skip value of -lto_library + arg [-dynamic] ==> ignore + arg [-arch] ==> ignore + arg [arm64] ==> ignore + arg [-platform_version] ==> ignore + arg [macos] ==> ignore + arg [12.0.0] ==> ignore + arg [12.3] ==> ignore + arg [-syslibroot] ==> ignore + arg [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk] ==> ignore + arg [-o] ==> ignore + arg [cmTC_48750] ==> ignore + arg [-search_paths_first] ==> ignore + arg [-headerpad_max_install_names] ==> ignore + arg [-v] ==> ignore + arg [CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o] ==> ignore + arg [-lc++] ==> lib [c++] + arg [-lSystem] ==> lib [System] + arg [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] ==> lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + Library search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + Framework search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] + remove lib [System] + remove lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + collapse library dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + collapse framework dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] + implicit libs: [c++] + implicit objs: [] + implicit dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + implicit fwks: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] + + diff --git a/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache b/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache new file mode 100644 index 00000000..3dccd731 --- /dev/null +++ b/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache @@ -0,0 +1 @@ +# This file is generated by cmake for dependency checking of the CMakeCache.txt file diff --git a/languages/c/templates/sdk/cmake/CopySymlink.cmake b/languages/c/templates/sdk/cmake/CopySymlink.cmake new file mode 100644 index 00000000..b25a5e22 --- /dev/null +++ b/languages/c/templates/sdk/cmake/CopySymlink.cmake @@ -0,0 +1,17 @@ +# 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 + +file(COPY "${LIBRARY}" DESTINATION "${DESTINATION}" FOLLOW_SYMLINK_CHAIN) diff --git a/languages/c/templates/sdk/cmake/HelperFunctions.cmake b/languages/c/templates/sdk/cmake/HelperFunctions.cmake new file mode 100644 index 00000000..bbd7ce65 --- /dev/null +++ b/languages/c/templates/sdk/cmake/HelperFunctions.cmake @@ -0,0 +1,139 @@ +# 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 + +macro(GetSubDirs subdirs currentdir) + file(GLOB subdirectories RELATIVE ${currentdir} ${currentdir}/*) + set(subdirs "") + foreach(subdir ${subdirectories}) + if (IS_DIRECTORY ${currentdir}/${subdir}) + list(APPEND subdirs ${subdir}) + endif() + endforeach() +endmacro() + +function(InstallHeaders) + set(optionsArgs EXCLUDE_ROOT_DIR) + set(oneValueArgs TARGET NAMESPACE SOURCE DESTINATION) + set(multiValueArgs HEADERS) + + cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) + if (Argument_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to InstallHeaders(): \"${Argument_UNPARSED_ARGUMENTS}\"") + endif() + if (Argument_HEADERS) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMENT "=================== Installing Headers ======================" + ) + foreach(directory ${Argument_HEADERS}) + if (Argument_EXCLUDE_ROOT_DIR) + set(destination ${Argument_DESTINATION}) + else() + set(destination ${Argument_DESTINATION}/${directory}) + endif() + + if (Argument_SOURCE) + set(source ${Argument_SOURCE}) + else() + set(source ${CMAKE_CURRENT_LIST_DIR}) + endif() + + GetSubDirs(subdirs ${source}/${directory}) + list(APPEND subdirs ${directory}) + + foreach(subdir ${subdirs}) + set(dest ${destination}/${subdir}) + file(GLOB headers "${source}/${directory}/${subdir}/*.h") + if (headers) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_NAMESPACE}/usr/include/${dest} + COMMAND ${CMAKE_COMMAND} -E copy ${source}/${directory}/${subdir}/*.h ${CMAKE_BINARY_DIR}/${Argument_NAMESPACE}/usr/include/${dest} + ) + endif() + endforeach(subdir) + endforeach(directory) + endif() +endfunction(InstallHeaders) + +function(InstallLibraries) + set(optionsArgs SHARED) + set(oneValueArgs TARGET DESTINATION) + set(multiValueArgs LIBRARIES) + + cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) + if (Argument_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to InstallLibraries(): \"${Argument_UNPARSED_ARGUMENTS}\"") + endif() + if (Argument_LIBRARIES) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMENT "=================== Installing Libraries ======================" + ) + foreach(LIBRARY ${Argument_LIBRARIES}) + if (Argument_SHARED) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + COMMAND ${CMAKE_COMMAND} -D "LIBRARY=${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR}" -D "DESTINATION=${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib" -P ${CMAKE_SOURCE_DIR}/cmake/CopySymlink.cmake + COMMAND ${CMAKE_COMMAND} -D "LIBRARY=${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so" -D "DESTINATION=${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib" -P ${CMAKE_SOURCE_DIR}/cmake/CopySymlink.cmake + ) + else() + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/lib${LIBRARY}.a ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + ) + + endif() + endforeach(LIBRARY) + endif() +endfunction(InstallLibraries) + +function(InstallCMakeConfigs) + set(optionsArgs) + set(oneValueArgs TARGET DESTINATION) + set(multiValueArgs) + + cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) + if (Argument_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to InstallCMakeConfigs(): \"${Argument_UNPARSED_ARGUMENTS}\"") + endif() + if (Argument_TARGET) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMENT "=================== Installing CMakeConfigs ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}Config*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Export/lib/cmake/${Argument_TARGET}/${Argument_TARGET}Targets*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} + ) + if (EXISTS ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}.pc) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/pkgconfig + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}.pc ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/pkgconfig + ) + endif() + endif() +endfunction(InstallCMakeConfigs) diff --git a/languages/c/templates/sdk/cmake/project.cmake.in b/languages/c/templates/sdk/cmake/project.cmake.in new file mode 100644 index 00000000..0855ca12 --- /dev/null +++ b/languages/c/templates/sdk/cmake/project.cmake.in @@ -0,0 +1,30 @@ +# 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 + +set(FIREBOLT_NAMESPACE "@FIREBOLT_NAMESPACE@" CACHE INTERNAL "" FORCE) +set("${FIREBOLT_NAMESPACE}_FOUND" TRUE CACHE INTERNAL "" FORCE) + +list(APPEND CMAKE_MODULE_PATH + "${CMAKE_SOURCE_DIR}/cmake" + "${SYSROOT_PATH}/usr/lib/cmake" + "${SYSROOT_PATH}/usr/lib/cmake/Firebolt" + "${SYSROOT_PATH}/tools/cmake") + +if (NOT DEFINED CMAKE_PREFIX_PATH) + set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) +endif() + + diff --git a/languages/c/templates/sdk/include/Error.h b/languages/c/templates/sdk/include/Error.h new file mode 100644 index 00000000..87cda9dd --- /dev/null +++ b/languages/c/templates/sdk/include/Error.h @@ -0,0 +1,41 @@ +/* + * 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 + */ + +#ifndef _FIREBOLT_ERROR_H +#define _FIREBOLT_ERROR_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum FireboltSDKError { + FireboltSDKErrorNone = 0, + FireboltSDKErrorGeneral = 1, + FireboltSDKErrorUnavailable = 2, + FireboltSDKErrorTimedout = 3, + FireboltSDKErrorNotSubscribed = 4, + FireboltSDKErrorUnknown = 5, + FireboltSDKErrorInUse = 6, + FireboltSDKErrorNotSupported = 7 +} FireboltSDKError_t; + +#ifdef __cplusplus +} +#endif + +#endif // _FIREBOLT_ERROR_H diff --git a/languages/c/templates/sdk/include/Types.h b/languages/c/templates/sdk/include/Types.h new file mode 100644 index 00000000..e7456cdd --- /dev/null +++ b/languages/c/templates/sdk/include/Types.h @@ -0,0 +1,43 @@ +/* + * 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 + */ + +#ifndef _FIREBOLT_TYPES_H +#define _FIREBOLT_TYPES_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + Test1, + Test2, + Test3, + Test4 +} TestEnum; + +typedef void* FireboltTypes_StringHandle; +const char* FireboltTypes_String(FireboltTypes_StringHandle handle); +void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle); + +#ifdef __cplusplus +} +#endif + +#endif // _FIREBOLT_TYPES_H diff --git a/languages/c/templates/sdk/scripts/install.js b/languages/c/templates/sdk/scripts/install.js new file mode 100644 index 00000000..5c332ceb --- /dev/null +++ b/languages/c/templates/sdk/scripts/install.js @@ -0,0 +1,32 @@ +import { createRequire } from 'module'; +const require = createRequire(import.meta.url); +const fs = require('fs'); +const path = require('path'); + +var dest = process.env.NODE_INSTALL_PATH; +var src = 'src/native/build/' + process.env.TARGET_NAME; + +installFiles(src, dest); +function installFiles(src, dest) { + if (!fs.existsSync(dest)) { + fs.mkdirSync(dest); + } + + var entries = fs.readdirSync(src); + entries.forEach((entry) => { + const srcPath = path.join(src, entry); + const destPath = path.join(dest, entry); + const stat = fs.lstatSync(srcPath); + + if (stat.isFile()) { + fs.copyFileSync(srcPath, destPath); + } else if (stat.isDirectory()) { + installFiles(srcPath, destPath); + } else if (stat.isSymbolicLink()) { + if (fs.existsSync(destPath)) { + fs.unlinkSync(destPath); + } + fs.symlinkSync(fs.readlinkSync(srcPath), destPath); + } + }); +} diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.cpp b/languages/c/templates/sdk/src/Accessor/Accessor.cpp new file mode 100644 index 00000000..b4cada4b --- /dev/null +++ b/languages/c/templates/sdk/src/Accessor/Accessor.cpp @@ -0,0 +1,134 @@ +/* + * 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 "Accessor.h" + +namespace FireboltSDK { + + Accessor* Accessor::_singleton = nullptr; + Accessor::Accessor() + : _threadCount(DefaultThreadCount) + , _queueSize(DefaultQueueSize) + , _workerPool() + , _transport(nullptr) + { + _singleton = this; + Config config; + LoadConfigs(config); + + Logger::SetLogLevel(WPEFramework::Core::EnumerateType(config.LogLevel.Value().c_str()).Value()); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Url = %s", config.Url.Value().c_str()); + CreateTransport(config.Url.Value(), config.WaitTime.Value()); + CreateEventHandler(); + + _workerPool = WPEFramework::Core::ProxyType::Create(_threadCount, WPEFramework::Core::Thread::DefaultStackSize(), _queueSize); + WPEFramework::Core::WorkerPool::Assign(&(*_workerPool)); + _workerPool->Run(); + } + + Accessor::~Accessor() + { + DestroyTransport(); + DestroyEventHandler(); + WPEFramework::Core::IWorkerPool::Assign(nullptr); + _workerPool->Stop(); + _singleton = nullptr; + } + + void Accessor::LoadConfigs(Config& config) + { + string prefixPath; + WPEFramework::Core::SystemInfo::GetEnvironment("OPENRPC_NATIVE_SDK_PREFIX", prefixPath); + string configFilePath = (prefixPath.empty() != true) ? + (prefixPath + '/' + Accessor::ConfigFile) : Accessor::ConfigFile; + WPEFramework::Core::File configFile(configFilePath); + + if (configFile.Open(true) == true) { + WPEFramework::Core::OptionalType error; + config.IElement::FromFile(configFile, error); + if (error.IsSet() == true) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in reading config"); + } + } + } + + uint32_t Accessor::CreateEventHandler() + { + Event::Instance().Configure(_transport); + return FireboltSDKErrorNone; + } + + uint32_t Accessor::DestroyEventHandler() + { + Event::Dispose(); + return FireboltSDKErrorNone; + } + + Event& Accessor::GetEventManager() + { + return Event::Instance(); + } + + uint32_t Accessor::CreateTransport(const string& url, const uint32_t waitTime) + { + if (_transport != nullptr) { + delete _transport; + } + + _transport = new Transport(static_cast(url), waitTime); + if (WaitForLinkReady(_transport, DefaultWaitTime) != FireboltSDKErrorNone) { + delete _transport; + _transport = nullptr; + } + + ASSERT(_transport != nullptr); + return ((_transport != nullptr) ? FireboltSDKErrorNone : FireboltSDKErrorUnavailable); + } + + uint32_t Accessor::DestroyTransport() + { + if (_transport != nullptr) { + delete _transport; + _transport = nullptr; + } + return FireboltSDKErrorNone; + } + + Transport* Accessor::GetTransport() + { + ASSERT(_transport != nullptr); + return _transport; + } + + uint32_t Accessor::WaitForLinkReady(Transport* transport, const uint32_t waitTime = DefaultWaitTime) { + uint32_t waiting = (waitTime == WPEFramework::Core::infinite ? WPEFramework::Core::infinite : waitTime); + static constexpr uint32_t SLEEPSLOT_TIME = 100; + + // Right, a wait till connection is closed is requested.. + while ((waiting > 0) && (transport->IsOpen() == false)) { + + uint32_t sleepSlot = (waiting > SLEEPSLOT_TIME ? SLEEPSLOT_TIME : waiting); + + // Right, lets sleep in slices of 100 ms + SleepMs(sleepSlot); + + waiting -= (waiting == WPEFramework::Core::infinite ? 0 : sleepSlot); + } + return (((waiting == 0) || (transport->IsOpen() == true)) ? FireboltSDKErrorNone : FireboltSDKErrorTimedout); + } +} diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.h b/languages/c/templates/sdk/src/Accessor/Accessor.h new file mode 100644 index 00000000..3e9b8784 --- /dev/null +++ b/languages/c/templates/sdk/src/Accessor/Accessor.h @@ -0,0 +1,79 @@ +/* + * 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 "Module.h" +#include "Config.h" +#include "WorkerPool.h" +#include "Transport/Transport.h" +#include "Event/Event.h" +#include "Logger/Logger.h" + +namespace FireboltSDK { + class Accessor { + private: + static constexpr uint8_t JSONVersion = 2; + static constexpr const TCHAR* ConfigFile = _T("/etc/Firebolt/config.json"); + static constexpr uint32_t DefaultWaitTime = 1000; + static constexpr uint8_t DefaultQueueSize = 8; + static constexpr uint8_t DefaultThreadCount = 3; + + public: + Accessor(const Accessor&) = delete; + Accessor& operator= (const Accessor&) = delete; + + Accessor(); + ~Accessor(); + + static Accessor& Instance() + { + static Accessor *instance = new Accessor(); + ASSERT(instance != nullptr); + return *instance; + } + + static void Dispose() + { + ASSERT(_singleton != nullptr); + + if (_singleton != nullptr) { + delete _singleton; + } + } + + uint32_t CreateEventHandler(); + uint32_t DestroyEventHandler(); + Event& GetEventManager(); + + uint32_t CreateTransport(const string& url, const uint32_t waitTime); + uint32_t DestroyTransport(); + Transport* GetTransport(); + uint32_t WaitForLinkReady(Transport* transport, const uint32_t waitTime); + + private: + void LoadConfigs(Config& config); + + private: + uint8_t _threadCount; + uint8_t _queueSize; + WPEFramework::Core::ProxyType _workerPool; + Transport* _transport; + static Accessor* _singleton; + }; +} diff --git a/languages/c/templates/sdk/src/Accessor/Config.h b/languages/c/templates/sdk/src/Accessor/Config.h new file mode 100644 index 00000000..f8389bf6 --- /dev/null +++ b/languages/c/templates/sdk/src/Accessor/Config.h @@ -0,0 +1,41 @@ +/* + * 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 + */ + +namespace FireboltSDK { + class EXTERNAL Config : public WPEFramework::Core::JSON::Container { + public: + Config(const Config&) = delete; + Config& operator=(const Config&) = delete; + + Config() + : WPEFramework::Core::JSON::Container() + , Url(_T("")) + , WaitTime(1000) + , LogLevel(_T("Info")) + { + Add(_T("url"), &Url); + Add(_T("waittime"), &WaitTime); + Add(_T("loglevel"), &LogLevel); + } + + public: + WPEFramework::Core::JSON::String Url; + WPEFramework::Core::JSON::DecUInt32 WaitTime; + WPEFramework::Core::JSON::String LogLevel; + }; +} diff --git a/languages/c/templates/sdk/src/Accessor/WorkerPool.h b/languages/c/templates/sdk/src/Accessor/WorkerPool.h new file mode 100644 index 00000000..521ccc65 --- /dev/null +++ b/languages/c/templates/sdk/src/Accessor/WorkerPool.h @@ -0,0 +1,72 @@ +/* + * 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 "Module.h" + +namespace FireboltSDK { + + class WorkerPoolImplementation : public WPEFramework::Core::WorkerPool { + public: + WorkerPoolImplementation() = delete; + WorkerPoolImplementation(const WorkerPoolImplementation&) = delete; + WorkerPoolImplementation& operator=(const WorkerPoolImplementation&) = delete; + + WorkerPoolImplementation(const uint8_t threads, const uint32_t stackSize, const uint32_t queueSize) + : WorkerPool(threads, stackSize, queueSize, &_dispatcher) + { + } + + ~WorkerPoolImplementation() + { + // Diable the queue so the minions can stop, even if they are processing and waiting for work.. + Stop(); + } + + public: + void Stop() + { + WPEFramework::Core::WorkerPool::Stop(); + } + + void Run() + { + WPEFramework::Core::WorkerPool::Run(); + } + + private: + class Dispatcher : public WPEFramework::Core::ThreadPool::IDispatcher { + public: + Dispatcher(const Dispatcher&) = delete; + Dispatcher& operator=(const Dispatcher&) = delete; + + Dispatcher() = default; + ~Dispatcher() override = default; + + private: + void Initialize() override { } + void Deinitialize() override { } + void Dispatch(WPEFramework::Core::IDispatch* job) override + { job->Dispatch(); } + }; + + Dispatcher _dispatcher; + }; + +} diff --git a/languages/c/templates/sdk/src/CMakeLists.txt b/languages/c/templates/sdk/src/CMakeLists.txt new file mode 100644 index 00000000..c411582a --- /dev/null +++ b/languages/c/templates/sdk/src/CMakeLists.txt @@ -0,0 +1,93 @@ +# 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 + +cmake_minimum_required(VERSION 3.3) + +project(FireboltSDK) +project_version(1.0.0) +set(TARGET ${PROJECT_NAME}) +message("Setup ${TARGET} v${PROJECT_VERSION}") + +add_library(${TARGET} SHARED + Types.cpp + Module.cpp + Logger/Logger.cpp + Transport/Transport.cpp + Accessor/Accessor.cpp + Event/Event.cpp) + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +find_package(${NAMESPACE}Core CONFIG REQUIRED) +find_package(${NAMESPACE}WebSocket CONFIG REQUIRED) + +target_link_libraries(${TARGET} + PUBLIC + ${NAMESPACE}Core::${NAMESPACE}Core + ${NAMESPACE}WebSocket::${NAMESPACE}WebSocket +) + +target_include_directories(${TARGET} + PRIVATE + $ + $ + $ +) + +set_target_properties(${TARGET} PROPERTIES + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED YES + FRAMEWORK FALSE + LINK_WHAT_YOU_USE TRUE + VERSION ${PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} +) + +install( + TARGETS ${TARGET} EXPORT ${TARGET}Targets + LIBRARY DESTINATION lib COMPONENT libs + PUBLIC_HEADER DESTINATION include/${TARGET} COMPONENT devel # headers for mac (note the different component -> different package) + INCLUDES DESTINATION include/${TARGET} # headers +) + +InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION ${FIREBOLT_NAMESPACE}SDK) +InstallHeaders(TARGET ${TARGET} EXCLUDE_ROOT_DIR HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} + SOURCE ${GENERATED_CODE_PATH}/include DESTINATION ${FIREBOLT_NAMESPACE}/generated) +InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} + SOURCE ${CMAKE_SOURCE_DIR}/include DESTINATION ${FIREBOLT_NAMESPACE}) + +InstallLibraries(TARGET ${TARGET} SHARED LIBRARIES ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallCMakeConfig(TARGETS ${TARGET}) +InstallPackageConfig(TARGETS ${TARGET} DESCRIPTION "Firebolt SDK Library") +InstallCMakeConfigs(TARGET ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) + +add_custom_command( + TARGET ${TARGET} + POST_BUILD + COMMENT "=================== Installing JsonConfig ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/etc/${FIREBOLT_NAMESPACE} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/config/${TARGET}.json ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/etc/${FIREBOLT_NAMESPACE}/config.json +) + +add_custom_command( + TARGET ${TARGET} + POST_BUILD + COMMENT "=================== Installing FireboltConfig & Helper CMakes ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/cmake/*.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} +) + +include(Config.cmake) diff --git a/languages/c/templates/sdk/src/Config.cmake b/languages/c/templates/sdk/src/Config.cmake new file mode 100644 index 00000000..a420ce32 --- /dev/null +++ b/languages/c/templates/sdk/src/Config.cmake @@ -0,0 +1,34 @@ +# 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 + +set(SERVER_PORT 9998 CACHE STRING "The port of the server") +set(SERVER_ADDRESS "127.0.0.1" CACHE STRING "The address of the server") + + #[[ ================================ Add additional config above this line ================================ ]] + + +find_package(ConfigGenerator REQUIRED) + +write_config( + SKIP_COMPARE + SKIP_CLASSNAME + SKIP_LOCATOR + DISABLE_LEGACY_GENERATOR + CUSTOM_PARAMS_WHITELIST "${CMAKE_CURRENT_LIST_DIR}/Params.config" + INSTALL_PATH "${CMAKE_INSTALL_PREFIX}/../etc/" + INSTALL_NAME "config.json" +) + diff --git a/languages/c/templates/sdk/src/Event/Event.cpp b/languages/c/templates/sdk/src/Event/Event.cpp new file mode 100644 index 00000000..69b448f6 --- /dev/null +++ b/languages/c/templates/sdk/src/Event/Event.cpp @@ -0,0 +1,148 @@ +/* + * 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 "Transport/Transport.h" +#include "Event.h" + +namespace FireboltSDK { + Event* Event::_singleton = nullptr; + Event::Event() + : _id(0) + , _eventMap() + , _adminLock() + , _transport(nullptr) + { + ASSERT(_singleton == nullptr); + _singleton = this; + } + + Event::~Event() /* override */ + { + _transport->SetEventHandler(nullptr); + _transport = nullptr; + + _singleton = nullptr; + } + + /* static */ Event& Event::Instance() + { + static Event *instance = new Event(); + ASSERT(instance != nullptr); + return *instance; + } + + /* static */ void Event::Dispose() + { + ASSERT(_singleton != nullptr); + + if (_singleton != nullptr) { + delete _singleton; + } + } + + void Event::Configure(Transport* transport) + { + _transport = transport; + _transport->SetEventHandler(this); + } + + uint32_t Event::Unsubscribe(const string& eventName, const uint32_t id) + { + uint32_t status = Revoke(eventName, id); + + if (status == FireboltSDKErrorNone) { + if (_transport != nullptr) { + + const string parameters("{\"listen\":false}"); + status = _transport->Unsubscribe(eventName, parameters); + } + } + return ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone: status); + } + + uint32_t Event::ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) /* override */ + { + uint32_t result = FireboltSDKErrorGeneral; + Response response; + _transport->FromMessage((WPEFramework::Core::JSON::IElement*)&response, *jsonResponse); + if (response.Listening.IsSet() == true) { + result = FireboltSDKErrorNone; + enabled = response.Listening.Value(); + } + return result; + } + + uint32_t Event::Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) /* override */ + { + string response = jsonResponse->Result.Value(); + _adminLock.Lock(); + EventMap::iterator eventIndex = _eventMap.find(eventName); + if (eventIndex != _eventMap.end()) { + IdMap::iterator idIndex = eventIndex->second.begin(); + while(idIndex != eventIndex->second.end()) { + State state; + if (idIndex->second.state != State::REVOKED) { + idIndex->second.state = State::EXECUTING; + } + state = idIndex->second.state; + _adminLock.Unlock(); + if (state == State::EXECUTING) { + idIndex->second.lambda(idIndex->second.userdata, (jsonResponse->Result.Value())); + } + _adminLock.Lock(); + if (idIndex->second.state == State::REVOKED) { + idIndex = eventIndex->second.erase(idIndex); + if (eventIndex->second.size() == 0) { + _eventMap.erase(eventIndex); + } + } else { + idIndex->second.state = State::IDLE; + idIndex++; + } + } + } + _adminLock.Unlock(); + + return FireboltSDKErrorNone;; + } + + uint32_t Event::Revoke(const string& eventName, const uint32_t id) + { + uint32_t status = FireboltSDKErrorNone; + _adminLock.Lock(); + EventMap::iterator eventIndex = _eventMap.find(eventName); + if (eventIndex != _eventMap.end()) { + IdMap::iterator idIndex = eventIndex->second.find(id); + if (idIndex->second.state != State::EXECUTING) { + if (idIndex != eventIndex->second.end()) { + eventIndex->second.erase(idIndex); + } + } else { + idIndex->second.state = State::REVOKED; + } + if (eventIndex->second.size() == 0) { + _eventMap.erase(eventIndex); + } else { + status = FireboltSDKErrorInUse; + } + } + _adminLock.Unlock(); + + return status; + } +} diff --git a/languages/c/templates/sdk/src/Event/Event.h b/languages/c/templates/sdk/src/Event/Event.h new file mode 100644 index 00000000..df9b1dc9 --- /dev/null +++ b/languages/c/templates/sdk/src/Event/Event.h @@ -0,0 +1,154 @@ +/* + * 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 "Module.h" + +namespace FireboltSDK { + + static constexpr uint32_t DefaultWaitTime = 1000; + + class Event : public IEventHandler { + public: + typedef std::function DispatchFunction; + private: + enum State : uint8_t { + IDLE, + EXECUTING, + REVOKED + }; + + struct CallbackData { + const DispatchFunction lambda; + const void* userdata; + State state; + }; + using IdMap = std::map; + using EventMap = std::map; + + + class Response : public WPEFramework::Core::JSON::Container { + public: + Response& operator=(const Response&) = delete; + Response() + : WPEFramework::Core::JSON::Container() + , Listening(false) + { + Add(_T("listening"), &Listening); + } + Response(const Response& copy) + : WPEFramework::Core::JSON::Container() + , Listening(copy.Listening) + { + Add(_T("listening"), &Listening); + } + ~Response() override = default; + + public: + WPEFramework::Core::JSON::Boolean Listening; + }; + + public: + Event(); + ~Event() override; + static Event& Instance(); + static void Dispose(); + void Configure(Transport* transport); + + public: + template + uint32_t Subscribe(const string& eventName, const CALLBACK& callback, const void* userdata, uint32_t& id) + { + uint32_t status = FireboltSDKErrorUnavailable; + if (_transport != nullptr) { + + status = Assign(eventName, callback, userdata, id); + if (status == FireboltSDKErrorNone) { + const string parameters("{\"listen\":true}"); + Response response; + status = _transport->Subscribe(eventName, parameters, response); + + if (status != FireboltSDKErrorNone) { + Revoke(eventName, id); + } else if ((response.Listening.IsSet() == true) && + (response.Listening.Value() == true)) { + status = FireboltSDKErrorNone; + } else { + status = FireboltSDKErrorNotSubscribed; + } + } + } + + return ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone: status); + } + + uint32_t Unsubscribe(const string& eventName, const uint32_t id); + + private: + template + uint32_t Assign(const string& eventName, const CALLBACK& callback, const void* userdata, uint32_t& id) + { + uint32_t status = FireboltSDKErrorNone; + id = Id(); + std::function actualCallback = callback; + DispatchFunction implementation = [actualCallback](const void* userdata, const string& parameters) -> uint32_t { + + WPEFramework::Core::ProxyType inbound = WPEFramework::Core::ProxyType::Create(); + inbound->FromString(parameters); + actualCallback(userdata, static_cast(&inbound)); + return (FireboltSDKErrorNone); + }; + CallbackData callbackData = {implementation, userdata, State::IDLE}; + + _adminLock.Lock(); + EventMap::iterator eventIndex = _eventMap.find(eventName); + if (eventIndex != _eventMap.end()) { + // Already registered, no need to register again; + status = FireboltSDKErrorInUse; + eventIndex->second.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(callbackData)); + } else { + + IdMap idMap; + idMap.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(callbackData)); + _eventMap.emplace(std::piecewise_construct, std::forward_as_tuple(eventName), std::forward_as_tuple(idMap)); + + } + + _adminLock.Unlock(); + return status; + } + uint32_t Revoke(const string& eventName, const uint32_t id); + + private: + uint32_t Id() const + { + return (++_id); + } + uint32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) override; + uint32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) override; + + private: + mutable std::atomic _id; + EventMap _eventMap; + WPEFramework::Core::CriticalSection _adminLock; + Transport* _transport; + + static Event* _singleton; + }; +} diff --git a/languages/c/templates/sdk/src/Firebolt.h b/languages/c/templates/sdk/src/Firebolt.h new file mode 100644 index 00000000..6a8f51a2 --- /dev/null +++ b/languages/c/templates/sdk/src/Firebolt.h @@ -0,0 +1,25 @@ +/* + * 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 "Transport/Transport.h" +#include "Properties/Properties.h" +#include "Accessor/Accessor.h" +#include "Logger/Logger.h" +#include "Types.h" diff --git a/languages/c/templates/sdk/src/FireboltSDK.conf.in b/languages/c/templates/sdk/src/FireboltSDK.conf.in new file mode 100644 index 00000000..6964a7bc --- /dev/null +++ b/languages/c/templates/sdk/src/FireboltSDK.conf.in @@ -0,0 +1,3 @@ +url = "@FIREBOLT_SERVER_URL@" +waittime = "@FIREBOLT_TRANSPORT_WAITTIME@" +loglevel = "@FIREBOLT_LOGLEVEL@" diff --git a/languages/c/templates/sdk/src/Logger/Logger.cpp b/languages/c/templates/sdk/src/Logger/Logger.cpp new file mode 100644 index 00000000..8acd8a14 --- /dev/null +++ b/languages/c/templates/sdk/src/Logger/Logger.cpp @@ -0,0 +1,84 @@ +/* + * 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 "Module.h" +#include "Error.h" +#include "Logger.h" + +namespace WPEFramework { + +ENUM_CONVERSION_BEGIN(FireboltSDK::Logger::LogLevel) + + { FireboltSDK::Logger::LogLevel::Error, _TXT("Error") }, + { FireboltSDK::Logger::LogLevel::Warning, _TXT("Warning") }, + { FireboltSDK::Logger::LogLevel::Info, _TXT("Info") }, + { FireboltSDK::Logger::LogLevel::Debug, _TXT("Debug") }, + +ENUM_CONVERSION_END(FireboltSDK::Logger::LogLevel) + +ENUM_CONVERSION_BEGIN(FireboltSDK::Logger::Category) + + { FireboltSDK::Logger::Category::OpenRPC, _TXT("FireboltSDK::OpenRPC") }, + { FireboltSDK::Logger::Category::Core, _TXT("FireboltSDK::Core") }, + { FireboltSDK::Logger::Category::Management, _TXT("FireboltSDK::Management") }, + { FireboltSDK::Logger::Category::Discovery, _TXT("FireboltSDK::Discovery") }, + +ENUM_CONVERSION_END(FireboltSDK::Logger::Category) + +} + +namespace FireboltSDK { + /* static */ Logger::LogLevel Logger::_logLevel = Logger::LogLevel::Error; + + uint32_t Logger::SetLogLevel(Logger::LogLevel logLevel) + { + ASSERT(logLevel < Logger::LogLevel::MaxLevel); + uint32_t status = FireboltSDKErrorNotSupported; + if (logLevel < Logger::LogLevel::MaxLevel) { + _logLevel = logLevel; + status = FireboltSDKErrorNone; + } + printf("logLevel = %d _logLevel = %d\n", logLevel, _logLevel); + return status; + } + + void Logger::Log(LogLevel logLevel, Category category, const std::string& module, const std::string file, const std::string function, const uint16_t line, const std::string& format, ...) + { + if (logLevel <= _logLevel) { + va_list arg; + char msg[Logger::MaxBufSize]; + va_start(arg, format); + int length = vsnprintf(msg, Logger::MaxBufSize, format.c_str(), arg); + va_end(arg); + + uint32_t position = (length >= Logger::MaxBufSize) ? (Logger::MaxBufSize - 1) : length; + msg[position] = '\0'; + + char formattedMsg[Logger::MaxBufSize]; + const string time = WPEFramework::Core::Time::Now().ToTimeOnly(true); + const string categoryName = WPEFramework::Core::EnumerateType(category).Data(); + if (categoryName.empty() != true) { + sprintf(formattedMsg, "--->\033[1;32m[%s]:[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), categoryName.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); + } else { + sprintf(formattedMsg, "--->\033[1;32m[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); + } + LOG_MESSAGE(formattedMsg); + } + } +} + diff --git a/languages/c/templates/sdk/src/Logger/Logger.h b/languages/c/templates/sdk/src/Logger/Logger.h new file mode 100644 index 00000000..cffeff54 --- /dev/null +++ b/languages/c/templates/sdk/src/Logger/Logger.h @@ -0,0 +1,85 @@ +/* + * 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 "Types.h" + +namespace FireboltSDK { + + class Logger { + private: + static constexpr uint16_t MaxBufSize = 512; + + public: + enum class LogLevel : uint8_t { + Error, + Warning, + Info, + Debug, + MaxLevel + }; + + enum class Category : uint8_t { + OpenRPC, + Core, + Management, + Discovery + }; + + public: + Logger() = default; + Logger(const Logger&) = delete; + Logger& operator=(const Logger&) = delete; + ~Logger() = default; + + public: + static uint32_t SetLogLevel(LogLevel logLevel); + static void Log(LogLevel logLevel, Category category, const std::string& module, const std::string file, const std::string function, const uint16_t line, const std::string& format, ...); + + public: + template + static const string Module() + { + return WPEFramework::Core::ClassNameOnly(typeid(CLASS).name()).Text(); + } + + private: + static LogLevel _logLevel; + }; +} + +#define FIREBOLT_LOG(level, category, module, ...) \ + FireboltSDK::Logger::Log(level, category, module, __FILE__, __func__, __LINE__, __VA_ARGS__) + +#define FIREBOLT_LOG_ERROR(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Error, category, module, __VA_ARGS__) +#define FIREBOLT_LOG_WARNING(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Warning, category, module, __VA_ARGS__) +#define FIREBOLT_LOG_INFO(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Info, category, module, __VA_ARGS__) +#define FIREBOLT_LOG_DEBUG(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Debug, category, module, __VA_ARGS__) + +#ifdef ENABLE_SYSLOG +#define LOG_MESSAGE(message) \ + syslog(sLOG_NOTIC, "%s", message); +#else +#define LOG_MESSAGE(message) \ + fprintf(stderr, "%s", message); fflush(stdout); +#endif diff --git a/languages/c/templates/schemas/src/Module.cpp b/languages/c/templates/sdk/src/Module.cpp similarity index 85% rename from languages/c/templates/schemas/src/Module.cpp rename to languages/c/templates/sdk/src/Module.cpp index 26a26050..d63badc4 100644 --- a/languages/c/templates/schemas/src/Module.cpp +++ b/languages/c/templates/sdk/src/Module.cpp @@ -16,14 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 */ -/* ${IMPORTS} */ +#include "Module.h" - -namespace FireboltSDK { - - namespace ${info.title} { - - /* ${METHODS} */ - - } -} +MODULE_NAME_DECLARATION(BUILD_REFERENCE) diff --git a/languages/c/templates/sdk/main.cpp b/languages/c/templates/sdk/src/Module.h similarity index 61% rename from languages/c/templates/sdk/main.cpp rename to languages/c/templates/sdk/src/Module.h index a9f2f5ca..5107d93e 100644 --- a/languages/c/templates/sdk/main.cpp +++ b/languages/c/templates/sdk/src/Module.h @@ -1,5 +1,5 @@ /* - * Copyright 2021 Comcast Cable Communications Management, LLC + * 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. @@ -16,15 +16,16 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { setMockResponses } from './Transport/MockTransport.mjs' +#pragma once -/* ${MOCK_IMPORTS} */ +#ifndef MODULE_NAME +#define MODULE_NAME OpenRPCNativeSDK +#endif -setMockResponses({ - /* ${MOCK_OBJECTS} */ -}) +#include +#include +#include +#include -/* ${EXPORTS} */ -export { default as Log } from './Log/index.mjs' -export { default as Events } from './Events/index.mjs' -export { default as Settings } from './Settings/index.mjs' +#undef EXTERNAL +#define EXTERNAL diff --git a/languages/c/templates/sdk/src/Params.config b/languages/c/templates/sdk/src/Params.config new file mode 100644 index 00000000..71a58750 --- /dev/null +++ b/languages/c/templates/sdk/src/Params.config @@ -0,0 +1,3 @@ +url +waittime +loglevel diff --git a/languages/c/templates/sdk/src/Properties/Properties.h b/languages/c/templates/sdk/src/Properties/Properties.h new file mode 100644 index 00000000..611811f8 --- /dev/null +++ b/languages/c/templates/sdk/src/Properties/Properties.h @@ -0,0 +1,90 @@ +/* + * 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 "Accessor/Accessor.h" +#include "Event/Event.h" + +namespace FireboltSDK { + + class Properties { + public: + Properties(const Properties&) = delete; + Properties& operator= (const Properties&) = delete; + + Properties() = default; + ~Properties() = default; + + public: + template + static uint32_t Get(const string& propertyName, WPEFramework::Core::ProxyType& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject parameters; + RESPONSETYPE responseType; + status = transport->Invoke(propertyName, parameters, responseType); + if (status == FireboltSDKErrorNone) { + ASSERT(response.IsValid() == false); + if (response.IsValid() == true) { + response.Release(); + } + response = WPEFramework::Core::ProxyType::Create(); + (*response) = responseType; + } + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static uint32_t Set(const string& propertyName, const PARAMETERS& parameters) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject responseType; + status = transport->Invoke(propertyName, parameters, responseType); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static uint32_t Subscribe(const string& propertyName, const CALLBACK& callback, const void* userdata, uint32_t& id) + { + return Event::Instance().Subscribe(EventName(propertyName), callback, userdata, id); + } + + static uint32_t Unsubscribe(const string& propertyName, const uint32_t id) + { + return Event::Instance().Unsubscribe(EventName(propertyName), id); + } + private: + static inline string EventName(const string& propertyName) { + size_t pos = propertyName.find_first_of('.'); + return string(propertyName.substr(0, pos + 1) + "on" + propertyName.substr(pos + 1) + "Changed"); + } + }; +} diff --git a/languages/c/templates/schemas/include/Module.h b/languages/c/templates/sdk/src/Transport/Transport.cpp similarity index 96% rename from languages/c/templates/schemas/include/Module.h rename to languages/c/templates/sdk/src/Transport/Transport.cpp index 4cee1781..280944c6 100644 --- a/languages/c/templates/schemas/include/Module.h +++ b/languages/c/templates/sdk/src/Transport/Transport.cpp @@ -16,8 +16,9 @@ * SPDX-License-Identifier: Apache-2.0 */ -namespace FireboltSDK { +#include "Transport.h" - /* ${DECLARATIONS} */ +namespace FireboltSDK { } + diff --git a/languages/c/templates/sdk/src/Transport/Transport.h b/languages/c/templates/sdk/src/Transport/Transport.h new file mode 100644 index 00000000..e0bff38c --- /dev/null +++ b/languages/c/templates/sdk/src/Transport/Transport.h @@ -0,0 +1,897 @@ +/* + * 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 "Module.h" +#include "Error.h" + +namespace FireboltSDK { + + using namespace WPEFramework::Core::TypeTraits; + + template + class CommunicationChannel { + public: + typedef std::function Callback; + class Entry { + private: + Entry(const Entry&) = delete; + Entry& operator=(const Entry& rhs) = delete; + struct Synchronous { + Synchronous() + : _signal(false, true) + , _response() + { + } + WPEFramework::Core::Event _signal; + std::list> _response; + }; + struct ASynchronous { + ASynchronous(const uint32_t waitTime, const Callback& completed) + : _waitTime(WPEFramework::Core::Time::Now().Add(waitTime).Ticks()) + , _completed(completed) + { + } + uint64_t _waitTime; + Callback _completed; + }; + + public: + Entry() + : _synchronous(true) + , _info() + { + } + Entry(const uint32_t waitTime, const Callback& completed) + : _synchronous(false) + , _info(waitTime, completed) + { + } + ~Entry() + { + if (_synchronous == true) { + _info.sync.~Synchronous(); + } + else { + _info.async.~ASynchronous(); + } + } + + public: + const WPEFramework::Core::ProxyType& Response() const + { + return (*(_info.sync._response.begin())); + } + bool Signal(const WPEFramework::Core::ProxyType& response) + { + if (_synchronous == true) { + _info.sync._response.push_back(response); + _info.sync._signal.SetEvent(); + } + else { + _info.async._completed(*response); + } + + return (_synchronous == false); + } + const uint64_t& Expiry() const + { + return (_info.async._waitTime); + } + void Abort(const uint32_t id) + { + if (_synchronous == true) { + _info.sync._signal.SetEvent(); + } + else { + MESSAGETYPE message; + ToMessage(id, message, WPEFramework::Core::ERROR_ASYNC_ABORTED); + _info.async._completed(message); + } + } + bool Expired(const uint32_t id, const uint64_t& currentTime, uint64_t& nextTime) + { + bool expired = false; + + if (_synchronous == false) { + if (_info.async._waitTime > currentTime) { + if (_info.async._waitTime < nextTime) { + nextTime = _info.async._waitTime; + } + } + else { + MESSAGETYPE message; + ToMessage(id, message, WPEFramework::Core::ERROR_TIMEDOUT); + _info.async._completed(message); + expired = true; + } + } + return (expired); + } + bool WaitForResponse(const uint32_t waitTime) + { + return (_info.sync._signal.Lock(waitTime) == WPEFramework::Core::ERROR_NONE); + } + + private: + void ToMessage(const uint32_t id, WPEFramework::Core::JSONRPC::Message& message, uint32_t error) + { + message.Id = id; + message.Error.Code = error; + switch (error) { + case WPEFramework::Core::ERROR_ASYNC_ABORTED: { + message.Error.Text = _T("Pending a-sync call has been aborted"); + break; + } + case WPEFramework::Core::ERROR_TIMEDOUT: { + message.Error.Text = _T("Pending a-sync call has timed out"); + break; + } + } + } + + bool _synchronous; + union Info { + public: + Info() + : sync() + { + } + Info(const uint32_t waitTime, const Callback& completed) + : async(waitTime, completed) + { + } + ~Info() + { + } + Synchronous sync; + ASynchronous async; + } _info; + }; + + + + private: + class FactoryImpl { + private: + FactoryImpl(const FactoryImpl&) = delete; + FactoryImpl& operator=(const FactoryImpl&) = delete; + + class WatchDog { + private: + WatchDog() = delete; + WatchDog& operator=(const WatchDog&) = delete; + + public: + WatchDog(CLIENT* client) + : _client(client) + { + } + WatchDog(const WatchDog& copy) + : _client(copy._client) + { + } + ~WatchDog() + { + } + + bool operator==(const WatchDog& rhs) const + { + return (rhs._client == _client); + } + bool operator!=(const WatchDog& rhs) const + { + return (!operator==(rhs)); + } + + public: + uint64_t Timed(const uint64_t scheduledTime) { + return (_client->Timed()); + } + + private: + CLIENT* _client; + }; + + friend WPEFramework::Core::SingletonType; + + FactoryImpl() + : _messageFactory(2) + , _watchDog(WPEFramework::Core::Thread::DefaultStackSize(), _T("TransportCleaner")) + { + } + + public: + static FactoryImpl& Instance() + { + return (WPEFramework::Core::SingletonType::Instance()); + } + + ~FactoryImpl() + { + } + + public: + WPEFramework::Core::ProxyType Element(const string&) + { + return (_messageFactory.Element()); + } + void Trigger(const uint64_t& time, CLIENT* client) + { + _watchDog.Trigger(time, client); + } + void Revoke(CLIENT* client) + { + _watchDog.Revoke(client); + } + private: + WPEFramework::Core::ProxyPoolType _messageFactory; + WPEFramework::Core::TimerType _watchDog; + }; + + class ChannelImpl : public WPEFramework::Core::StreamJSONType, FactoryImpl&, INTERFACE> { + private: + ChannelImpl(const ChannelImpl&) = delete; + ChannelImpl& operator=(const ChannelImpl&) = delete; + + typedef WPEFramework::Core::StreamJSONType, FactoryImpl&, INTERFACE> BaseClass; + + public: + ChannelImpl(CommunicationChannel* parent, const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask) + : BaseClass(5, FactoryImpl::Instance(), path, _T("JSON"), query, "", false, mask, false, remoteNode.AnyInterface(), remoteNode, 256, 256) + , _parent(*parent) + { + } + ~ChannelImpl() override = default; + + public: + void Received(WPEFramework::Core::ProxyType& response) override + { + WPEFramework::Core::ProxyType inbound(response); + + ASSERT(inbound.IsValid() == true); + if (inbound.IsValid() == true) { + _parent.Inbound(inbound); + } + } + void Send(WPEFramework::Core::ProxyType& msg) override + { +#ifdef __DEBUG__ + string message; + ToMessage(msg, message); + TRACE_L1("Message: %s send", message.c_str()); +#endif + } + void StateChange() override + { + _parent.StateChange(); + } + bool IsIdle() const override + { + return (true); + } + + private: + void ToMessage(const WPEFramework::Core::ProxyType& jsonObject, string& message) const + { + WPEFramework::Core::ProxyType inbound(jsonObject); + + ASSERT(inbound.IsValid() == true); + if (inbound.IsValid() == true) { + inbound->ToString(message); + } + } + void ToMessage(const WPEFramework::Core::ProxyType& jsonObject, string& message) const + { + WPEFramework::Core::ProxyType inbound(jsonObject); + + ASSERT(inbound.IsValid() == true); + if (inbound.IsValid() == true) { + std::vector values; + inbound->ToBuffer(values); + if (values.empty() != true) { + WPEFramework::Core::ToString(values.data(), static_cast(values.size()), false, message); + } + } + } + + private: + CommunicationChannel& _parent; + }; + + protected: + CommunicationChannel(const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask) + : _channel(this, remoteNode, path, query, mask) + , _sequence(0) + { + } + + public: + ~CommunicationChannel() = default; + static WPEFramework::Core::ProxyType Instance(const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask = true) + { + static WPEFramework::Core::ProxyMapType channelMap; + + string searchLine = remoteNode.HostAddress() + '@' + path; + + return (channelMap.template Instance(searchLine, remoteNode, path, query, mask)); + } + + public: + static void Trigger(const uint64_t& time, CLIENT* client) + { + FactoryImpl::Instance().Trigger(time, client); + } + static WPEFramework::Core::ProxyType Message() + { + return (FactoryImpl::Instance().Element(string())); + } + uint32_t Sequence() const + { + return (++_sequence); + } + void Register(CLIENT& client) + { + _adminLock.Lock(); + ASSERT(std::find(_observers.begin(), _observers.end(), &client) == _observers.end()); + _observers.push_back(&client); + if (_channel.IsOpen() == true) { + client.Opened(); + } + _adminLock.Unlock(); + } + void Unregister(CLIENT& client) + { + _adminLock.Lock(); + typename std::list::iterator index(std::find(_observers.begin(), _observers.end(), &client)); + if (index != _observers.end()) { + _observers.erase(index); + } + FactoryImpl::Instance().Revoke(&client); + _adminLock.Unlock(); + } + + void Submit(const WPEFramework::Core::ProxyType& message) + { + _channel.Submit(message); + } + bool IsSuspended() const + { + return (_channel.IsSuspended()); + } + uint32_t Initialize() + { + return (Open(0)); + } + void Deinitialize() + { + Close(); + } + bool IsOpen() + { + return (_channel.IsOpen() == true); + } + + protected: + void StateChange() + { + _adminLock.Lock(); + typename std::list::iterator index(_observers.begin()); + while (index != _observers.end()) { + if (_channel.IsOpen() == true) { + (*index)->Opened(); + } + else { + (*index)->Closed(); + } + index++; + } + _adminLock.Unlock(); + } + bool Open(const uint32_t waitTime) + { + bool result = true; + if (_channel.IsClosed() == true) { + result = (_channel.Open(waitTime) == WPEFramework::Core::ERROR_NONE); + } + return (result); + } + void Close() + { + _channel.Close(WPEFramework::Core::infinite); + } + + private: + uint32_t Inbound(const WPEFramework::Core::ProxyType& inbound) + { + uint32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + _adminLock.Lock(); + typename std::list::iterator index(_observers.begin()); + while ((result != WPEFramework::Core::ERROR_NONE) && (index != _observers.end())) { + result = (*index)->Submit(inbound); + index++; + } + _adminLock.Unlock(); + + return (result); + } + + private: + WPEFramework::Core::CriticalSection _adminLock; + ChannelImpl _channel; + mutable std::atomic _sequence; + std::list _observers; + }; + + class IEventHandler { + public: + virtual uint32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) = 0; + virtual uint32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) = 0; + virtual ~IEventHandler() = default; + }; + + template + class Transport { + private: + using Channel = CommunicationChannel; + using Entry = typename CommunicationChannel::Entry; + using PendingMap = std::unordered_map; + using EventMap = std::map; + typedef std::function& jsonResponse, bool& enabled)> EventResponseValidatioionFunction; + + class Job : public WPEFramework::Core::IDispatch { + protected: + Job(const WPEFramework::Core::ProxyType& inbound, class Transport* parent) + : _inbound(inbound) + , _parent(parent) + { + } + + public: + Job() = delete; + Job(const Job&) = delete; + Job& operator=(const Job&) = delete; + + ~Job() = default; + + public: + static WPEFramework::Core::ProxyType Create(const WPEFramework::Core::ProxyType& inbound, class Transport* parent); + + void Dispatch() override + { + _parent->Inbound(_inbound); + } + + private: + const WPEFramework::Core::ProxyType _inbound; + class Transport* _parent; + }; + + protected: + static constexpr uint32_t DefaultWaitTime = 10000; + + inline void Announce() { + _channel->Register(*this); + } + + private: + static constexpr const TCHAR* PathPrefix = _T("/"); + public: + Transport() = delete; + Transport(const Transport&) = delete; + Transport& operator=(Transport&) = delete; + Transport(const WPEFramework::Core::URL& url, const uint32_t waitTime) + : _adminLock() + , _connectId(WPEFramework::Core::NodeId(url.Host().Value().c_str(), url.Port().Value())) + , _channel(Channel::Instance(_connectId, ((url.Path().Value().rfind(PathPrefix, 0) == 0) ? url.Path().Value() : string(PathPrefix + url.Path().Value())), url.Query().Value(), true)) + , _eventHandler(nullptr) + , _pendingQueue() + , _scheduledTime(0) + , _waitTime(waitTime) + { + _channel->Register(*this); + } + + virtual ~Transport() + { + _channel->Unregister(*this); + + for (auto& element : _pendingQueue) { + element.second.Abort(element.first); + } + } + + public: + inline bool IsOpen() + { + _channel->IsOpen(); + } + + void Revoke(const string& eventName) + { + _adminLock.Lock(); + _eventMap.erase(eventName); + _adminLock.Unlock(); + } + + void SetEventHandler(IEventHandler* eventHandler) + { + _eventHandler = eventHandler; + } + + template + uint32_t Invoke(const string& method, const PARAMETERS& parameters, RESPONSE& response) + { + Entry slot; + uint32_t id = _channel->Sequence(); + uint32_t result = Send(method, parameters, id); + if (result == WPEFramework::Core::ERROR_NONE) { + result = WaitForResponse(id, response, _waitTime); + } + + return (FireboltErrorValue(result)); + } + + template + uint32_t Subscribe(const string& eventName, const string& parameters, RESPONSE& response) + { + Entry slot; + uint32_t id = _channel->Sequence(); + uint32_t result = Send(eventName, parameters, id); + if (result == WPEFramework::Core::ERROR_NONE) { + _adminLock.Lock(); + _eventMap.emplace(std::piecewise_construct, + std::forward_as_tuple(eventName), + std::forward_as_tuple(~0)); + _adminLock.Unlock(); + + result = WaitForEventResponse(id, eventName, response, _waitTime); + } + + return (FireboltErrorValue(result)); + } + + uint32_t Unsubscribe(const string& eventName, const string& parameters) + { + Revoke(eventName); + Entry slot; + uint32_t id = _channel->Sequence(); + uint32_t result = Send(eventName, parameters, id); + + return (FireboltErrorValue(result)); + } + + private: + friend Channel; + inline bool IsEvent(const uint32_t id, string& eventName) + { + _adminLock.Lock(); + for (auto& event : _eventMap) { + if (event.second == id) { + eventName = event.first; + break; + } + } + _adminLock.Unlock(); + return (eventName.empty() != true); + } + uint64_t Timed() + { + uint64_t result = ~0; + uint64_t currentTime = WPEFramework::Core::Time::Now().Ticks(); + + // Lets see if some callback are expire. If so trigger and remove... + _adminLock.Lock(); + + typename PendingMap::iterator index = _pendingQueue.begin(); + + while (index != _pendingQueue.end()) { + + if (index->second.Expired(index->first, currentTime, result) == true) { + index = _pendingQueue.erase(index); + } + else { + index++; + } + } + _scheduledTime = (result != static_cast(~0) ? result : 0); + + _adminLock.Unlock(); + + return (_scheduledTime); + } + + virtual void Opened() + { + // Nice to know :-) + } + + void Closed() + { + // Abort any in progress RPC command: + _adminLock.Lock(); + + // See if we issued anything, if so abort it.. + while (_pendingQueue.size() != 0) { + + _pendingQueue.begin()->second.Abort(_pendingQueue.begin()->first); + _pendingQueue.erase(_pendingQueue.begin()); + } + + _adminLock.Unlock(); + } + + uint32_t Submit(const WPEFramework::Core::ProxyType& inbound) + { + uint32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(inbound, this)); + WPEFramework::Core::IWorkerPool::Instance().Submit(job); + return result; + } + + uint32_t Inbound(const WPEFramework::Core::ProxyType& inbound) + { + uint32_t result = WPEFramework::Core::ERROR_INVALID_SIGNATURE; + + ASSERT(inbound.IsValid() == true); + + if ((inbound->Id.IsSet() == true) && (inbound->Result.IsSet() || inbound->Error.IsSet())) { + // Looks like this is a response.. + ASSERT(inbound->Parameters.IsSet() == false); + ASSERT(inbound->Designator.IsSet() == false); + + _adminLock.Lock(); + + // See if we issued this.. + typename PendingMap::iterator index = _pendingQueue.find(inbound->Id.Value()); + + if (index != _pendingQueue.end()) { + + if (index->second.Signal(inbound) == true) { + _pendingQueue.erase(index); + } + + result = WPEFramework::Core::ERROR_NONE; + } else { + + string eventName; + if (IsEvent(inbound->Id.Value(), eventName)) { + _eventHandler->Dispatch(eventName, inbound); + } + + } + _adminLock.Unlock(); + } + + return (result); + } + + + template + uint32_t Send(const string& method, const PARAMETERS& parameters, const uint32_t& id) + { + uint32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + + if ((_channel.IsValid() == true) && (_channel->IsSuspended() == true)) { + result = WPEFramework::Core::ERROR_ASYNC_FAILED; + } + else if (_channel.IsValid() == true) { + + result = WPEFramework::Core::ERROR_ASYNC_FAILED; + + WPEFramework::Core::ProxyType message(Channel::Message()); + message->Id = id; + message->Designator = method; + ToMessage(parameters, message); + + _adminLock.Lock(); + + typename std::pair< typename PendingMap::iterator, bool> newElement = + _pendingQueue.emplace(std::piecewise_construct, + std::forward_as_tuple(id), + std::forward_as_tuple()); + ASSERT(newElement.second == true); + + if (newElement.second == true) { + + _adminLock.Unlock(); + + _channel->Submit(WPEFramework::Core::ProxyType(message)); + + message.Release(); + result = WPEFramework::Core::ERROR_NONE; + } + } + return result; + } + + template + uint32_t WaitForResponse(const uint32_t& id, RESPONSE& response, const uint32_t waitTime) + { + uint32_t result = WPEFramework::Core::ERROR_TIMEDOUT; + _adminLock.Lock(); + typename PendingMap::iterator index = _pendingQueue.find(id); + Entry& slot(index->second); + _adminLock.Unlock(); + + if (slot.WaitForResponse(waitTime) == true) { + WPEFramework::Core::ProxyType jsonResponse = slot.Response(); + + // See if we have a jsonResponse, maybe it was just the connection + // that closed? + if (jsonResponse.IsValid() == true) { + if (jsonResponse->Error.IsSet() == true) { + result = jsonResponse->Error.Code.Value(); + } + else { + result = WPEFramework::Core::ERROR_NONE; + if ((jsonResponse->Result.IsSet() == true) + && (jsonResponse->Result.Value().empty() == false)) { + FromMessage((INTERFACE*)&response, *jsonResponse); + } + } + } + } else { + result = WPEFramework::Core::ERROR_TIMEDOUT; + } + _adminLock.Lock(); + _pendingQueue.erase(id); + _adminLock.Unlock(); + return result; + } + + static constexpr uint32_t WAITSLOT_TIME = 100; + template + uint32_t WaitForEventResponse(const uint32_t& id, const string& eventName, RESPONSE& response, const uint32_t waitTime) + { + uint32_t result = WPEFramework::Core::ERROR_TIMEDOUT; + _adminLock.Lock(); + typename PendingMap::iterator index = _pendingQueue.find(id); + Entry& slot(index->second); + _adminLock.Unlock(); + + uint8_t waiting = waitTime; + do { + uint32_t waitSlot = (waiting > WAITSLOT_TIME ? WAITSLOT_TIME : waiting); + if (slot.WaitForResponse(waitSlot) == true) { + WPEFramework::Core::ProxyType jsonResponse = slot.Response(); + + // See if we have a jsonResponse, maybe it was just the connection + // that closed? + if (jsonResponse.IsValid() == true) { + if (jsonResponse->Error.IsSet() == true) { + result = jsonResponse->Error.Code.Value(); + } else { + if ((jsonResponse->Result.IsSet() == true) + && (jsonResponse->Result.Value().empty() == false)) { + result = WPEFramework::Core::ERROR_NONE; + bool enabled; + result = _eventHandler->ValidateResponse(jsonResponse, enabled); + if (result == WPEFramework::Core::ERROR_NONE) { + FromMessage((INTERFACE*)&response, *jsonResponse); + if (enabled) { + _adminLock.Lock(); + typename EventMap::iterator index = _eventMap.find(eventName); + if (index != _eventMap.end()) { + index->second = id; + } + _adminLock.Unlock(); + } + } + } + } + } + } else { + result = WPEFramework::Core::ERROR_TIMEDOUT; + } + waiting -= (waiting == WPEFramework::Core::infinite ? 0 : waitSlot); + } while ((result != WPEFramework::Core::ERROR_NONE) && (waiting > 0 )); + _adminLock.Lock(); + _pendingQueue.erase(id); + _adminLock.Unlock(); + + return result; + } + + public: + void FromMessage(WPEFramework::Core::JSON::IElement* response, const WPEFramework::Core::JSONRPC::Message& message) const + { + response->FromString(message.Result.Value()); + } + + void FromMessage(WPEFramework::Core::JSON::IMessagePack* response, const WPEFramework::Core::JSONRPC::Message& message) const + { + string value = message.Result.Value(); + std::vector result(value.begin(), value.end()); + response->FromBuffer(result); + } + + + private: + + void ToMessage(const string& parameters, WPEFramework::Core::ProxyType& message) const + { + if (parameters.empty() != true) { + message->Parameters = parameters; + } + } + + template + void ToMessage(PARAMETERS& parameters, WPEFramework::Core::ProxyType& message) const + { + ToMessage((INTERFACE*)(¶meters), message); + return; + } + + void ToMessage(WPEFramework::Core::JSON::IMessagePack* parameters, WPEFramework::Core::ProxyType& message) const + { + std::vector values; + parameters->ToBuffer(values); + if (values.empty() != true) { + string strValues(values.begin(), values.end()); + message->Parameters = strValues; + } + return; + } + + void ToMessage(WPEFramework::Core::JSON::IElement* parameters, WPEFramework::Core::ProxyType& message) const + { + string values; + parameters->ToString(values); + if (values.empty() != true) { + message->Parameters = values; + } + return; + } + + uint32_t FireboltErrorValue(const uint32_t error) + { + + uint32_t fireboltError = FireboltSDKErrorUnknown; + switch (error) { + case WPEFramework::Core::ERROR_NONE: + fireboltError = FireboltSDKErrorNone; + break; + case WPEFramework::Core::ERROR_GENERAL: + fireboltError = FireboltSDKErrorGeneral; + break; + case WPEFramework::Core::ERROR_UNAVAILABLE: + fireboltError = FireboltSDKErrorUnavailable; + break; + case WPEFramework::Core::ERROR_TIMEDOUT: + fireboltError = FireboltSDKErrorTimedout; + break; + default: + break; + } + + return fireboltError; + } + + private: + WPEFramework::Core::CriticalSection _adminLock; + WPEFramework::Core::NodeId _connectId; + WPEFramework::Core::ProxyType _channel; + IEventHandler* _eventHandler; + PendingMap _pendingQueue; + EventMap _eventMap; + uint64_t _scheduledTime; + uint32_t _waitTime; + }; +} diff --git a/languages/c/templates/sdk/src/Types.cpp b/languages/c/templates/sdk/src/Types.cpp new file mode 100644 index 00000000..e573c0c9 --- /dev/null +++ b/languages/c/templates/sdk/src/Types.cpp @@ -0,0 +1,41 @@ +/* + * 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 "Module.h" +#include "Types.h" +#include "TypesPriv.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// String Type Handler Interfaces +const char* FireboltTypes_String(FireboltTypes_StringHandle handle) +{ + FireboltSDK::String* str = static_cast(handle); + return (str->Value().c_str()); +} +void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle) +{ + FireboltSDK::String* str = static_cast(handle); + delete str; +} + +#ifdef __cplusplus +} +#endif diff --git a/languages/c/templates/sdk/src/TypesPriv.h b/languages/c/templates/sdk/src/TypesPriv.h new file mode 100644 index 00000000..eda9547f --- /dev/null +++ b/languages/c/templates/sdk/src/TypesPriv.h @@ -0,0 +1,55 @@ +/* + * 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 + +namespace FireboltSDK { +class String { + public: + String() + : _value() + { + } + String(const std::string& value) + : _value(value) + { + } + String(const String& copy) + : _value(copy._value) + { + + } + inline ~String() = default; + String& operator=(const String& RHS) + { + _value = RHS._value; + return (*this); + } + + public: + const std::string& Value() const + { + return _value; + } + + private: + std::string _value; + }; +} diff --git a/languages/c/templates/sdk/src/cmake/CopySymlink.cmake b/languages/c/templates/sdk/src/cmake/CopySymlink.cmake new file mode 100644 index 00000000..8ac3c1f8 --- /dev/null +++ b/languages/c/templates/sdk/src/cmake/CopySymlink.cmake @@ -0,0 +1 @@ +file(COPY "${LIBRARY}" DESTINATION "${DESTINATION}" FOLLOW_SYMLINK_CHAIN) diff --git a/languages/c/templates/sdk/test/CMakeLists.txt b/languages/c/templates/sdk/test/CMakeLists.txt new file mode 100644 index 00000000..a56ca20a --- /dev/null +++ b/languages/c/templates/sdk/test/CMakeLists.txt @@ -0,0 +1,86 @@ +# 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 + +cmake_minimum_required(VERSION 3.3) + +project(FireboltSDKTests) +project_version(1.0.0) + +set(TESTLIB ${PROJECT_NAME}) + +message("Setup ${TESTLIB} v${PROJECT_VERSION}") + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +find_package(${NAMESPACE}Core CONFIG REQUIRED) + +add_library(${TESTLIB} STATIC OpenRPCTests.cpp) + +target_link_libraries(${TESTLIB} + PUBLIC + ${NAMESPACE}Core::${NAMESPACE}Core + ${FIREBOLT_NAMESPACE}SDK +) + +target_include_directories(${TESTLIB} + PRIVATE + $ + $ +) + +set_target_properties(${TESTLIB} PROPERTIES + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED YES + LINK_WHAT_YOU_USE TRUE + FRAMEWORK FALSE +) + +install( + TARGETS ${TESTLIB} EXPORT ${TESTLIB}Targets + LIBRARY DESTINATION lib COMPONENT libs + PUBLIC_HEADER DESTINATION include/${FIREBOLT_NAMESPACE}Test COMPONENT devel # headers for mac (note the different component -> different package) + INCLUDES DESTINATION include/${FIREBOLT_NAMESPACE}Test # headers +) + +InstallCMakeConfig(TARGETS ${TESTLIB}) +InstallCMakeConfigs(TARGET ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallHeaders(TARGET ${TESTLIB} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION FireboltTest) +InstallLibraries(TARGET ${TESTLIB} LIBRARIES ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) + +set(TESTAPP "FireboltSDKTestApp") + +message("Setup ${TESTAPP}") + +add_executable(${TESTAPP} Main.c) + +target_link_libraries(${TESTAPP} + PRIVATE + ${TESTLIB} +) + +target_include_directories(${TESTAPP} + PRIVATE + $ + $ +) + +add_custom_command( + TARGET ${TESTAPP} + POST_BUILD + COMMENT "=================== Installing TestApp ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/bin + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${TESTAPP} ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/bin +) + diff --git a/languages/c/templates/sdk/test/Main.c b/languages/c/templates/sdk/test/Main.c new file mode 100644 index 00000000..7c4c94a5 --- /dev/null +++ b/languages/c/templates/sdk/test/Main.c @@ -0,0 +1,44 @@ +/* + * 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 "OpenRPCCTests.h" + +int __cnt = 0; +int __pass = 0; + +int TotalTests = 0; +int TotalTestsPassed = 0; + +int main() +{ + test_firebolt_create_instance(); + test_firebolt_main(); + + // Calling C function sequences + printf("%s:%s:%d Calling C function tests\n", __FILE__, __func__, __LINE__); + EXECUTE("test_properties_get_device_id", test_properties_get_device_id); + EXECUTE("test_properties_set", test_properties_set); + EXECUTE("test_eventregister_by_providing_callback", test_eventregister_by_providing_callback); + EXECUTE("test_eventregister", test_eventregister); + EXECUTE("test_string_set_get_value", test_string_set_get_value); + + test_firebolt_dispose_instance(); + + printf("TOTAL: %i tests; %i PASSED, %i FAILED\n", TotalTests, TotalTestsPassed, (TotalTests - TotalTestsPassed)); +} + diff --git a/languages/c/templates/sdk/test/Module.cpp b/languages/c/templates/sdk/test/Module.cpp new file mode 100644 index 00000000..d63badc4 --- /dev/null +++ b/languages/c/templates/sdk/test/Module.cpp @@ -0,0 +1,21 @@ +/* + * 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 "Module.h" + +MODULE_NAME_DECLARATION(BUILD_REFERENCE) diff --git a/languages/c/templates/modules/src/Module_Common.cpp b/languages/c/templates/sdk/test/Module.h similarity index 79% rename from languages/c/templates/modules/src/Module_Common.cpp rename to languages/c/templates/sdk/test/Module.h index bce775ff..d5340b68 100644 --- a/languages/c/templates/modules/src/Module_Common.cpp +++ b/languages/c/templates/sdk/test/Module.h @@ -16,16 +16,14 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "FireboltSDK.h" -#include "Common/${info.title}.h" -#include "JsonData_${info.title}.h" -} -#ifdef __cplusplus -extern "C" { +#pragma once + +#ifndef MODULE_NAME +#define MODULE_NAME OpenRPCTestApp #endif - /* ${SCHEMAS}} */ +#include +#include -#ifdef __cplusplus -} -#endif \ No newline at end of file +#undef EXTERNAL +#define EXTERNAL diff --git a/languages/c/templates/sdk/test/OpenRPCCTests.h b/languages/c/templates/sdk/test/OpenRPCCTests.h new file mode 100644 index 00000000..7f2fb59e --- /dev/null +++ b/languages/c/templates/sdk/test/OpenRPCCTests.h @@ -0,0 +1,42 @@ +/* + * 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 + */ + +#ifndef _OPENRPC_C_TESTS_H +#define _OPENRPC_C_TESTS_H + +#include "TestUtils.h" + +#ifdef __cplusplus +extern "C" { +#endif + +uint32_t test_firebolt_create_instance(); +uint32_t test_firebolt_dispose_instance(); + +uint32_t test_firebolt_main(); +uint32_t test_properties_get_device_id(); +uint32_t test_properties_set(); +uint32_t test_eventregister(); +uint32_t test_eventregister_by_providing_callback(); +uint32_t test_string_set_get_value(); + +#ifdef __cplusplus +} +#endif + +#endif // _OPENRPC_C_TESTS_H diff --git a/languages/c/templates/sdk/test/OpenRPCTests.cpp b/languages/c/templates/sdk/test/OpenRPCTests.cpp new file mode 100644 index 00000000..cf9ea5a0 --- /dev/null +++ b/languages/c/templates/sdk/test/OpenRPCTests.cpp @@ -0,0 +1,385 @@ +/* + * 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 "Module.h" +#include "OpenRPCTests.h" +#include "OpenRPCCTests.h" + +namespace WPEFramework { + +ENUM_CONVERSION_BEGIN(::JsonValue::type) + + { JsonValue::type::EMPTY, _TXT("empty") }, + { JsonValue::type::BOOLEAN, _TXT("boolean") }, + { JsonValue::type::NUMBER, _TXT("number") }, + { JsonValue::type::STRING, _TXT("string") }, + +ENUM_CONVERSION_END(::JsonValue::type) + +ENUM_CONVERSION_BEGIN(TestEnum) + { TestEnum::Test1, _TXT("Test1ValueCheck") }, + { TestEnum::Test2, _TXT("Test2ValueCheck") }, + { TestEnum::Test3, _TXT("Test3ValueCheck") }, + { TestEnum::Test4, _TXT("Test4ValueCheck") }, +ENUM_CONVERSION_END(TestEnum) +} +namespace FireboltSDK { + Tests::Tests() + { + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEventWithMultipleCallback"), + std::forward_as_tuple(&SubscribeEventWithMultipleCallback)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEvent"), + std::forward_as_tuple(&SubscribeEvent)); + + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Set UnKnown Method"), + std::forward_as_tuple(&SetUnKnownMethod)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Set LifeCycle Close"), + std::forward_as_tuple(&SetLifeCycleClose)); + + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Get UnKnown Method"), + std::forward_as_tuple(&GetUnKnownMethod)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Get Device Version"), + std::forward_as_tuple(&GetDeviceVersion)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Get Device Id"), + std::forward_as_tuple(&GetDeviceId)); + } + + /* static */ void Tests::PrintJsonObject(const JsonObject::Iterator& iterator) + { + JsonObject::Iterator index = iterator; + while (index.Next() == true) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "Element [%s]: <%s> = \"%s\"\n", + index.Label(), + WPEFramework::Core::EnumerateType(index.Current().Content()).Data(), + index.Current().Value().c_str()); + } + } + + /* static */ uint32_t Tests::GetDeviceId() + { + const string method = _T("device.id"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "DeviceId : %s", response->Value().c_str()); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d\n", method.c_str(), status); + } + + return status; + } + + /*static */ uint32_t Tests::GetDeviceVersion() + { + const string method = _T("device.version"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "DeviceVersion"); + PrintJsonObject(response->Variants()); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d", method.c_str(), status); + } + + return status; + } + + /* static */ uint32_t Tests::GetUnKnownMethod() + { + const string method = _T("get.unknownMethod"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_NE(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d\n", method.c_str(), status); + } + + return status; + } + + /* static */ uint32_t Tests::SetLifeCycleClose() + { + const string method = _T("lifecycle.close"); + JsonObject parameters; + parameters["reason"] = "remoteButton"; + uint32_t status = FireboltSDK::Properties::Set(method, parameters); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d\n", method.c_str(), status); + } + + return status; + } + + /* static */ uint32_t Tests::SetUnKnownMethod() + { + const string method = _T("set.unknownMethod"); + JsonObject parameters; + uint32_t status = FireboltSDK::Properties::Set(method, parameters); + + EXPECT_NE(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", method.c_str(), status); + } + + return status; + } + + static void deviceNameChangeCallback(const void* userData, void* response) + { + WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Received a new event: %s", jsonResponse->Value().c_str()); + jsonResponse.Release(); + FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + eventControl->NotifyEvent(); + } + + /* static */ uint32_t Tests::SubscribeEvent() + { + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + + uint32_t id = 0; + + eventControl->ResetEvent(); + uint32_t status = Properties::Subscribe(eventName, deviceNameChangeCallback, userdata, id); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), + "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered successfully", __func__); + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + EXPECT_EQ(Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + delete eventControl; + + return status; + } + + template + /* static */ uint32_t Tests::SubscribeEventForC(const string& eventName, CALLBACK& callbackFunc, const void* userdata, uint32_t& id) + { + return Properties::Subscribe(eventName, callbackFunc, userdata, id);; + } + + static void deviceNameChangeMultipleCallback(const void* userData, void* response) + { + WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "Received a new event from deviceNameChangeMultipleCallback: %s", jsonResponse->Value().c_str()); + jsonResponse.Release(); + FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + eventControl->NotifyEvent(); + } + + /* static */ uint32_t Tests::SubscribeEventWithMultipleCallback() + { + FireboltSDK::Tests::EventControl* eventControl1 = new FireboltSDK::Tests::EventControl(); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl1); + uint32_t id1 = 0, id2 = 0; + + eventControl1->ResetEvent(); + uint32_t status = Properties::Subscribe(eventName, deviceNameChangeCallback, userdata, id1); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), + "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered successfully", __func__); + } + + if (status == FireboltSDKErrorNone) { + FireboltSDK::Tests::EventControl* eventControl2 = new FireboltSDK::Tests::EventControl(); + userdata = static_cast(eventControl2); + + status = Properties::Subscribe(eventName, deviceNameChangeMultipleCallback, userdata, id2); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered second callback also successfully", __func__); + eventControl1->WaitForEvent(WPEFramework::Core::infinite); + eventControl2->WaitForEvent(WPEFramework::Core::infinite); + } + EXPECT_EQ(Properties::Unsubscribe(eventName, id1), FireboltSDKErrorNone); + delete eventControl2; + } + EXPECT_EQ(Properties::Unsubscribe(eventName, id2), FireboltSDKErrorNone); + + delete eventControl1; + return status; + } + +} + +#ifdef __cplusplus +extern "C" { +#endif + +uint32_t test_firebolt_create_instance() +{ + FireboltSDK::Accessor::Instance(); +} + +uint32_t test_firebolt_dispose_instance() +{ + FireboltSDK::Accessor::Dispose(); +} + +uint32_t test_firebolt_main() +{ + return FireboltSDK::Tests::Main(); +} + +uint32_t test_properties_get_device_id() +{ + const string method = _T("device.id"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "DeviceId : %s", response->Value().c_str()); + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "Get %s status = %d", method.c_str(), status); + } + + return status; +} + +uint32_t test_properties_set() +{ + const string method = _T("lifecycle.close"); + JsonObject parameters; + parameters["reason"] = "remoteButton"; + uint32_t status = FireboltSDK::Properties::Set(method, parameters); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "Set %s status = %d", method.c_str(), status); + } + + return status; +} + +static void deviceNameChangeCallbackForC(const void* userData, void* response) +{ + WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "Received a new event--->: %s", jsonResponse->Value().c_str()); + jsonResponse.Release(); + + FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + eventControl->NotifyEvent(); +} + +uint32_t test_eventregister() +{ + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + JsonObject parameters; + + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + uint32_t id = 0; + + eventControl->ResetEvent(); + uint32_t status = FireboltSDK::Properties::Subscribe(eventName, deviceNameChangeCallbackForC, userdata, id); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Set %s status = %d", __func__, eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes registered successfully", __func__); + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + delete eventControl; + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + + return status; +} + +uint32_t test_eventregister_by_providing_callback() +{ + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + uint32_t id = 0; + + eventControl->ResetEvent(); + uint32_t status = FireboltSDK::Tests::SubscribeEventForC(eventName, deviceNameChangeCallbackForC, userdata, id); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Set %s status = %d", __func__, eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes registered successfully", __func__); + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + delete eventControl; + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); +} + +#include "TypesPriv.h" +uint32_t test_string_set_get_value() +{ + uint32_t status = FireboltSDKErrorNone; + FireboltSDK::String* str = new FireboltSDK::String("testString"); + void* handle = static_cast(str); + + const char* value = FireboltTypes_String(handle); + EXPECT_EQ(strncmp(value, str->Value().c_str(), str->Value().length()), 0); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + " ---> type name = %s %s", str->Value().c_str(), value); + + WPEFramework::Core::JSON::EnumType<::TestEnum> testEnum = Test4; + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + " EnumTest = %d %s", testEnum.Value(), testEnum.Data()); + FireboltTypes_StringHandle_Release(handle); + return status; +} + +#ifdef __cplusplus +} +#endif diff --git a/languages/c/templates/sdk/test/OpenRPCTests.h b/languages/c/templates/sdk/test/OpenRPCTests.h new file mode 100644 index 00000000..00abd364 --- /dev/null +++ b/languages/c/templates/sdk/test/OpenRPCTests.h @@ -0,0 +1,99 @@ +/* + * 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 "TestUtils.h" +#include "Firebolt.h" + +namespace FireboltSDK { + typedef uint32_t (*Func)(); + + class Tests { + public: + class EventControl { + public: + EventControl() + : _event(false, true) + { + } + ~EventControl() = default; + + public: + void NotifyEvent() + { + _event.SetEvent(); + } + uint32_t WaitForEvent(uint32_t waitTime) + { + return _event.Lock(waitTime); + } + void ResetEvent() + { + _event.ResetEvent(); + } + private: + WPEFramework::Core::Event _event; + }; + + private: + typedef std::unordered_map TestFunctionMap; + + public: + Tests(); + virtual ~Tests() = default; + + inline TestFunctionMap& TestList() + { + return _functionMap; + } + + template + static uint32_t Main() + { + TESTS fireboltTest; + for (auto i = fireboltTest.TestList().begin(); i != fireboltTest.TestList().end(); i++) { + EXECUTE(i->first.c_str(), i->second); + } + + printf("TOTAL: %i tests; %i PASSED, %i FAILED\n", TotalTests, TotalTestsPassed, (TotalTests - TotalTestsPassed)); + + return 0; + } + + static uint32_t GetDeviceId(); + static uint32_t GetDeviceVersion(); + static uint32_t GetUnKnownMethod(); + + static uint32_t SetLifeCycleClose(); + static uint32_t SetUnKnownMethod(); + + static uint32_t SubscribeEvent(); + static uint32_t SubscribeEventWithMultipleCallback(); + + template + static uint32_t SubscribeEventForC(const string& eventName, CALLBACK& callbackFunc, const void* userdata, uint32_t& id); + + protected: + static void PrintJsonObject(const JsonObject::Iterator& iterator); + + protected: + std::list menu; + TestFunctionMap _functionMap; + }; +} diff --git a/languages/c/templates/sdk/test/TestUtils.h b/languages/c/templates/sdk/test/TestUtils.h new file mode 100644 index 00000000..8c3cb732 --- /dev/null +++ b/languages/c/templates/sdk/test/TestUtils.h @@ -0,0 +1,38 @@ +#ifndef _TEST_UTILS_H +#define _TEST_UTILS_H + +#include +#include +#include + +#define MAX(x, y) (((x) > (y)) ? (x) : (y)) +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) + +#define _RESULT(expr, exprorig, result) if (expr) { printf(" SUCCESS: %s\n", #exprorig); __pass++; } else printf(" FAILED: %s, actual: %u\n", #exprorig, result) +#define _EVAL(result, expected, op) do { __cnt++; uint32_t resval = ((uint32_t)(result)); uint32_t expval = ((uint32_t)(expected)); _RESULT(resval op expval, result op expected, resval); } while(0) +#define _HEAD(name) printf("\n======== %s\n", name); __cnt = 0; __pass = 0 +#define _FOOT(name) printf("\n======== %s - %i PASSED, %i FAILED\n", name, __pass, (__cnt - __pass)); TotalTests += __cnt; TotalTestsPassed += __pass; + +#define EXECUTE(name, test) do { _HEAD(name); test(); _FOOT(name); printf("\n"); } while(0) +#define EXPECT_EQ(result, expected) _EVAL(result, expected, ==) +#define EXPECT_NE(result, expected) _EVAL(result, expected, !=) +#define EXPECT_LT(result, expected) _EVAL(result, expected, <) +#define EXPECT_LE(result, expected) _EVAL(result, expected, <=) +#define EXPECT_GT(result, expected) _EVAL(result, expected, >) +#define EXPECT_GE(result, expected) _EVAL(result, expected, >=) + +#ifdef __cplusplus +extern "C" { +#endif + +extern int __cnt; +extern int __pass; + +extern int TotalTests ; +extern int TotalTestsPassed; + +#ifdef __cplusplus +} +#endif + +#endif // _TEST_UTILS_H diff --git a/languages/c/templates/sections/accessors.c b/languages/c/templates/sections/accessors.c new file mode 100644 index 00000000..0586b2a5 --- /dev/null +++ b/languages/c/templates/sections/accessors.c @@ -0,0 +1,3 @@ +// Accessors + +${schema.list} diff --git a/languages/c/templates/sections/declarations.js b/languages/c/templates/sections/declarations.c similarity index 100% rename from languages/c/templates/sections/declarations.js rename to languages/c/templates/sections/declarations.c diff --git a/languages/c/templates/sections/events.js b/languages/c/templates/sections/events.c similarity index 100% rename from languages/c/templates/sections/events.js rename to languages/c/templates/sections/events.c diff --git a/languages/c/templates/sections/methods.js b/languages/c/templates/sections/methods.c similarity index 100% rename from languages/c/templates/sections/methods.js rename to languages/c/templates/sections/methods.c diff --git a/languages/c/templates/sections/provider-interfaces.js b/languages/c/templates/sections/provider-interfaces.c similarity index 100% rename from languages/c/templates/sections/provider-interfaces.js rename to languages/c/templates/sections/provider-interfaces.c diff --git a/languages/c/templates/sections/schemas.c b/languages/c/templates/sections/schemas.c new file mode 100644 index 00000000..a1847009 --- /dev/null +++ b/languages/c/templates/sections/schemas.c @@ -0,0 +1,3 @@ +// Types & Enums + +${schema.list} diff --git a/languages/c/templates/sections/schemas.js b/languages/c/templates/sections/types.c similarity index 100% rename from languages/c/templates/sections/schemas.js rename to languages/c/templates/sections/types.c diff --git a/languages/c/templates/types/enum.c b/languages/c/templates/types/enum.c new file mode 100644 index 00000000..2a8e94d7 --- /dev/null +++ b/languages/c/templates/types/enum.c @@ -0,0 +1,3 @@ +typedef enum { + ${info.TITLE}_${NAME}_${key}, +} ${info.title}_${name}; diff --git a/languages/c/templates/types/enum.mjs b/languages/c/templates/types/enum.mjs deleted file mode 100644 index 907fb37d..00000000 --- a/languages/c/templates/types/enum.mjs +++ /dev/null @@ -1,3 +0,0 @@ -${name}: { - ${key}: '${value}', -}, diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 6404a059..f0b5959c 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -60,7 +60,8 @@ let config = { } const state = { - destination: undefined + destination: undefined, + section: undefined } const setTyper = (t) => { @@ -106,7 +107,7 @@ const getLinkForSchema = (schema, json) => { schema = schema.schema } - const type = types.getSchemaType(schema, json, { destination: state.destination }) + const type = types.getSchemaType(schema, json, { 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]) { @@ -337,8 +338,12 @@ const generateMacros = (obj, templates, languages, options = {}) => { 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 schemasArray = generateSchemas(obj, templates, { baseUrl: '' }).filter(s => (options.copySchemasIntoModules || !s.uri)) + const schemasArray = generateSchemas(obj, templates, { baseUrl: '', section: 'schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) + const accessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).join('\n')) : '' + const typesArray = schemasArray.filter(x => !x.enum) + const types = typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).join('\n')) : '' + const accessors = accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).join('\n')) : '' const module = getTemplate('/codeblocks/module', templates) const macros = { @@ -350,10 +355,12 @@ const generateMacros = (obj, templates, languages, options = {}) => { eventsEnum, methods, methodList, + accessors, declarations, defaults, examples, schemas, + types, providerInterfaces, version: getSemanticVersion(obj), title: obj.info.title, @@ -385,12 +392,14 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{module.list\}/g, macros.module) fContents = fContents.replace(/[ \t]*\/\* \$\{METHODS\} \*\/[ \t]*\n/, macros.methods) + fContents = fContents.replace(/[ \t]*\/\* \$\{ACCESSORS\} \*\/[ \t]*\n/, macros.accessors) fContents = fContents.replace(/[ \t]*\/\* \$\{DECLARATIONS\} \*\/[ \t]*\n/, macros.declarations) 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) fContents = fContents.replace(/[ \t]*\/\* \$\{SCHEMAS\} \*\/[ \t]*\n/, macros.schemas) + fContents = fContents.replace(/[ \t]*\/\* \$\{TYPES\} \*\/[ \t]*\n/, macros.types) fContents = fContents.replace(/[ \t]*\/\* \$\{PROVIDERS\} \*\/[ \t]*\n/, macros.providerInterfaces) fContents = fContents.replace(/[ \t]*\/\* \$\{ENUMS\} \*\/[ \t]*\n/, macros.enums) fContents = fContents.replace(/[ \t]*\/\* \$\{IMPORTS\} \*\/[ \t]*\n/, macros.imports) @@ -402,6 +411,7 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{minor\}/g, macros.version.minor) fContents = fContents.replace(/\$\{patch\}/g, macros.version.patch) fContents = fContents.replace(/\$\{info\.title\}/g, macros.title) + fContents = fContents.replace(/\$\{info\.TITLE\}/g, macros.title.toUpperCase()) fContents = fContents.replace(/\$\{info\.description\}/g, macros.description) fContents = fContents.replace(/\$\{info\.version\}/g, macros.version.readable) @@ -492,11 +502,12 @@ const generateEnums = (json, templates) => { if (template[i].indexOf('${key}') >= 0) { template[i] = schema.enum.map(value => { const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() - return template[i].replace(/\$\{key\}/g, safeName).replace(/\$\{value\}/g, value) + return template[i].replace(/\$\{key\}/g, safeName) + .replace(/\$\{value\}/g, value) }).join('\n') } } - return template.join('\n').replace(/\$\{name\}/g, schema.title) + return template.join('\n').replace(/\$\{name\}/g, schema.title).replace(/\$\{NAME\}/g, schema.title.toUpperCase()) })), map(enumFinder), getSchemas @@ -579,7 +590,7 @@ function generateSchemas(json, templates, options) { else { content = content.replace(/\$\{if\.description\}(.*?)\{end\.if\.description\}/gms, '$1') } - const schemaShape = types.getSchemaShape(schema, json, { name, destination: state.destination }) + const schemaShape = types.getSchemaShape(schema, json, { name, destination: state.destination, section: options.section }) content = content .replace(/\$\{schema.title\}/, (schema.title || name)) @@ -598,13 +609,17 @@ function generateSchemas(json, templates, options) { content = content.replace(/.*\$\{schema.seeAlso\}/, '') } + const isEnum = x => x.type === 'string' && Array.isArray(x.enum) && x.title + const result = uri ? { uri: uri, name: schema.title || name, - body: content + body: content, + enum: isEnum(schema) } : { name: schema.title || name, - body: content + body: content, + enum: isEnum(schema) } results.push(result) @@ -641,7 +656,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, { destination: state.destination }) + '](' + getLinkForSchema(schema, json, true) + ')') // need full module here, not just the schema + .map(schema => '[' + types.getSchemaType(schema, json, { destination: state.destination, section: state.section }) + '](' + getLinkForSchema(schema, json, true) + ')') // need full module here, not just the schema .filter(link => link) .join('\n') @@ -679,6 +694,12 @@ const generateImports = (json, templates) => { imports += getTemplate('/imports/x-method', templates) } + + + if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0) { + imports += Object.keys(json['x-schemas']).map(shared => getTemplate('/imports/default', templates).replace(/\$\{info.title\}/g, shared)).join('\n') + } + return imports } @@ -919,13 +940,13 @@ function insertMethodMacros(template, methodObj, json, templates, 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 - const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination }) - const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination }) - const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination }) : '' + const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) + const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) + const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' let seeAlso = '' - if (isPolymorphicPullMethod(methodObj)) { + if (isPolymorphicPullMethod(methodObj) && pullsForType) { seeAlso = `See also: [${pullsForType}](#${pullsForType.toLowerCase()}-1)` // this assumes the schema will be after the method... } else if (methodObj.tags.find(t => t.name === 'polymorphic-pull')) { @@ -936,7 +957,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { if (isTemporalSetMethod(methodObj)) { itemName = result.schema.items.title || 'item' itemName = itemName.charAt(0).toLowerCase() + itemName.substring(1) - itemType = types.getSchemaType(result.schema.items, json, { destination: state.destination }) + itemType = types.getSchemaType(result.schema.items, json, { destination: state.destination, section: state.section }) } template = insertExampleMacros(template, examples[methodObj.name] || [], methodObj, json, templates) @@ -956,8 +977,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/gms, method.params.length ? '$1' : '') .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event.params.length ? '$1' : '') // Typed signature stuff - .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination })) - .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination })) + .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) + .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(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\.deprecation\}/g, deprecation) @@ -965,7 +986,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{event\.name\}/g, method.name.toLowerCase()[2] + method.name.substr(3)) .replace(/\$\{event\.params\}/g, eventParams) .replace(/\$\{event\.params\.table\.rows\}/g, eventParamsRows) - .replace(/\$\{event\.signature\.params\}/g, types.getMethodSignatureParams(event, json, { destination: state.destination })) + .replace(/\$\{event\.signature\.params\}/g, types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section })) .replace(/\$\{info\.title\}/g, info.title) .replace(/\$\{info\.TITLE\}/g, info.title.toUpperCase()) .replace(/\$\{method\.property\.immutable\}/g, hasTag(methodObj, 'property:immutable')) @@ -1111,7 +1132,7 @@ function insertExampleMacros(template, examples, method, json, templates) { } function generateResult(result, json, templates) { - const type = types.getSchemaType(result, json, { destination: state.destination }) + const type = types.getSchemaType(result, json, { destination: state.destination, section: state.section }) if (result.type === 'object' && result.properties) { let content = getTemplate('/types/object', templates).split('\n') @@ -1132,7 +1153,7 @@ function generateResult(result, json, templates) { // if we get a real link use it if (link !== '#') { - return `[${types.getSchemaType(result, json, { destination: state.destination })}](${link})` + return `[${types.getSchemaType(result, json, { destination: state.destination, section: state.section })}](${link})` } // otherwise this was a schema with no title, and we'll just copy it here else { @@ -1148,7 +1169,7 @@ function generateResult(result, json, templates) { function insertSchemaMacros(template, title, schema, module) { return template.replace(/\$\{property\}/g, title) - .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { destination: state.destination, code: false })) + .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { destination: state.destination, section: state.section, code: false })) .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module)) .replace(/\$\{description\}/g, schema.description || '') .replace(/\$\{name\}/g, title || '') @@ -1159,9 +1180,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, { destination: state.destination, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl + let type = types.getSchemaType(param.schema, module, { destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl let typeLink = getLinkForSchema(param, module) - let jsonType = types.getJsonType(param.schema, module, { destination: state.destination, code: false, link: false, title: true, asPath: false, expandEnums: false }) + let jsonType = types.getJsonType(param.schema, module, { destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) if (constraints && type) { constraints = '
' + constraints @@ -1210,7 +1231,7 @@ function generateProviderInterfaces(json, templates) { } function insertProviderInterfaceMacros(template, capability, moduleJson = {}, templates) { - const iface = getProviderInterface(capability, moduleJson, { destination: state.destination })//.map(method => { method.name = method.name.charAt(9).toLowerCase() + method.name.substr(10); return method } ) + const iface = getProviderInterface(capability, moduleJson, { destination: state.destination, section: state.section })//.map(method => { method.name = method.name.charAt(9).toLowerCase() + method.name.substr(10); return method } ) const capitalize = str => str[0].toUpperCase() + str.substr(1) const uglyName = capability.split(":").slice(-2).map(capitalize).reverse().join('') + "Provider" @@ -1224,7 +1245,7 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te interfaceShape = interfaceShape.replace(/\$\{name\}/g, name) .replace(/\$\{capability\}/g, capability) - .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => `\t${types.getMethodSignature(method, moduleJson, { destination: state.destination, isInterface: true })}`).join('\n') + '\n') + .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => `\t${types.getMethodSignature(method, moduleJson, { destination: state.destination, section: state.section, isInterface: true })}`).join('\n') + '\n') if (iface.length === 0) { template = template.replace(/\$\{provider\.methods\}/gms, '') @@ -1243,7 +1264,7 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te name: 'provider' }) const parametersSchema = method.params[0].schema - const parametersShape = types.getSchemaShape(parametersSchema, moduleJson, { destination: state.destination }) + const parametersShape = types.getSchemaShape(parametersSchema, moduleJson, { destination: state.destination, section: state.section }) let methodBlock = insertMethodMacros(getTemplateForMethod(method, templates), method, moduleJson, templates) methodBlock = methodBlock.replace(/\${parameters\.shape\}/g, parametersShape) const hasProviderParameters = parametersSchema && parametersSchema.properties && Object.keys(parametersSchema.properties).length > 0 @@ -1335,7 +1356,7 @@ function insertProviderParameterMacros(data = '', parameters, module = {}, optio Object.entries(parameters.properties).forEach(([name, param]) => { let constraints = getSchemaConstraints(param, module) - let type = types.getSchemaType(param, module, { destination: state.destination, code: true, link: true, title: true, asPath: options.asPath, baseUrl: options.baseUrl }) + let type = types.getSchemaType(param, module, { destination: state.destination, section: state.section, code: true, link: true, title: true, asPath: options.asPath, baseUrl: options.baseUrl }) if (constraints && type) { constraints = '
' + constraints From ef9c924f4f0c7850412170b540ae702b8c8b7d6a Mon Sep 17 00:00:00 2001 From: sramani-metro <71630728+sramani-metro@users.noreply.github.com> Date: Tue, 23 May 2023 12:33:26 +0530 Subject: [PATCH 038/137] fix: Sort the macrofied schemas based on schema refs (#90) * fix: Sort the macrofied schemas based on schema refs * fix: Sort the schemas before macrofying * fix: Handle the schemas part --- languages/c/templates/modules/src/Module.cpp | 15 ++++++++-- src/macrofier/engine.mjs | 29 ++++++++++++-------- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 0783b416..b5522fd6 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -22,16 +22,25 @@ /* ${IMPORTS} */ +namespace FireboltSDK { + namespace ${info.title} { + + /* ${TYPES} */ + + } +} + #ifdef __cplusplus extern "C" { #endif -/* ${TYPES} */ +/* ${ACCESSORS} */ +/* ${METHODS} */ + #ifdef __cplusplus } #endif -/* ${ACCESSORS} */ -/* ${METHODS} */ + diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index f0b5959c..958f0bea 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -31,7 +31,7 @@ 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 isEmpty from 'crocks/core/isEmpty.js' -import { getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies } from '../shared/json-schema.mjs' +import { getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies, isDefinitionReferencedBySchema } from '../shared/json-schema.mjs' // util for visually debugging crocks ADTs const _inspector = obj => { @@ -564,6 +564,8 @@ function generateDefaults(json = {}, templates) { return reducer(json) } +const isEnum = x => x.type && x.type === 'string' && Array.isArray(x.enum) && x.title + function generateSchemas(json, templates, options) { let results = [] @@ -609,8 +611,6 @@ function generateSchemas(json, templates, options) { content = content.replace(/.*\$\{schema.seeAlso\}/, '') } - const isEnum = x => x.type === 'string' && Array.isArray(x.enum) && x.title - const result = uri ? { uri: uri, name: schema.title || name, @@ -625,21 +625,28 @@ function generateSchemas(json, templates, options) { results.push(result) } + const list = [] + // schemas may be 1 or 2 levels deeps Object.entries(schemas).forEach( ([name, schema]) => { if (isSchema(schema)) { - generate(name, schema) + list.push([name, schema]) } - else if (typeof schema === 'object') { - const uri = schema.uri - Object.entries(schema).forEach( ([name, schema]) => { - if (name !== 'uri') { - generate(name, schema, uri) - } - }) + }) + + list.sort((a, b) => { + const aInB = isDefinitionReferencedBySchema('#/components/schemas/' + a[0], b[1]) + const bInA = isDefinitionReferencedBySchema('#/components/schemas/' + b[0], a[1]) + if(isEnum(a[1]) || (aInB && !bInA)) { + return -1 + } else if(isEnum(b[1]) || (!aInB && bInA)) { + return 1 } + return 0; }) + list.forEach(item => generate(...item)) + return results } From 7c8d0259c676f40c87c0f64ae5d5933b04c6c681 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 1 Jun 2023 20:08:21 +0530 Subject: [PATCH 039/137] Enum fixes (#93) Enum fixes : 1. missing description added 2. alignment fixes 3. implementation added for enum inside properties 4. Enum to String value Conversion logic added for C --- languages/c/src/types/JSONHelpers.mjs | 31 +------ languages/c/templates/declarations/default.c | 9 +- .../declarations/polymorphic-reducer.c | 11 ++- .../templates/modules/include/Common/Module.h | 10 +- .../c/templates/modules/include/Module.h | 15 ++- languages/c/templates/modules/src/Module.cpp | 6 +- languages/c/templates/schemas/default.c | 7 +- .../templates/schemas/include/Common/Module.h | 10 +- .../c/templates/schemas/src/JsonData_Module.h | 6 +- .../c/templates/schemas/src/Module_Common.cpp | 3 +- languages/c/templates/sections/enum.cpp | 5 + languages/c/templates/sections/schemas.c | 2 - languages/c/templates/sections/types.c | 2 - languages/c/templates/types/enum.cpp | 4 + .../c/templates/types/{enum.c => enum.h} | 1 + src/macrofier/engine.mjs | 92 ++++++++++++++----- 16 files changed, 125 insertions(+), 89 deletions(-) create mode 100644 languages/c/templates/sections/enum.cpp create mode 100644 languages/c/templates/types/enum.cpp rename languages/c/templates/types/{enum.c => enum.h} (71%) diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index 25d1ad3b..97a9385a 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -27,35 +27,6 @@ function getJsonContainerDefinition (name, props) { return c } -/* - -ENUM_CONVERSION_BEGIN(Advertising_SkipRestriction) - { ADVERTISING_SKIPRESTRICTION_NONE, _T("none") }, - { ADVERTISING_SKIPRESTRICTION_ADS_UNWATCHED, _T("adsUnwatched") }, - { ADVERTISING_SKIPRESTRICTION_ADS_ALL, _T("adsAll") }, - { ADVERTISING_SKIPRESTRICTION_ALL, _T("all") }, -ENUM_CONVERSION_END(Advertising_SkipRestriction) - - -*/ - -// TODO - this should be a global function in the main /src/ directory... not part of a language pack -const keyName = val => val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() - -function getJsonEnumConversion(schema, module, { name }) { - name = capitalize(schema.title || name) - let e = `ENUM_CONVERSION_BEGIN(${module.info.title}_${name})\n` - - schema.enum.forEach(value => { - e += `{ ${module.info.title.toUpperCase()}_${name.toUpperCase()}_${keyName(value)}, _T("${value}") },` - }) - - e += `ENUM_CONVERSION_END(${module.info.title}_${name})` - - return e -} - export { - getJsonContainerDefinition, - getJsonEnumConversion + getJsonContainerDefinition } diff --git a/languages/c/templates/declarations/default.c b/languages/c/templates/declarations/default.c index 72fbf14f..be0b1e14 100644 --- a/languages/c/templates/declarations/default.c +++ b/languages/c/templates/declarations/default.c @@ -1,4 +1,5 @@ - /** - * ${method.summary} - ${method.params} */ - ${method.signature}; +/* + * ${method.summary} + * ${method.params} + */ +${method.signature}; diff --git a/languages/c/templates/declarations/polymorphic-reducer.c b/languages/c/templates/declarations/polymorphic-reducer.c index 979832b2..cf974e1a 100644 --- a/languages/c/templates/declarations/polymorphic-reducer.c +++ b/languages/c/templates/declarations/polymorphic-reducer.c @@ -1,6 +1,7 @@ - /** - * ${method.summary} - ${method.params} */ - ${method.signature} +/* + * ${method.summary} + * ${method.params} + */ +${method.signature} -// TODO: generate reducer signature \ No newline at end of file +// TODO: generate reducer signature diff --git a/languages/c/templates/modules/include/Common/Module.h b/languages/c/templates/modules/include/Common/Module.h index 2834b997..809418a2 100644 --- a/languages/c/templates/modules/include/Common/Module.h +++ b/languages/c/templates/modules/include/Common/Module.h @@ -25,16 +25,16 @@ extern "C" { #endif - // Enums +// Enums - /* ${ENUMS}} */ +/* ${ENUMS} */ - // Schemas +// Schemas - /* ${SCHEMAS} */ +/* ${SCHEMAS} */ #ifdef __cplusplus } #endif -#endif // Header Include Guard \ No newline at end of file +#endif // Header Include Guard diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h index e24c869f..ee034605 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/Module.h @@ -26,13 +26,20 @@ extern "C" { #endif - /* ${SCHEMAS} */ +// Enums - /* ${ACCESSORS} */ - /* ${DECLARATIONS} */ +/* ${ENUMS} */ + +// Types + +/* ${TYPES} */ + +/* ${ACCESSORS} */ + +/* ${DECLARATIONS} */ #ifdef __cplusplus } #endif -#endif // Header Include Guard \ No newline at end of file +#endif // Header Include Guard diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index b5522fd6..346d07cd 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -24,12 +24,13 @@ namespace FireboltSDK { namespace ${info.title} { + // Types - /* ${TYPES} */ - + /* ${TYPES} */ } } +/* ${ENUMS} */ #ifdef __cplusplus extern "C" { @@ -38,7 +39,6 @@ extern "C" { /* ${ACCESSORS} */ /* ${METHODS} */ - #ifdef __cplusplus } #endif diff --git a/languages/c/templates/schemas/default.c b/languages/c/templates/schemas/default.c index bc9ab873..a2058da5 100644 --- a/languages/c/templates/schemas/default.c +++ b/languages/c/templates/schemas/default.c @@ -1,5 +1,4 @@ - /** - * ${schema.description} - */ - +/* + * ${schema.description} + */ ${schema.shape} diff --git a/languages/c/templates/schemas/include/Common/Module.h b/languages/c/templates/schemas/include/Common/Module.h index 50ef1fd9..0326c220 100644 --- a/languages/c/templates/schemas/include/Common/Module.h +++ b/languages/c/templates/schemas/include/Common/Module.h @@ -25,16 +25,14 @@ extern "C" { #endif - // Enums +// Enums - /* ${ENUMS} */ +/* ${ENUMS} */ - // Types - - /* ${TYPES} */ +/* ${TYPES} */ #ifdef __cplusplus } #endif -#endif // Header Include Guard \ No newline at end of file +#endif // Header Include Guard diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/JsonData_Module.h index 4cee1781..9ba90428 100644 --- a/languages/c/templates/schemas/src/JsonData_Module.h +++ b/languages/c/templates/schemas/src/JsonData_Module.h @@ -17,7 +17,9 @@ */ namespace FireboltSDK { + namespace ${info.title} { + // Types - /* ${DECLARATIONS} */ - + /* ${SCHEMAS}*/ + } } diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/Module_Common.cpp index 632f38d6..9dc2ee0a 100644 --- a/languages/c/templates/schemas/src/Module_Common.cpp +++ b/languages/c/templates/schemas/src/Module_Common.cpp @@ -21,11 +21,12 @@ #include "Common/${info.title}.h" #include "JsonData_${info.title}.h" +/* ${ENUMS} */ + #ifdef __cplusplus extern "C" { #endif - /* ${TYPES} */ /* ${ACCESSORS} */ /* ${METHODS} */ diff --git a/languages/c/templates/sections/enum.cpp b/languages/c/templates/sections/enum.cpp new file mode 100644 index 00000000..e5165c61 --- /dev/null +++ b/languages/c/templates/sections/enum.cpp @@ -0,0 +1,5 @@ +namespace WPEFramework { + +${schema.list} + +} diff --git a/languages/c/templates/sections/schemas.c b/languages/c/templates/sections/schemas.c index a1847009..9295133c 100644 --- a/languages/c/templates/sections/schemas.c +++ b/languages/c/templates/sections/schemas.c @@ -1,3 +1 @@ -// Types & Enums - ${schema.list} diff --git a/languages/c/templates/sections/types.c b/languages/c/templates/sections/types.c index a2d20dbb..9295133c 100644 --- a/languages/c/templates/sections/types.c +++ b/languages/c/templates/sections/types.c @@ -1,3 +1 @@ -// Types - ${schema.list} diff --git a/languages/c/templates/types/enum.cpp b/languages/c/templates/types/enum.cpp new file mode 100644 index 00000000..ddda2ae9 --- /dev/null +++ b/languages/c/templates/types/enum.cpp @@ -0,0 +1,4 @@ + /* ${title} ${description} */ + ENUM_CONVERSION_BEGIN(${info.title}_${name}) + { ${info.TITLE}_${NAME}_${key}, _T("${value}") }, + ENUM_CONVERSION_END(${info.title}_${name}) diff --git a/languages/c/templates/types/enum.c b/languages/c/templates/types/enum.h similarity index 71% rename from languages/c/templates/types/enum.c rename to languages/c/templates/types/enum.h index 2a8e94d7..6926fa77 100644 --- a/languages/c/templates/types/enum.c +++ b/languages/c/templates/types/enum.h @@ -1,3 +1,4 @@ +/* ${title} ${description} */ typedef enum { ${info.TITLE}_${NAME}_${key}, } ${info.title}_${name}; diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 958f0bea..2e5e4f93 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -64,6 +64,8 @@ const state = { section: undefined } +const capitalize = str => str[0].toUpperCase() + str.substr(1) + const setTyper = (t) => { types = t } @@ -73,7 +75,7 @@ const setConfig = (c) => { } const getTemplate = (name, templates) => { - return templates[Object.keys(templates).find(k => k.startsWith(name + '.'))] || '' + return templates[Object.keys(templates).find(k => k === name)] || templates[Object.keys(templates).find(k => k.startsWith(name + '.'))] || '' } const getTemplateTypeForMethod = (method, type, templates) => { @@ -322,7 +324,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { const imports = generateImports(obj, templates) const initialization = generateInitialization(obj, templates) - const enums = generateEnums(obj, templates) + const enums = generateEnums(obj, templates, { destination : (options.destination ? options.destination : '') }) const eventsEnum = generateEvents(obj, templates) const examples = generateExamples(obj, templates, languages) @@ -486,29 +488,80 @@ function insertTableofContents(content) { return content } +const isEnumType = x => x.type !== 'undefined' && x.type === 'string' && Array.isArray(x.enum) + +const getProperties = x => { + return Array.isArray(x.properties) ? x.properties[0] : x.properties +} + +const isEnumProperties = schema => compose( + getProperties, + filter(enm => enm), + map(filter(enm => enm)), + map(props => props.map(([k, v]) => ((v.type === 'object') ? isEnumProperties(v) : ((v.type === 'array') ? isEnumType(v.items[0] ? v.items[0] : v.items): isEnumType(v))))), + map(Object.entries), + filter(schema => isObject(schema)) +)(schema) + +const getEnumProperties = schema => compose( + getProperties, + filter(enm => enm), + map(filter(isEnumType)), + map(props => props.map(([k, v]) => { + let enm = v + if (isEnumType(v) == true) { + enm = Object.assign({}, v) + enm.title = k + } else if (v.type === 'object') { + enm = getEnumProperties(v) + } else if (v.type === 'array') { + enm = Object.assign({}, (v.items[0] ? v.items[0] : v.items)) + enm.title = k + } + return enm + })), + map(Object.entries), + filter(schema => isObject(schema)) +)(schema) + +const convertEnumTemplate = (sch, templateName, templates) => { + const template = getTemplate(templateName, templates).split('\n') + let schema = isEnumType(sch) ? sch : getEnumProperties(sch) + for (var i = 0; i < template.length; i++) { + if (template[i].indexOf('${key}') >= 0) { + template[i] = schema.enum.map(value => { + const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + return template[i].replace(/\$\{key\}/g, safeName) + .replace(/\$\{value\}/g, value) + }).join('\n') + if (!templateName.includes(".cpp")) { + template[i] = template[i].replace(/,*$/, ''); + } + } + } + return template.join('\n') + .replace(/\$\{title\}/g, capitalize(schema.title)) + .replace(/\$\{description\}/g, schema.description ? ('- ' + schema.description) : '') + .replace(/\$\{name\}/g, schema.title) + .replace(/\$\{NAME\}/g, schema.title.toUpperCase()) +} + const enumFinder = compose( - filter(x => x.type === 'string' && Array.isArray(x.enum) && x.title), + filter(x => ((isEnumType(x) && x.title) || isEnumProperties(x))), map(([_, val]) => val), filter(([_key, val]) => isObject(val)) ) -const generateEnums = (json, templates) => { +const generateEnums = (json, templates, options = { destination: '' }) => { + const suffix = options.destination.split('.').pop() return compose( option(''), + map(val => { + let template = getTemplate(`/sections/enum.${suffix}`, templates) + return template ? template.replace(/\$\{schema.list\}/g, val.trimEnd()) : val + }), map(reduce((acc, val) => acc.concat(val).concat('\n'), '')), - map(map((schema) => { - const template = getTemplate('/types/enum', templates).split('\n') - for (var i = 0; i < template.length; i++) { - if (template[i].indexOf('${key}') >= 0) { - template[i] = schema.enum.map(value => { - const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() - return template[i].replace(/\$\{key\}/g, safeName) - .replace(/\$\{value\}/g, value) - }).join('\n') - } - } - return template.join('\n').replace(/\$\{name\}/g, schema.title).replace(/\$\{NAME\}/g, schema.title.toUpperCase()) - })), + map(map((schema) => convertEnumTemplate(schema, suffix ? `/types/enum.${suffix}` : '/types/enum', templates))), map(enumFinder), getSchemas )(json) @@ -701,8 +754,6 @@ const generateImports = (json, templates) => { imports += getTemplate('/imports/x-method', templates) } - - if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0) { imports += Object.keys(json['x-schemas']).map(shared => getTemplate('/imports/default', templates).replace(/\$\{info.title\}/g, shared)).join('\n') } @@ -1240,7 +1291,6 @@ function generateProviderInterfaces(json, templates) { function insertProviderInterfaceMacros(template, capability, moduleJson = {}, templates) { const iface = getProviderInterface(capability, moduleJson, { destination: state.destination, section: state.section })//.map(method => { method.name = method.name.charAt(9).toLowerCase() + method.name.substr(10); return method } ) - const capitalize = str => str[0].toUpperCase() + str.substr(1) const uglyName = capability.split(":").slice(-2).map(capitalize).reverse().join('') + "Provider" let name = iface.length === 1 ? iface[0].name.charAt(0).toUpperCase() + iface[0].name.substr(1) + "Provider" : uglyName @@ -1394,4 +1444,4 @@ export default { insertAggregateMacros, setTyper, setConfig -} \ No newline at end of file +} From e3cf4712ddc763634c9503204d851c30e7742c68 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 5 Jun 2023 21:54:53 +0530 Subject: [PATCH 040/137] Types and Accessor related fixes (#94) Types and Accessor related fixes: 1. Accessor creation 2. JsonContainer creation 3. Types order placed based on depenedencies 4. filtered redundant new lines 5. UnamedSchema issue fixes 6. Types and Accessors: generation added for objects inside methods result/params 7. AnyOf support added --- languages/c/Types.mjs | 915 ++++++++++++------ languages/c/src/types/ImplHelpers.mjs | 392 ++++---- languages/c/src/types/JSONHelpers.mjs | 67 +- languages/c/src/types/NativeHelpers.mjs | 141 +-- languages/c/templates/methods/property.c | 16 +- .../c/templates/modules/include/Module.h | 4 - languages/c/templates/modules/src/Module.cpp | 1 - languages/c/templates/schemas/default.c | 3 - .../c/templates/schemas/src/JsonData_Module.h | 2 +- languages/c/templates/sections/accessors.c | 1 - languages/c/templates/sections/methods.c | 3 +- .../c/templates/sections/methods_accessors.c | 1 + .../c/templates/sections/methods_types.c | 1 + src/macrofier/engine.mjs | 79 +- src/macrofier/index.mjs | 4 +- 15 files changed, 993 insertions(+), 637 deletions(-) create mode 100644 languages/c/templates/sections/methods_accessors.c create mode 100644 languages/c/templates/sections/methods_types.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index e44b4a78..0bb6cc59 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -18,365 +18,660 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' -import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors } from './src/types/NativeHelpers.mjs' -import { getObjectHandleManagementImpl, getPropertyAccessorsImpl } from './src/types/ImplHelpers.mjs' -import { getJsonContainerDefinition } from './src/types/JSONHelpers.mjs' +import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema } from './src/types/NativeHelpers.mjs' +import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getPropertyAccessorsImpl } from './src/types/ImplHelpers.mjs' +import { getJsonContainerDefinition, getJsonDataStructName } from './src/types/JSONHelpers.mjs' -function getMethodSignature(method, module, { destination, isInterface = false }) { - const extraParam = '${method.result.type}* ${method.result.name}' - - const prefix = method.tags.find(t => t.name.split(":")[0] === "property") ? "Get" : "" +const getSdkNameSpace = () => 'FireboltSDK' +const getJsonNativeTypeForOpaqueString = () => getSdkNameSpace() + '::JSON::String' +const getEnumName = (name, prefix) => ((prefix.length > 0) ? (prefix + '_' + name) : name) - return 'uint32_t ${info.title}_' + prefix + '${method.Name}(' + extraParam + ')' +const getRefModule = (title) => { + let module = { + info: { + title: `${title}` + } + } + return module } -function getMethodSignatureParams(method, module, { destination }) { - return method.params.map(param => param.name + (!param.required ? '?' : '') + ': ' + getSchemaType(param.schema, module, { title: true, destination })).join(', ') +const hasProperties = (prop) => { + let hasProperty = false + if (prop.properties) { + hasProperty = true + } else if (prop.additionalProperties && ( prop.additionalProperties.type && (((prop.additionalProperties.type === 'object') && prop.additionalProperties.properties) || (prop.additionalProperties.type !== 'object')))) { + hasProperty = true + } + return hasProperty } -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaType(schema, module, { name, destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - let type = '' - let theTitle = schema.title || name || ('UnamedSchema' + (Math.floor(Math.random() * 100))) +function validJsonObjectProperties(json = {}) { - if (schema['x-method']) { - console.log(`WARNING UNHANDLED: x-method in ${theTitle}`) - //throw "x-methods not supported yet" - } - - if (schema['$ref']) { - if (schema['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType - let definition = getPath(schema['$ref'], module) - let tName = definition.title || schema['$ref'].split('/').pop() - return getSchemaType(definition, module, { name: tName, destination, link, title, code, asPath, event, expandEnums, baseUrl }) + let valid = true + if (json.type === 'object' || (json.additonalProperties && typeof json.additonalProperties.type === 'object')) { + if (json.properties || json.additonalProperties) { + Object.entries(json.properties || json.additonalProperties).every(([pname, prop]) => { + if (!prop['$ref'] && (pname !== 'additionalProperties') && + ((!prop.type && !prop.const && (prop.schema && !prop.schema.type)) || (Array.isArray(prop.type) && (prop.type.find(t => t === 'null'))))) { + valid = false } + return valid + }) } - else if (schema.const) { - type = getNativeType(schema) - return type - } - else if (schema.type === 'string' && schema.enum) { - //Enum - let typeName = getTypeName(getModuleName(module), theTitle) - return typeName - } - else if (Array.isArray(schema.type)) { - let type = schema.type.find(t => t !== 'null') - console.log(`WARNING UNHANDLED: type is an array containing ${schema.type}`) - } - else if (schema.type === 'array' && schema.items) { - let res - if (Array.isArray(schema.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(schema.items)) { - throw 'Heterogenous Arrays not supported yet' - } - res = getSchemaType(schema.items[0], module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) - } - else { - // grab the type for the non-array schema - res = getSchemaType(schema.items, module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) - } + } + return valid +} - if (!schema.title && !name) { - console.log(`WARNING: generated name for ${module.info.title} schema w/ no title: ${theTitle}`) - console.dir(schema) +function union(schemas, module, commonSchemas) { + + const result = {}; + for (const schema of schemas) { + for (const [key, value] of Object.entries(schema)) { + if (!result.hasOwnProperty(key)) { + // If the key does not already exist in the result schema, add it + if (value && value.anyOf) { + result[key] = union(value.anyOf, module, commonSchemas) + } else if (key === 'title' || key === 'description' || key === 'required') { + //console.warn(`Ignoring "${key}"`) + } else { + result[key] = value; } - - let n = getTypeName(getModuleName(module), theTitle) - return n + 'ArrayHandle' - } - else if (schema.allOf) { - let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x)]) - if (theTitle) { - union['title'] = theTitle + } else if (key === 'type') { + // If the key is 'type', merge the types of the two schemas + if(result[key] === value) { + //console.warn(`Ignoring "${key}" that is already present and same`) + } else { + console.warn(`ERROR "${key}" is not same -${JSON.stringify(result, null, 4)} ${key} ${result[key]} - ${value}`); + throw "ERROR: type is not same" } - delete union['$ref'] - return getSchemaType(union, module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) - } - else if (schema.oneOf || schema.anyOf) { - return type - //TODO - } - else if (schema.type === 'object') { - if (!schema.title && !name) { - console.log(`WARNING: generated name for ${module.info.title} schema w/ no title: ${theTitle}`) - console.dir(schema) + } else { + //If the Key is a const then merge them into an enum + if(value && value.const) { + if(result[key].enum) { + result[key].enum = Array.from(new Set([...result[key].enum, value.const])) + } + else { + result[key].enum = Array.from(new Set([result[key].const, value.const])) + delete result[key].const + } } - return getTypeName(getModuleName(module), theTitle) + 'Handle' - //TODO - } - else if (schema.type) { - type = getNativeType(schema) - return type + // If the key exists in both schemas and is not 'type', merge the values + else if (Array.isArray(result[key])) { + // If the value is an array, concatenate the arrays and remove duplicates + result[key] = Array.from(new Set([...result[key], ...value])) + } else if (result[key] && result[key].enum && value && value.enum) { + //If the value is an enum, merge the enums together and remove duplicates + result[key].enum = Array.from(new Set([...result[key].enum, ...value.enum])) + } else if (typeof result[key] === 'object' && typeof value === 'object') { + // If the value is an object, recursively merge the objects + result[key] = union([result[key], value], module, commonSchemas); + } else if (result[key] !== value) { + // If the value is a primitive and is not the same in both schemas, ignore it + //console.warn(`Ignoring conflicting value for key "${key}"`) + } + } } - - // TODO: deal with dependencies - return type + } + return result; } -//function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, summary, descriptions = true, destination, enums = true } = {}) -// function getSchemaType() -function getSchemaShape(schema, module, { name = '', level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { - const isHeader = destination.endsWith(".h") - const isCPP = (destination.endsWith(".cpp") && section !== 'accessors') +function getMergedSchema(module, json, name, schemas) { + let refsResolved = [...json.anyOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)] + let allOfsResolved = refsResolved.map(sch => sch.allOf ? deepmerge.all([...sch.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)]) : sch) - schema = JSON.parse(JSON.stringify(schema)) + let mergedSchema = union(allOfsResolved, module, schemas) + if (json.title) { + mergedSchema['title'] = json.title + } + else { + mergedSchema['title'] = name + } - let shape = '' + delete mergedSchema['$ref'] + return mergedSchema +} - name = schema.title || name +const deepMergeAll = (module, name, schema, schemas, options) => { + let nonRefsProperty = [...schema.allOf.map(x => x['$ref'] ? '' : x)].filter(elm => elm) + let refsProperty = [...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) : '')].filter(elm => elm) + let mergedProperty = [] + let mergedParamSchema = { + type: "object", + properties: {} + } + + nonRefsProperty.forEach(p => { + if (p.properties) { + Object.entries(p.properties).every(([pname, prop]) => { + let present = false + refsProperty.forEach(refP => { + if (refP.properties) { + Object.entries(refP.properties).every(([refname, refprop]) => { + if (refname == pname) { + present = true + } + return !present + }) + } + }) + let prefixedName = (present == false) ? (name + capitalize(pname)) : pname + mergedParamSchema.properties[prefixedName] = prop + return true + }) + mergedProperty.push(mergedParamSchema) + } + }) + refsProperty.forEach(ref => mergedProperty.push(ref)) + let union = deepmerge.all(mergedProperty) + + return union +} - if (!name) { - console.log(`WARNING: schema without a name in ${module.info.title}`) - return shape - } +function getMethodSignature(method, module, { destination, isInterface = false }) { + const extraParam = '${method.result.type}* ${method.result.name}' - if (schema['$ref']) { - if (schema['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType + const prefix = method.tags.find(t => t.name.split(":")[0] === "property") ? "Get" : "" - const schema = getPath(schema['$ref'], module) - const tname = name || schema['$ref'].split('/').pop() - return getSchemaShape(schema, module, { name: tname, descriptions: descriptions, level: level }) - } - } - //If the schema is a const, - else if (schema.hasOwnProperty('const') && !isCPP) { - if (level > 0) { + return 'uint32_t ${info.title}_' + prefix + '${method.Name}(' + extraParam + ')' +} - let t = description(name, schema.description) - typeName = getTypeName(getModuleName(module), name) - t += (isHeader ? getPropertyAccessors(typeName, capitalize(name), typeof schema.const, { level: level, readonly: true, optional: false }) : getPropertyAccessorsImpl(typeName, capitalize(name), getJsonType(schema, module, { level, name }), typeof schema.const, { level: level, readonly: true, optional: false })) - shape += '\n' + t - } - } - else if (schema.type === 'object') { - if (!name) { - console.log(`WARNING: unnamed schema in ${module.info.title}.`) - console.dir(schema) - shape = '' - } - else if (schema.properties) { - let tName = getTypeName(getModuleName(module), name) - let c_shape = description(name, schema.description) - let cpp_shape = '' - c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(schema, module, { name }))) - Object.entries(schema.properties).forEach(([pname, prop]) => { - c_shape += '\n' + description(pname, prop.description) - let res - if (prop.type === 'array') { - if (Array.isArray(prop.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(prop.items)) { - throw 'Heterogenous Arrays not supported yet' - } - res = getSchemaType(prop.items[0], module, { name: pname, level: level, descriptions: descriptions, title: true }) - } - else { - // grab the type for the non-array schema - res = getSchemaType(prop.items, module, { name: pname, level: level, descriptions: descriptions, title: true }) - } - if (res && res.length > 0) { - let n = tName + '_' + capitalize(pname || prop.title) - let def = getArrayAccessors(n + 'Array', res) - c_shape += '\n' + def - } - else { - console.log(`a. WARNING: Type undetermined for ${name}:${pname}`) - } - } else { - res = getSchemaType(prop, module, { name: pname, descriptions: descriptions, level: level + 1, title: true }) - if (res && res.length > 0) { - c_shape += '\n' + (isHeader ? getPropertyAccessors(tName, capitalize(pname), res, { level: level, readonly: false, optional: isOptional(pname, schema) }) : getPropertyAccessorsImpl(tName, capitalize(pname), getJsonType(prop, module, { level, name }), res, { level: level, readonly: false, optional: isOptional(pname, schema) })) - } - else { - console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) - } - } - }) - cpp_shape += getJsonContainerDefinition(tName, Object.entries(schema.properties).map(([name, prop]) => ({ name, type: getJsonType(prop, module) }))) +function getMethodSignatureParams(method, module, { destination }) { - if (isCPP) { - shape += '\n' + cpp_shape - } - else { - shape += '\n' + c_shape - } - } - else if (schema.propertyNames && schema.propertyNames.enum) { - //propertyNames in object not handled yet - } - else if (schema.additionalProperties && (typeof schema.additionalProperties === 'object') && !isCPP) { - //This is a map of string to type in schema - //Get the Type - let type = getSchemaType(schema.additionalProperties, module, { name: name }) - if (type && type.length > 0) { - let tName = getTypeName(getModuleName(module), name) - // type.deps.forEach(dep => structure.deps.add(dep)) - let t = description(name, schema.description) - t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(schema, module, { name }))) - t += getMapAccessors(getTypeName(getModuleName(module), name), type, { descriptions: descriptions, level: level }) - shape += '\n' + t - } - else { - console.log(`c. WARNING: Type undetermined for ${name}`) - } - } - else if (schema.patternProperties) { - console.log(`WARNING: patternProperties not supported yet...`) - // throw "patternProperties are not supported by Firebolt" - } - } - else if (schema.anyOf) { + return method.params.map(param => param.name + (!param.required ? '?' : '') + ': ' + getSchemaType(param.schema, module, { name: param.name, title: true, destination })).join(', ') +} - } - else if (schema.oneOf) { +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - } - else if (schema.allOf) { - let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x)]) - if (name) { - union['title'] = name - } - delete union['$ref'] - return getSchemaShape(union, module, { name, level, title, summary, descriptions, destination, section, enums }) +function getSchemaType(schema, module, { name, prefix = '', destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + let info = getSchemaTypeInfo(module, schema, name, module['x-schemas'], prefix, { title: title }) + return info.type +} - } - else if (schema.type === 'array') { - let res = getSchemaType(schema, module, { name, level: 0, descriptions: descriptions }) - // res.deps.forEach(dep => structure.deps.add(dep)) +function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = {level: 0, descriptions: true, title: false}) { + + if (json.schema) { + json = json.schema + } + + let structure = {} + structure["type"] = '' + structure["json"] = [] + structure["name"] = {} + structure["namespace"] = {} + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(json['$ref'], module, schemas) + let tName = definition.title || json['$ref'].split('/').pop() + let schema = module + if (json['$ref'].includes('x-schemas')) { + schema = (getRefModule(json['$ref'].split('/')[2])) + } + + const res = getSchemaTypeInfo(schema, definition, tName, schemas, '', options) + structure.type = res.type + structure.json = res.json + structure.name = res.name + structure.namespace = res.namespace + return structure + } + } + else if (json.const) { + structure.type = getNativeType(json) + structure.json = json + return structure + } + else if (json['x-method']) { + console.log(`WARNING UNHANDLED: x-method in ${name}`) + return structure + //throw "x-methods not supported yet" + } + else if (json.type === 'string' && json.enum) { + //Enum + structure.name = name || json.title + let typeName = getTypeName(getModuleName(module), name || json.title, prefix, false, false) + let res = description(capitalize(name || json.title), json.description) + '\n' + generateEnum(json, typeName) + structure.json = json + structure.type = typeName + structure.namespace = getModuleName(module) + return structure + } + else if (Array.isArray(json.type)) { + let type = json.type.find(t => t !== 'null') + console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) + } + else if (json.type === 'array' && json.items && (validJsonObjectProperties(json) === true)) { + let res = '' + if (Array.isArray(json.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(json.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getSchemaTypeInfo(module, json.items[0], json.items[0].name || name, schemas, prefix) } else { - let res = getSchemaType(schema, module, { name, level: level, descriptions: descriptions }) - // res.deps.forEach(dep => structure.deps.add(dep)) + // grab the type for the non-array schema + res = getSchemaTypeInfo(module, json.items, json.items.name || name, schemas, prefix) + } + + let arrayName = capitalize(res.name) + capitalize(res.json.type) + let n = getTypeName(getModuleName(module), arrayName, prefix) + structure.name = res.name || name && (capitalize(name)) + structure.type = n + 'ArrayHandle' + structure.json = json + structure.namespace = getModuleName(module) + return structure + } + else if (json.allOf) { + let title = json.title ? json.title : name + let union = deepMergeAll(module, title, json, schemas, options) + union['title'] = title + + delete union['$ref'] + return getSchemaTypeInfo(module, union, '', schemas, '', options) + } + else if (json.oneOf) { + structure.type = 'char*' + structure.json.type = 'string' + return structure + } + else if (json.anyOf) { + let mergedSchema = getMergedSchema(module, json, name, schemas) + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + return getSchemaTypeInfo(module, mergedSchema, '', schemas, prefixName, options) + } + else if (json.type === 'object') { + structure.json = json + if (hasProperties(json)) { + structure.type = getTypeName(getModuleName(module), json.title || name, prefix) + 'Handle' + structure.name = (json.name ? json.name : (json.title ? json.title : name)) + structure.namespace = (json.namespace ? json.namespace : getModuleName(module)) } - // console.dir(structure.deps) - return shape -} - -// function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - -const getJsonDataStructName = (modName, name) => `${capitalize(modName)}::${capitalize(name)}` - -const getJsonNativeType = json => { - let type - let jsonType = json.const ? typeof json.const : json.type - - if (jsonType === 'string') { - type = 'WPEFramework::Core::JSON::String' - } - else if (jsonType === 'number' || json.type === 'integer') { //Lets keep it simple for now - type = 'WPEFramework::Core::JSON::Number' + else { + structure.type = 'char*' } - else if (jsonType === 'boolean') { - type = 'WPEFramework::Core::JSON::Boolean' + if (name) { + structure.name = capitalize(name) } - else { - throw 'Unknown JSON Native Type !!!' + + return structure + } + else if (json.type) { + structure.type = getNativeType(json) + structure.json = json + if (name || json.title) { + structure.name = capitalize(name || json.title) } - return type -} + structure.namespace = getModuleName(module) -function getJsonType(schema = {}, module = {}, { name = '', descriptions = false, level = 0 } = {}) { + return structure + } + return structure +} - let type = '' +function getSchemaShape(json, module, { name = '', prefix = '', level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { - if (schema['$ref']) { - if (schema['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType - let definition = getPath(schema['$ref'], module) - let tName = definition.title || schema['$ref'].split('/').pop() - return getJsonType(definition, module, { name: tName, descriptions: descriptions, level: level }) - } - } - else if (schema.const) { - return getJsonNativeType(schema) - } - else if (schema['x-method']) { - console.log(`WARNING: x-methods are not supported yet...`) - return type - //throw "x-methods not supported yet" - } - else if (schema.type === 'string' && schema.enum) { - //Enum - let t = getSchemaType(schema, module, { name }) - return 'WPEFramework::Core::JSON::EnumType<::' + t + '>' - } - else if (Array.isArray(schema.type)) { - let type = schema.type.find(t => t !== 'null') - console.log(`WARNING UNHANDLED: type is an array containing ${schema.type}`) + let shape = getSchemaShapeInfo(json, module, module['x-schemas'], { name, prefix, merged: false, level, title, summary, descriptions, destination, section, enums }) + return shape +} +function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '', merged = false, level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { + const isHeader = (destination.includes("JsonData_") !== true) && destination.endsWith(".h") + const isCPP = ((destination.endsWith(".cpp") || destination.includes("JsonData_")) && (section.includes('accessors') !== true)) + json = JSON.parse(JSON.stringify(json)) + + name = json.title || name + let shape = '' + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + const schema = getPath(json['$ref'], module, schemas) + const tname = schema.title || json['$ref'].split('/').pop() + if (json['$ref'].includes('x-schemas')) { + schema = (getRefModule(json['$ref'].split('/')[2])) + } + + shape = getSchemaShapeInfo(schema, module, schemas, { name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) + } + } + //If the schema is a const, + else if (json.hasOwnProperty('const') && !isCPP) { + if (level > 0) { + + let t = description(capitalize(name), json.description) + typeName = getTypeName(getModuleName(module), name, prefix) + t += (isHeader ? getPropertyAccessors(typeName, capitalize(name), typeof schema.const, { level: level, readonly: true, optional: false }) : getPropertyAccessorsImpl(typeName, getJsonType(schema, module, { level, name }), typeof schema.const, { level: level, readonly: true, optional: false })) + shape += '\n' + t } - else if (schema.type === 'array' && schema.items) { - let res - if (Array.isArray(schema.items)) { + } + else if (json.type === 'object') { + if (!name) { + console.log(`WARNING: unnamed schema in ${module.info.title}.`) + console.dir(json) + shape = '' + } + else if (json.properties && (validJsonObjectProperties(json) === true)) { + let c_shape = description(capitalize(name), json.description) + let cpp_shape = '' + let tName = getTypeName(getModuleName(module), name, prefix) + c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(json, module, { name }))) + let props = [] + let containerName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? (prefix + '_' + capitalize(name)) : capitalize(name) + Object.entries(json.properties).forEach(([pname, prop]) => { + let items + var desc = '\n' + description(capitalize(pname), prop.description) + if (prop.type === 'array') { + if (Array.isArray(prop.items)) { //TODO - const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(schema.items)) { - throw 'Heterogenous Arrays not supported yet' + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(prop.items)) { + throw 'Heterogenous Arrays not supported yet' } - res = getJsonType(schema.items[0], module, { name: '' }) - } - else { + items = prop.items[0] + } + else { // grab the type for the non-array schema - res = getJsonType(schema.items, module, { name: '' }) + items = prop.items + } + let info = getSchemaTypeInfo(module, items, items.name || pname, schemas, prefix, {level : level, descriptions: descriptions, title: true}) + if (info.type && info.type.length > 0) { + let objName = tName + '_' + capitalize(prop.title || pname) + let moduleName = info.namespace + info.json.namespace = info.namespace + let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) + let prefixName = ((prefix.length > 0) && items['$ref']) ? '' : prefix + let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, schemas, prefix) + + let t = description(capitalize(info.name), json.description) + '\n' + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) + c_shape += '\n' + t + props.push({name: `${pname}`, type: `WPEFramework::Core::JSON::ArrayType<${subModuleProperty.type}>`}) + } + else { + console.log(`a. WARNING: Type undetermined for ${name}:${pname}`) + } + } else { + if (((merged === false) || ((merged === true) && (pname.includes(name)))) && (prop.type === 'object' || prop.anyOf || prop.allOf)) { + shape += getSchemaShapeInfo(prop, module, schemas, { name : pname, prefix, merged: false, level: 1, title, summary, descriptions, destination, section, enums }) + } + let info = getSchemaTypeInfo(module, prop, pname, module['x-schemas'], prefix, {descriptions: descriptions, level: level + 1, title: true}) + if (info.type && info.type.length > 0) { + let subPropertyName = ((pname.length !== 0) ? capitalize(pname) : info.name) + let moduleProperty = getJsonTypeInfo(module, json, name, schemas, prefix) + let subProperty = getJsonTypeInfo(module, prop, pname, schemas, prefix) + c_shape += '\n' + description(capitalize(pname), info.json.description) + c_shape += '\n' + (isHeader ? getPropertyAccessors(tName, capitalize(pname), info.type, { level: 0, readonly: false, optional: isOptional(pname, json) }) : getPropertyAccessorsImpl(tName, moduleProperty.type, subProperty.type, subPropertyName, info.type, info.json, {readonly:false, optional:isOptional(pname, json)})) + let property = getJsonType(prop, module, { name : pname, prefix }) + props.push({name: `${pname}`, type: `${property}`}) + } + else { + console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) + } } - - return `WPEFramework::Core::JSON::ArrayType<${res}>` + }) + + cpp_shape += getJsonContainerDefinition(json, containerName, props) + + if (isCPP) { + shape += '\n' + cpp_shape + } + else { + shape += '\n' + c_shape + } + } + else if (json.propertyNames && json.propertyNames.enum) { + //propertyNames in object not handled yet + } + else if (json.additionalProperties && (typeof json.additionalProperties === 'object') && (validJsonObjectProperties(json) === true) && !isCPP) { + let info = getSchemaTypeInfo(module, json.additionalProperties, name, module['x-schemas'], prefix) + if (!info.type || (info.type.length === 0)) { + info.type = 'char*' + info.json = json.additionalProperties + info.json.type = 'string' + } + + let tName = getTypeName(getModuleName(module), name, prefix) + let t = description(capitalize(name), json.description) + '\n' + let containerType = 'WPEFramework::Core::JSON::VariantContainer' + + let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, module['x-schemas']) + if (isCPP && ((info.json.type === 'object' && info.json.properties) || info.json.type === 'array')) { + // Handle Container generation here + } + + t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, containerType)) + t += (isHeader ? getMapAccessors(tName, info.type, { descriptions: descriptions, level: level }) : getMapAccessorsImpl(tName, containerType, subModuleProperty.type, info.type, info.json, { readonly: true, optional: false })) + shape += '\n' + t + } + else if (json.patternProperties) { + console.log(`WARNING: patternProperties are not supported by Firebolt(inside getModuleName(module):${name})`) + } + } + else if (json.anyOf) { + if (level > 0) { + let mergedSchema = getMergedSchema(module, json, name, schemas) + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + shape += getSchemaShapeInfo(mergedSchema, module, schemas, { name, prefix: prefixName, merged, level, title, summary, descriptions, destination, section, enums }) + } + } + else if (json.oneOf) { + //Just ignore schema shape, since this has to be treated as string + } + else if (json.allOf) { + let title = (json.title ? json.title : name) + let union = deepMergeAll(module, title, json, schemas) + union.title = title + + delete union['$ref'] + + return getSchemaShapeInfo(union, module, schemas, { name, prefix, merged: true, level, title, summary, descriptions, destination, section, enums }) + } + else if (json.type === 'array' && !isCPP) { + let j + if (Array.isArray(json.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(json.items)) { + throw 'Heterogenous Arrays not supported yet' + } + j = json.items[0] } - else if (schema.allOf) { - let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)]) - if (schema.title) { - union['title'] = schema.title - } - else { - union['title'] = name - } - delete union['$ref'] - return getJsonType(union, module, { name: '', level, descriptions }) - } - else if (schema.oneOf || schema.anyOf) { - return type - //TODO - } - else if (schema.type === 'object') { - if (!schema.title && !name) { - console.log(`WARNING: schema with no name`) - console.dir(schema) - return 'Unknown' - } - return getJsonDataStructName(getModuleName(module), schema.title || name) - //TODO - } - else if (schema.type) { - return getJsonNativeType(schema) - } - return type + else { + j = json.items + } + + let info = getSchemaTypeInfo(module, j, j.name || name, schemas, prefix, {level : level, descriptions: descriptions, title: true}) + + if (info.type && info.type.length > 0) { + let type = getArrayElementSchema(json, module, schemas, info.name) + let arrayName = capitalize(info.name) + capitalize(type.type) + let objName = getTypeName(info.namespace, arrayName, prefix) + let tName = objName + 'Array' + let moduleName = info.namespace + info.json.namespace = info.namespace + let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) + let t = '' + if (level === 0) { + t += description(capitalize(info.name), json.description) + '\n' + t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, moduleProperty.type)) + } + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + 'Handle'), getJsonNativeType(type), '', info.type, info.json)) + shape += '\n' + t + } + } + else { + shape += '\n' + getSchemaType(module, json, name, schemas, prefix, {level: level, descriptions: descriptions}) + } + + return shape } -function getTypeScriptType(jsonType) { - if (jsonType === 'integer') { - return 'number' +const getJsonNativeType = json => { + let type + let jsonType = json.const ? typeof json.const : json.type + + if (jsonType === 'string') { + type = getSdkNameSpace() + '::JSON::String' + } + else if (jsonType === 'number') { + type = 'WPEFramework::Core::JSON::Float' + } + else if (json.type === 'integer') { + type = 'WPEFramework::Core::JSON::DecSInt32' + } + else if (jsonType === 'boolean') { + type = 'WPEFramework::Core::JSON::Boolean' + } + else { + throw 'Unknown JSON Native Type !!!' + } + return type +} + +function getJsonType(schema = {}, module = {}, { name = '', prefix = '', descriptions = false, level = 0 } = {}) { + let info = getJsonTypeInfo(module, schema, name, module['x-schemas'], prefix, { descriptions: descriptions, level: level }) + return info.type +} + +function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '', {descriptions = false, level = 0} = {}) { + + if (json.schema) { + json = json.schema + } + + let structure = {} + structure["deps"] = new Set() //To avoid duplication of local ref definitions + structure["type"] = [] + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(json['$ref'], module, schemas) + let tName = definition.title || json['$ref'].split('/').pop() + + let schema = module + if (json['$ref'].includes('x-schemas')) { + schema = (getRefModule(json['$ref'].split('/')[2])) + } + + const res = getJsonTypeInfo(schema, definition, tName, schemas, '', {descriptions, level}) + structure.deps = res.deps + structure.type = res.type + return structure + } + } + else if (json.const) { + structure.type = getJsonNativeType(json) + return structure + } + else if (json['x-method']) { + return structure + //throw "x-methods not supported yet" + } + else if (json.additionalProperties && (typeof json.additionalProperties === 'object')) { + //This is a map of string to type in schema + //Get the Type + let type = getJsonTypeInfo(module, json.additionalProperties, name, schemas, prefix) + if (type.type && type.type.length > 0) { + structure.type = 'WPEFramework::Core::JSON::VariantContainer'; + return structure + } + else { + console.log(`WARNING: Type undetermined for ${name}`) + } + } + else if (json.type === 'string' && json.enum) { + //Enum + let t = 'WPEFramework::Core::JSON::EnumType<' + (json.namespace ? json.namespace : getModuleName(module)) + '_' + (getEnumName(name, prefix)) + '>' + structure.type.push(t) + return structure + } + else if (Array.isArray(json.type)) { + let type = json.type.find(t => t !== 'null') + console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) + } + else if (json.type === 'array' && json.items) { + let res + let items + if (Array.isArray(json.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(json.items)) { + throw 'Heterogenous Arrays not supported yet' + } + items = json.items[0] } else { - return jsonType + items = json.items + // grab the type for the non-array schema + } + res = getJsonTypeInfo(module, items, items.name || name, schemas, prefix) + structure.deps = res.deps + structure.type.push(`WPEFramework::Core::JSON::ArrayType<${res.type}>`) + + return structure + } + else if (json.allOf) { + let title = json.title ? json.title : name + let union = deepMergeAll(module, title, json, schemas) + union['title'] = title + + delete union['$ref'] + return getJsonTypeInfo(module, union, '', schemas, '', {descriptions, level}) + } + else if (json.oneOf) { + structure.type = getJsonNativeTypeForOpaqueString() + return structure + } + else if (json.patternProperties) { + structure.type = getJsonNativeTypeForOpaqueString() + return structure + } + else if (json.anyOf) { + let mergedSchema = getMergedSchema(module, json, name, schemas) + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + structure = getJsonTypeInfo(module, mergedSchema, name, schemas, prefixName, {descriptions, level}) + } + else if (json.type === 'object') { + if (hasProperties(json) !== true) { + structure.type = getJsonNativeTypeForOpaqueString() } + else { + let schema = getSchemaTypeInfo(module, json, name, module['x-schemas'], prefix) + if (schema.namespace && schema.namespace.length > 0) { + structure.type.push(getJsonDataStructName(schema.namespace, json.title || name, prefix)) + } + } + return structure + } + else if (json.type) { + structure.type = getJsonNativeType(json) + return structure + } + return structure +} + +function getTypeScriptType(jsonType) { + if (jsonType === 'integer') { + return 'number' + } + else { + return jsonType + } } const enumReducer = (acc, val, i, arr) => { - const keyName = val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() - acc = acc + ` ${keyName} = '${val}'` - if (i < arr.length - 1) { - acc = acc.concat(',\n') - } - return acc + const keyName = val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + acc = acc + ` ${keyName} = '${val}'` + if (i < arr.length - 1) { + acc = acc.concat(',\n') + } + return acc } export default { @@ -385,4 +680,4 @@ export default { getSchemaShape, getSchemaType, getJsonType -} \ No newline at end of file +} diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index f3b39cbf..47852c9e 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -1,28 +1,35 @@ const Indent = '\t' +const getSdkNameSpace = () => 'FireboltSDK' +const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' +const getFireboltStringType = () => 'FireboltTypes_StringHandle' + const getObjectHandleManagementImpl = (varName, jsonDataName) => { - let result = ` -${varName}Handle ${varName}Handle_Create(void) { + let result = `${varName}Handle ${varName}Handle_Create(void) +{ WPEFramework::Core::ProxyType<${jsonDataName}>* type = new WPEFramework::Core::ProxyType<${jsonDataName}>(); *type = WPEFramework::Core::ProxyType<${jsonDataName}>::Create(); return (static_cast<${varName}Handle>(type)); } -void ${varName}Handle_Addref(${varName}Handle handle) { +void ${varName}Handle_Addref(${varName}Handle handle) +{ ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); ASSERT(var->IsValid()); var->AddRef(); } -void ${varName}Handle_Release(${varName}Handle handle) { +void ${varName}Handle_Release(${varName}Handle handle) +{ ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); var->Release(); - if(var->IsValid() != true) { + if (var->IsValid() != true) { delete var; } } -bool ${varName}Handle_IsValid(${varName}Handle handle) { +bool ${varName}Handle_IsValid(${varName}Handle handle) +{ ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); ASSERT(var->IsValid()); @@ -32,263 +39,258 @@ bool ${varName}Handle_IsValid(${varName}Handle handle) { return result } -const getPropertyAccessorsImpl = (objName, propertyName, jsonDataName, propertyType, json = {}, options = {readonly:false, optional:false}) => { - - let result - if (json.type === 'object') { - result += `${objName}_${propertyName}Handle ${objName}_Get_${propertyName}(${objName}Handle handle) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); - - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyName}>(); - *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); - *(*object) = (*var)->${propertyName}; - return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' - } else if (json.type === 'array') { - result += `${objName}_${propertyName}ArrayHandle ${objName}_Get_${propertyName}(${objName}Handle handle) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); - - WPEFramework::Core::ProxyType>* object = new WPEFramework::Core::ProxyType>(); - *object = WPEFramework::Core::ProxyType>::Create(); - *(*object) = (*var)->${propertyName}.Element(); - return (static_cast<${objName}_${propertyType}ArrayHandle>(object));` + '\n' - } else if (json.enum) { - result += `${objName}_${propertyName} ${objName}_Get_${propertyName}(${objName}Handle handle) { +const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, subPropertyName, accessorPropertyType, json = {}, options = {readonly:false, optional:false}) => { + let result = '' + result += `${accessorPropertyType} ${objName}_Get_${subPropertyName}(${objName}Handle handle) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - - return static_cast<${propertyType}>((*var)->${propertyName}.Value());` + '\n' - } else { - result += `${propertyType} ${objName}_Get_${propertyName}(${objName}Handle handle) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid());` + '\n' - if (json.type === 'string') { - result += ` - return static_cast<${propertyType}>((*var)->${propertyName}.Value().c_str());` + '\n' - } else { - result += ` - return static_cast<${propertyType}>((*var)->${propertyName}.Value());` + '\n' +` + '\n' + if ((json.type === 'object') && (accessorPropertyType !== 'char*')) { + result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); + *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); + *(*element) = (*var)->${subPropertyName}; + return (static_cast<${accessorPropertyType}>(element));` + '\n' + } + else { + if ((typeof json.const === 'string') || (json.type === 'string' && !json.enum) || (accessorPropertyType === 'char*')) { + result += ` return (const_cast<${accessorPropertyType}>((*var)->${subPropertyName}.Value().c_str()));` + '\n' + } + else { + result += ` return (static_cast<${accessorPropertyType}>((*var)->${subPropertyName}.Value()));` + '\n' } } - result += ` -}` + '\n' - if (!options.readonly) { - if (json.type === 'object') { - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName}Handle ${propertyName.toLowerCase()}) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); + result += `}` + '\n' - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* object = static_cast*>(${propertyName.toLowerCase()}); - (*var)->${propertyName} = *(*object);` + '\n' - } - if (json.type === 'array') { - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName}ArrayHandle ${propertyName.toLowerCase()}) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); - WPEFramework::Core::ProxyType>* object = static_cast>*>(${propertyName.toLowerCase()}).Element(); - (*var)->${propertyName} = *(*object);` + '\n' - } if (json.enum) { - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName} ${propertyName.toLowerCase()}) { + if (!options.readonly) { + let type = (accessorPropertyType === getFireboltStringType()) ? 'char*' : accessorPropertyType + result += `void ${objName}_Set_${subPropertyName}(${objName}Handle handle, ${type} value)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); +` + '\n' - (*var)->${propertyName} = static_cast<${propertyType}>(${propertyName.toLowerCase()});` + '\n' + if (json.type === 'object' && (accessorPropertyType !== 'char*')) { + result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* object = static_cast*>(value); + (*var)->${subPropertyName} = *(*object);` + '\n' } else { - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${propertyType} ${propertyName.toLowerCase()}) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); - - (*var)->${propertyName} = static_cast<${propertyType}>(${propertyName.toLowerCase()});` + '\n' + result += ` (*var)->${subPropertyName} = value;` + '\n' } -result += `}` + '\n' + result += `}` + '\n' } if (options.optional === true) { - result += `${Indent.repeat(options.level)}bool ${objName}_has_${propertyName}(${objName}Handle handle) { + result += `bool ${objName}_Has_${subPropertyName}(${objName}Handle handle)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - return ((*var)->${propertyName}.IsSet()); + + return ((*var)->${subPropertyName}.IsSet()); }` + '\n' - result += `${Indent.repeat(options.level)}void ${objName}_clear_${propertyName}(${objName}Handle handle) { + result += `void ${objName}_Clear_${subPropertyName}(${objName}Handle handle)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - ((*var)->${propertyName}.Clear()); + ((*var)->${subPropertyName}.Clear()); }` + '\n' } + return result } +const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPropertyType, subPropertyName, accessorPropertyType, json = {}) => { + + let propertyName + if (subPropertyName) { + propertyName = '(*var)->' + `${subPropertyName}` + objName = objName + '_' + subPropertyName + } + else { + propertyName = '(*(*var))' + } -const getArrayAccessors = (objName, propertyName, propertyType, json = {}, options = {readonly:false, optional:false}) => { - let result = ` -uint32_t ${objName}_${propertyName}Array_Size(${objName}::${propertyName}ArrayHandle handle) { + let result = `uint32_t ${objName}Array_Size(${objHandleType} handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - return ((*var)->Length()); + return (${propertyName}.Length()); }` + '\n' - if (json.type === 'object') { -result += `${objName}_${propertyType}Handle ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { + result += `${accessorPropertyType} ${objName}Array_Get(${objHandleType} handle, uint32_t index) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); - ASSERT(var->IsValid()); - WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyType}>(); - *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); - *(*object) = (*var)->Get(index); - return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' - } else if (json.enum) { - result += `${objName}_${propertyType} ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); - ASSERT(var->IsValid()); - - return (static_cast<${propertyType}>((*var)->Get(index)));` + '\n' - } else { - result += `${propertyType} ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid());` + '\n' - if (json.type === 'string') { - result += `return (static_cast<${propertyType}>((*var)->Get(index).Value().c_str()));` + '\n' - } else { - result += `return (static_cast<${propertyType}>((*var)->Get(index)));` + '\n' - } + if ((json.type === 'object') || (json.type === 'array')) { + result += `WPEFramework::Core::ProxyType<${subPropertyType}>* object = new WPEFramework::Core::ProxyType<${subPropertyType}>(); + *object = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); + *(*object) = ${propertyName}.Get(index); + return (static_cast<${accessorPropertyType}>(object));` + '\n' + } + else { + if ((typeof json.const === 'string') || (json.type === 'string' && !json.enum)) { + result += ` return (const_cast<${accessorPropertyType}>(${propertyName}.Get(index).Value().c_str()));` + '\n' + } + else { + result += ` return (static_cast<${accessorPropertyType}>(${propertyName}.Get(index)));` + '\n' + } } result += `}` + '\n' - if (json.type === 'object') { - result += `void ${objName}_${propertyName}Array_Add(${objName}_${propertyName}ArrayHandle handle, ${objName}_${propertyType}Handle value) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); - ASSERT(var->IsValid()); - WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = static_cast*>(value); - - (*var)->Add(*(*object));` + '\n' - } else { - result += `void ${objName}_${propertyName}Array_Add(${objName}_${propertyName}ArrayHandle handle, ${propertyType} value) { + let type = (accessorPropertyType === getFireboltStringType()) ? 'char*' : accessorPropertyType + result += `void ${objName}Array_Add(${objHandleType} handle, ${type} value) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid());` + '\n' - if (json.type === 'string') { - result += `WPEFramework::Core::JSON::String element(value);` + '\n' - } else if (json.type === 'number') { - result += `WPEFramework::Core::JSON::Number element(value);` + '\n' - } else if (json.enum) { - result += `WPEFramework::Core::JSON::EnumType<${propertyType}> element(value);` + '\n' - } - result += `(*var)->Add(element);` + '\n' + + if ((json.type === 'object') || (json.type === 'array')) { + result += ` ${subPropertyType}& element = *(*(static_cast*>(value)));` + '\n' } - result += `}` + '\n' + else { + result += ` ${subPropertyType} element(value);` + '\n' + } + result += ` + ${propertyName}.Add(element); +}` + '\n' - result += `void ${objName}_${propertyName}Array_Clear(${objName}_${propertyName}ArrayHandle handle) { + result += `void ${objName}Array_Clear(${objHandleType} handle) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - (*var)->Clear(); + + ${propertyName}.Clear(); }` + '\n' return result } -const getMapAccessors = (objName, propertyName, propertyType, json = {}, options = {readonly:false, optional:false}) => { - let result = `uint32_t ${objName}_${propertyName}_KeysCount(${objName}_${propertyName}Handle handle) { +const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPropertyType, json = {}, options = {readonly:false, optional:false}) => { + let result = `uint32_t ${objName}_KeysCount(${objName}Handle handle) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - return (*var)->Size()); - - }` + '\n' - result += `void ${objName}_${propertyName}_AddKey(${objName}_${propertyName}Handle handle, char* key, ${propertyType} value) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); - ASSERT(var->IsValid());` + '\n' - - if (json.type === 'object') { - result += ` - (*var)->Add(key, value);` + '\n' - } else if (json.type === 'boolean') { - result += ` - WPEFramework::Core::JSON::Boolean element(value);` - } else if (json.type === 'string') { - result += ` - WPEFramework::Core::JSON::String element(value);` - } else if (json.type === 'number') { - result += ` - WPEFramework::Core::JSON::Number element(value);` - } else if (json.type === 'array') { - result += ` - WPEFramework::Core::JSON::ArrayType element(value);` - } else if (json.enum) { - result += ` - WPEFramework::Core::JSON::EnumType element(value); - (*var)->Add(key, element);` + '\n' + ${containerType}::Iterator elements = (*var)->Variants(); + uint32_t count = 0; + while (elements.Next()) { + count++; } - result += ` - }` + '\n' - result += `void ${objName}_${propertyName}_RemoveKey(${objName}_${propertyName}Handle handle, char* key) { + return (count); +}` + '\n' + result += `void ${objName}_AddKey(${objName}Handle handle, char* key, ${accessorPropertyType} value) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - - (*var)->Remove(key); - }` + '\n' +` + '\n' + let elementContainer = subPropertyType + if (containerType.includes('VariantContainer')) { + elementContainer = 'WPEFramework::Core::JSON::Variant' + } + if ((json.type === 'object') || (json.type === 'array' && json.items)) { + if (containerType.includes('VariantContainer')) { + result += ` ${subPropertyType}& container = *(*(static_cast*>(value)));` + '\n' + result += ` string containerStr;` + '\n' + result += ` element.ToString(containerStr);` + '\n' + result += ` WPEFramework::Core::JSON::VariantContainer containerVariant(containerStr);` + '\n' + result += ` WPEFramework::Core::JSON::Variant element = containerVariant;` + '\n' + } + else { + result += ` ${subPropertyType}& element = *(*(static_cast*>(value)));` + '\n' + } + } else { + result += ` ${elementContainer} element(value);` + '\n' + } + result += ` (*var)->Set(const_cast(key), element); +}` + '\n' - if (json.type === 'object') { - result += `${objName}_${propertyType}Handle ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { + result += `void ${objName}_RemoveKey(${objName}Handle handle, char* key) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyType}>(); - *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); - *(*object) = (*var)->Find(key); - return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' - } else if (json.type === 'array') { - result += `${objName}_${propertyType}ArrayHandle ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); - WPEFramework::Core::ProxyType>* object = new WPEFramework::Core::ProxyType>(); - *object = WPEFramework::Core::ProxyType>::Create(); - *(*object) = (*var)->Find(key); - return (static_cast<${objName}_${propertyType}ArrayHandle>(object));` + '\n' + (*var)->Remove(key); +}` + '\n' - } else { - result += `${propertyType} ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { + result += `${accessorPropertyType} ${objName}_FindKey(${objName}Handle handle, char* key) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); ASSERT(var->IsValid());` + '\n' - - if (json.type === 'string') { + if ((json.type === 'object') || (json.type === 'array') || + ((json.type === 'string' || (typeof json.const === 'string')) && !json.enum)) { + result += ` ${accessorPropertyType} status = nullptr;` + '\n' + } + else if (json.type === 'boolean') { + result += ` ${accessorPropertyType} status = false;` + '\n' + } + else { + result += ` ${accessorPropertyType} status = 0;` + '\n' + } + + result += ` + if ((*var)->HasLabel(key) == true) {` + if (json.type === 'object') { + result += ` + string objectStr; + (*var)->Get(key).Object().ToString(objectStr); + ${subPropertyType} objectMap; + objectMap.FromString(objectStr); + + WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); + *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); + *(*element) = objectMap; + + status = (static_cast<${accessorPropertyType}>(element));` + '\n' + } + else if (json.type === 'array' && json.items) { + result += ` + WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); + *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); + *(*element) = (*var)->Get(key).Array(); + status = (static_cast<${accessorPropertyType}>(element));` + '\n' + } + else { + if (json.type === 'string' || (typeof json.const === 'string')) { + if (json.enum) { + result += ` + status = (const_cast<${accessorPropertyType}>((*var)->Get(key).));` + '\n' + } + else { + result += ` + status = (const_cast<${accessorPropertyType}>((*var)->Get(key).String().c_str()));` + '\n' + } + } + else if (json.type === 'boolean') { + result += ` + status = (static_cast<${accessorPropertyType}>((*var)->Get(key).Boolean()));` + '\n' + } + else if (json.type === 'number') { result += ` - return (static_cast<${propertyType}>((*var)->(Find(key).Value().c_str())));` + '\n' - } else { + status = (static_cast<${accessorPropertyType}>((*var)->Get(key).Float()));` + '\n' + } + else if (json.type === 'integer') { result += ` - return (static_cast<${propertyType}>((*var)->(Find(key).Value())));` + '\n' + status = (static_cast<${accessorPropertyType}>((*var)->Get(key).Number()));` + '\n' } } - result += ` -}` + '\n' + result += ` } + return status; +}` return result } export { + getArrayAccessorsImpl, + getMapAccessorsImpl, getObjectHandleManagementImpl, getPropertyAccessorsImpl } diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index 97a9385a..3437c98c 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -1,31 +1,54 @@ const capitalize = str => str[0].toUpperCase() + str.substr(1) +const getSdkNameSpace = () => 'FireboltSDK' +const getJsonDataPrefix = () => 'JsonData_' +const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' -function getJsonContainerDefinition (name, props) { - name = capitalize(name) - let c = ` class ${name}: public Core::JSON::Container { - public: - ${name}(const ${name}&) = delete; - ${name}& operator=(const ${name}&) = delete; - ~${name}() override = default; - - public: - ${name}() - : Core::JSON::Container() - {` +const getJsonDataStructName = (modName, name, prefix = '') => { + let result =((prefix.length > 0) && (!name.startsWith(prefix))) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}_${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` + + return ((result.includes(wpeJsonNameSpace()) === true) ? result : `${getSdkNameSpace()}::${result}`) +} + +function getJsonContainerDefinition (schema, name, props) { + let c = schema.description ? (' /*\n * ${info.title} - ' + `${schema.description}\n */\n`) : '' + name = getJsonDataPrefix() + capitalize(name) + c += ` class ${name}: public WPEFramework::Core::JSON::Container { + public: + ~${name}() override = default; - props.forEach(prop => { - c += `\n Add(_T("${prop.name}"), &${capitalize(prop.name)});` - }) + public: + ${name}() + : WPEFramework::Core::JSON::Container() + {` - c += `\n }\n\n public:` + props.forEach(prop => { + c += `\n Add(_T("${prop.name}"), &${capitalize(prop.name)});` + }) + c += `\n }\n` + c += `\n ${name}(const ${name}& copy) + {` + props.forEach(prop => { + c += `\n Add(_T("${prop.name}"), &${capitalize(prop.name)});` + c += `\n ${capitalize(prop.name)} = copy.${capitalize(prop.name)};` + }) + c += ` + }\n + ${name}& operator=(const ${name}& rhs) + {` + props.forEach(prop => { + c += `\n ${capitalize(prop.name)} = rhs.${capitalize(prop.name)};` + }) + c += `\n return (*this); + }\n + public:` - props.forEach(prop => { - c += `\n ${prop.type} ${capitalize(prop.name)};` - }) + props.forEach(prop => { + c += `\n ${prop.type} ${capitalize(prop.name)};` + }) - c += '\n };' - return c - } + c += '\n };' + return c +} export { getJsonContainerDefinition diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 79242d1f..eac20c16 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -29,6 +29,7 @@ const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = pre const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' +const getFireboltStringType = () => 'FireboltTypes_StringHandle' const getHeaderText = () => { return `/* @@ -83,35 +84,53 @@ const SdkTypesPrefix = 'Firebolt' const Indent = ' ' -const getNativeType = json => { - let type - - if (json.const) { - if (typeof json.const === 'string') { - type = 'char*' - } - else if (typeof json.const === 'number') { - type = 'uint32_t' - if (json.const < 0) - type = 'int32_t' - } else if (typeof json.const === 'boolean'){ - type = 'bool' - } +const getArrayElementSchema = (json, module, schemas = {}, name) => { + let result = '' + if (json.type === 'array' && json.items) { + if (Array.isArray(json.items)) { + result = json.items[0] } - else if (json.type === 'string') { - type = 'char*' + else { + // grab the type for the non-array schema + result = json.items } - else if (json.type === 'number' || json.type === 'integer') { //Lets keep it simple for now - type = 'uint32_t' - if ((json.minimum && json.minimum < 0) - || (json.exclusiveMinimum && json.exclusiveMinimum < 0)) { - type = 'int32_t' - } + if (result['$ref']) { + result = getPath(result['$ref'], module, schemas) } - else if (json.type === 'boolean') { - type = 'bool' + } + else if (json.type == 'object') { + if (json.properties) { + Object.entries(json.properties).every(([pname, prop]) => { + if (prop.type === 'array') { + result = getArrayElementSchema(prop, module, schemas) + if (name === capitalize(pname)) { + return false + } + } + return true + }) } - return type + } + + return result +} + +const getNativeType = json => { + let type = '' + let jsonType = json.const ? typeof json.const : json.type + if (jsonType === 'string') { + type = 'char*' + } + else if (jsonType === 'number') { + type = 'float' + } + else if (jsonType === 'integer') { + type = 'int32_t' + } + else if (jsonType === 'boolean') { + type = 'bool' + } + return type } const getObjectHandleManagement = varName => { @@ -126,46 +145,51 @@ bool ${varName}Handle_IsValid(${varName}Handle handle); } const getPropertyAccessors = (objName, propertyName, propertyType, options = {level:0, readonly:false, optional:false}) => { - let result = `${Indent.repeat(options.level)}${propertyType} ${objName}_Get_${propertyName}(${objName}Handle handle);` + '\n' if (!options.readonly) { - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${propertyType} ${propertyName.toLowerCase()});` + '\n' + let type = (propertyType === getFireboltStringType()) ? 'char*' : propertyType + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${type} ${propertyName.toLowerCase()});` + '\n' } if (options.optional === true) { - result += `${Indent.repeat(options.level)}bool ${objName}_has_${propertyName}(${objName}Handle handle);` + '\n' - result += `${Indent.repeat(options.level)}void ${objName}_clear_${propertyName}(${objName}Handle handle);` + '\n' + result += `${Indent.repeat(options.level)}bool ${objName}_Has_${propertyName}(${objName}Handle handle);` + '\n' + result += `${Indent.repeat(options.level)}void ${objName}_Clear_${propertyName}(${objName}Handle handle);` + '\n' } return result } -const getMapAccessors = (typeName, nativeType, level=0) => { +const getMapAccessors = (typeName, accessorPropertyType, level = 0) => { let res res = `${Indent.repeat(level)}uint32_t ${typeName}_KeysCount(${typeName}Handle handle);` + '\n' - res += `${Indent.repeat(level)}void ${typeName}_AddKey(${typeName}Handle handle, char* key, ${nativeType} value);` + '\n' + res += `${Indent.repeat(level)}void ${typeName}_AddKey(${typeName}Handle handle, char* key, ${accessorPropertyType} value);` + '\n' res += `${Indent.repeat(level)}void ${typeName}_RemoveKey(${typeName}Handle handle, char* key);` + '\n' - res += `${Indent.repeat(level)}${nativeType} ${typeName}_FindKey(${typeName}Handle handle, char* key);` + '\n' + res += `${Indent.repeat(level)}${accessorPropertyType} ${typeName}_FindKey(${typeName}Handle handle, char* key);` + '\n' return res } -const getTypeName = (moduleName, varName, upperCase = false) => { - let mName = upperCase ? moduleName.toUpperCase() : capitalize(moduleName) - let vName = upperCase ? varName.toUpperCase() : capitalize(varName) +const getTypeName = (moduleName, varName, prefix = '', upperCase = false, capitalCase = true) => { - return `${mName}_${vName}` + let mName = upperCase ? moduleName.toUpperCase() : capitalize(moduleName) + let vName = upperCase ? varName.toUpperCase() : capitalCase ? capitalize(varName) : varName + if (prefix.length > 0) { + prefix = (!varName.startsWith(prefix)) ? (upperCase ? prefix.toUpperCase() : capitalize(prefix)) : '' + } + prefix = (prefix.length > 0) ?(upperCase ? prefix.toUpperCase() : capitalize(prefix)) : prefix + let name = (prefix.length > 0) ? `${mName}_${prefix}_${vName}` : `${mName}_${vName}` + return name } -const getArrayAccessors = (arrayName, valueType) => { +const getArrayAccessors = (arrayName, propertyType, valueType) => { - let res = `uint32_t ${arrayName}_Size(${arrayName}Handle handle);` + '\n' - res += `${valueType} ${arrayName}_Get(${arrayName}Handle handle, uint32_t index);` + '\n' - res += `void ${arrayName}_Add(${arrayName}Handle handle, ${valueType} value);` + '\n' - res += `void ${arrayName}_Clear(${arrayName}Handle handle);` + '\n' + let res = `uint32_t ${arrayName}Array_Size(${propertyType}Handle handle);` + '\n' + res += `${valueType} ${arrayName}Array_Get(${propertyType}Handle handle, uint32_t index);` + '\n' + res += `void ${arrayName}Array_Add(${propertyType}Handle handle, ${valueType} value);` + '\n' + res += `void ${arrayName}Array_Clear(${propertyType}Handle handle);` + '\n' return res } @@ -201,25 +225,25 @@ const getIncludeDefinitions = (json = {}, jsonData = false) => { .concat([`#include "Firebolt/Types.h"`]) } - function getPropertyGetterSignature(method, module, paramType) { - let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` - return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` - } +function getPropertyGetterSignature(method, module, paramType) { + let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` + return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` +} - function getPropertySetterSignature(method, module, paramType) { - let m = `${capitalize(getModuleName(module))}_Set${capitalize(method.name)}` - return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType} ${method.result.name || method.name} )` - } +function getPropertySetterSignature(method, module, paramType) { + let m = `${capitalize(getModuleName(module))}_Set${capitalize(method.name)}` + return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType} ${method.result.name || method.name} )` +} - function getPropertyEventCallbackSignature(method, module, paramType) { - return `typedef void (*On${capitalize(method.name)}Changed)(${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType})` - } +function getPropertyEventCallbackSignature(method, module, paramType) { + return `typedef void (*On${capitalize(method.name)}Changed)(${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType})` +} - function getPropertyEventSignature(method, module) { - return `${description(method.name, 'Listen to updates')}\n` + `uint32_t ${capitalize(getModuleName(module))}_Listen${capitalize(method.name)}Update(On${capitalize(method.name)}Changed notification, uint16_t* listenerId)` - } +function getPropertyEventSignature(method, module) { + return `${description(method.name, 'Listen to updates')}\n` + `uint32_t ${capitalize(getModuleName(module))}_Listen${capitalize(method.name)}Update(On${capitalize(method.name)}Changed notification, uint16_t* listenerId)` +} - export { +export { getHeaderText, getIncludeGuardOpen, getStyleGuardOpen, @@ -240,5 +264,6 @@ const getIncludeDefinitions = (json = {}, jsonData = false) => { getObjectHandleManagement, getPropertyAccessors, isOptional, - generateEnum - } + generateEnum, + getArrayElementSchema +} diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 8f301bea..1c70ba29 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,12 +1,12 @@ /* ${method.name} - ${method.description} */ uint32_t ${info.title}_Get${method.Name}(${method.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { - const string method = _T("${info.title}.${method.name}"); - FireboltSDK::${info.title}::${method.result.type} jsonResult; + const string method = _T("${info.title}.${method.name}"); + FireboltSDK::${info.title}::${method.result.type} jsonResult; - uint32_t status = FireboltSDK::Properties::Get(method, jsonResult); - if (status == FireboltSDKErrorNone) { - WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); - *${method.result.name} = static_cast<${info.title}_${method.result.type}Handle>(resultPtr); - } - return status; + uint32_t status = FireboltSDK::Properties::Get(method, jsonResult); + if (status == FireboltSDKErrorNone) { + WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); + *${method.result.name} = static_cast<${info.title}_${method.result.type}Handle>(resultPtr); + } + return status; } diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h index ee034605..a202f643 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/Module.h @@ -30,10 +30,6 @@ extern "C" { /* ${ENUMS} */ -// Types - -/* ${TYPES} */ - /* ${ACCESSORS} */ /* ${DECLARATIONS} */ diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 346d07cd..c412abf2 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -25,7 +25,6 @@ namespace FireboltSDK { namespace ${info.title} { // Types - /* ${TYPES} */ } } diff --git a/languages/c/templates/schemas/default.c b/languages/c/templates/schemas/default.c index a2058da5..9a52cff7 100644 --- a/languages/c/templates/schemas/default.c +++ b/languages/c/templates/schemas/default.c @@ -1,4 +1 @@ -/* - * ${schema.description} - */ ${schema.shape} diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/JsonData_Module.h index 9ba90428..7fa2b6f4 100644 --- a/languages/c/templates/schemas/src/JsonData_Module.h +++ b/languages/c/templates/schemas/src/JsonData_Module.h @@ -20,6 +20,6 @@ namespace FireboltSDK { namespace ${info.title} { // Types - /* ${SCHEMAS}*/ + /* ${SCHEMAS} */ } } diff --git a/languages/c/templates/sections/accessors.c b/languages/c/templates/sections/accessors.c index 0586b2a5..1c790810 100644 --- a/languages/c/templates/sections/accessors.c +++ b/languages/c/templates/sections/accessors.c @@ -1,3 +1,2 @@ // Accessors - ${schema.list} diff --git a/languages/c/templates/sections/methods.c b/languages/c/templates/sections/methods.c index 3f382a63..3ab606c0 100644 --- a/languages/c/templates/sections/methods.c +++ b/languages/c/templates/sections/methods.c @@ -1,3 +1,4 @@ - // Methods +// Methods + ${method.list} diff --git a/languages/c/templates/sections/methods_accessors.c b/languages/c/templates/sections/methods_accessors.c new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/c/templates/sections/methods_accessors.c @@ -0,0 +1 @@ +${schema.list} diff --git a/languages/c/templates/sections/methods_types.c b/languages/c/templates/sections/methods_types.c new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/c/templates/sections/methods_types.c @@ -0,0 +1 @@ +${schema.list} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 2e5e4f93..13ce46f4 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -65,6 +65,7 @@ const state = { } const capitalize = str => str[0].toUpperCase() + str.substr(1) +const hasMethodsSchema = (json, options) => json.methods && json.methods.length const setTyper = (t) => { types = t @@ -101,15 +102,11 @@ const getTemplateForExampleResult = (method, templates) => { return template || JSON.stringify(method.examples[0].result.value, null, '\t') } -const getLinkForSchema = (schema, json) => { +const getLinkForSchema = (schema, json, { name = '' } = {}) => { const dirs = config.createModuleDirectories const copySchemasIntoModules = config.copySchemasIntoModules - if (schema.schema) { - schema = schema.schema - } - - const type = types.getSchemaType(schema, json, { destination: state.destination, section: state.section }) + const type = types.getSchemaType(schema, json, { name: name, 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]) { @@ -336,16 +333,22 @@ const generateMacros = (obj, templates, languages, options = {}) => { const declarations = declarationsArray.length ? getTemplate('/sections/declarations', templates).replace(/\$\{declaration\.list\}/g, declarationsArray.map(m => m.declaration).join('\n')) : '' 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 methodTypesArray = generateSchemas(obj, templates, { baseUrl: '', section: 'methods_schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) + const methodTypes = methodTypesArray.length ? getTemplate('/sections/methods_types', templates).replace(/\$\{schema.list\}/g, methodTypesArray.map(s => s.body).filter(body => body).join('\n')) : '' + const methodAccessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'methods_accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) + const methodAccessors = methodAccessorsArray.length ? getTemplate('/sections/methods_accessors', templates).replace(/\$\{schema.list\}/g, methodAccessorsArray.map(s => s.body).filter(body => body).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 schemasArray = generateSchemas(obj, templates, { baseUrl: '', section: 'schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) const accessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) - const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).join('\n')) : '' + const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).filter(body => body).join('\n')) : '' const typesArray = schemasArray.filter(x => !x.enum) - const types = typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).join('\n')) : '' - const accessors = accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).join('\n')) : '' + const types = (typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodTypes + + const accessors = (accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodAccessors const module = getTemplate('/codeblocks/module', templates) const macros = { @@ -622,9 +625,9 @@ const isEnum = x => x.type && x.type === 'string' && Array.isArray(x.enum) && x. function generateSchemas(json, templates, options) { let results = [] - const schemas = json.definitions || (json.components && json.components.schemas) || {} + const schemas = (options.section.includes('methods') ? (hasMethodsSchema(json) ? json.methods : '') : (json.definitions || (json.components && json.components.schemas) || {})) - const generate = (name, schema, uri) => { + const generate = (name, schema, uri, { prefix = '' } = {}) => { // these are internal schemas used by the firebolt-openrpc tooling, and not meant to be used in code/doc generation if (['ListenResponse', 'ProviderRequest', 'ProviderResponse', 'FederatedResponse', 'FederatedRequest'].includes(name)) { return @@ -645,7 +648,7 @@ function generateSchemas(json, templates, options) { else { content = content.replace(/\$\{if\.description\}(.*?)\{end\.if\.description\}/gms, '$1') } - const schemaShape = types.getSchemaShape(schema, json, { name, destination: state.destination, section: options.section }) + const schemaShape = types.getSchemaShape(schema, json, { name, prefix, destination: state.destination, section: options.section }) content = content .replace(/\$\{schema.title\}/, (schema.title || name)) @@ -663,6 +666,9 @@ function generateSchemas(json, templates, options) { else { content = content.replace(/.*\$\{schema.seeAlso\}/, '') } + content = content.trim().length ? content.trimEnd() : content.trim() + + const isEnum = x => x.type === 'string' && Array.isArray(x.enum) && x.title const result = uri ? { uri: uri, @@ -685,6 +691,18 @@ function generateSchemas(json, templates, options) { if (isSchema(schema)) { list.push([name, schema]) } + else if (schema.tags) { + if (!isDeprecatedMethod(schema)) { + schema.params.forEach(param => { + if (param.schema && (param.schema.type === 'object')) { + list.push([param.name, param.schema, '', { prefix : schema.name}]) + } + }) + if (schema.result.schema && (schema.result.schema.type === 'object')) { + list.push([schema.result.name, schema.result.schema, '', { prefix : schema.name}]) + } + } + } }) list.sort((a, b) => { @@ -716,7 +734,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, { destination: state.destination, section: state.section }) + '](' + getLinkForSchema(schema, json, true) + ')') // need full module here, not just the schema + .map(schema => '[' + types.getSchemaType(schema, json, { name: schema.title, 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') @@ -1058,10 +1076,10 @@ 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, json)) //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result.schema, json, {title: true, asPath: false, destination: state.destination })) //, baseUrl: options.baseUrl - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates)) + .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, title: true, asPath: false, destination: state.destination })) //, baseUrl: options.baseUrl + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name : result.name })) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) .replace(/\$\{method\.alternative.link\}/g, '#'+(method.alternative || "").toLowerCase()) @@ -1189,8 +1207,9 @@ function insertExampleMacros(template, examples, method, json, templates) { return template.replace(/\$\{method\.examples\}/g, content) } -function generateResult(result, json, templates) { - const type = types.getSchemaType(result, json, { destination: state.destination, section: state.section }) +function generateResult(result, json, templates, { name = '' } = {}) { + + const type = types.getSchemaType(result, json, { name: name, destination: state.destination, section: state.section }) if (result.type === 'object' && result.properties) { let content = getTemplate('/types/object', templates).split('\n') @@ -1201,13 +1220,13 @@ function generateResult(result, json, templates) { } } - return insertSchemaMacros(content.join('\n'), result.title, result, json) + return insertSchemaMacros(content.join('\n'), name, result, json) } else if (type === 'string' && Array.isArray(result.enum)) { - return insertSchemaMacros(getTemplate('/types/enum', templates), result, json) + return insertSchemaMacros(getTemplate('/types/enum', templates), name, result, json) } else if (result.$ref) { - const link = getLinkForSchema(result, json) + const link = getLinkForSchema(result, json, { name: name}) // if we get a real link use it if (link !== '#') { @@ -1217,18 +1236,18 @@ function generateResult(result, json, templates) { else { const schema = localizeDependencies(result, json) return getTemplate('/types/default', templates) - .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { name: result.$ref.split("/").pop()})) + .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { name: result.$ref.split("/").pop() })) } } else { - return insertSchemaMacros(getTemplate('/types/default', templates), result.title, result, json) + return insertSchemaMacros(getTemplate('/types/default', templates), name, result, json) } } function insertSchemaMacros(template, title, schema, module) { return template.replace(/\$\{property\}/g, title) - .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { destination: state.destination, section: state.section, code: false })) - .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module)) + .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { name: title, destination: state.destination, section: state.section, code: false })) + .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module, { name: title })) .replace(/\$\{description\}/g, schema.description || '') .replace(/\$\{name\}/g, title || '') } @@ -1238,9 +1257,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, { destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl - let typeLink = getLinkForSchema(param, module) - let jsonType = types.getJsonType(param.schema, module, { destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) + let type = types.getSchemaType(param.schema, module, { name: param.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl + let typeLink = getLinkForSchema(param.schema, module, { name: param.name }) + let jsonType = types.getJsonType(param.schema, module, { name: param.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) if (constraints && type) { constraints = '
' + constraints @@ -1253,7 +1272,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, module)) //getType(param)) + .replace(/\$\{method.param.link\}/g, getLinkForSchema(param.schema, module, { name: param.name} )) //getType(param)) .replace(/\$\{method.param.constraints\}/g, constraints) //getType(param)) } diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 89c194e2..f8acada8 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -199,8 +199,6 @@ const macrofy = async ( delete outputFiles[file] } }) - - console.log() } // Grab all schema groups w/ a URI string. These came from some external json-schema that was bundled into the OpenRPC @@ -271,4 +269,4 @@ const macrofy = async ( }) } -export default macrofy \ No newline at end of file +export default macrofy From 77abef628edd1c0a70d67c51f2a32d2337af753c Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 8 Jun 2023 09:23:36 +0530 Subject: [PATCH 041/137] Static code implementation updates (#96) Static code implementation updates Co-authored-by: Jeremy LaCivita --- languages/c/templates/modules/src/Module.cpp | 2 - languages/c/templates/sdk/CMakeLists.txt | 24 +- .../c/templates/sdk/build/CMakeCache.txt | 407 -------- .../CMakeFiles/3.25.3/CMakeCCompiler.cmake | 72 -- .../CMakeFiles/3.25.3/CMakeCXXCompiler.cmake | 83 -- .../3.25.3/CMakeDetermineCompilerABI_C.bin | Bin 16999 -> 0 bytes .../3.25.3/CMakeDetermineCompilerABI_CXX.bin | Bin 16983 -> 0 bytes .../build/CMakeFiles/3.25.3/CMakeSystem.cmake | 15 - .../3.25.3/CompilerIdC/CMakeCCompilerId.c | 868 ------------------ .../3.25.3/CompilerIdC/CMakeCCompilerId.o | Bin 1712 -> 0 bytes .../CompilerIdCXX/CMakeCXXCompilerId.cpp | 857 ----------------- .../3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o | Bin 1712 -> 0 bytes .../sdk/build/CMakeFiles/CMakeError.log | 0 .../sdk/build/CMakeFiles/CMakeOutput.log | 266 ------ .../sdk/build/CMakeFiles/cmake.check_cache | 1 - .../c/templates/sdk/cmake/CopySymlink.cmake | 17 - .../templates/sdk/cmake/HelperFunctions.cmake | 19 +- .../c/templates/sdk/cmake/project.cmake.in | 5 + languages/c/templates/sdk/include/Firebolt.h | 65 ++ languages/c/templates/sdk/include/Types.h | 8 +- languages/c/templates/sdk/scripts/build.sh | 11 + .../c/templates/sdk/src/Accessor/Accessor.cpp | 41 +- .../c/templates/sdk/src/Accessor/Accessor.h | 77 +- .../c/templates/sdk/src/Accessor/WorkerPool.h | 30 + languages/c/templates/sdk/src/CMakeLists.txt | 29 +- languages/c/templates/sdk/src/Config.cmake | 34 - languages/c/templates/sdk/src/Event/Event.cpp | 39 +- languages/c/templates/sdk/src/Event/Event.h | 75 +- .../src/{Accessor/Config.h => Firebolt.cpp} | 43 +- .../sdk/src/{Firebolt.h => FireboltSDK.h} | 1 + .../c/templates/sdk/src/Logger/Logger.cpp | 1 - languages/c/templates/sdk/src/Module.h | 2 - languages/c/templates/sdk/src/Params.config | 3 - .../templates/sdk/src/Properties/Properties.h | 72 +- .../c/templates/sdk/src/Transport/Transport.h | 4 +- languages/c/templates/sdk/src/Types.cpp | 7 +- languages/c/templates/sdk/src/TypesPriv.h | 29 +- .../templates/sdk/src/cmake/CopySymlink.cmake | 1 - 38 files changed, 393 insertions(+), 2815 deletions(-) delete mode 100644 languages/c/templates/sdk/build/CMakeCache.txt delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake delete mode 100755 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin delete mode 100755 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_CXX.bin delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeSystem.cmake delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.c delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.cpp delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/CMakeError.log delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/CMakeOutput.log delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache delete mode 100644 languages/c/templates/sdk/cmake/CopySymlink.cmake create mode 100644 languages/c/templates/sdk/include/Firebolt.h create mode 100755 languages/c/templates/sdk/scripts/build.sh delete mode 100644 languages/c/templates/sdk/src/Config.cmake rename languages/c/templates/sdk/src/{Accessor/Config.h => Firebolt.cpp} (50%) rename languages/c/templates/sdk/src/{Firebolt.h => FireboltSDK.h} (97%) delete mode 100644 languages/c/templates/sdk/src/Params.config delete mode 100644 languages/c/templates/sdk/src/cmake/CopySymlink.cmake diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index c412abf2..47a356d6 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -41,5 +41,3 @@ extern "C" { #ifdef __cplusplus } #endif - - diff --git a/languages/c/templates/sdk/CMakeLists.txt b/languages/c/templates/sdk/CMakeLists.txt index a29658f7..5efcad1a 100644 --- a/languages/c/templates/sdk/CMakeLists.txt +++ b/languages/c/templates/sdk/CMakeLists.txt @@ -20,19 +20,31 @@ project(Firebolt) set(FIREBOLT_TRANSPORT_WAITTIME 1000 CACHE STRING "Maximum time to wait for Transport layer to get response") set(FIREBOLT_LOGLEVEL "Info" CACHE STRING "Log level to be enabled") - +option(FIREBOLT_ENABLE_STATIC_LIB "Create Firebolt library as Static library" OFF) option(ENABLE_TESTS "Build openrpc native test" OFF) +if (NOT SYSROOT_PATH) + # Set sysroot to support PC builds, sysroot_path not configured case + set(SYSROOT_PATH "${CMAKE_SOURCE_DIR}/../../firebolt") +endif() + +if (FIREBOLT_ENABLE_STATIC_LIB) + set(FIREBOLT_LIBRARY_TYPE STATIC) +else () + set(FIREBOLT_LIBRARY_TYPE SHARED) +endif () + +if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${SYSROOT_PATH}/usr" CACHE INTERNAL "" FORCE) + set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) +endif() + list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake" "${SYSROOT_PATH}/usr/lib/cmake" "${SYSROOT_PATH}/tools/cmake") include(HelperFunctions) -if (NOT DEFINED CMAKE_PREFIX_PATH) - set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) -endif() - set(FIREBOLT_NAMESPACE ${PROJECT_NAME} CACHE STRING "Namespace of the project") find_package(WPEFramework CONFIG REQUIRED) @@ -45,5 +57,5 @@ endif() # make sure others can make use cmake settings of Firebolt OpenRPC configure_file( "${CMAKE_SOURCE_DIR}/cmake/project.cmake.in" - "${CMAKE_CURRENT_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake" + "${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake" @ONLY) diff --git a/languages/c/templates/sdk/build/CMakeCache.txt b/languages/c/templates/sdk/build/CMakeCache.txt deleted file mode 100644 index f10d476d..00000000 --- a/languages/c/templates/sdk/build/CMakeCache.txt +++ /dev/null @@ -1,407 +0,0 @@ -# This is the CMakeCache file. -# For build in directory: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build -# It was generated by CMake: /opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -# You can edit this file to change values found and used by cmake. -# If you do not want to change any of the values, simply exit the editor. -# If you do want to change a value, simply edit, save, and exit the editor. -# The syntax for the file is as follows: -# KEY:TYPE=VALUE -# KEY is the name of a variable in the cache. -# TYPE is a hint to GUIs for the type of VALUE, DO NOT EDIT TYPE!. -# VALUE is the current value for the KEY. - -######################## -# EXTERNAL cache entries -######################## - -//Path to a program. -CMAKE_ADDR2LINE:FILEPATH=CMAKE_ADDR2LINE-NOTFOUND - -//Path to a program. -CMAKE_AR:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ar - -//Choose the type of build, options are: None Debug Release RelWithDebInfo -// MinSizeRel ... -CMAKE_BUILD_TYPE:STRING=Release - -//Enable/Disable color output during build. -CMAKE_COLOR_MAKEFILE:BOOL=ON - -//CXX compiler -CMAKE_CXX_COMPILER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/c++ - -//Flags used by the CXX compiler during all build types. -CMAKE_CXX_FLAGS:STRING=-D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION - -//Flags used by the CXX compiler during DEBUG builds. -CMAKE_CXX_FLAGS_DEBUG:STRING=-g - -//Flags used by the CXX compiler during MINSIZEREL builds. -CMAKE_CXX_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG - -//Flags used by the CXX compiler during RELEASE builds. -CMAKE_CXX_FLAGS_RELEASE:STRING=-O3 -DNDEBUG - -//Flags used by the CXX compiler during RELWITHDEBINFO builds. -CMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG - -//C compiler -CMAKE_C_COMPILER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/cc - -//Flags used by the C compiler during all build types. -CMAKE_C_FLAGS:STRING= - -//Flags used by the C compiler during DEBUG builds. -CMAKE_C_FLAGS_DEBUG:STRING=-g - -//Flags used by the C compiler during MINSIZEREL builds. -CMAKE_C_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG - -//Flags used by the C compiler during RELEASE builds. -CMAKE_C_FLAGS_RELEASE:STRING=-O3 -DNDEBUG - -//Flags used by the C compiler during RELWITHDEBINFO builds. -CMAKE_C_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG - -//Path to a program. -CMAKE_DLLTOOL:FILEPATH=CMAKE_DLLTOOL-NOTFOUND - -//Flags used by the linker during all build types. -CMAKE_EXE_LINKER_FLAGS:STRING= - -//Flags used by the linker during DEBUG builds. -CMAKE_EXE_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during MINSIZEREL builds. -CMAKE_EXE_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during RELEASE builds. -CMAKE_EXE_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during RELWITHDEBINFO builds. -CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//Enable/Disable output of compile commands during generation. -CMAKE_EXPORT_COMPILE_COMMANDS:BOOL= - -//Value Computed by CMake. -CMAKE_FIND_PACKAGE_REDIRECTS_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/pkgRedirects - -//Path to a program. -CMAKE_INSTALL_NAME_TOOL:FILEPATH=/usr/bin/install_name_tool - -//Install path prefix, prepended onto install directories. -CMAKE_INSTALL_PREFIX:PATH=/usr - -//No help, variable specified on the command line. -CMAKE_JS_INC:UNINITIALIZED=/Users/JLaciv000/.cmake-js/node-arm64/v19.6.1/include/node - -//No help, variable specified on the command line. -CMAKE_JS_SRC:UNINITIALIZED= - -//No help, variable specified on the command line. -CMAKE_JS_VERSION:UNINITIALIZED=undefined - -//No help, variable specified on the command line. -CMAKE_LIBRARY_OUTPUT_DIRECTORY:UNINITIALIZED=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/Release - -//Path to a program. -CMAKE_LINKER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ld - -//Path to a program. -CMAKE_MAKE_PROGRAM:FILEPATH=/usr/bin/make - -//Flags used by the linker during the creation of modules during -// all build types. -CMAKE_MODULE_LINKER_FLAGS:STRING= - -//Flags used by the linker during the creation of modules during -// DEBUG builds. -CMAKE_MODULE_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during the creation of modules during -// MINSIZEREL builds. -CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during the creation of modules during -// RELEASE builds. -CMAKE_MODULE_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during the creation of modules during -// RELWITHDEBINFO builds. -CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//No help, variable specified on the command line. -CMAKE_MSVC_RUNTIME_LIBRARY:UNINITIALIZED=MultiThreaded$<$:Debug> - -//Path to a program. -CMAKE_NM:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/nm - -//Path to a program. -CMAKE_OBJCOPY:FILEPATH=CMAKE_OBJCOPY-NOTFOUND - -//Path to a program. -CMAKE_OBJDUMP:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/objdump - -//Build architectures for OSX -CMAKE_OSX_ARCHITECTURES:STRING=arm64 - -//Minimum OS X version to target for deployment (at runtime); newer -// APIs weak linked. Set to empty string for default value. -CMAKE_OSX_DEPLOYMENT_TARGET:STRING= - -//The product will be built against the headers and libraries located -// inside the indicated SDK. -CMAKE_OSX_SYSROOT:PATH=/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk - -//Value Computed by CMake -CMAKE_PROJECT_DESCRIPTION:STATIC= - -//Value Computed by CMake -CMAKE_PROJECT_HOMEPAGE_URL:STATIC= - -//Value Computed by CMake -CMAKE_PROJECT_NAME:STATIC=Firebolt - -//Path to a program. -CMAKE_RANLIB:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ranlib - -//Path to a program. -CMAKE_READELF:FILEPATH=CMAKE_READELF-NOTFOUND - -//Flags used by the linker during the creation of shared libraries -// during all build types. -CMAKE_SHARED_LINKER_FLAGS:STRING=-undefined dynamic_lookup - -//Flags used by the linker during the creation of shared libraries -// during DEBUG builds. -CMAKE_SHARED_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during the creation of shared libraries -// during MINSIZEREL builds. -CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during the creation of shared libraries -// during RELEASE builds. -CMAKE_SHARED_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during the creation of shared libraries -// during RELWITHDEBINFO builds. -CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//If set, runtime paths are not added when installing shared libraries, -// but are added when building. -CMAKE_SKIP_INSTALL_RPATH:BOOL=NO - -//If set, runtime paths are not added when using shared libraries. -CMAKE_SKIP_RPATH:BOOL=NO - -//Flags used by the linker during the creation of static libraries -// during all build types. -CMAKE_STATIC_LINKER_FLAGS:STRING= - -//Flags used by the linker during the creation of static libraries -// during DEBUG builds. -CMAKE_STATIC_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during the creation of static libraries -// during MINSIZEREL builds. -CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during the creation of static libraries -// during RELEASE builds. -CMAKE_STATIC_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during the creation of static libraries -// during RELWITHDEBINFO builds. -CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//Path to a program. -CMAKE_STRIP:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/strip - -//If this value is on, makefiles will be generated without the -// .SILENT directive, and all commands will be echoed to the console -// during the make. This is useful for debugging only. With Visual -// Studio IDE projects all commands are done without /nologo. -CMAKE_VERBOSE_MAKEFILE:BOOL=FALSE - -//Build openrpc native test -ENABLE_TESTS:BOOL=OFF - -//Log level to be enabled -FIREBOLT_LOGLEVEL:STRING=Info - -//Namespace of the project -FIREBOLT_NAMESPACE:STRING=Firebolt - -//Maximum time to wait for Transport layer to get response -FIREBOLT_TRANSPORT_WAITTIME:STRING=1000 - -//Value Computed by CMake -Firebolt_BINARY_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build - -//Value Computed by CMake -Firebolt_IS_TOP_LEVEL:STATIC=ON - -//Value Computed by CMake -Firebolt_SOURCE_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native - -//No help, variable specified on the command line. -GENERATED_CODE_PATH:UNINITIALIZED=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/build/sdk/native-c - -//No help, variable specified on the command line. -NODE_ARCH:UNINITIALIZED=arm64 - -//No help, variable specified on the command line. -NODE_RUNTIME:UNINITIALIZED=node - -//No help, variable specified on the command line. -NODE_RUNTIMEVERSION:UNINITIALIZED=19.6.1 - -//The directory containing a CMake configuration file for WPEFramework. -WPEFramework_DIR:PATH=WPEFramework_DIR-NOTFOUND - - -######################## -# INTERNAL cache entries -######################## - -//ADVANCED property for variable: CMAKE_ADDR2LINE -CMAKE_ADDR2LINE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_AR -CMAKE_AR-ADVANCED:INTERNAL=1 -//This is the directory where this CMakeCache.txt was created -CMAKE_CACHEFILE_DIR:INTERNAL=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build -//Major version of cmake used to create the current loaded cache -CMAKE_CACHE_MAJOR_VERSION:INTERNAL=3 -//Minor version of cmake used to create the current loaded cache -CMAKE_CACHE_MINOR_VERSION:INTERNAL=25 -//Patch version of cmake used to create the current loaded cache -CMAKE_CACHE_PATCH_VERSION:INTERNAL=3 -//ADVANCED property for variable: CMAKE_COLOR_MAKEFILE -CMAKE_COLOR_MAKEFILE-ADVANCED:INTERNAL=1 -//Path to CMake executable. -CMAKE_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -//Path to cpack program executable. -CMAKE_CPACK_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/cpack -//Path to ctest program executable. -CMAKE_CTEST_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/ctest -//ADVANCED property for variable: CMAKE_CXX_COMPILER -CMAKE_CXX_COMPILER-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_CXX_FLAGS -CMAKE_CXX_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_CXX_FLAGS_DEBUG -CMAKE_CXX_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_CXX_FLAGS_MINSIZEREL -CMAKE_CXX_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELEASE -CMAKE_CXX_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELWITHDEBINFO -CMAKE_CXX_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_COMPILER -CMAKE_C_COMPILER-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS -CMAKE_C_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_DEBUG -CMAKE_C_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_MINSIZEREL -CMAKE_C_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_RELEASE -CMAKE_C_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_RELWITHDEBINFO -CMAKE_C_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_DLLTOOL -CMAKE_DLLTOOL-ADVANCED:INTERNAL=1 -//Path to cache edit program executable. -CMAKE_EDIT_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/ccmake -//Executable file format -CMAKE_EXECUTABLE_FORMAT:INTERNAL=MACHO -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS -CMAKE_EXE_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_DEBUG -CMAKE_EXE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_MINSIZEREL -CMAKE_EXE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELEASE -CMAKE_EXE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXPORT_COMPILE_COMMANDS -CMAKE_EXPORT_COMPILE_COMMANDS-ADVANCED:INTERNAL=1 -//Name of external makefile project generator. -CMAKE_EXTRA_GENERATOR:INTERNAL= -//Name of generator. -CMAKE_GENERATOR:INTERNAL=Unix Makefiles -//Generator instance identifier. -CMAKE_GENERATOR_INSTANCE:INTERNAL= -//Name of generator platform. -CMAKE_GENERATOR_PLATFORM:INTERNAL= -//Name of generator toolset. -CMAKE_GENERATOR_TOOLSET:INTERNAL= -//Source directory with the top level CMakeLists.txt file for this -// project -CMAKE_HOME_DIRECTORY:INTERNAL=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native -//ADVANCED property for variable: CMAKE_INSTALL_NAME_TOOL -CMAKE_INSTALL_NAME_TOOL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_LINKER -CMAKE_LINKER-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MAKE_PROGRAM -CMAKE_MAKE_PROGRAM-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS -CMAKE_MODULE_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_DEBUG -CMAKE_MODULE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL -CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELEASE -CMAKE_MODULE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_NM -CMAKE_NM-ADVANCED:INTERNAL=1 -//number of local generators -CMAKE_NUMBER_OF_MAKEFILES:INTERNAL=1 -//ADVANCED property for variable: CMAKE_OBJCOPY -CMAKE_OBJCOPY-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_OBJDUMP -CMAKE_OBJDUMP-ADVANCED:INTERNAL=1 -//Platform information initialized -CMAKE_PLATFORM_INFO_INITIALIZED:INTERNAL=1 -CMAKE_PREFIX_PATH:INTERNAL=/usr/lib/cmake -//ADVANCED property for variable: CMAKE_RANLIB -CMAKE_RANLIB-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_READELF -CMAKE_READELF-ADVANCED:INTERNAL=1 -//Path to CMake installation. -CMAKE_ROOT:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/share/cmake -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS -CMAKE_SHARED_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_DEBUG -CMAKE_SHARED_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL -CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELEASE -CMAKE_SHARED_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SKIP_INSTALL_RPATH -CMAKE_SKIP_INSTALL_RPATH-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SKIP_RPATH -CMAKE_SKIP_RPATH-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS -CMAKE_STATIC_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_DEBUG -CMAKE_STATIC_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL -CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELEASE -CMAKE_STATIC_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STRIP -CMAKE_STRIP-ADVANCED:INTERNAL=1 -//uname command -CMAKE_UNAME:INTERNAL=/usr/bin/uname -//ADVANCED property for variable: CMAKE_VERBOSE_MAKEFILE -CMAKE_VERBOSE_MAKEFILE-ADVANCED:INTERNAL=1 - diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake deleted file mode 100644 index dc7a67f2..00000000 --- a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake +++ /dev/null @@ -1,72 +0,0 @@ -set(CMAKE_C_COMPILER "/Library/Developer/CommandLineTools/usr/bin/cc") -set(CMAKE_C_COMPILER_ARG1 "") -set(CMAKE_C_COMPILER_ID "AppleClang") -set(CMAKE_C_COMPILER_VERSION "13.1.6.13160021") -set(CMAKE_C_COMPILER_VERSION_INTERNAL "") -set(CMAKE_C_COMPILER_WRAPPER "") -set(CMAKE_C_STANDARD_COMPUTED_DEFAULT "17") -set(CMAKE_C_EXTENSIONS_COMPUTED_DEFAULT "ON") -set(CMAKE_C_COMPILE_FEATURES "c_std_90;c_function_prototypes;c_std_99;c_restrict;c_variadic_macros;c_std_11;c_static_assert;c_std_17;c_std_23") -set(CMAKE_C90_COMPILE_FEATURES "c_std_90;c_function_prototypes") -set(CMAKE_C99_COMPILE_FEATURES "c_std_99;c_restrict;c_variadic_macros") -set(CMAKE_C11_COMPILE_FEATURES "c_std_11;c_static_assert") -set(CMAKE_C17_COMPILE_FEATURES "c_std_17") -set(CMAKE_C23_COMPILE_FEATURES "c_std_23") - -set(CMAKE_C_PLATFORM_ID "Darwin") -set(CMAKE_C_SIMULATE_ID "") -set(CMAKE_C_COMPILER_FRONTEND_VARIANT "") -set(CMAKE_C_SIMULATE_VERSION "") - - - - -set(CMAKE_AR "/Library/Developer/CommandLineTools/usr/bin/ar") -set(CMAKE_C_COMPILER_AR "") -set(CMAKE_RANLIB "/Library/Developer/CommandLineTools/usr/bin/ranlib") -set(CMAKE_C_COMPILER_RANLIB "") -set(CMAKE_LINKER "/Library/Developer/CommandLineTools/usr/bin/ld") -set(CMAKE_MT "") -set(CMAKE_COMPILER_IS_GNUCC ) -set(CMAKE_C_COMPILER_LOADED 1) -set(CMAKE_C_COMPILER_WORKS TRUE) -set(CMAKE_C_ABI_COMPILED TRUE) - -set(CMAKE_C_COMPILER_ENV_VAR "CC") - -set(CMAKE_C_COMPILER_ID_RUN 1) -set(CMAKE_C_SOURCE_FILE_EXTENSIONS c;m) -set(CMAKE_C_IGNORE_EXTENSIONS h;H;o;O;obj;OBJ;def;DEF;rc;RC) -set(CMAKE_C_LINKER_PREFERENCE 10) - -# Save compiler ABI information. -set(CMAKE_C_SIZEOF_DATA_PTR "8") -set(CMAKE_C_COMPILER_ABI "") -set(CMAKE_C_BYTE_ORDER "LITTLE_ENDIAN") -set(CMAKE_C_LIBRARY_ARCHITECTURE "") - -if(CMAKE_C_SIZEOF_DATA_PTR) - set(CMAKE_SIZEOF_VOID_P "${CMAKE_C_SIZEOF_DATA_PTR}") -endif() - -if(CMAKE_C_COMPILER_ABI) - set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_C_COMPILER_ABI}") -endif() - -if(CMAKE_C_LIBRARY_ARCHITECTURE) - set(CMAKE_LIBRARY_ARCHITECTURE "") -endif() - -set(CMAKE_C_CL_SHOWINCLUDES_PREFIX "") -if(CMAKE_C_CL_SHOWINCLUDES_PREFIX) - set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_C_CL_SHOWINCLUDES_PREFIX}") -endif() - - - - - -set(CMAKE_C_IMPLICIT_INCLUDE_DIRECTORIES "/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include") -set(CMAKE_C_IMPLICIT_LINK_LIBRARIES "") -set(CMAKE_C_IMPLICIT_LINK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib") -set(CMAKE_C_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks") diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake deleted file mode 100644 index 67dc227a..00000000 --- a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake +++ /dev/null @@ -1,83 +0,0 @@ -set(CMAKE_CXX_COMPILER "/Library/Developer/CommandLineTools/usr/bin/c++") -set(CMAKE_CXX_COMPILER_ARG1 "") -set(CMAKE_CXX_COMPILER_ID "AppleClang") -set(CMAKE_CXX_COMPILER_VERSION "13.1.6.13160021") -set(CMAKE_CXX_COMPILER_VERSION_INTERNAL "") -set(CMAKE_CXX_COMPILER_WRAPPER "") -set(CMAKE_CXX_STANDARD_COMPUTED_DEFAULT "98") -set(CMAKE_CXX_EXTENSIONS_COMPUTED_DEFAULT "ON") -set(CMAKE_CXX_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters;cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates;cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates;cxx_std_17;cxx_std_20;cxx_std_23") -set(CMAKE_CXX98_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters") -set(CMAKE_CXX11_COMPILE_FEATURES "cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates") -set(CMAKE_CXX14_COMPILE_FEATURES "cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates") -set(CMAKE_CXX17_COMPILE_FEATURES "cxx_std_17") -set(CMAKE_CXX20_COMPILE_FEATURES "cxx_std_20") -set(CMAKE_CXX23_COMPILE_FEATURES "cxx_std_23") - -set(CMAKE_CXX_PLATFORM_ID "Darwin") -set(CMAKE_CXX_SIMULATE_ID "") -set(CMAKE_CXX_COMPILER_FRONTEND_VARIANT "") -set(CMAKE_CXX_SIMULATE_VERSION "") - - - - -set(CMAKE_AR "/Library/Developer/CommandLineTools/usr/bin/ar") -set(CMAKE_CXX_COMPILER_AR "") -set(CMAKE_RANLIB "/Library/Developer/CommandLineTools/usr/bin/ranlib") -set(CMAKE_CXX_COMPILER_RANLIB "") -set(CMAKE_LINKER "/Library/Developer/CommandLineTools/usr/bin/ld") -set(CMAKE_MT "") -set(CMAKE_COMPILER_IS_GNUCXX ) -set(CMAKE_CXX_COMPILER_LOADED 1) -set(CMAKE_CXX_COMPILER_WORKS TRUE) -set(CMAKE_CXX_ABI_COMPILED TRUE) - -set(CMAKE_CXX_COMPILER_ENV_VAR "CXX") - -set(CMAKE_CXX_COMPILER_ID_RUN 1) -set(CMAKE_CXX_SOURCE_FILE_EXTENSIONS C;M;c++;cc;cpp;cxx;m;mm;mpp;CPP;ixx;cppm) -set(CMAKE_CXX_IGNORE_EXTENSIONS inl;h;hpp;HPP;H;o;O;obj;OBJ;def;DEF;rc;RC) - -foreach (lang C OBJC OBJCXX) - if (CMAKE_${lang}_COMPILER_ID_RUN) - foreach(extension IN LISTS CMAKE_${lang}_SOURCE_FILE_EXTENSIONS) - list(REMOVE_ITEM CMAKE_CXX_SOURCE_FILE_EXTENSIONS ${extension}) - endforeach() - endif() -endforeach() - -set(CMAKE_CXX_LINKER_PREFERENCE 30) -set(CMAKE_CXX_LINKER_PREFERENCE_PROPAGATES 1) - -# Save compiler ABI information. -set(CMAKE_CXX_SIZEOF_DATA_PTR "8") -set(CMAKE_CXX_COMPILER_ABI "") -set(CMAKE_CXX_BYTE_ORDER "LITTLE_ENDIAN") -set(CMAKE_CXX_LIBRARY_ARCHITECTURE "") - -if(CMAKE_CXX_SIZEOF_DATA_PTR) - set(CMAKE_SIZEOF_VOID_P "${CMAKE_CXX_SIZEOF_DATA_PTR}") -endif() - -if(CMAKE_CXX_COMPILER_ABI) - set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_CXX_COMPILER_ABI}") -endif() - -if(CMAKE_CXX_LIBRARY_ARCHITECTURE) - set(CMAKE_LIBRARY_ARCHITECTURE "") -endif() - -set(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX "") -if(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX) - set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_CXX_CL_SHOWINCLUDES_PREFIX}") -endif() - - - - - -set(CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1;/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include") -set(CMAKE_CXX_IMPLICIT_LINK_LIBRARIES "c++") -set(CMAKE_CXX_IMPLICIT_LINK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib") -set(CMAKE_CXX_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks") diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin deleted file mode 100755 index 9b3e67d1d3825990645b4978d3a1e9da0ed43128..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 16999 zcmeI3Uuau(6vt1J4mw-bDPw=A+wvq%M%!73vA8vv&DOh>G+QHv1^Joe-nN%DNljAM zl(`jkY7xOI!Vn*PvJ@tW2r~~t@nOEH-NO_gw8E4Y8SKRe>sb7r-@Ug@j7;$P960yf zbI$K~a?a=G^?bX2`(8Vdk05^Nc4#O-beV#9BiaKUgenz}oQR%{o*Cw7qv*?xp(c;( zgm6%)L^PRbOzZpM#u&N&7KB;Rk`|@P)^yo*VE$R}&QWI=?+E)m*M_vv?8ZA@l*$(J zCGT`|J+t4b=e6wl^)>3>m72<*xAUg5^P>e_zj59#+QD&^VNZ&#>~h z;4}Y6w&79`ivJvSPnC+@6LzNCtW22jSvsNI$NH7x4Rex!tKWiOSUF)2!VyE|=*7+mzTkW;b zYDc)*>f743TAy1(u3}IBYc74XDYt?e_^tV+fVyeKjt}>h>=~;ts?5o9G1U`#o+xGv zAJ6oaE6OSsEHhO!j;Rx|s4)CVfjdF!HA3a*weJh$P*jJqFy()F*nK40$e zIUC+Q`%d-|^!D+w?~S}OJLiMg>~HQ(Z{;_1rF6GWd=t0I*kj7dn|3-+O}PoXT%NGJ zG=8gI)_-bW0>NE~aT_c<5JRWF0Qp;Z>6}N&LX(_?VE;T45Bl{=yc4VM6Pqn++5DY9SA;OK&E`)@a62ozG~Gg3vqrwOy?1(}Yo+U07k`F$ z7?Bt+1c@g+5Q2z4kcE(VVk9IUWCXE^ga;BL=A8RyyHz3a>YU`pZ)-|0EOudnCf zw+}yx7_%`DJ7_Uz)WO(6Ccuud$)NS1oHx4HdYU~O8t^n*w9DB?ITq$|K_KUTPr#q; z*6xehXUwoi!7(b7qzUIKr6Xk+u>6|u<4V05GX!nyYgqDF*YF-ToJSJzHZwXmpS()X zXO?W*)*RM7=k4*GYFy@Oyd|OK&+hl8kq?=opq*8pemwjg;qR4v>pgXnS%_#n8myWa zYm<=-nOfgv5o2BBFc9Kgu+$i~3+yVe@!BNN?O-GCURXO|Ed*@@MZq^f#aN8_7a0qe z1W@?TvC8(gWMxbZSIX&_3^qy`DAwVeb!t!?td8y9F?eTu;g@JNoC%I$f4{hdd)E zeq*{VrL>Y5g-CY zfCvx)B0vO)01+SpM1Tko0U|&IhyW2F0z`la5CI}U1c(3;AOb{y2oM1xKm>>Y5g-CY zfCvx)B0vO)01+SpM1Tko0U|&IhyW2F0z}}yA~1A-^$pEnnf@}Cd0EK54mnw7psXtc zGrC9fdsg%mr~|HdPBD{jD=2(t^$mb8t#xUfhTRpuF{#5dIGs{>A}K4$pjYzyy&mrI z)k$t2_;F--s_}Bx6=#}p<{9R_HC14~90hHhmBy**aoTM#1bqZrfGy5MqoP>Hk@fj% z{XFYy<1hnm=dDq$bSRN_C^V{spi(xoHKfMbY%IjVKJGRynH#KiEcnbhdYD7k>`u#^ zJ^D`=Hl}gfa8g>YYl3F$Jz|{#Oz`K{z_l7UZ}u)+f`j>_B0ZR-(lxt1=jV$0r_me)L)enUEBe|6e9e#*%eORpTb7ZmQE>poLc zH~P}0y%($?}6|C|5qI)^f8eSKp>24 & 0x00FF) -# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) -# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) - -#elif defined(__BORLANDC__) -# define COMPILER_ID "Borland" - /* __BORLANDC__ = 0xVRR */ -# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) -# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) - -#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 -# define COMPILER_ID "Watcom" - /* __WATCOMC__ = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__WATCOMC__) -# define COMPILER_ID "OpenWatcom" - /* __WATCOMC__ = VVRP + 1100 */ -# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__SUNPRO_C) -# define COMPILER_ID "SunPro" -# if __SUNPRO_C >= 0x5100 - /* __SUNPRO_C = 0xVRRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>12) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xFF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) -# else - /* __SUNPRO_CC = 0xVRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>8) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) -# endif - -#elif defined(__HP_cc) -# define COMPILER_ID "HP" - /* __HP_cc = VVRRPP */ -# define COMPILER_VERSION_MAJOR DEC(__HP_cc/10000) -# define COMPILER_VERSION_MINOR DEC(__HP_cc/100 % 100) -# define COMPILER_VERSION_PATCH DEC(__HP_cc % 100) - -#elif defined(__DECC) -# define COMPILER_ID "Compaq" - /* __DECC_VER = VVRRTPPPP */ -# define COMPILER_VERSION_MAJOR DEC(__DECC_VER/10000000) -# define COMPILER_VERSION_MINOR DEC(__DECC_VER/100000 % 100) -# define COMPILER_VERSION_PATCH DEC(__DECC_VER % 10000) - -#elif defined(__IBMC__) && defined(__COMPILER_VER__) -# define COMPILER_ID "zOS" - /* __IBMC__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) - -#elif defined(__open_xl__) && defined(__clang__) -# define COMPILER_ID "IBMClang" -# define COMPILER_VERSION_MAJOR DEC(__open_xl_version__) -# define COMPILER_VERSION_MINOR DEC(__open_xl_release__) -# define COMPILER_VERSION_PATCH DEC(__open_xl_modification__) -# define COMPILER_VERSION_TWEAK DEC(__open_xl_ptf_fix_level__) - - -#elif defined(__ibmxl__) && defined(__clang__) -# define COMPILER_ID "XLClang" -# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) -# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) -# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) -# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) - - -#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ >= 800 -# define COMPILER_ID "XL" - /* __IBMC__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) - -#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ < 800 -# define COMPILER_ID "VisualAge" - /* __IBMC__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) - -#elif defined(__NVCOMPILER) -# define COMPILER_ID "NVHPC" -# define COMPILER_VERSION_MAJOR DEC(__NVCOMPILER_MAJOR__) -# define COMPILER_VERSION_MINOR DEC(__NVCOMPILER_MINOR__) -# if defined(__NVCOMPILER_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__NVCOMPILER_PATCHLEVEL__) -# endif - -#elif defined(__PGI) -# define COMPILER_ID "PGI" -# define COMPILER_VERSION_MAJOR DEC(__PGIC__) -# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) -# if defined(__PGIC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) -# endif - -#elif defined(_CRAYC) -# define COMPILER_ID "Cray" -# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) -# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) - -#elif defined(__TI_COMPILER_VERSION__) -# define COMPILER_ID "TI" - /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ -# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) -# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) -# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) - -#elif defined(__CLANG_FUJITSU) -# define COMPILER_ID "FujitsuClang" -# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) -# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) -# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) -# define COMPILER_VERSION_INTERNAL_STR __clang_version__ - - -#elif defined(__FUJITSU) -# define COMPILER_ID "Fujitsu" -# if defined(__FCC_version__) -# define COMPILER_VERSION __FCC_version__ -# elif defined(__FCC_major__) -# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) -# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) -# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) -# endif -# if defined(__fcc_version) -# define COMPILER_VERSION_INTERNAL DEC(__fcc_version) -# elif defined(__FCC_VERSION) -# define COMPILER_VERSION_INTERNAL DEC(__FCC_VERSION) -# endif - - -#elif defined(__ghs__) -# define COMPILER_ID "GHS" -/* __GHS_VERSION_NUMBER = VVVVRP */ -# ifdef __GHS_VERSION_NUMBER -# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) -# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) -# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) -# endif - -#elif defined(__TASKING__) -# define COMPILER_ID "Tasking" - # define COMPILER_VERSION_MAJOR DEC(__VERSION__/1000) - # define COMPILER_VERSION_MINOR DEC(__VERSION__ % 100) -# define COMPILER_VERSION_INTERNAL DEC(__VERSION__) - -#elif defined(__TINYC__) -# define COMPILER_ID "TinyCC" - -#elif defined(__BCC__) -# define COMPILER_ID "Bruce" - -#elif defined(__SCO_VERSION__) -# define COMPILER_ID "SCO" - -#elif defined(__ARMCC_VERSION) && !defined(__clang__) -# define COMPILER_ID "ARMCC" -#if __ARMCC_VERSION >= 1000000 - /* __ARMCC_VERSION = VRRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#else - /* __ARMCC_VERSION = VRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#endif - - -#elif defined(__clang__) && defined(__apple_build_version__) -# define COMPILER_ID "AppleClang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif -# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) - -#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) -# define COMPILER_ID "ARMClang" - # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) -# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) - -#elif defined(__clang__) -# define COMPILER_ID "Clang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif - -#elif defined(__LCC__) && (defined(__GNUC__) || defined(__GNUG__) || defined(__MCST__)) -# define COMPILER_ID "LCC" -# define COMPILER_VERSION_MAJOR DEC(1) -# if defined(__LCC__) -# define COMPILER_VERSION_MINOR DEC(__LCC__- 100) -# endif -# if defined(__LCC_MINOR__) -# define COMPILER_VERSION_PATCH DEC(__LCC_MINOR__) -# endif -# if defined(__GNUC__) && defined(__GNUC_MINOR__) -# define SIMULATE_ID "GNU" -# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) -# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) -# if defined(__GNUC_PATCHLEVEL__) -# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif -# endif - -#elif defined(__GNUC__) -# define COMPILER_ID "GNU" -# define COMPILER_VERSION_MAJOR DEC(__GNUC__) -# if defined(__GNUC_MINOR__) -# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) -# endif -# if defined(__GNUC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif - -#elif defined(_MSC_VER) -# define COMPILER_ID "MSVC" - /* _MSC_VER = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) -# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) -# if defined(_MSC_FULL_VER) -# if _MSC_VER >= 1400 - /* _MSC_FULL_VER = VVRRPPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) -# else - /* _MSC_FULL_VER = VVRRPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) -# endif -# endif -# if defined(_MSC_BUILD) -# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) -# endif - -#elif defined(_ADI_COMPILER) -# define COMPILER_ID "ADSP" -#if defined(__VERSIONNUM__) - /* __VERSIONNUM__ = 0xVVRRPPTT */ -# define COMPILER_VERSION_MAJOR DEC(__VERSIONNUM__ >> 24 & 0xFF) -# define COMPILER_VERSION_MINOR DEC(__VERSIONNUM__ >> 16 & 0xFF) -# define COMPILER_VERSION_PATCH DEC(__VERSIONNUM__ >> 8 & 0xFF) -# define COMPILER_VERSION_TWEAK DEC(__VERSIONNUM__ & 0xFF) -#endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# define COMPILER_ID "IAR" -# if defined(__VER__) && defined(__ICCARM__) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) -# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) -# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__) || defined(__ICCSTM8__)) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) -# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) -# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# endif - -#elif defined(__SDCC_VERSION_MAJOR) || defined(SDCC) -# define COMPILER_ID "SDCC" -# if defined(__SDCC_VERSION_MAJOR) -# define COMPILER_VERSION_MAJOR DEC(__SDCC_VERSION_MAJOR) -# define COMPILER_VERSION_MINOR DEC(__SDCC_VERSION_MINOR) -# define COMPILER_VERSION_PATCH DEC(__SDCC_VERSION_PATCH) -# else - /* SDCC = VRP */ -# define COMPILER_VERSION_MAJOR DEC(SDCC/100) -# define COMPILER_VERSION_MINOR DEC(SDCC/10 % 10) -# define COMPILER_VERSION_PATCH DEC(SDCC % 10) -# endif - - -/* These compilers are either not known or too old to define an - identification macro. Try to identify the platform and guess that - it is the native compiler. */ -#elif defined(__hpux) || defined(__hpua) -# define COMPILER_ID "HP" - -#else /* unknown compiler */ -# define COMPILER_ID "" -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; -#ifdef SIMULATE_ID -char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; -#endif - -#ifdef __QNXNTO__ -char const* qnxnto = "INFO" ":" "qnxnto[]"; -#endif - -#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) -char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; -#endif - -#define STRINGIFY_HELPER(X) #X -#define STRINGIFY(X) STRINGIFY_HELPER(X) - -/* Identify known platforms by name. */ -#if defined(__linux) || defined(__linux__) || defined(linux) -# define PLATFORM_ID "Linux" - -#elif defined(__MSYS__) -# define PLATFORM_ID "MSYS" - -#elif defined(__CYGWIN__) -# define PLATFORM_ID "Cygwin" - -#elif defined(__MINGW32__) -# define PLATFORM_ID "MinGW" - -#elif defined(__APPLE__) -# define PLATFORM_ID "Darwin" - -#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) -# define PLATFORM_ID "Windows" - -#elif defined(__FreeBSD__) || defined(__FreeBSD) -# define PLATFORM_ID "FreeBSD" - -#elif defined(__NetBSD__) || defined(__NetBSD) -# define PLATFORM_ID "NetBSD" - -#elif defined(__OpenBSD__) || defined(__OPENBSD) -# define PLATFORM_ID "OpenBSD" - -#elif defined(__sun) || defined(sun) -# define PLATFORM_ID "SunOS" - -#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) -# define PLATFORM_ID "AIX" - -#elif defined(__hpux) || defined(__hpux__) -# define PLATFORM_ID "HP-UX" - -#elif defined(__HAIKU__) -# define PLATFORM_ID "Haiku" - -#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) -# define PLATFORM_ID "BeOS" - -#elif defined(__QNX__) || defined(__QNXNTO__) -# define PLATFORM_ID "QNX" - -#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) -# define PLATFORM_ID "Tru64" - -#elif defined(__riscos) || defined(__riscos__) -# define PLATFORM_ID "RISCos" - -#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) -# define PLATFORM_ID "SINIX" - -#elif defined(__UNIX_SV__) -# define PLATFORM_ID "UNIX_SV" - -#elif defined(__bsdos__) -# define PLATFORM_ID "BSDOS" - -#elif defined(_MPRAS) || defined(MPRAS) -# define PLATFORM_ID "MP-RAS" - -#elif defined(__osf) || defined(__osf__) -# define PLATFORM_ID "OSF1" - -#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) -# define PLATFORM_ID "SCO_SV" - -#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) -# define PLATFORM_ID "ULTRIX" - -#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) -# define PLATFORM_ID "Xenix" - -#elif defined(__WATCOMC__) -# if defined(__LINUX__) -# define PLATFORM_ID "Linux" - -# elif defined(__DOS__) -# define PLATFORM_ID "DOS" - -# elif defined(__OS2__) -# define PLATFORM_ID "OS2" - -# elif defined(__WINDOWS__) -# define PLATFORM_ID "Windows3x" - -# elif defined(__VXWORKS__) -# define PLATFORM_ID "VxWorks" - -# else /* unknown platform */ -# define PLATFORM_ID -# endif - -#elif defined(__INTEGRITY) -# if defined(INT_178B) -# define PLATFORM_ID "Integrity178" - -# else /* regular Integrity */ -# define PLATFORM_ID "Integrity" -# endif - -# elif defined(_ADI_COMPILER) -# define PLATFORM_ID "ADSP" - -#else /* unknown platform */ -# define PLATFORM_ID - -#endif - -/* For windows compilers MSVC and Intel we can determine - the architecture of the compiler being used. This is because - the compilers do not have flags that can change the architecture, - but rather depend on which compiler is being used -*/ -#if defined(_WIN32) && defined(_MSC_VER) -# if defined(_M_IA64) -# define ARCHITECTURE_ID "IA64" - -# elif defined(_M_ARM64EC) -# define ARCHITECTURE_ID "ARM64EC" - -# elif defined(_M_X64) || defined(_M_AMD64) -# define ARCHITECTURE_ID "x64" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# elif defined(_M_ARM64) -# define ARCHITECTURE_ID "ARM64" - -# elif defined(_M_ARM) -# if _M_ARM == 4 -# define ARCHITECTURE_ID "ARMV4I" -# elif _M_ARM == 5 -# define ARCHITECTURE_ID "ARMV5I" -# else -# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) -# endif - -# elif defined(_M_MIPS) -# define ARCHITECTURE_ID "MIPS" - -# elif defined(_M_SH) -# define ARCHITECTURE_ID "SHx" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__WATCOMC__) -# if defined(_M_I86) -# define ARCHITECTURE_ID "I86" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# if defined(__ICCARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__ICCRX__) -# define ARCHITECTURE_ID "RX" - -# elif defined(__ICCRH850__) -# define ARCHITECTURE_ID "RH850" - -# elif defined(__ICCRL78__) -# define ARCHITECTURE_ID "RL78" - -# elif defined(__ICCRISCV__) -# define ARCHITECTURE_ID "RISCV" - -# elif defined(__ICCAVR__) -# define ARCHITECTURE_ID "AVR" - -# elif defined(__ICC430__) -# define ARCHITECTURE_ID "MSP430" - -# elif defined(__ICCV850__) -# define ARCHITECTURE_ID "V850" - -# elif defined(__ICC8051__) -# define ARCHITECTURE_ID "8051" - -# elif defined(__ICCSTM8__) -# define ARCHITECTURE_ID "STM8" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__ghs__) -# if defined(__PPC64__) -# define ARCHITECTURE_ID "PPC64" - -# elif defined(__ppc__) -# define ARCHITECTURE_ID "PPC" - -# elif defined(__ARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__x86_64__) -# define ARCHITECTURE_ID "x64" - -# elif defined(__i386__) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__TI_COMPILER_VERSION__) -# if defined(__TI_ARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__MSP430__) -# define ARCHITECTURE_ID "MSP430" - -# elif defined(__TMS320C28XX__) -# define ARCHITECTURE_ID "TMS320C28x" - -# elif defined(__TMS320C6X__) || defined(_TMS320C6X) -# define ARCHITECTURE_ID "TMS320C6x" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -# elif defined(__ADSPSHARC__) -# define ARCHITECTURE_ID "SHARC" - -# elif defined(__ADSPBLACKFIN__) -# define ARCHITECTURE_ID "Blackfin" - -#elif defined(__TASKING__) - -# if defined(__CTC__) || defined(__CPTC__) -# define ARCHITECTURE_ID "TriCore" - -# elif defined(__CMCS__) -# define ARCHITECTURE_ID "MCS" - -# elif defined(__CARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__CARC__) -# define ARCHITECTURE_ID "ARC" - -# elif defined(__C51__) -# define ARCHITECTURE_ID "8051" - -# elif defined(__CPCP__) -# define ARCHITECTURE_ID "PCP" - -# else -# define ARCHITECTURE_ID "" -# endif - -#else -# define ARCHITECTURE_ID -#endif - -/* Convert integer to decimal digit literals. */ -#define DEC(n) \ - ('0' + (((n) / 10000000)%10)), \ - ('0' + (((n) / 1000000)%10)), \ - ('0' + (((n) / 100000)%10)), \ - ('0' + (((n) / 10000)%10)), \ - ('0' + (((n) / 1000)%10)), \ - ('0' + (((n) / 100)%10)), \ - ('0' + (((n) / 10)%10)), \ - ('0' + ((n) % 10)) - -/* Convert integer to hex digit literals. */ -#define HEX(n) \ - ('0' + ((n)>>28 & 0xF)), \ - ('0' + ((n)>>24 & 0xF)), \ - ('0' + ((n)>>20 & 0xF)), \ - ('0' + ((n)>>16 & 0xF)), \ - ('0' + ((n)>>12 & 0xF)), \ - ('0' + ((n)>>8 & 0xF)), \ - ('0' + ((n)>>4 & 0xF)), \ - ('0' + ((n) & 0xF)) - -/* Construct a string literal encoding the version number. */ -#ifdef COMPILER_VERSION -char const* info_version = "INFO" ":" "compiler_version[" COMPILER_VERSION "]"; - -/* Construct a string literal encoding the version number components. */ -#elif defined(COMPILER_VERSION_MAJOR) -char const info_version[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', - COMPILER_VERSION_MAJOR, -# ifdef COMPILER_VERSION_MINOR - '.', COMPILER_VERSION_MINOR, -# ifdef COMPILER_VERSION_PATCH - '.', COMPILER_VERSION_PATCH, -# ifdef COMPILER_VERSION_TWEAK - '.', COMPILER_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct a string literal encoding the internal version number. */ -#ifdef COMPILER_VERSION_INTERNAL -char const info_version_internal[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', - 'i','n','t','e','r','n','a','l','[', - COMPILER_VERSION_INTERNAL,']','\0'}; -#elif defined(COMPILER_VERSION_INTERNAL_STR) -char const* info_version_internal = "INFO" ":" "compiler_version_internal[" COMPILER_VERSION_INTERNAL_STR "]"; -#endif - -/* Construct a string literal encoding the version number components. */ -#ifdef SIMULATE_VERSION_MAJOR -char const info_simulate_version[] = { - 'I', 'N', 'F', 'O', ':', - 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', - SIMULATE_VERSION_MAJOR, -# ifdef SIMULATE_VERSION_MINOR - '.', SIMULATE_VERSION_MINOR, -# ifdef SIMULATE_VERSION_PATCH - '.', SIMULATE_VERSION_PATCH, -# ifdef SIMULATE_VERSION_TWEAK - '.', SIMULATE_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; -char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; - - - -#if !defined(__STDC__) && !defined(__clang__) -# if defined(_MSC_VER) || defined(__ibmxl__) || defined(__IBMC__) -# define C_VERSION "90" -# else -# define C_VERSION -# endif -#elif __STDC_VERSION__ > 201710L -# define C_VERSION "23" -#elif __STDC_VERSION__ >= 201710L -# define C_VERSION "17" -#elif __STDC_VERSION__ >= 201000L -# define C_VERSION "11" -#elif __STDC_VERSION__ >= 199901L -# define C_VERSION "99" -#else -# define C_VERSION "90" -#endif -const char* info_language_standard_default = - "INFO" ":" "standard_default[" C_VERSION "]"; - -const char* info_language_extensions_default = "INFO" ":" "extensions_default[" -#if (defined(__clang__) || defined(__GNUC__) || defined(__xlC__) || \ - defined(__TI_COMPILER_VERSION__)) && \ - !defined(__STRICT_ANSI__) - "ON" -#else - "OFF" -#endif -"]"; - -/*--------------------------------------------------------------------------*/ - -#ifdef ID_VOID_MAIN -void main() {} -#else -# if defined(__CLASSIC_C__) -int main(argc, argv) int argc; char *argv[]; -# else -int main(int argc, char* argv[]) -# endif -{ - int require = 0; - require += info_compiler[argc]; - require += info_platform[argc]; - require += info_arch[argc]; -#ifdef COMPILER_VERSION_MAJOR - require += info_version[argc]; -#endif -#ifdef COMPILER_VERSION_INTERNAL - require += info_version_internal[argc]; -#endif -#ifdef SIMULATE_ID - require += info_simulate[argc]; -#endif -#ifdef SIMULATE_VERSION_MAJOR - require += info_simulate_version[argc]; -#endif -#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) - require += info_cray[argc]; -#endif - require += info_language_standard_default[argc]; - require += info_language_extensions_default[argc]; - (void)argv; - return require; -} -#endif diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o deleted file mode 100644 index 537fbf261a76f93972038901b25169a2bbc47274..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1712 zcmb_cJ!n%=6uz;wrbZJ52c@6^7pIWdlqyOfp;1&q+aW_FlnbM8Iw+;_kGKK=Uf`-Bi7 z0i(w>M)3$9aSYfwjIS!I=z&L%dbCZ%s}_<rdz)YvA0HYv+3-?QBs2c#UYr|Wo}&rIo+0dl*8pp+HUHwP5`=CXzCkY{+GmpJqe z^{C`F`qO(H&ZhmA8*Xd3;mQ8ix!yHi)SKvUv=;ePuiiAvzHGbqZMPz2J~uk&HP?%C zFpj>cWEaS(u`SOdcNQbasV}Tn(j%)}% za%=g<%2hfV+p)Y-w%K&7CC7AYYeHq3j_Fq$UcHnvJscZHO|QIOV!!2^ZpHK}vSL-u zw&RzK%bdY|vD}so84YqP%WHr6vB&z8_biVJmXgYhR3dPahISScM#@-BCg+Wb7peOc zS66bZgO^}XPkuYV^b_Do@J9iro4^>j6JVM&1pVam0j3v#QSfAdY0@6FmOm3y4i@8<*X7~Z$a`P`qk_SaKIb%|g!jTF5YI&NLI#U*ukag2`Ii@wwl*BF^ czusKnN(nfiDNW&k&T9$>)X)?TD9J>24 & 0x00FF) -# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) -# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) - -#elif defined(__BORLANDC__) -# define COMPILER_ID "Borland" - /* __BORLANDC__ = 0xVRR */ -# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) -# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) - -#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 -# define COMPILER_ID "Watcom" - /* __WATCOMC__ = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__WATCOMC__) -# define COMPILER_ID "OpenWatcom" - /* __WATCOMC__ = VVRP + 1100 */ -# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__SUNPRO_CC) -# define COMPILER_ID "SunPro" -# if __SUNPRO_CC >= 0x5100 - /* __SUNPRO_CC = 0xVRRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>12) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xFF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) -# else - /* __SUNPRO_CC = 0xVRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>8) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) -# endif - -#elif defined(__HP_aCC) -# define COMPILER_ID "HP" - /* __HP_aCC = VVRRPP */ -# define COMPILER_VERSION_MAJOR DEC(__HP_aCC/10000) -# define COMPILER_VERSION_MINOR DEC(__HP_aCC/100 % 100) -# define COMPILER_VERSION_PATCH DEC(__HP_aCC % 100) - -#elif defined(__DECCXX) -# define COMPILER_ID "Compaq" - /* __DECCXX_VER = VVRRTPPPP */ -# define COMPILER_VERSION_MAJOR DEC(__DECCXX_VER/10000000) -# define COMPILER_VERSION_MINOR DEC(__DECCXX_VER/100000 % 100) -# define COMPILER_VERSION_PATCH DEC(__DECCXX_VER % 10000) - -#elif defined(__IBMCPP__) && defined(__COMPILER_VER__) -# define COMPILER_ID "zOS" - /* __IBMCPP__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) - -#elif defined(__open_xl__) && defined(__clang__) -# define COMPILER_ID "IBMClang" -# define COMPILER_VERSION_MAJOR DEC(__open_xl_version__) -# define COMPILER_VERSION_MINOR DEC(__open_xl_release__) -# define COMPILER_VERSION_PATCH DEC(__open_xl_modification__) -# define COMPILER_VERSION_TWEAK DEC(__open_xl_ptf_fix_level__) - - -#elif defined(__ibmxl__) && defined(__clang__) -# define COMPILER_ID "XLClang" -# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) -# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) -# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) -# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) - - -#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ >= 800 -# define COMPILER_ID "XL" - /* __IBMCPP__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) - -#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ < 800 -# define COMPILER_ID "VisualAge" - /* __IBMCPP__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) - -#elif defined(__NVCOMPILER) -# define COMPILER_ID "NVHPC" -# define COMPILER_VERSION_MAJOR DEC(__NVCOMPILER_MAJOR__) -# define COMPILER_VERSION_MINOR DEC(__NVCOMPILER_MINOR__) -# if defined(__NVCOMPILER_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__NVCOMPILER_PATCHLEVEL__) -# endif - -#elif defined(__PGI) -# define COMPILER_ID "PGI" -# define COMPILER_VERSION_MAJOR DEC(__PGIC__) -# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) -# if defined(__PGIC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) -# endif - -#elif defined(_CRAYC) -# define COMPILER_ID "Cray" -# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) -# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) - -#elif defined(__TI_COMPILER_VERSION__) -# define COMPILER_ID "TI" - /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ -# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) -# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) -# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) - -#elif defined(__CLANG_FUJITSU) -# define COMPILER_ID "FujitsuClang" -# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) -# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) -# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) -# define COMPILER_VERSION_INTERNAL_STR __clang_version__ - - -#elif defined(__FUJITSU) -# define COMPILER_ID "Fujitsu" -# if defined(__FCC_version__) -# define COMPILER_VERSION __FCC_version__ -# elif defined(__FCC_major__) -# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) -# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) -# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) -# endif -# if defined(__fcc_version) -# define COMPILER_VERSION_INTERNAL DEC(__fcc_version) -# elif defined(__FCC_VERSION) -# define COMPILER_VERSION_INTERNAL DEC(__FCC_VERSION) -# endif - - -#elif defined(__ghs__) -# define COMPILER_ID "GHS" -/* __GHS_VERSION_NUMBER = VVVVRP */ -# ifdef __GHS_VERSION_NUMBER -# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) -# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) -# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) -# endif - -#elif defined(__TASKING__) -# define COMPILER_ID "Tasking" - # define COMPILER_VERSION_MAJOR DEC(__VERSION__/1000) - # define COMPILER_VERSION_MINOR DEC(__VERSION__ % 100) -# define COMPILER_VERSION_INTERNAL DEC(__VERSION__) - -#elif defined(__SCO_VERSION__) -# define COMPILER_ID "SCO" - -#elif defined(__ARMCC_VERSION) && !defined(__clang__) -# define COMPILER_ID "ARMCC" -#if __ARMCC_VERSION >= 1000000 - /* __ARMCC_VERSION = VRRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#else - /* __ARMCC_VERSION = VRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#endif - - -#elif defined(__clang__) && defined(__apple_build_version__) -# define COMPILER_ID "AppleClang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif -# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) - -#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) -# define COMPILER_ID "ARMClang" - # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) -# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) - -#elif defined(__clang__) -# define COMPILER_ID "Clang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif - -#elif defined(__LCC__) && (defined(__GNUC__) || defined(__GNUG__) || defined(__MCST__)) -# define COMPILER_ID "LCC" -# define COMPILER_VERSION_MAJOR DEC(1) -# if defined(__LCC__) -# define COMPILER_VERSION_MINOR DEC(__LCC__- 100) -# endif -# if defined(__LCC_MINOR__) -# define COMPILER_VERSION_PATCH DEC(__LCC_MINOR__) -# endif -# if defined(__GNUC__) && defined(__GNUC_MINOR__) -# define SIMULATE_ID "GNU" -# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) -# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) -# if defined(__GNUC_PATCHLEVEL__) -# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif -# endif - -#elif defined(__GNUC__) || defined(__GNUG__) -# define COMPILER_ID "GNU" -# if defined(__GNUC__) -# define COMPILER_VERSION_MAJOR DEC(__GNUC__) -# else -# define COMPILER_VERSION_MAJOR DEC(__GNUG__) -# endif -# if defined(__GNUC_MINOR__) -# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) -# endif -# if defined(__GNUC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif - -#elif defined(_MSC_VER) -# define COMPILER_ID "MSVC" - /* _MSC_VER = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) -# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) -# if defined(_MSC_FULL_VER) -# if _MSC_VER >= 1400 - /* _MSC_FULL_VER = VVRRPPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) -# else - /* _MSC_FULL_VER = VVRRPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) -# endif -# endif -# if defined(_MSC_BUILD) -# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) -# endif - -#elif defined(_ADI_COMPILER) -# define COMPILER_ID "ADSP" -#if defined(__VERSIONNUM__) - /* __VERSIONNUM__ = 0xVVRRPPTT */ -# define COMPILER_VERSION_MAJOR DEC(__VERSIONNUM__ >> 24 & 0xFF) -# define COMPILER_VERSION_MINOR DEC(__VERSIONNUM__ >> 16 & 0xFF) -# define COMPILER_VERSION_PATCH DEC(__VERSIONNUM__ >> 8 & 0xFF) -# define COMPILER_VERSION_TWEAK DEC(__VERSIONNUM__ & 0xFF) -#endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# define COMPILER_ID "IAR" -# if defined(__VER__) && defined(__ICCARM__) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) -# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) -# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__) || defined(__ICCSTM8__)) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) -# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) -# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# endif - - -/* These compilers are either not known or too old to define an - identification macro. Try to identify the platform and guess that - it is the native compiler. */ -#elif defined(__hpux) || defined(__hpua) -# define COMPILER_ID "HP" - -#else /* unknown compiler */ -# define COMPILER_ID "" -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; -#ifdef SIMULATE_ID -char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; -#endif - -#ifdef __QNXNTO__ -char const* qnxnto = "INFO" ":" "qnxnto[]"; -#endif - -#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) -char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; -#endif - -#define STRINGIFY_HELPER(X) #X -#define STRINGIFY(X) STRINGIFY_HELPER(X) - -/* Identify known platforms by name. */ -#if defined(__linux) || defined(__linux__) || defined(linux) -# define PLATFORM_ID "Linux" - -#elif defined(__MSYS__) -# define PLATFORM_ID "MSYS" - -#elif defined(__CYGWIN__) -# define PLATFORM_ID "Cygwin" - -#elif defined(__MINGW32__) -# define PLATFORM_ID "MinGW" - -#elif defined(__APPLE__) -# define PLATFORM_ID "Darwin" - -#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) -# define PLATFORM_ID "Windows" - -#elif defined(__FreeBSD__) || defined(__FreeBSD) -# define PLATFORM_ID "FreeBSD" - -#elif defined(__NetBSD__) || defined(__NetBSD) -# define PLATFORM_ID "NetBSD" - -#elif defined(__OpenBSD__) || defined(__OPENBSD) -# define PLATFORM_ID "OpenBSD" - -#elif defined(__sun) || defined(sun) -# define PLATFORM_ID "SunOS" - -#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) -# define PLATFORM_ID "AIX" - -#elif defined(__hpux) || defined(__hpux__) -# define PLATFORM_ID "HP-UX" - -#elif defined(__HAIKU__) -# define PLATFORM_ID "Haiku" - -#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) -# define PLATFORM_ID "BeOS" - -#elif defined(__QNX__) || defined(__QNXNTO__) -# define PLATFORM_ID "QNX" - -#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) -# define PLATFORM_ID "Tru64" - -#elif defined(__riscos) || defined(__riscos__) -# define PLATFORM_ID "RISCos" - -#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) -# define PLATFORM_ID "SINIX" - -#elif defined(__UNIX_SV__) -# define PLATFORM_ID "UNIX_SV" - -#elif defined(__bsdos__) -# define PLATFORM_ID "BSDOS" - -#elif defined(_MPRAS) || defined(MPRAS) -# define PLATFORM_ID "MP-RAS" - -#elif defined(__osf) || defined(__osf__) -# define PLATFORM_ID "OSF1" - -#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) -# define PLATFORM_ID "SCO_SV" - -#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) -# define PLATFORM_ID "ULTRIX" - -#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) -# define PLATFORM_ID "Xenix" - -#elif defined(__WATCOMC__) -# if defined(__LINUX__) -# define PLATFORM_ID "Linux" - -# elif defined(__DOS__) -# define PLATFORM_ID "DOS" - -# elif defined(__OS2__) -# define PLATFORM_ID "OS2" - -# elif defined(__WINDOWS__) -# define PLATFORM_ID "Windows3x" - -# elif defined(__VXWORKS__) -# define PLATFORM_ID "VxWorks" - -# else /* unknown platform */ -# define PLATFORM_ID -# endif - -#elif defined(__INTEGRITY) -# if defined(INT_178B) -# define PLATFORM_ID "Integrity178" - -# else /* regular Integrity */ -# define PLATFORM_ID "Integrity" -# endif - -# elif defined(_ADI_COMPILER) -# define PLATFORM_ID "ADSP" - -#else /* unknown platform */ -# define PLATFORM_ID - -#endif - -/* For windows compilers MSVC and Intel we can determine - the architecture of the compiler being used. This is because - the compilers do not have flags that can change the architecture, - but rather depend on which compiler is being used -*/ -#if defined(_WIN32) && defined(_MSC_VER) -# if defined(_M_IA64) -# define ARCHITECTURE_ID "IA64" - -# elif defined(_M_ARM64EC) -# define ARCHITECTURE_ID "ARM64EC" - -# elif defined(_M_X64) || defined(_M_AMD64) -# define ARCHITECTURE_ID "x64" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# elif defined(_M_ARM64) -# define ARCHITECTURE_ID "ARM64" - -# elif defined(_M_ARM) -# if _M_ARM == 4 -# define ARCHITECTURE_ID "ARMV4I" -# elif _M_ARM == 5 -# define ARCHITECTURE_ID "ARMV5I" -# else -# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) -# endif - -# elif defined(_M_MIPS) -# define ARCHITECTURE_ID "MIPS" - -# elif defined(_M_SH) -# define ARCHITECTURE_ID "SHx" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__WATCOMC__) -# if defined(_M_I86) -# define ARCHITECTURE_ID "I86" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# if defined(__ICCARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__ICCRX__) -# define ARCHITECTURE_ID "RX" - -# elif defined(__ICCRH850__) -# define ARCHITECTURE_ID "RH850" - -# elif defined(__ICCRL78__) -# define ARCHITECTURE_ID "RL78" - -# elif defined(__ICCRISCV__) -# define ARCHITECTURE_ID "RISCV" - -# elif defined(__ICCAVR__) -# define ARCHITECTURE_ID "AVR" - -# elif defined(__ICC430__) -# define ARCHITECTURE_ID "MSP430" - -# elif defined(__ICCV850__) -# define ARCHITECTURE_ID "V850" - -# elif defined(__ICC8051__) -# define ARCHITECTURE_ID "8051" - -# elif defined(__ICCSTM8__) -# define ARCHITECTURE_ID "STM8" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__ghs__) -# if defined(__PPC64__) -# define ARCHITECTURE_ID "PPC64" - -# elif defined(__ppc__) -# define ARCHITECTURE_ID "PPC" - -# elif defined(__ARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__x86_64__) -# define ARCHITECTURE_ID "x64" - -# elif defined(__i386__) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__TI_COMPILER_VERSION__) -# if defined(__TI_ARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__MSP430__) -# define ARCHITECTURE_ID "MSP430" - -# elif defined(__TMS320C28XX__) -# define ARCHITECTURE_ID "TMS320C28x" - -# elif defined(__TMS320C6X__) || defined(_TMS320C6X) -# define ARCHITECTURE_ID "TMS320C6x" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -# elif defined(__ADSPSHARC__) -# define ARCHITECTURE_ID "SHARC" - -# elif defined(__ADSPBLACKFIN__) -# define ARCHITECTURE_ID "Blackfin" - -#elif defined(__TASKING__) - -# if defined(__CTC__) || defined(__CPTC__) -# define ARCHITECTURE_ID "TriCore" - -# elif defined(__CMCS__) -# define ARCHITECTURE_ID "MCS" - -# elif defined(__CARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__CARC__) -# define ARCHITECTURE_ID "ARC" - -# elif defined(__C51__) -# define ARCHITECTURE_ID "8051" - -# elif defined(__CPCP__) -# define ARCHITECTURE_ID "PCP" - -# else -# define ARCHITECTURE_ID "" -# endif - -#else -# define ARCHITECTURE_ID -#endif - -/* Convert integer to decimal digit literals. */ -#define DEC(n) \ - ('0' + (((n) / 10000000)%10)), \ - ('0' + (((n) / 1000000)%10)), \ - ('0' + (((n) / 100000)%10)), \ - ('0' + (((n) / 10000)%10)), \ - ('0' + (((n) / 1000)%10)), \ - ('0' + (((n) / 100)%10)), \ - ('0' + (((n) / 10)%10)), \ - ('0' + ((n) % 10)) - -/* Convert integer to hex digit literals. */ -#define HEX(n) \ - ('0' + ((n)>>28 & 0xF)), \ - ('0' + ((n)>>24 & 0xF)), \ - ('0' + ((n)>>20 & 0xF)), \ - ('0' + ((n)>>16 & 0xF)), \ - ('0' + ((n)>>12 & 0xF)), \ - ('0' + ((n)>>8 & 0xF)), \ - ('0' + ((n)>>4 & 0xF)), \ - ('0' + ((n) & 0xF)) - -/* Construct a string literal encoding the version number. */ -#ifdef COMPILER_VERSION -char const* info_version = "INFO" ":" "compiler_version[" COMPILER_VERSION "]"; - -/* Construct a string literal encoding the version number components. */ -#elif defined(COMPILER_VERSION_MAJOR) -char const info_version[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', - COMPILER_VERSION_MAJOR, -# ifdef COMPILER_VERSION_MINOR - '.', COMPILER_VERSION_MINOR, -# ifdef COMPILER_VERSION_PATCH - '.', COMPILER_VERSION_PATCH, -# ifdef COMPILER_VERSION_TWEAK - '.', COMPILER_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct a string literal encoding the internal version number. */ -#ifdef COMPILER_VERSION_INTERNAL -char const info_version_internal[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', - 'i','n','t','e','r','n','a','l','[', - COMPILER_VERSION_INTERNAL,']','\0'}; -#elif defined(COMPILER_VERSION_INTERNAL_STR) -char const* info_version_internal = "INFO" ":" "compiler_version_internal[" COMPILER_VERSION_INTERNAL_STR "]"; -#endif - -/* Construct a string literal encoding the version number components. */ -#ifdef SIMULATE_VERSION_MAJOR -char const info_simulate_version[] = { - 'I', 'N', 'F', 'O', ':', - 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', - SIMULATE_VERSION_MAJOR, -# ifdef SIMULATE_VERSION_MINOR - '.', SIMULATE_VERSION_MINOR, -# ifdef SIMULATE_VERSION_PATCH - '.', SIMULATE_VERSION_PATCH, -# ifdef SIMULATE_VERSION_TWEAK - '.', SIMULATE_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; -char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; - - - -#if defined(__INTEL_COMPILER) && defined(_MSVC_LANG) && _MSVC_LANG < 201403L -# if defined(__INTEL_CXX11_MODE__) -# if defined(__cpp_aggregate_nsdmi) -# define CXX_STD 201402L -# else -# define CXX_STD 201103L -# endif -# else -# define CXX_STD 199711L -# endif -#elif defined(_MSC_VER) && defined(_MSVC_LANG) -# define CXX_STD _MSVC_LANG -#else -# define CXX_STD __cplusplus -#endif - -const char* info_language_standard_default = "INFO" ":" "standard_default[" -#if CXX_STD > 202002L - "23" -#elif CXX_STD > 201703L - "20" -#elif CXX_STD >= 201703L - "17" -#elif CXX_STD >= 201402L - "14" -#elif CXX_STD >= 201103L - "11" -#else - "98" -#endif -"]"; - -const char* info_language_extensions_default = "INFO" ":" "extensions_default[" -#if (defined(__clang__) || defined(__GNUC__) || defined(__xlC__) || \ - defined(__TI_COMPILER_VERSION__)) && \ - !defined(__STRICT_ANSI__) - "ON" -#else - "OFF" -#endif -"]"; - -/*--------------------------------------------------------------------------*/ - -int main(int argc, char* argv[]) -{ - int require = 0; - require += info_compiler[argc]; - require += info_platform[argc]; - require += info_arch[argc]; -#ifdef COMPILER_VERSION_MAJOR - require += info_version[argc]; -#endif -#ifdef COMPILER_VERSION_INTERNAL - require += info_version_internal[argc]; -#endif -#ifdef SIMULATE_ID - require += info_simulate[argc]; -#endif -#ifdef SIMULATE_VERSION_MAJOR - require += info_simulate_version[argc]; -#endif -#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) - require += info_cray[argc]; -#endif - require += info_language_standard_default[argc]; - require += info_language_extensions_default[argc]; - (void)argv; - return require; -} diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o deleted file mode 100644 index aacee10dfddc5e3114bb159eee743a03c1b12206..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1712 zcmb_cJ#5oZ5PqShqzWV;F@P#TBo?M9PO7SaA|+}-fULGdhCoz3ti(wzIgaHx(6I;x z1_sK?QX~e%#7HI>vr!hr7?|3DoiY%1^Z6O|W@vfbVNlAN;TuDUd5eWoVTAL%&&wQohkn#@ z7xSq-j;d+D)t1v9ZFqXVP40J%U+PcIH{OeU>eqCQsxLdv1IwvNsTapLka_697F8IR1n^Z*cJ-l}YwvWy2!N#ELP!jS<=b%*cH!^r6J`FC4Zht{^ zzsAJjAR)R@A)ZAe`NM;S?e4sFu)LqhccYQ{*#1A{s8`rm?EJ5ueawaVcRtL>&$m`@ ztX-vFW7(!xDY&j}uGogt*bqU+wGF@C@|u;R;o-M&)bOgC753Y{;nWPTCTnKh=-7Vc z$}(qgUQDNLfkwmJ+Umw1e(Z_)ySp2^@ z#c`j+Ps4(Dam47{VX1)UfyFv=G-sR%Pq{mU!DV&cx`aV;sv}u}j^j6kad6amf6w`E zuq1DxRR1GDLcC-=%WFPoe1Y)`!ei?{C5*wsqwOppCjtl9ou4RJe%qk(9hUIXb hB0fW6ys-VIyU6WQZ~(Ik!U4=E2nSG85Dp-5 search starts here: - /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include - /Library/Developer/CommandLineTools/usr/include - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory) -End of search list. -Linking C executable cmTC_5913a -/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_5913a.dir/link.txt --verbose=1 -/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names -v -Wl,-v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -o cmTC_5913a -Apple clang version 13.1.6 (clang-1316.0.21.2.5) -Target: arm64-apple-darwin21.6.0 -Thread model: posix -InstalledDir: /Library/Developer/CommandLineTools/usr/bin - "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_5913a -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a -@(#)PROGRAM:ld PROJECT:ld64-764 -BUILD 11:22:55 Apr 28 2022 -configured to support archs: armv6 armv7 armv7s arm64 arm64e arm64_32 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em -Library search paths: - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib -Framework search paths: - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/ - - - -Parsed C implicit include dir info from above output: rv=done - found start of include info - found start of implicit include info - add: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - add: [/Library/Developer/CommandLineTools/usr/include] - end of search list found - collapse include dir [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] ==> [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - collapse include dir [/Library/Developer/CommandLineTools/usr/include] ==> [/Library/Developer/CommandLineTools/usr/include] - implicit include dirs: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include] - - -Parsed C implicit link information from above output: - link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] - ignore line: [Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-LcrFWX] - ignore line: [] - ignore line: [Run Build Command(s):/usr/bin/make -f Makefile cmTC_5913a/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_5913a.dir/build.make CMakeFiles/cmTC_5913a.dir/build] - ignore line: [Building C object CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o] - ignore line: [/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl -v -MD -MT CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -MF CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o.d -o CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCCompilerABI.c] - ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] - ignore line: [Target: arm64-apple-darwin21.6.0] - ignore line: [Thread model: posix] - ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] - ignore line: [clang: warning: -Wl -v: 'linker' input unused [-Wunused-command-line-argument]] - ignore line: [ "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCCompilerABI.c -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-LcrFWX -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -x c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCCompilerABI.c] - ignore line: [clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0] - ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include"] - ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks"] - ignore line: [#include "..." search starts here:] - ignore line: [#include <...> search starts here:] - ignore line: [ /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - ignore line: [ /Library/Developer/CommandLineTools/usr/include] - ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory)] - ignore line: [End of search list.] - ignore line: [Linking C executable cmTC_5913a] - ignore line: [/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_5913a.dir/link.txt --verbose=1] - ignore line: [/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl -search_paths_first -Wl -headerpad_max_install_names -v -Wl -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -o cmTC_5913a ] - ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] - ignore line: [Target: arm64-apple-darwin21.6.0] - ignore line: [Thread model: posix] - ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] - link line: [ "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_5913a -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - arg [/Library/Developer/CommandLineTools/usr/bin/ld] ==> ignore - arg [-demangle] ==> ignore - arg [-lto_library] ==> ignore, skip following value - arg [/Library/Developer/CommandLineTools/usr/lib/libLTO.dylib] ==> skip value of -lto_library - arg [-dynamic] ==> ignore - arg [-arch] ==> ignore - arg [arm64] ==> ignore - arg [-platform_version] ==> ignore - arg [macos] ==> ignore - arg [12.0.0] ==> ignore - arg [12.3] ==> ignore - arg [-syslibroot] ==> ignore - arg [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk] ==> ignore - arg [-o] ==> ignore - arg [cmTC_5913a] ==> ignore - arg [-search_paths_first] ==> ignore - arg [-headerpad_max_install_names] ==> ignore - arg [-v] ==> ignore - arg [CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o] ==> ignore - arg [-lSystem] ==> lib [System] - arg [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] ==> lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - Library search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - Framework search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] - remove lib [System] - remove lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - collapse library dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - collapse framework dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] - implicit libs: [] - implicit objs: [] - implicit dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - implicit fwks: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] - - -Detecting CXX compiler ABI info compiled with the following output: -Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C - -Run Build Command(s):/usr/bin/make -f Makefile cmTC_48750/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_48750.dir/build.make CMakeFiles/cmTC_48750.dir/build -Building CXX object CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl,-v -MD -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -MF CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp -Apple clang version 13.1.6 (clang-1316.0.21.2.5) -Target: arm64-apple-darwin21.6.0 -Thread model: posix -InstalledDir: /Library/Developer/CommandLineTools/usr/bin -clang: warning: -Wl,-v: 'linker' input unused [-Wunused-command-line-argument] - "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -D _DARWIN_USE_64_BIT_INODE=1 -D _LARGEFILE_SOURCE -D _FILE_OFFSET_BITS=64 -D BUILDING_NODE_EXTENSION -stdlib=libc++ -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdeprecated-macro -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fno-cxx-modules -fcxx-exceptions -fexceptions -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -x c++ /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp -clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0 -ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include" -ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks" -#include "..." search starts here: -#include <...> search starts here: - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 - /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include - /Library/Developer/CommandLineTools/usr/include - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory) -End of search list. -Linking CXX executable cmTC_48750 -/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_48750.dir/link.txt --verbose=1 -/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names -v -Wl,-v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_48750 -Apple clang version 13.1.6 (clang-1316.0.21.2.5) -Target: arm64-apple-darwin21.6.0 -Thread model: posix -InstalledDir: /Library/Developer/CommandLineTools/usr/bin - "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_48750 -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -lc++ -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a -@(#)PROGRAM:ld PROJECT:ld64-764 -BUILD 11:22:55 Apr 28 2022 -configured to support archs: armv6 armv7 armv7s arm64 arm64e arm64_32 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em -Library search paths: - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib -Framework search paths: - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/ - - - -Parsed CXX implicit include dir info from above output: rv=done - found start of include info - found start of implicit include info - add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] - add: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - add: [/Library/Developer/CommandLineTools/usr/include] - end of search list found - collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] - collapse include dir [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] ==> [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - collapse include dir [/Library/Developer/CommandLineTools/usr/include] ==> [/Library/Developer/CommandLineTools/usr/include] - implicit include dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1;/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include] - - -Parsed CXX implicit link information from above output: - link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] - ignore line: [Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C] - ignore line: [] - ignore line: [Run Build Command(s):/usr/bin/make -f Makefile cmTC_48750/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_48750.dir/build.make CMakeFiles/cmTC_48750.dir/build] - ignore line: [Building CXX object CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o] - ignore line: [/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl -v -MD -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -MF CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp] - ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] - ignore line: [Target: arm64-apple-darwin21.6.0] - ignore line: [Thread model: posix] - ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] - ignore line: [clang: warning: -Wl -v: 'linker' input unused [-Wunused-command-line-argument]] - ignore line: [ "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -D _DARWIN_USE_64_BIT_INODE=1 -D _LARGEFILE_SOURCE -D _FILE_OFFSET_BITS=64 -D BUILDING_NODE_EXTENSION -stdlib=libc++ -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdeprecated-macro -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fno-cxx-modules -fcxx-exceptions -fexceptions -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -x c++ /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp] - ignore line: [clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0] - ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include"] - ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks"] - ignore line: [#include "..." search starts here:] - ignore line: [#include <...> search starts here:] - ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] - ignore line: [ /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - ignore line: [ /Library/Developer/CommandLineTools/usr/include] - ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory)] - ignore line: [End of search list.] - ignore line: [Linking CXX executable cmTC_48750] - ignore line: [/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_48750.dir/link.txt --verbose=1] - ignore line: [/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl -search_paths_first -Wl -headerpad_max_install_names -v -Wl -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_48750 ] - ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] - ignore line: [Target: arm64-apple-darwin21.6.0] - ignore line: [Thread model: posix] - ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] - link line: [ "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_48750 -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -lc++ -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - arg [/Library/Developer/CommandLineTools/usr/bin/ld] ==> ignore - arg [-demangle] ==> ignore - arg [-lto_library] ==> ignore, skip following value - arg [/Library/Developer/CommandLineTools/usr/lib/libLTO.dylib] ==> skip value of -lto_library - arg [-dynamic] ==> ignore - arg [-arch] ==> ignore - arg [arm64] ==> ignore - arg [-platform_version] ==> ignore - arg [macos] ==> ignore - arg [12.0.0] ==> ignore - arg [12.3] ==> ignore - arg [-syslibroot] ==> ignore - arg [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk] ==> ignore - arg [-o] ==> ignore - arg [cmTC_48750] ==> ignore - arg [-search_paths_first] ==> ignore - arg [-headerpad_max_install_names] ==> ignore - arg [-v] ==> ignore - arg [CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o] ==> ignore - arg [-lc++] ==> lib [c++] - arg [-lSystem] ==> lib [System] - arg [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] ==> lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - Library search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - Framework search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] - remove lib [System] - remove lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - collapse library dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - collapse framework dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] - implicit libs: [c++] - implicit objs: [] - implicit dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - implicit fwks: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] - - diff --git a/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache b/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache deleted file mode 100644 index 3dccd731..00000000 --- a/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache +++ /dev/null @@ -1 +0,0 @@ -# This file is generated by cmake for dependency checking of the CMakeCache.txt file diff --git a/languages/c/templates/sdk/cmake/CopySymlink.cmake b/languages/c/templates/sdk/cmake/CopySymlink.cmake deleted file mode 100644 index b25a5e22..00000000 --- a/languages/c/templates/sdk/cmake/CopySymlink.cmake +++ /dev/null @@ -1,17 +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 - -file(COPY "${LIBRARY}" DESTINATION "${DESTINATION}" FOLLOW_SYMLINK_CHAIN) diff --git a/languages/c/templates/sdk/cmake/HelperFunctions.cmake b/languages/c/templates/sdk/cmake/HelperFunctions.cmake index bbd7ce65..b3647c16 100644 --- a/languages/c/templates/sdk/cmake/HelperFunctions.cmake +++ b/languages/c/templates/sdk/cmake/HelperFunctions.cmake @@ -72,8 +72,8 @@ function(InstallHeaders) endfunction(InstallHeaders) function(InstallLibraries) - set(optionsArgs SHARED) - set(oneValueArgs TARGET DESTINATION) + set(optionsArgs SHARED STATIC) + set(oneValueArgs TARGET DESTINATION LIBDIR) set(multiValueArgs LIBRARIES) cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) @@ -92,11 +92,11 @@ function(InstallLibraries) TARGET ${Argument_TARGET} POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib - COMMAND ${CMAKE_COMMAND} -D "LIBRARY=${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR}" -D "DESTINATION=${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib" -P ${CMAKE_SOURCE_DIR}/cmake/CopySymlink.cmake - COMMAND ${CMAKE_COMMAND} -D "LIBRARY=${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so" -D "DESTINATION=${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib" -P ${CMAKE_SOURCE_DIR}/cmake/CopySymlink.cmake + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_LIBDIR}/lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + COMMAND ${CMAKE_COMMAND} -E create_symlink lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR} + COMMAND ${CMAKE_COMMAND} -E create_symlink lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/lib${LIBRARY}.so ) - else() + elseif (Argument_STATIC) add_custom_command( TARGET ${Argument_TARGET} POST_BUILD @@ -119,13 +119,18 @@ function(InstallCMakeConfigs) message(FATAL_ERROR "Unknown keywords given to InstallCMakeConfigs(): \"${Argument_UNPARSED_ARGUMENTS}\"") endif() if (Argument_TARGET) + if (${CMAKE_VERSION} VERSION_LESS "3.25.0") + set(EXPORT_CONFIG_PATH "lib/cmake/${Argument_TARGET}") + else () + set(EXPORT_CONFIG_PATH "*") + endif () add_custom_command( TARGET ${Argument_TARGET} POST_BUILD COMMENT "=================== Installing CMakeConfigs ======================" COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}Config*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Export/lib/cmake/${Argument_TARGET}/${Argument_TARGET}Targets*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Export/${EXPORT_CONFIG_PATH}/${Argument_TARGET}Targets*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} ) if (EXISTS ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}.pc) add_custom_command( diff --git a/languages/c/templates/sdk/cmake/project.cmake.in b/languages/c/templates/sdk/cmake/project.cmake.in index 0855ca12..eca32f8c 100644 --- a/languages/c/templates/sdk/cmake/project.cmake.in +++ b/languages/c/templates/sdk/cmake/project.cmake.in @@ -27,4 +27,9 @@ if (NOT DEFINED CMAKE_PREFIX_PATH) set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) endif() +if (FIREBOLT_ENABLE_STATIC_LIB) + set(FIREBOLT_LIBRARY_TYPE STATIC) +else () + set(FIREBOLT_LIBRARY_TYPE SHARED) +endif () diff --git a/languages/c/templates/sdk/include/Firebolt.h b/languages/c/templates/sdk/include/Firebolt.h new file mode 100644 index 00000000..2223bad3 --- /dev/null +++ b/languages/c/templates/sdk/include/Firebolt.h @@ -0,0 +1,65 @@ +/* + * 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 + */ + +#ifndef _FIREBOLT_H +#define _FIREBOLT_H + +#include "Error.h" +#include "Types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Intitialize the Firebolt SDK + * + * @param configLine JSON String with configuration options + * + * CONFIG Format: + * { + * "waitTime": 1000, + * "logLevel": "Info", + * "workerPool":{ + * "queueSize": 8, + * "threadCount": 3 + * }, + * "wsUrl": "ws://127.0.0.1:9998" + * } + * + * + * @return FireboltSDKErrorNone if success, appropriate error otherwise. + * + */ +uint32_t FireboltSDK_Initialize(char* configLine); + + +/** + * @brief Deintitialize the Firebolt SDK + * + * @return FireboltSDKErrorNone if success, appropriate error otherwise. + * + */ +uint32_t FireboltSDK_Deinitialize(void); + +#ifdef __cplusplus +} +#endif + + +#endif // _FIREBOLT_H diff --git a/languages/c/templates/sdk/include/Types.h b/languages/c/templates/sdk/include/Types.h index e7456cdd..4fd16256 100644 --- a/languages/c/templates/sdk/include/Types.h +++ b/languages/c/templates/sdk/include/Types.h @@ -20,18 +20,12 @@ #define _FIREBOLT_TYPES_H #include +#include #ifdef __cplusplus extern "C" { #endif -typedef enum { - Test1, - Test2, - Test3, - Test4 -} TestEnum; - typedef void* FireboltTypes_StringHandle; const char* FireboltTypes_String(FireboltTypes_StringHandle handle); void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle); diff --git a/languages/c/templates/sdk/scripts/build.sh b/languages/c/templates/sdk/scripts/build.sh new file mode 100755 index 00000000..e9b01f20 --- /dev/null +++ b/languages/c/templates/sdk/scripts/build.sh @@ -0,0 +1,11 @@ +#!/bin/bash +SDK_PATH="." +if [ "$1" != "" ] +then + SDK_PATH=$1 + echo "inside ${1}" +fi +echo ${SDK_PATH} +rm -rf ${SDK_PATH}/build +cmake -B${SDK_PATH}/build -S${SDK_PATH} -DSYSROOT_PATH=${SYSROOT_PATH} +cmake --build ${SDK_PATH}/build diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.cpp b/languages/c/templates/sdk/src/Accessor/Accessor.cpp index b4cada4b..e4a5df32 100644 --- a/languages/c/templates/sdk/src/Accessor/Accessor.cpp +++ b/languages/c/templates/sdk/src/Accessor/Accessor.cpp @@ -21,22 +21,22 @@ namespace FireboltSDK { Accessor* Accessor::_singleton = nullptr; - Accessor::Accessor() - : _threadCount(DefaultThreadCount) - , _queueSize(DefaultQueueSize) - , _workerPool() + + Accessor::Accessor(const string& configLine) + : _workerPool() , _transport(nullptr) + , _config() { _singleton = this; - Config config; - LoadConfigs(config); + _config.FromString(configLine); + + Logger::SetLogLevel(WPEFramework::Core::EnumerateType(_config.LogLevel.Value().c_str()).Value()); - Logger::SetLogLevel(WPEFramework::Core::EnumerateType(config.LogLevel.Value().c_str()).Value()); - FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Url = %s", config.Url.Value().c_str()); - CreateTransport(config.Url.Value(), config.WaitTime.Value()); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Url = %s", _config.WsUrl.Value().c_str()); + CreateTransport(_config.WsUrl.Value().c_str(), _config.WaitTime.Value()); CreateEventHandler(); - _workerPool = WPEFramework::Core::ProxyType::Create(_threadCount, WPEFramework::Core::Thread::DefaultStackSize(), _queueSize); + _workerPool = WPEFramework::Core::ProxyType::Create(_config.WorkerPool.ThreadCount.Value(), _config.WorkerPool.StackSize.Value(), _config.WorkerPool.QueueSize.Value()); WPEFramework::Core::WorkerPool::Assign(&(*_workerPool)); _workerPool->Run(); } @@ -50,23 +50,6 @@ namespace FireboltSDK { _singleton = nullptr; } - void Accessor::LoadConfigs(Config& config) - { - string prefixPath; - WPEFramework::Core::SystemInfo::GetEnvironment("OPENRPC_NATIVE_SDK_PREFIX", prefixPath); - string configFilePath = (prefixPath.empty() != true) ? - (prefixPath + '/' + Accessor::ConfigFile) : Accessor::ConfigFile; - WPEFramework::Core::File configFile(configFilePath); - - if (configFile.Open(true) == true) { - WPEFramework::Core::OptionalType error; - config.IElement::FromFile(configFile, error); - if (error.IsSet() == true) { - FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in reading config"); - } - } - } - uint32_t Accessor::CreateEventHandler() { Event::Instance().Configure(_transport); @@ -84,14 +67,14 @@ namespace FireboltSDK { return Event::Instance(); } - uint32_t Accessor::CreateTransport(const string& url, const uint32_t waitTime) + uint32_t Accessor::CreateTransport(const string& url, const uint32_t waitTime = DefaultWaitTime) { if (_transport != nullptr) { delete _transport; } _transport = new Transport(static_cast(url), waitTime); - if (WaitForLinkReady(_transport, DefaultWaitTime) != FireboltSDKErrorNone) { + if (WaitForLinkReady(_transport, waitTime) != FireboltSDKErrorNone) { delete _transport; _transport = nullptr; } diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.h b/languages/c/templates/sdk/src/Accessor/Accessor.h index 3e9b8784..f12dc51c 100644 --- a/languages/c/templates/sdk/src/Accessor/Accessor.h +++ b/languages/c/templates/sdk/src/Accessor/Accessor.h @@ -19,7 +19,6 @@ #pragma once #include "Module.h" -#include "Config.h" #include "WorkerPool.h" #include "Transport/Transport.h" #include "Event/Event.h" @@ -29,21 +28,69 @@ namespace FireboltSDK { class Accessor { private: static constexpr uint8_t JSONVersion = 2; - static constexpr const TCHAR* ConfigFile = _T("/etc/Firebolt/config.json"); - static constexpr uint32_t DefaultWaitTime = 1000; - static constexpr uint8_t DefaultQueueSize = 8; - static constexpr uint8_t DefaultThreadCount = 3; + + private: + //Singleton + Accessor(const string& configLine); public: + class EXTERNAL Config : public WPEFramework::Core::JSON::Container { + public: + Config(const Config&) = delete; + Config& operator=(const Config&) = delete; + + class WorkerPoolConfig : public WPEFramework::Core::JSON::Container { + public: + WorkerPoolConfig& operator=(const WorkerPoolConfig&); + + WorkerPoolConfig() + : WPEFramework::Core::JSON::Container() + , QueueSize(8) + , ThreadCount(3) + , StackSize(WPEFramework::Core::Thread::DefaultStackSize()) + { + Add("queueSize", &QueueSize); + Add("threadCount", &ThreadCount); + Add("stackSize", &StackSize); + } + + virtual ~WorkerPoolConfig() = default; + + public: + WPEFramework::Core::JSON::DecUInt32 QueueSize; + WPEFramework::Core::JSON::DecUInt32 ThreadCount; + WPEFramework::Core::JSON::DecUInt32 StackSize; + }; + + + Config() + : WPEFramework::Core::JSON::Container() + , WaitTime(1000) + , LogLevel(_T("Info")) + , WorkerPool() + , WsUrl(_T("ws://127.0.0.1:9998")) + { + Add(_T("waitTime"), &WaitTime); + Add(_T("logLevel"), &LogLevel); + Add(_T("workerPool"), &WorkerPool); + Add(_T("wsUrl"), &WsUrl); + } + + public: + WPEFramework::Core::JSON::DecUInt32 WaitTime; + WPEFramework::Core::JSON::String LogLevel; + WorkerPoolConfig WorkerPool; + WPEFramework::Core::JSON::String WsUrl; + }; + Accessor(const Accessor&) = delete; Accessor& operator= (const Accessor&) = delete; - - Accessor(); + Accessor() = delete; ~Accessor(); - static Accessor& Instance() + static Accessor& Instance(const string& configLine = "") { - static Accessor *instance = new Accessor(); + static Accessor *instance = new Accessor(configLine); ASSERT(instance != nullptr); return *instance; } @@ -56,24 +103,20 @@ namespace FireboltSDK { delete _singleton; } } + Event& GetEventManager(); + Transport* GetTransport(); + private: uint32_t CreateEventHandler(); uint32_t DestroyEventHandler(); - Event& GetEventManager(); - uint32_t CreateTransport(const string& url, const uint32_t waitTime); uint32_t DestroyTransport(); - Transport* GetTransport(); uint32_t WaitForLinkReady(Transport* transport, const uint32_t waitTime); private: - void LoadConfigs(Config& config); - - private: - uint8_t _threadCount; - uint8_t _queueSize; WPEFramework::Core::ProxyType _workerPool; Transport* _transport; static Accessor* _singleton; + Config _config; }; } diff --git a/languages/c/templates/sdk/src/Accessor/WorkerPool.h b/languages/c/templates/sdk/src/Accessor/WorkerPool.h index 521ccc65..69005a5e 100644 --- a/languages/c/templates/sdk/src/Accessor/WorkerPool.h +++ b/languages/c/templates/sdk/src/Accessor/WorkerPool.h @@ -69,4 +69,34 @@ namespace FireboltSDK { Dispatcher _dispatcher; }; + class Worker : public WPEFramework::Core::IDispatch { + public: + typedef std::function Dispatcher; + + protected: + Worker(const Dispatcher& dispatcher, const void* userData) + : _dispatcher(dispatcher) + , _userData(userData) + { + } + + public: + Worker() = delete; + Worker(const Worker&) = delete; + Worker& operator=(const Worker&) = delete; + + ~Worker() = default; + + public: + static WPEFramework::Core::ProxyType Create(const Dispatcher& dispatcher, const void* userData); + + void Dispatch() override + { + _dispatcher(_userData); + } + + private: + Dispatcher _dispatcher; + const void* _userData; + }; } diff --git a/languages/c/templates/sdk/src/CMakeLists.txt b/languages/c/templates/sdk/src/CMakeLists.txt index c411582a..2f00bdf1 100644 --- a/languages/c/templates/sdk/src/CMakeLists.txt +++ b/languages/c/templates/sdk/src/CMakeLists.txt @@ -20,29 +20,30 @@ project(FireboltSDK) project_version(1.0.0) set(TARGET ${PROJECT_NAME}) message("Setup ${TARGET} v${PROJECT_VERSION}") +file(GLOB GENERATED_SOURCES "${GENERATED_CODE_PATH}/src/*.cpp") -add_library(${TARGET} SHARED - Types.cpp - Module.cpp +file(GLOB SOURCES *.cpp) +add_library(${TARGET} ${FIREBOLT_LIBRARY_TYPE} + ${SOURCES} Logger/Logger.cpp Transport/Transport.cpp Accessor/Accessor.cpp - Event/Event.cpp) + Event/Event.cpp +) set(CMAKE_POSITION_INDEPENDENT_CODE ON) -find_package(${NAMESPACE}Core CONFIG REQUIRED) find_package(${NAMESPACE}WebSocket CONFIG REQUIRED) target_link_libraries(${TARGET} PUBLIC - ${NAMESPACE}Core::${NAMESPACE}Core ${NAMESPACE}WebSocket::${NAMESPACE}WebSocket ) target_include_directories(${TARGET} PRIVATE $ - $ + $ + $ $ ) @@ -66,21 +67,13 @@ InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTIN InstallHeaders(TARGET ${TARGET} EXCLUDE_ROOT_DIR HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} SOURCE ${GENERATED_CODE_PATH}/include DESTINATION ${FIREBOLT_NAMESPACE}/generated) InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} - SOURCE ${CMAKE_SOURCE_DIR}/include DESTINATION ${FIREBOLT_NAMESPACE}) + SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../include DESTINATION ${FIREBOLT_NAMESPACE}) -InstallLibraries(TARGET ${TARGET} SHARED LIBRARIES ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallLibraries(TARGET ${TARGET} ${FIREBOLT_LIBRARY_TYPE} LIBDIR ${LIBDIR} LIBRARIES ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) InstallCMakeConfig(TARGETS ${TARGET}) InstallPackageConfig(TARGETS ${TARGET} DESCRIPTION "Firebolt SDK Library") InstallCMakeConfigs(TARGET ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) -add_custom_command( - TARGET ${TARGET} - POST_BUILD - COMMENT "=================== Installing JsonConfig ======================" - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/etc/${FIREBOLT_NAMESPACE} - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/config/${TARGET}.json ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/etc/${FIREBOLT_NAMESPACE}/config.json -) - add_custom_command( TARGET ${TARGET} POST_BUILD @@ -89,5 +82,3 @@ add_custom_command( COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/cmake/*.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} ) - -include(Config.cmake) diff --git a/languages/c/templates/sdk/src/Config.cmake b/languages/c/templates/sdk/src/Config.cmake deleted file mode 100644 index a420ce32..00000000 --- a/languages/c/templates/sdk/src/Config.cmake +++ /dev/null @@ -1,34 +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 - -set(SERVER_PORT 9998 CACHE STRING "The port of the server") -set(SERVER_ADDRESS "127.0.0.1" CACHE STRING "The address of the server") - - #[[ ================================ Add additional config above this line ================================ ]] - - -find_package(ConfigGenerator REQUIRED) - -write_config( - SKIP_COMPARE - SKIP_CLASSNAME - SKIP_LOCATOR - DISABLE_LEGACY_GENERATOR - CUSTOM_PARAMS_WHITELIST "${CMAKE_CURRENT_LIST_DIR}/Params.config" - INSTALL_PATH "${CMAKE_INSTALL_PREFIX}/../etc/" - INSTALL_NAME "config.json" -) - diff --git a/languages/c/templates/sdk/src/Event/Event.cpp b/languages/c/templates/sdk/src/Event/Event.cpp index 69b448f6..5e98a36f 100644 --- a/languages/c/templates/sdk/src/Event/Event.cpp +++ b/languages/c/templates/sdk/src/Event/Event.cpp @@ -22,8 +22,7 @@ namespace FireboltSDK { Event* Event::_singleton = nullptr; Event::Event() - : _id(0) - , _eventMap() + : _eventMap() , _adminLock() , _transport(nullptr) { @@ -61,9 +60,9 @@ namespace FireboltSDK { _transport->SetEventHandler(this); } - uint32_t Event::Unsubscribe(const string& eventName, const uint32_t id) + uint32_t Event::Unsubscribe(const string& eventName, void* usercb) { - uint32_t status = Revoke(eventName, id); + uint32_t status = Revoke(eventName, usercb); if (status == FireboltSDKErrorNone) { if (_transport != nullptr) { @@ -93,26 +92,26 @@ namespace FireboltSDK { _adminLock.Lock(); EventMap::iterator eventIndex = _eventMap.find(eventName); if (eventIndex != _eventMap.end()) { - IdMap::iterator idIndex = eventIndex->second.begin(); - while(idIndex != eventIndex->second.end()) { + CallbackMap::iterator callbackIndex = eventIndex->second.begin(); + while(callbackIndex != eventIndex->second.end()) { State state; - if (idIndex->second.state != State::REVOKED) { - idIndex->second.state = State::EXECUTING; + if (callbackIndex->second.state != State::REVOKED) { + callbackIndex->second.state = State::EXECUTING; } - state = idIndex->second.state; + state = callbackIndex->second.state; _adminLock.Unlock(); if (state == State::EXECUTING) { - idIndex->second.lambda(idIndex->second.userdata, (jsonResponse->Result.Value())); + callbackIndex->second.lambda(callbackIndex->first, callbackIndex->second.userdata, (jsonResponse->Result.Value())); } _adminLock.Lock(); - if (idIndex->second.state == State::REVOKED) { - idIndex = eventIndex->second.erase(idIndex); + if (callbackIndex->second.state == State::REVOKED) { + callbackIndex = eventIndex->second.erase(callbackIndex); if (eventIndex->second.size() == 0) { _eventMap.erase(eventIndex); } } else { - idIndex->second.state = State::IDLE; - idIndex++; + callbackIndex->second.state = State::IDLE; + callbackIndex++; } } } @@ -121,19 +120,19 @@ namespace FireboltSDK { return FireboltSDKErrorNone;; } - uint32_t Event::Revoke(const string& eventName, const uint32_t id) + uint32_t Event::Revoke(const string& eventName, void* usercb) { uint32_t status = FireboltSDKErrorNone; _adminLock.Lock(); EventMap::iterator eventIndex = _eventMap.find(eventName); if (eventIndex != _eventMap.end()) { - IdMap::iterator idIndex = eventIndex->second.find(id); - if (idIndex->second.state != State::EXECUTING) { - if (idIndex != eventIndex->second.end()) { - eventIndex->second.erase(idIndex); + CallbackMap::iterator callbackIndex = eventIndex->second.find(usercb); + if (callbackIndex->second.state != State::EXECUTING) { + if (callbackIndex != eventIndex->second.end()) { + eventIndex->second.erase(callbackIndex); } } else { - idIndex->second.state = State::REVOKED; + callbackIndex->second.state = State::REVOKED; } if (eventIndex->second.size() == 0) { _eventMap.erase(eventIndex); diff --git a/languages/c/templates/sdk/src/Event/Event.h b/languages/c/templates/sdk/src/Event/Event.h index df9b1dc9..efa8457a 100644 --- a/languages/c/templates/sdk/src/Event/Event.h +++ b/languages/c/templates/sdk/src/Event/Event.h @@ -26,7 +26,7 @@ namespace FireboltSDK { class Event : public IEventHandler { public: - typedef std::function DispatchFunction; + typedef std::function DispatchFunction; private: enum State : uint8_t { IDLE, @@ -39,9 +39,8 @@ namespace FireboltSDK { const void* userdata; State state; }; - using IdMap = std::map; - using EventMap = std::map; - + using CallbackMap = std::map; + using EventMap = std::map; class Response : public WPEFramework::Core::JSON::Container { public: @@ -64,28 +63,41 @@ namespace FireboltSDK { WPEFramework::Core::JSON::Boolean Listening; }; - public: + private: Event(); + public: ~Event() override; static Event& Instance(); static void Dispose(); void Configure(Transport* transport); public: - template - uint32_t Subscribe(const string& eventName, const CALLBACK& callback, const void* userdata, uint32_t& id) + template + uint32_t Subscribe(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) + { + JsonObject jsonParameters; + return Subscribe(eventName, jsonParameters, callback, usercb, userdata); + } + + template + uint32_t Subscribe(const string& eventName, JsonObject& jsonParameters, const CALLBACK& callback, void* usercb, const void* userdata) { uint32_t status = FireboltSDKErrorUnavailable; if (_transport != nullptr) { - status = Assign(eventName, callback, userdata, id); + status = Assign(eventName, callback, usercb, userdata); if (status == FireboltSDKErrorNone) { - const string parameters("{\"listen\":true}"); Response response; - status = _transport->Subscribe(eventName, parameters, response); + + WPEFramework::Core::JSON::Variant Listen = true; + jsonParameters.Set(_T("listen"), Listen); + string parameters; + jsonParameters.ToString(parameters); + + status = _transport->Subscribe(eventName, parameters, response); if (status != FireboltSDKErrorNone) { - Revoke(eventName, id); + Revoke(eventName, usercb); } else if ((response.Listening.IsSet() == true) && (response.Listening.Value() == true)) { status = FireboltSDKErrorNone; @@ -95,23 +107,23 @@ namespace FireboltSDK { } } - return ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone: status); + return status; } - uint32_t Unsubscribe(const string& eventName, const uint32_t id); + uint32_t Unsubscribe(const string& eventName, void* usercb); private: template - uint32_t Assign(const string& eventName, const CALLBACK& callback, const void* userdata, uint32_t& id) + uint32_t Assign(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) { uint32_t status = FireboltSDKErrorNone; - id = Id(); - std::function actualCallback = callback; - DispatchFunction implementation = [actualCallback](const void* userdata, const string& parameters) -> uint32_t { + std::function actualCallback = callback; + DispatchFunction implementation = [actualCallback](void* usercb, const void* userdata, const string& parameters) -> uint32_t { - WPEFramework::Core::ProxyType inbound = WPEFramework::Core::ProxyType::Create(); - inbound->FromString(parameters); - actualCallback(userdata, static_cast(&inbound)); + WPEFramework::Core::ProxyType* inbound = new WPEFramework::Core::ProxyType(); + *inbound = WPEFramework::Core::ProxyType::Create(); + (*inbound)->FromString(parameters); + actualCallback(usercb, userdata, static_cast(inbound)); return (FireboltSDKErrorNone); }; CallbackData callbackData = {implementation, userdata, State::IDLE}; @@ -119,32 +131,31 @@ namespace FireboltSDK { _adminLock.Lock(); EventMap::iterator eventIndex = _eventMap.find(eventName); if (eventIndex != _eventMap.end()) { - // Already registered, no need to register again; - status = FireboltSDKErrorInUse; - eventIndex->second.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(callbackData)); + CallbackMap::iterator callbackIndex = eventIndex->second.find(usercb); + if (callbackIndex == eventIndex->second.end()) { + eventIndex->second.emplace(std::piecewise_construct, std::forward_as_tuple(usercb), std::forward_as_tuple(callbackData)); + } else { + // Already registered, no need to register again; + status = FireboltSDKErrorInUse; + } } else { - IdMap idMap; - idMap.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(callbackData)); - _eventMap.emplace(std::piecewise_construct, std::forward_as_tuple(eventName), std::forward_as_tuple(idMap)); + CallbackMap callbackMap; + callbackMap.emplace(std::piecewise_construct, std::forward_as_tuple(usercb), std::forward_as_tuple(callbackData)); + _eventMap.emplace(std::piecewise_construct, std::forward_as_tuple(eventName), std::forward_as_tuple(callbackMap)); } _adminLock.Unlock(); return status; } - uint32_t Revoke(const string& eventName, const uint32_t id); + uint32_t Revoke(const string& eventName, void* usercb); private: - uint32_t Id() const - { - return (++_id); - } uint32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) override; uint32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) override; private: - mutable std::atomic _id; EventMap _eventMap; WPEFramework::Core::CriticalSection _adminLock; Transport* _transport; diff --git a/languages/c/templates/sdk/src/Accessor/Config.h b/languages/c/templates/sdk/src/Firebolt.cpp similarity index 50% rename from languages/c/templates/sdk/src/Accessor/Config.h rename to languages/c/templates/sdk/src/Firebolt.cpp index f8389bf6..ffc1369a 100644 --- a/languages/c/templates/sdk/src/Accessor/Config.h +++ b/languages/c/templates/sdk/src/Firebolt.cpp @@ -16,26 +16,25 @@ * SPDX-License-Identifier: Apache-2.0 */ -namespace FireboltSDK { - class EXTERNAL Config : public WPEFramework::Core::JSON::Container { - public: - Config(const Config&) = delete; - Config& operator=(const Config&) = delete; - - Config() - : WPEFramework::Core::JSON::Container() - , Url(_T("")) - , WaitTime(1000) - , LogLevel(_T("Info")) - { - Add(_T("url"), &Url); - Add(_T("waittime"), &WaitTime); - Add(_T("loglevel"), &LogLevel); - } - - public: - WPEFramework::Core::JSON::String Url; - WPEFramework::Core::JSON::DecUInt32 WaitTime; - WPEFramework::Core::JSON::String LogLevel; - }; +#include "FireboltSDK.h" + + +#ifdef __cplusplus +extern "C" { +#endif + + + +uint32_t FireboltSDK_Initialize(char* configLine) { + FireboltSDK::Accessor::Instance(configLine); + return FireboltSDKErrorNone; +} + +uint32_t FireboltSDK_Deinitialize(void) { + FireboltSDK::Accessor::Dispose(); + return FireboltSDKErrorNone; +} + +#ifdef __cplusplus } +#endif diff --git a/languages/c/templates/sdk/src/Firebolt.h b/languages/c/templates/sdk/src/FireboltSDK.h similarity index 97% rename from languages/c/templates/sdk/src/Firebolt.h rename to languages/c/templates/sdk/src/FireboltSDK.h index 6a8f51a2..19946126 100644 --- a/languages/c/templates/sdk/src/Firebolt.h +++ b/languages/c/templates/sdk/src/FireboltSDK.h @@ -22,4 +22,5 @@ #include "Properties/Properties.h" #include "Accessor/Accessor.h" #include "Logger/Logger.h" +#include "TypesPriv.h" #include "Types.h" diff --git a/languages/c/templates/sdk/src/Logger/Logger.cpp b/languages/c/templates/sdk/src/Logger/Logger.cpp index 8acd8a14..0e49dfce 100644 --- a/languages/c/templates/sdk/src/Logger/Logger.cpp +++ b/languages/c/templates/sdk/src/Logger/Logger.cpp @@ -53,7 +53,6 @@ namespace FireboltSDK { _logLevel = logLevel; status = FireboltSDKErrorNone; } - printf("logLevel = %d _logLevel = %d\n", logLevel, _logLevel); return status; } diff --git a/languages/c/templates/sdk/src/Module.h b/languages/c/templates/sdk/src/Module.h index 5107d93e..00ea64bb 100644 --- a/languages/c/templates/sdk/src/Module.h +++ b/languages/c/templates/sdk/src/Module.h @@ -23,8 +23,6 @@ #endif #include -#include -#include #include #undef EXTERNAL diff --git a/languages/c/templates/sdk/src/Params.config b/languages/c/templates/sdk/src/Params.config deleted file mode 100644 index 71a58750..00000000 --- a/languages/c/templates/sdk/src/Params.config +++ /dev/null @@ -1,3 +0,0 @@ -url -waittime -loglevel diff --git a/languages/c/templates/sdk/src/Properties/Properties.h b/languages/c/templates/sdk/src/Properties/Properties.h index 611811f8..d75c3ba5 100644 --- a/languages/c/templates/sdk/src/Properties/Properties.h +++ b/languages/c/templates/sdk/src/Properties/Properties.h @@ -52,7 +52,60 @@ namespace FireboltSDK { } else { FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); } - + + return status; + } + + template + static uint32_t Get(const string& propertyName, const PARAMETERS& parameters, WPEFramework::Core::ProxyType& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + RESPONSETYPE responseType; + status = transport->Invoke(propertyName, parameters, responseType); + if (status == FireboltSDKErrorNone) { + ASSERT(response.IsValid() == false); + if (response.IsValid() == true) { + response.Release(); + } + response = WPEFramework::Core::ProxyType::Create(); + (*response) = responseType; + } + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + + template + static uint32_t Get(const string& propertyName, RESPONSETYPE& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject parameters; + status = transport->Invoke(propertyName, parameters, response); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static uint32_t Get(const string& propertyName, const PARAMETERS& parameters, RESPONSETYPE& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + status = transport->Invoke(propertyName, parameters, response); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + return status; } @@ -71,20 +124,25 @@ namespace FireboltSDK { return status; } - template - static uint32_t Subscribe(const string& propertyName, const CALLBACK& callback, const void* userdata, uint32_t& id) + template + static uint32_t Subscribe(const string& propertyName, JsonObject& paramsters, const CALLBACK& callback, void* usercb, const void* userdata) { - return Event::Instance().Subscribe(EventName(propertyName), callback, userdata, id); + return Event::Instance().Subscribe(EventName(propertyName), paramsters, callback, usercb, userdata); } - static uint32_t Unsubscribe(const string& propertyName, const uint32_t id) + static uint32_t Unsubscribe(const string& propertyName, void* usercb) { - return Event::Instance().Unsubscribe(EventName(propertyName), id); + return Event::Instance().Unsubscribe(EventName(propertyName), usercb); } private: static inline string EventName(const string& propertyName) { size_t pos = propertyName.find_first_of('.'); - return string(propertyName.substr(0, pos + 1) + "on" + propertyName.substr(pos + 1) + "Changed"); + string eventName = propertyName; + if (pos != std::string::npos) { + eventName[pos + 1] = std::toupper(eventName[pos + 1]); + eventName = string(eventName.substr(0, pos + 1) + "on" + eventName.substr(pos + 1) + "Changed"); + } + return eventName; } }; } diff --git a/languages/c/templates/sdk/src/Transport/Transport.h b/languages/c/templates/sdk/src/Transport/Transport.h index e0bff38c..2aff350d 100644 --- a/languages/c/templates/sdk/src/Transport/Transport.h +++ b/languages/c/templates/sdk/src/Transport/Transport.h @@ -254,7 +254,7 @@ namespace FireboltSDK { public: ChannelImpl(CommunicationChannel* parent, const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask) - : BaseClass(5, FactoryImpl::Instance(), path, _T("JSON"), query, "", false, mask, false, remoteNode.AnyInterface(), remoteNode, 256, 256) + : BaseClass(5, FactoryImpl::Instance(), path, _T("JSON"), query, "", false, mask, false, remoteNode.AnyInterface(), remoteNode, 1024 * 2, 1024 * 2) //TODO Relook this size issue , _parent(*parent) { } @@ -520,7 +520,7 @@ namespace FireboltSDK { public: inline bool IsOpen() { - _channel->IsOpen(); + return _channel->IsOpen(); } void Revoke(const string& eventName) diff --git a/languages/c/templates/sdk/src/Types.cpp b/languages/c/templates/sdk/src/Types.cpp index e573c0c9..f19cfe63 100644 --- a/languages/c/templates/sdk/src/Types.cpp +++ b/languages/c/templates/sdk/src/Types.cpp @@ -27,13 +27,12 @@ extern "C" { // String Type Handler Interfaces const char* FireboltTypes_String(FireboltTypes_StringHandle handle) { - FireboltSDK::String* str = static_cast(handle); - return (str->Value().c_str()); + return ((static_cast(handle))->Value().c_str()); } + void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle) { - FireboltSDK::String* str = static_cast(handle); - delete str; + delete static_cast(handle); } #ifdef __cplusplus diff --git a/languages/c/templates/sdk/src/TypesPriv.h b/languages/c/templates/sdk/src/TypesPriv.h index eda9547f..6e365ec7 100644 --- a/languages/c/templates/sdk/src/TypesPriv.h +++ b/languages/c/templates/sdk/src/TypesPriv.h @@ -21,35 +21,36 @@ #include namespace FireboltSDK { -class String { +namespace JSON { +class String : public WPEFramework::Core::JSON::String { + using Base = WPEFramework::Core::JSON::String; public: String() - : _value() + : Base() + , _value() { } - String(const std::string& value) - : _value(value) + String(const char value[]) + : Base(value) + , _value(value) { } - String(const String& copy) - : _value(copy._value) + String& operator=(const char RHS[]) { - - } - inline ~String() = default; - String& operator=(const String& RHS) - { - _value = RHS._value; + Base::operator = (RHS); + _value = RHS; return (*this); } public: - const std::string& Value() const + const string& Value() const { + _value = Base::Value(); return _value; } private: - std::string _value; + mutable std::string _value; }; } +} diff --git a/languages/c/templates/sdk/src/cmake/CopySymlink.cmake b/languages/c/templates/sdk/src/cmake/CopySymlink.cmake deleted file mode 100644 index 8ac3c1f8..00000000 --- a/languages/c/templates/sdk/src/cmake/CopySymlink.cmake +++ /dev/null @@ -1 +0,0 @@ -file(COPY "${LIBRARY}" DESTINATION "${DESTINATION}" FOLLOW_SYMLINK_CHAIN) From 88186544f97b0fca44d3514ee41020fd571fe92e Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 15 Jun 2023 09:09:06 +0530 Subject: [PATCH 042/137] Add support to generate file inclusion for common schema also (#97) Add support to generate file inclusion for common schema also --- languages/c/Types.mjs | 336 +++++++++--------- languages/c/src/types/JSONHelpers.mjs | 3 +- languages/c/src/types/NativeHelpers.mjs | 15 - languages/c/templates/imports/default.cpp | 1 + .../imports/{default.c => default.h} | 0 .../c/templates/imports/default.jsondata | 1 + .../templates/modules/include/Common/Module.h | 40 --- .../c/templates/modules/src/JsonData_Module.h | 29 -- languages/c/templates/modules/src/Module.cpp | 6 +- .../templates/schemas/include/Common/Module.h | 1 + .../c/templates/schemas/src/JsonData_Module.h | 5 + .../c/templates/schemas/src/Module_Common.cpp | 5 +- src/macrofier/engine.mjs | 50 ++- src/shared/typescript.mjs | 2 +- 14 files changed, 226 insertions(+), 268 deletions(-) create mode 100644 languages/c/templates/imports/default.cpp rename languages/c/templates/imports/{default.c => default.h} (100%) create mode 100644 languages/c/templates/imports/default.jsondata delete mode 100644 languages/c/templates/modules/include/Common/Module.h delete mode 100644 languages/c/templates/modules/src/JsonData_Module.h diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 0bb6cc59..bbd74eec 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -318,193 +318,201 @@ function getSchemaShape(json, module, { name = '', prefix = '', level = 0, title return shape } function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '', merged = false, level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { - const isHeader = (destination.includes("JsonData_") !== true) && destination.endsWith(".h") - const isCPP = ((destination.endsWith(".cpp") || destination.includes("JsonData_")) && (section.includes('accessors') !== true)) - json = JSON.parse(JSON.stringify(json)) - - name = json.title || name let shape = '' - if (json['$ref']) { - if (json['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType - const schema = getPath(json['$ref'], module, schemas) - const tname = schema.title || json['$ref'].split('/').pop() - if (json['$ref'].includes('x-schemas')) { - schema = (getRefModule(json['$ref'].split('/')[2])) - } - - shape = getSchemaShapeInfo(schema, module, schemas, { name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) - } - } - //If the schema is a const, - else if (json.hasOwnProperty('const') && !isCPP) { - if (level > 0) { + if (destination && section) { + const isHeader = (destination.includes("JsonData_") !== true) && destination.endsWith(".h") + const isCPP = ((destination.endsWith(".cpp") || destination.includes("JsonData_")) && (section.includes('accessors') !== true)) + json = JSON.parse(JSON.stringify(json)) + + name = json.title || name + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + const schema = getPath(json['$ref'], module, schemas) + const tname = schema.title || json['$ref'].split('/').pop() + if (json['$ref'].includes('x-schemas')) { + schema = (getRefModule(json['$ref'].split('/')[2])) + } - let t = description(capitalize(name), json.description) - typeName = getTypeName(getModuleName(module), name, prefix) - t += (isHeader ? getPropertyAccessors(typeName, capitalize(name), typeof schema.const, { level: level, readonly: true, optional: false }) : getPropertyAccessorsImpl(typeName, getJsonType(schema, module, { level, name }), typeof schema.const, { level: level, readonly: true, optional: false })) - shape += '\n' + t + shape = getSchemaShapeInfo(schema, module, schemas, { name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) + } } - } - else if (json.type === 'object') { - if (!name) { - console.log(`WARNING: unnamed schema in ${module.info.title}.`) - console.dir(json) - shape = '' + //If the schema is a const, + else if (json.hasOwnProperty('const') && !isCPP) { + if (level > 0) { + + let t = description(capitalize(name), json.description) + typeName = getTypeName(getModuleName(module), name, prefix) + t += (isHeader ? getPropertyAccessors(typeName, capitalize(name), typeof schema.const, { level: level, readonly: true, optional: false }) : getPropertyAccessorsImpl(typeName, getJsonType(schema, module, { level, name }), typeof schema.const, { level: level, readonly: true, optional: false })) + shape += '\n' + t + } } - else if (json.properties && (validJsonObjectProperties(json) === true)) { - let c_shape = description(capitalize(name), json.description) - let cpp_shape = '' - let tName = getTypeName(getModuleName(module), name, prefix) - c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(json, module, { name }))) - let props = [] - let containerName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? (prefix + '_' + capitalize(name)) : capitalize(name) - Object.entries(json.properties).forEach(([pname, prop]) => { - let items - var desc = '\n' + description(capitalize(pname), prop.description) - if (prop.type === 'array') { - if (Array.isArray(prop.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(prop.items)) { - throw 'Heterogenous Arrays not supported yet' + else if (json.type === 'object') { + if (!name) { + console.log(`WARNING: unnamed schema in ${module.info.title}.`) + console.dir(json) + shape = '' + } + else if (json.properties && (validJsonObjectProperties(json) === true)) { + let c_shape = description(capitalize(name), json.description) + let cpp_shape = '' + let tName = getTypeName(getModuleName(module), name, prefix) + c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(json, module, { name }))) + let props = [] + let containerName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? (prefix + '_' + capitalize(name)) : capitalize(name) + Object.entries(json.properties).forEach(([pname, prop]) => { + let items + var desc = '\n' + description(capitalize(pname), prop.description) + if (prop.type === 'array') { + if (Array.isArray(prop.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(prop.items)) { + throw 'Heterogenous Arrays not supported yet' + } + items = prop.items[0] + } + else { + // grab the type for the non-array schema + items = prop.items + } + + let info = getSchemaTypeInfo(module, items, items.name || pname, schemas, prefix, {level : level, descriptions: descriptions, title: true}) + if (info.type && info.type.length > 0) { + let objName = tName + '_' + capitalize(prop.title || pname) + let moduleName = info.namespace + info.json.namespace = info.namespace + let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) + let prefixName = ((prefix.length > 0) && items['$ref']) ? '' : prefix + let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, schemas, prefix) + + let t = description(capitalize(info.name), json.description) + '\n' + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) + c_shape += '\n' + t + props.push({name: `${pname}`, type: `WPEFramework::Core::JSON::ArrayType<${subModuleProperty.type}>`}) + } + else { + console.log(`a. WARNING: Type undetermined for ${name}:${pname}`) + } + } else { + if (((merged === false) || ((merged === true) && (pname.includes(name)))) && (prop.type === 'object' || prop.anyOf || prop.allOf)) { + shape += getSchemaShapeInfo(prop, module, schemas, { name : pname, prefix, merged: false, level: 1, title, summary, descriptions, destination, section, enums }) + } + let info = getSchemaTypeInfo(module, prop, pname, module['x-schemas'], prefix, {descriptions: descriptions, level: level + 1, title: true}) + if (info.type && info.type.length > 0) { + let subPropertyName = ((pname.length !== 0) ? capitalize(pname) : info.name) + let moduleProperty = getJsonTypeInfo(module, json, name, schemas, prefix) + let subProperty = getJsonTypeInfo(module, prop, pname, schemas, prefix) + c_shape += '\n' + description(capitalize(pname), info.json.description) + c_shape += '\n' + (isHeader ? getPropertyAccessors(tName, capitalize(pname), info.type, { level: 0, readonly: false, optional: isOptional(pname, json) }) : getPropertyAccessorsImpl(tName, moduleProperty.type, subProperty.type, subPropertyName, info.type, info.json, {readonly:false, optional:isOptional(pname, json)})) + let property = getJsonType(prop, module, { name : pname, prefix }) + props.push({name: `${pname}`, type: `${property}`}) + } + else { + console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) } - items = prop.items[0] - } - else { - // grab the type for the non-array schema - items = prop.items - } - let info = getSchemaTypeInfo(module, items, items.name || pname, schemas, prefix, {level : level, descriptions: descriptions, title: true}) - if (info.type && info.type.length > 0) { - let objName = tName + '_' + capitalize(prop.title || pname) - let moduleName = info.namespace - info.json.namespace = info.namespace - let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) - let prefixName = ((prefix.length > 0) && items['$ref']) ? '' : prefix - let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, schemas, prefix) - - let t = description(capitalize(info.name), json.description) + '\n' - t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) - c_shape += '\n' + t - props.push({name: `${pname}`, type: `WPEFramework::Core::JSON::ArrayType<${subModuleProperty.type}>`}) - } - else { - console.log(`a. WARNING: Type undetermined for ${name}:${pname}`) - } - } else { - if (((merged === false) || ((merged === true) && (pname.includes(name)))) && (prop.type === 'object' || prop.anyOf || prop.allOf)) { - shape += getSchemaShapeInfo(prop, module, schemas, { name : pname, prefix, merged: false, level: 1, title, summary, descriptions, destination, section, enums }) - } - let info = getSchemaTypeInfo(module, prop, pname, module['x-schemas'], prefix, {descriptions: descriptions, level: level + 1, title: true}) - if (info.type && info.type.length > 0) { - let subPropertyName = ((pname.length !== 0) ? capitalize(pname) : info.name) - let moduleProperty = getJsonTypeInfo(module, json, name, schemas, prefix) - let subProperty = getJsonTypeInfo(module, prop, pname, schemas, prefix) - c_shape += '\n' + description(capitalize(pname), info.json.description) - c_shape += '\n' + (isHeader ? getPropertyAccessors(tName, capitalize(pname), info.type, { level: 0, readonly: false, optional: isOptional(pname, json) }) : getPropertyAccessorsImpl(tName, moduleProperty.type, subProperty.type, subPropertyName, info.type, info.json, {readonly:false, optional:isOptional(pname, json)})) - let property = getJsonType(prop, module, { name : pname, prefix }) - props.push({name: `${pname}`, type: `${property}`}) - } - else { - console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) } - } - }) + }) - cpp_shape += getJsonContainerDefinition(json, containerName, props) + cpp_shape += getJsonContainerDefinition(json, containerName, props) - if (isCPP) { - shape += '\n' + cpp_shape - } - else { - shape += '\n' + c_shape + if (isCPP) { + shape += '\n' + cpp_shape + } + else { + shape += '\n' + c_shape + } } - } - else if (json.propertyNames && json.propertyNames.enum) { - //propertyNames in object not handled yet - } - else if (json.additionalProperties && (typeof json.additionalProperties === 'object') && (validJsonObjectProperties(json) === true) && !isCPP) { - let info = getSchemaTypeInfo(module, json.additionalProperties, name, module['x-schemas'], prefix) - if (!info.type || (info.type.length === 0)) { - info.type = 'char*' - info.json = json.additionalProperties - info.json.type = 'string' + else if (json.propertyNames && json.propertyNames.enum) { + //propertyNames in object not handled yet } + else if (json.additionalProperties && (typeof json.additionalProperties === 'object') && (validJsonObjectProperties(json) === true) && !isCPP) { + let info = getSchemaTypeInfo(module, json.additionalProperties, name, module['x-schemas'], prefix) + if (!info.type || (info.type.length === 0)) { + info.type = 'char*' + info.json = json.additionalProperties + info.json.type = 'string' + } - let tName = getTypeName(getModuleName(module), name, prefix) - let t = description(capitalize(name), json.description) + '\n' - let containerType = 'WPEFramework::Core::JSON::VariantContainer' + let tName = getTypeName(getModuleName(module), name, prefix) + let t = description(capitalize(name), json.description) + '\n' + let containerType = 'WPEFramework::Core::JSON::VariantContainer' - let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, module['x-schemas']) - if (isCPP && ((info.json.type === 'object' && info.json.properties) || info.json.type === 'array')) { - // Handle Container generation here - } + let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, module['x-schemas']) + if (isCPP && ((info.json.type === 'object' && info.json.properties) || info.json.type === 'array')) { + // Handle Container generation here + } - t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, containerType)) - t += (isHeader ? getMapAccessors(tName, info.type, { descriptions: descriptions, level: level }) : getMapAccessorsImpl(tName, containerType, subModuleProperty.type, info.type, info.json, { readonly: true, optional: false })) - shape += '\n' + t + t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, containerType)) + t += (isHeader ? getMapAccessors(tName, info.type, { descriptions: descriptions, level: level }) : getMapAccessorsImpl(tName, containerType, subModuleProperty.type, info.type, info.json, { readonly: true, optional: false })) + shape += '\n' + t + } + else if (json.patternProperties) { + console.log(`WARNING: patternProperties are not supported by Firebolt(inside getModuleName(module):${name})`) + } } - else if (json.patternProperties) { - console.log(`WARNING: patternProperties are not supported by Firebolt(inside getModuleName(module):${name})`) + else if (json.anyOf) { + if (level > 0) { + let mergedSchema = getMergedSchema(module, json, name, schemas) + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + shape += getSchemaShapeInfo(mergedSchema, module, schemas, { name, prefix: prefixName, merged, level, title, summary, descriptions, destination, section, enums }) + } } - } - else if (json.anyOf) { - if (level > 0) { - let mergedSchema = getMergedSchema(module, json, name, schemas) - let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) - shape += getSchemaShapeInfo(mergedSchema, module, schemas, { name, prefix: prefixName, merged, level, title, summary, descriptions, destination, section, enums }) + else if (json.oneOf) { + //Just ignore schema shape, since this has to be treated as string } - } - else if (json.oneOf) { - //Just ignore schema shape, since this has to be treated as string - } - else if (json.allOf) { - let title = (json.title ? json.title : name) - let union = deepMergeAll(module, title, json, schemas) - union.title = title + else if (json.allOf) { + let title = (json.title ? json.title : name) + let union = deepMergeAll(module, title, json, schemas) + union.title = title - delete union['$ref'] + delete union['$ref'] - return getSchemaShapeInfo(union, module, schemas, { name, prefix, merged: true, level, title, summary, descriptions, destination, section, enums }) - } - else if (json.type === 'array' && !isCPP) { - let j - if (Array.isArray(json.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(json.items)) { - throw 'Heterogenous Arrays not supported yet' + return getSchemaShapeInfo(union, module, schemas, { name, prefix, merged: true, level, title, summary, descriptions, destination, section, enums }) + } + else if (json.type === 'array') { + let j + if (Array.isArray(json.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(json.items)) { + throw 'Heterogenous Arrays not supported yet' + } + j = json.items[0] + } + else { + j = json.items + } + shape += getSchemaShapeInfo(j, module, schemas, { name: j.title || name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) + + if (!isCPP) { + let info = getSchemaTypeInfo(module, j, j.title || name, schemas, prefix, {level : level, descriptions: descriptions, title: true}) + + if (info.type && info.type.length > 0) { + let type = getArrayElementSchema(json, module, schemas, info.name) + let arrayName = capitalize(name) + capitalize(type.type) + let objName = getTypeName(info.namespace, arrayName, prefix) + let tName = objName + 'Array' + let moduleName = info.namespace + info.json.namespace = info.namespace + let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) + let subModuleProperty = getJsonTypeInfo(module, j, j.title, schemas, prefix) + let t = '' + if (level === 0) { + t += description(capitalize(info.name), json.description) + '\n' + t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, moduleProperty.type)) + } + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, '', info.type, info.json)) + shape += '\n' + t + } } - j = json.items[0] } else { - j = json.items + shape += '\n' + getSchemaType(module, json, name, schemas, prefix, {level: level, descriptions: descriptions}) } - - let info = getSchemaTypeInfo(module, j, j.name || name, schemas, prefix, {level : level, descriptions: descriptions, title: true}) - - if (info.type && info.type.length > 0) { - let type = getArrayElementSchema(json, module, schemas, info.name) - let arrayName = capitalize(info.name) + capitalize(type.type) - let objName = getTypeName(info.namespace, arrayName, prefix) - let tName = objName + 'Array' - let moduleName = info.namespace - info.json.namespace = info.namespace - let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) - let t = '' - if (level === 0) { - t += description(capitalize(info.name), json.description) + '\n' - t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, moduleProperty.type)) - } - t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + 'Handle'), getJsonNativeType(type), '', info.type, info.json)) - shape += '\n' + t - } - } - else { - shape += '\n' + getSchemaType(module, json, name, schemas, prefix, {level: level, descriptions: descriptions}) } return shape diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index 3437c98c..b2a260b5 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -51,5 +51,6 @@ function getJsonContainerDefinition (schema, name, props) { } export { - getJsonContainerDefinition + getJsonContainerDefinition, + getJsonDataStructName } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index eac20c16..489b3f52 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -211,20 +211,6 @@ const generateEnum = (schema, prefix)=> { } } -const getIncludeDefinitions = (json = {}, jsonData = false) => { - return getExternalSchemaPaths(json) - .map(ref => { - const mod = ref.split('#')[0].split('/').pop() - let i = `#include "Common/${capitalize(mod)}.h"` - if(jsonData === true) { - i += '\n' + `#include "JsonData_${capitalize(mod)}.h"` - } - return i - }) - .filter((item, index, arr) => arr.indexOf(item) === index) - .concat([`#include "Firebolt/Types.h"`]) -} - function getPropertyGetterSignature(method, module, paramType) { let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` @@ -251,7 +237,6 @@ export { getIncludeGuardClose, getNativeType, getModuleName, - getIncludeDefinitions, getPropertyGetterSignature, getPropertySetterSignature, getPropertyEventCallbackSignature, diff --git a/languages/c/templates/imports/default.cpp b/languages/c/templates/imports/default.cpp new file mode 100644 index 00000000..69e241f9 --- /dev/null +++ b/languages/c/templates/imports/default.cpp @@ -0,0 +1 @@ +#include "JsonData_${info.title}.h" diff --git a/languages/c/templates/imports/default.c b/languages/c/templates/imports/default.h similarity index 100% rename from languages/c/templates/imports/default.c rename to languages/c/templates/imports/default.h diff --git a/languages/c/templates/imports/default.jsondata b/languages/c/templates/imports/default.jsondata new file mode 100644 index 00000000..69e241f9 --- /dev/null +++ b/languages/c/templates/imports/default.jsondata @@ -0,0 +1 @@ +#include "JsonData_${info.title}.h" diff --git a/languages/c/templates/modules/include/Common/Module.h b/languages/c/templates/modules/include/Common/Module.h deleted file mode 100644 index 809418a2..00000000 --- a/languages/c/templates/modules/include/Common/Module.h +++ /dev/null @@ -1,40 +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 - */ - -#ifndef _COMMON_${info.TITLE}_H -#define _COMMON_${info.TITLE}_H - -#include "Firebolt.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// Enums - -/* ${ENUMS} */ - -// Schemas - -/* ${SCHEMAS} */ - -#ifdef __cplusplus -} -#endif - -#endif // Header Include Guard diff --git a/languages/c/templates/modules/src/JsonData_Module.h b/languages/c/templates/modules/src/JsonData_Module.h deleted file mode 100644 index 2c7ca8c8..00000000 --- a/languages/c/templates/modules/src/JsonData_Module.h +++ /dev/null @@ -1,29 +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 - */ - -#pragma once - -#include "Firebolt.h" - -namespace FireboltSDK { - namespace ${info.title} { - - /* ${SCHEMAS}} */ - - } -} diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 47a356d6..d34c1da5 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -16,11 +16,9 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "Firebolt.h" -#include "${info.title}.h" -#include "JsonData_${info.title}.h" - +#include "FireboltSDK.h" /* ${IMPORTS} */ +#include "${info.title}.h" namespace FireboltSDK { namespace ${info.title} { diff --git a/languages/c/templates/schemas/include/Common/Module.h b/languages/c/templates/schemas/include/Common/Module.h index 0326c220..ff037fba 100644 --- a/languages/c/templates/schemas/include/Common/Module.h +++ b/languages/c/templates/schemas/include/Common/Module.h @@ -20,6 +20,7 @@ #define _COMMON_${info.TITLE}_H #include "Firebolt.h" +/* ${IMPORTS} */ #ifdef __cplusplus extern "C" { diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/JsonData_Module.h index 7fa2b6f4..d0ecbbac 100644 --- a/languages/c/templates/schemas/src/JsonData_Module.h +++ b/languages/c/templates/schemas/src/JsonData_Module.h @@ -16,6 +16,11 @@ * SPDX-License-Identifier: Apache-2.0 */ +#pragma once + +/* ${IMPORTS} */ +#include "Common/${info.title}.h" + namespace FireboltSDK { namespace ${info.title} { // Types diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/Module_Common.cpp index 9dc2ee0a..e2389d50 100644 --- a/languages/c/templates/schemas/src/Module_Common.cpp +++ b/languages/c/templates/schemas/src/Module_Common.cpp @@ -16,9 +16,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "Firebolt.h" -#include "${info.title}.h" -#include "Common/${info.title}.h" +#include "FireboltSDK.h" +/* ${IMPORTS} */ #include "JsonData_${info.title}.h" /* ${ENUMS} */ diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 13ce46f4..a2c64ec0 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -46,6 +46,7 @@ const _inspector = obj => { // getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) // getSchemaType(schema, module, options = { destination: 'file.txt', title: true }) // getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getJsonType(schema, module, options = { name: 'Foo', prefix: '', descriptions: false, level: 0 }) let types = { getMethodSignature: ()=>null, @@ -133,6 +134,24 @@ const getLinkForSchema = (schema, json, { name = '' } = {}) => { return '#' } +const getComponentExternalSchema = (json) => { + let refSchemas = [] + if (json.components && json.components.schemas) { + Object.entries(json.components.schemas).forEach(([name, schema]) => { + let refs = getLinkedSchemaPaths(schema).map(path => getPathOr(null, path, schema)) + refs.map(ref => { + let title = '' + if (ref.includes('x-schemas')) { + if (ref.split('/')[2] !== json.info.title) { + title = ref.split('/')[2] + } + } + title && !refSchemas.includes(title) ? refSchemas.push(title) : null + }) + }) + } + return (refSchemas) +} // Maybe methods array of objects const getMethods = compose( @@ -319,7 +338,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { // grab the options so we don't have to pass them from method to method Object.assign(state, options) - const imports = generateImports(obj, templates) + const imports = generateImports(obj, templates, { destination : (options.destination ? options.destination : '') }) const initialization = generateInitialization(obj, templates) const enums = generateEnums(obj, templates, { destination : (options.destination ? options.destination : '') }) const eventsEnum = generateEvents(obj, templates) @@ -345,7 +364,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { const schemasArray = generateSchemas(obj, templates, { baseUrl: '', section: 'schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) const accessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).filter(body => body).join('\n')) : '' - const typesArray = schemasArray.filter(x => !x.enum) + const typesArray = schemasArray.length ? schemasArray.filter(x => !x.enum) : [] const types = (typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodTypes const accessors = (accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodAccessors @@ -632,7 +651,6 @@ function generateSchemas(json, templates, options) { if (['ListenResponse', 'ProviderRequest', 'ProviderResponse', 'FederatedResponse', 'FederatedRequest'].includes(name)) { return } - let content = getTemplate('/schemas/default', templates) if (!schema.examples || schema.examples.length === 0) { @@ -695,11 +713,11 @@ function generateSchemas(json, templates, options) { if (!isDeprecatedMethod(schema)) { schema.params.forEach(param => { if (param.schema && (param.schema.type === 'object')) { - list.push([param.name, param.schema, '', { prefix : schema.name}]) + list.push([param.name, param.schema, '', { prefix : schema.name }]) } }) if (schema.result.schema && (schema.result.schema.type === 'object')) { - list.push([schema.result.name, schema.result.schema, '', { prefix : schema.name}]) + list.push([schema.result.name, schema.result.schema, '', { prefix : schema.name }]) } } } @@ -741,8 +759,8 @@ function getRelatedSchemaLinks(schema = {}, json = {}, templates = {}, options = return links } -const generateImports = (json, templates) => { - let imports = getTemplate('/imports/default', templates) +const generateImports = (json, templates, options = { destination: '' }) => { + let imports = '' if (rpcMethodsOrEmptyArray(json).length) { imports += getTemplate('/imports/rpc', templates) @@ -771,11 +789,22 @@ const generateImports = (json, templates) => { 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() + + let template = prefix ? getTemplate(`/imports/default.${prefix}`, templates) : '' + if (!template) { + template = getTemplate(suffix ? `/imports/default.${suffix}` : '/imports/default', templates) + } - if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0) { - imports += Object.keys(json['x-schemas']).map(shared => getTemplate('/imports/default', templates).replace(/\$\{info.title\}/g, shared)).join('\n') + if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0 && !json.info['x-uri-titles']) { + imports += Object.keys(json['x-schemas']).map(shared => template.replace(/\$\{info.title\}/g, shared)).join('') } + let componentExternalSchema = getComponentExternalSchema(json) + if (componentExternalSchema.length && json.info['x-uri-titles']) { + imports += componentExternalSchema.map(shared => template.replace(/\$\{info.title\}/g, shared)).join('') + } return imports } @@ -1019,9 +1048,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' - + let seeAlso = '' - if (isPolymorphicPullMethod(methodObj) && pullsForType) { seeAlso = `See also: [${pullsForType}](#${pullsForType.toLowerCase()}-1)` // this assumes the schema will be after the method... } diff --git a/src/shared/typescript.mjs b/src/shared/typescript.mjs index e53747cd..79c3e022 100644 --- a/src/shared/typescript.mjs +++ b/src/shared/typescript.mjs @@ -327,7 +327,7 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { return '' } - + function getTypeScriptType(jsonType) { if (jsonType === 'integer') { return 'number' From a168c8d7c05d1306c85edeed31577bdc5da2f9c4 Mon Sep 17 00:00:00 2001 From: sramani-metro <71630728+sramani-metro@users.noreply.github.com> Date: Tue, 20 Jun 2023 20:19:13 +0530 Subject: [PATCH 043/137] C-Language: Templates based property methods (#100) * feat: Add method templates for properties * feat: Property setters using templates * fix: Macro name correction --- languages/c/Types.mjs | 98 ++++++++++++++++--- languages/c/src/types/ImplHelpers.mjs | 63 +++++++++++- languages/c/src/types/NativeHelpers.mjs | 70 ++++++++++--- languages/c/templates/codeblocks/setter.c | 9 ++ languages/c/templates/declarations/default.c | 5 - languages/c/templates/declarations/property.c | 5 + languages/c/templates/defaults/default.c | 1 - languages/c/templates/defaults/property.c | 1 - .../c/templates/methods/{clear.js => clear.c} | 0 languages/c/templates/methods/property.c | 19 +++- languages/c/templates/methods/provide.c | 3 - languages/c/templates/methods/setter.c | 0 src/macrofier/engine.mjs | 12 ++- src/shared/typescript.mjs | 6 +- 14 files changed, 243 insertions(+), 49 deletions(-) create mode 100644 languages/c/templates/codeblocks/setter.c create mode 100644 languages/c/templates/declarations/property.c rename languages/c/templates/methods/{clear.js => clear.c} (100%) create mode 100644 languages/c/templates/methods/setter.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index bbd74eec..0886d3dc 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -18,8 +18,8 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' -import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema } from './src/types/NativeHelpers.mjs' -import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getPropertyAccessorsImpl } from './src/types/ImplHelpers.mjs' +import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature } from './src/types/NativeHelpers.mjs' +import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation } from './src/types/ImplHelpers.mjs' import { getJsonContainerDefinition, getJsonDataStructName } from './src/types/JSONHelpers.mjs' const getSdkNameSpace = () => 'FireboltSDK' @@ -166,33 +166,65 @@ const deepMergeAll = (module, name, schema, schemas, options) => { return union } +const hasTag = (method, tag) => { + return method.tags && method.tags.filter(t => t.name === tag).length > 0 +} function getMethodSignature(method, module, { destination, isInterface = false }) { - const extraParam = '${method.result.type}* ${method.result.name}' - const prefix = method.tags.find(t => t.name.split(":")[0] === "property") ? "Get" : "" + let signature = '' + let paramList = [] + if(hasTag(method, 'property') || hasTag(method, 'property:readonly') || hasTag(method, 'property:immutable')) { + + method.params.map(param => { + /* + paramList = [{name='', nativeType='', jsonType='', required=boolean}] + */ + paramList['nativeType'] = getSchemaType(param.schema, module, { title: true, name: param.name }) + paramList['jsonType'] = getJsonType(param.schema, module, {name: param.name}) + paramList['name'] = param.name + paramList['required'] = param.required + + }) - return 'uint32_t ${info.title}_' + prefix + '${method.Name}(' + extraParam + ')' + let resultType = method.result && getSchemaType(method.result.schema, module, { title: true, name: method.result.name, resultSchema: true}) || '' + + signature = getPropertyGetterSignature(method, module, resultType, paramList) + ';\n\n' + + if(hasTag(method, 'property') || hasTag(method, 'property:readonly')) { + signature += getPropertyEventCallbackSignature(method, module, resultType, paramList) + ';\n\n' + signature += getPropertyEventRegisterSignature(method, module, paramList) + ';\n\n' + signature += getPropertyEventUnregisterSignature(method, module) + ';\n\n' + } + + if(hasTag(method, 'property')) { + signature += getPropertySetterSignature(method, module, resultType, paramList) + ';\n\n' + } + } + return signature } + function getMethodSignatureParams(method, module, { destination }) { - return method.params.map(param => param.name + (!param.required ? '?' : '') + ': ' + getSchemaType(param.schema, module, { name: param.name, title: true, destination })).join(', ') + return method.params.map(param => getSchemaType(param.schema, module, { name: param.name, title: true, destination }) + (!param.required ? '* ' : ' ') + param.name ).join(', ') } const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop -function getSchemaType(schema, module, { name, prefix = '', destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - let info = getSchemaTypeInfo(module, schema, name, module['x-schemas'], prefix, { title: title }) +function getSchemaType(schema, module, { name, prefix = '', destination, resultSchema = false, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + let info = getSchemaTypeInfo(module, schema, name, module['x-schemas'], prefix, { title: title, resultSchema: resultSchema, event: event }) return info.type } -function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = {level: 0, descriptions: true, title: false}) { +function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = {level: 0, descriptions: true, title: false, resultSchema: false, event: false}) { if (json.schema) { json = json.schema } + let stringAsHandle = options.resultSchema || options.event + let structure = {} structure["type"] = '' structure["json"] = [] @@ -219,7 +251,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref } } else if (json.const) { - structure.type = getNativeType(json) + structure.type = getNativeType(json, stringAsHandle) structure.json = json return structure } @@ -240,7 +272,9 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref } else if (Array.isArray(json.type)) { let type = json.type.find(t => t !== 'null') - console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) + let sch = JSON.parse(JSON.stringify(json)) + sch.type = type + return getSchemaTypeInfo(module, sch, name, schemas, prefix, options) } else if (json.type === 'array' && json.items && (validJsonObjectProperties(json) === true)) { let res = '' @@ -300,7 +334,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref return structure } else if (json.type) { - structure.type = getNativeType(json) + structure.type = getNativeType(json, stringAsHandle) structure.json = json if (name || json.title) { structure.name = capitalize(name || json.title) @@ -534,6 +568,9 @@ const getJsonNativeType = json => { else if (jsonType === 'boolean') { type = 'WPEFramework::Core::JSON::Boolean' } + else if (jsonType === 'null') { + type = 'void' + } else { throw 'Unknown JSON Native Type !!!' } @@ -601,7 +638,9 @@ function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '' } else if (Array.isArray(json.type)) { let type = json.type.find(t => t !== 'null') - console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) + let sch = JSON.parse(JSON.stringify(json)) + sch.type = type + return getJsonTypeInfo(module, sch, name, schemas, prefix ) } else if (json.type === 'array' && json.items) { let res @@ -682,10 +721,41 @@ const enumReducer = (acc, val, i, arr) => { return acc } +function getSchemaInstantiation(schema, module, name, { instantiationType = '' } = {}) { + + if(instantiationType === 'params') { + if (schema.params.length > 0) { + let paramList = [] + schema.params.map(param => { + /* + paramList = [{name='', nativeType='', jsonType='', required=boolean}] + */ + const parameter = {} + parameter['nativeType'] = getSchemaType(param.schema, module, { title: true, name: param.name }) + parameter['jsonType'] = getJsonType(param.schema, module, {name: param.name}) + parameter['name'] = param.name + parameter['required'] = param.required + paramList.push(parameter) + + }) + return getParameterInstantiation(paramList) + } + } else if(instantiationType === 'result') { + let resultType = getSchemaType(schema, module, { title: true, name: name, resultSchema: true}) || '' + let resultJsonType = getJsonType(schema, module, {name: name}) || '' + + return getResultInstantiation(name, resultType, resultJsonType) + } + + return '' +} + + export default { getMethodSignature, getMethodSignatureParams, getSchemaShape, getSchemaType, - getJsonType + getJsonType, + getSchemaInstantiation } diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index 47852c9e..a39af0b6 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -1,3 +1,5 @@ +import { capitalize } from "./NativeHelpers.mjs" + const Indent = '\t' const getSdkNameSpace = () => 'FireboltSDK' @@ -288,9 +290,68 @@ const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPr return result } +/* +paramList = [{name='', nativeType='', jsonType='', required=boolean}] +*/ +function getParameterInstantiation(paramList, container = '') { + + let impl = ` ${container.length>0 ? container : 'JsonObject'} jsonParameters;\n` + paramList.forEach(param => { + impl += `\n` + const jsonType = param.jsonType + if (jsonType.length) { + if (param.required) { + if (param.nativeType.includes('FireboltTypes_StringHandle')) { + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = *(static_cast<${jsonType}*>(${param.name}));\n` + } + else { + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = ${param.name};\n` + } + impl += ` jsonParameters.Set(_T("${param.name}"), ${capitalize(param.name)});` + } + else { + impl += ` if (${param.name} != nullptr) {\n` + if (param.nativeType.includes('char*')) { + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = ${param.name};\n` + } else { + + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = *(${param.name});\n` + } + impl += ` jsonParameters.Set(_T("${param.name}"), ${capitalize(param.name)});\n` + impl += ` }` + } + } + }) + + return impl +} + +function getResultInstantiation (name, nativeType, container, indentLevel = 3) { + + let impl = '' + + if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + impl += `${' '.repeat(indentLevel)}${container}* strResult = new ${container}(jsonResult);` + '\n' + impl += `${' '.repeat(indentLevel)}*${name} = static_cast<${getFireboltStringType()}>(strResult);` + } else if (nativeType.includes('Handle')) { + impl += `${' '.repeat(indentLevel)}WPEFramework::Core::ProxyType<${container}>* resultPtr = new WPEFramework::Core::ProxyType<${container}>();\n` + impl += `${' '.repeat(indentLevel)}*resultPtr = WPEFramework::Core::ProxyType<${container}>::Create();\n` + impl += `${' '.repeat(indentLevel)}*(*resultPtr) = jsonResult;\n` + impl += `${' '.repeat(indentLevel)}*${name} = static_cast<${nativeType}>(resultPtr);` + } else { + impl += `${' '.repeat(indentLevel)}*${name} = jsonResult.Value();` + } + + return impl + +} + + export { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, - getPropertyAccessorsImpl + getPropertyAccessorsImpl, + getParameterInstantiation, + getResultInstantiation } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 489b3f52..65a78443 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -115,24 +115,32 @@ const getArrayElementSchema = (json, module, schemas = {}, name) => { return result } -const getNativeType = json => { - let type = '' +const getNativeType = (json, stringAsHandle = false) => { + let type let jsonType = json.const ? typeof json.const : json.type if (jsonType === 'string') { - type = 'char*' + type = 'char*' + if(stringAsHandle) { + type = getFireboltStringType() + } } else if (jsonType === 'number') { - type = 'float' + type = 'float' } else if (jsonType === 'integer') { - type = 'int32_t' + type = 'int32_t' + } else if (jsonType === 'boolean') { type = 'bool' } + else if (jsonType === 'null' ) { + type = 'void' + } return type } + const getObjectHandleManagement = varName => { let result = `typedef void* ${varName}Handle; @@ -211,24 +219,53 @@ const generateEnum = (schema, prefix)=> { } } -function getPropertyGetterSignature(method, module, paramType) { - let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` - return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` +/* +paramList = [{name='', nativeType='', jsonType='', required=boolean}] +*/ + +const getContextParams = (paramList) => paramList.map(param => param.nativeType + (!param.required ? '*' : '') + ' ' + param.name).join(', ') + +function getPropertyGetterSignature(property, module, propType, paramList = []) { + + let contextParams = '' + contextParams = getContextParams(paramList) + return `uint32_t ${capitalize(getModuleName(module))}_Get${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType}* ${property.result.name || property.name})` +} + +function getPropertySetterSignature(property, module, propType, paramList = []) { + let contextParams = '' + contextParams = getContextParams(paramList) + return `uint32_t ${capitalize(getModuleName(module))}_Set${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType} ${property.result.name || property.name})` +} + +function getPropertyEventCallbackSignature(property, module, propType, paramList = []) { + + let contextParams = '' + contextParams = getContextParams(paramList) + return `/*Callback to listen to updates on ${property.Name} property*/\n` + + `typedef void (*On${capitalize(getModuleName(module))}${capitalize(property.name)}Changed)( ${contextParams}${contextParams.length > 0 ? ', ':''}const void* userData, ${propType} ${property.result.name || property.name})` } -function getPropertySetterSignature(method, module, paramType) { - let m = `${capitalize(getModuleName(module))}_Set${capitalize(method.name)}` - return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType} ${method.result.name || method.name} )` +function getPropertyEventInnerCallbackSignature(method, module, schemas) { + let signature = `static void ${capitalize(getModuleName(module)) + capitalize(method.name)}` } -function getPropertyEventCallbackSignature(method, module, paramType) { - return `typedef void (*On${capitalize(method.name)}Changed)(${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType})` +function getPropertyEventRegisterSignature(property, module, paramList = []) { + let contextParams = '' + contextParams = getContextParams(paramList) + + return `/*Register to listen to updates on ${capitalize(property.name)} property*/\n` + + `uint32_t ${capitalize(getModuleName(module))}_Register_${capitalize(property.name)}Update( ${contextParams}${contextParams.length > 0 ? ', ':''}On${capitalize(getModuleName(module))}${capitalize(property.name)}Changed userCB, const void* userData )` + } -function getPropertyEventSignature(method, module) { - return `${description(method.name, 'Listen to updates')}\n` + `uint32_t ${capitalize(getModuleName(module))}_Listen${capitalize(method.name)}Update(On${capitalize(method.name)}Changed notification, uint16_t* listenerId)` +function getPropertyEventUnregisterSignature(property, module) { + return `/*Unregister to listen to updates on ${capitalize(property.name)} property*/\n` + + `uint32_t ${capitalize(getModuleName(module))}_Unregister_${capitalize(property.name)}Update( On${capitalize(getModuleName(module))}${capitalize(property.name)}Changed userCB )` + } + export { getHeaderText, getIncludeGuardOpen, @@ -240,7 +277,8 @@ export { getPropertyGetterSignature, getPropertySetterSignature, getPropertyEventCallbackSignature, - getPropertyEventSignature, + getPropertyEventRegisterSignature, + getPropertyEventUnregisterSignature, getMapAccessors, getArrayAccessors, capitalize, diff --git a/languages/c/templates/codeblocks/setter.c b/languages/c/templates/codeblocks/setter.c new file mode 100644 index 00000000..9f496543 --- /dev/null +++ b/languages/c/templates/codeblocks/setter.c @@ -0,0 +1,9 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.title}_${method.Name}( ${method.signature.params} ) +{ + const string method = _T("${info.title}.${method.name}"); + ${if.params} +${method.params.serialization} + ${end.if.params} + return FireboltSDK::Properties::Set(method, jsonParameters); +} diff --git a/languages/c/templates/declarations/default.c b/languages/c/templates/declarations/default.c index be0b1e14..e69de29b 100644 --- a/languages/c/templates/declarations/default.c +++ b/languages/c/templates/declarations/default.c @@ -1,5 +0,0 @@ -/* - * ${method.summary} - * ${method.params} - */ -${method.signature}; diff --git a/languages/c/templates/declarations/property.c b/languages/c/templates/declarations/property.c new file mode 100644 index 00000000..3550b45e --- /dev/null +++ b/languages/c/templates/declarations/property.c @@ -0,0 +1,5 @@ +/* + * ${method.summary} + * ${method.params} + */ +${method.signature} diff --git a/languages/c/templates/defaults/default.c b/languages/c/templates/defaults/default.c index e29085d1..e69de29b 100644 --- a/languages/c/templates/defaults/default.c +++ b/languages/c/templates/defaults/default.c @@ -1 +0,0 @@ - ${method.name}: ${method.example.value} \ No newline at end of file diff --git a/languages/c/templates/defaults/property.c b/languages/c/templates/defaults/property.c index 95ef20cf..e69de29b 100644 --- a/languages/c/templates/defaults/property.c +++ b/languages/c/templates/defaults/property.c @@ -1 +0,0 @@ - ${method.name}: function () { return MockProps.mock('${info.title}', '${method.name}', arguments, ${method.example.value}) } \ No newline at end of file diff --git a/languages/c/templates/methods/clear.js b/languages/c/templates/methods/clear.c similarity index 100% rename from languages/c/templates/methods/clear.js rename to languages/c/templates/methods/clear.c diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 1c70ba29..0b2843a8 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,12 +1,21 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_Get${method.Name}(${method.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { +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}"); - FireboltSDK::${info.title}::${method.result.type} jsonResult; + JsonObject jsonParameters; + ${if.params} +${method.params.serialization} + ${end.if.params} - uint32_t status = FireboltSDK::Properties::Get(method, jsonResult); + ${method.result.json} jsonResult; + + uint32_t status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { - WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); - *${method.result.name} = static_cast<${info.title}_${method.result.type}Handle>(resultPtr); + if (${method.result.name} != nullptr) { +${method.result.instantiation} + } } return status; } + +${method.setter} \ No newline at end of file diff --git a/languages/c/templates/methods/provide.c b/languages/c/templates/methods/provide.c index 8cb48885..e69de29b 100644 --- a/languages/c/templates/methods/provide.c +++ b/languages/c/templates/methods/provide.c @@ -1,3 +0,0 @@ -function provide(capability, provider) { - return ProvideManager.provide(capability, provider) -} diff --git a/languages/c/templates/methods/setter.c b/languages/c/templates/methods/setter.c new file mode 100644 index 00000000..e69de29b diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index a2c64ec0..50c10667 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -47,13 +47,15 @@ const _inspector = obj => { // getSchemaType(schema, module, options = { destination: 'file.txt', title: true }) // getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) // getJsonType(schema, module, options = { name: 'Foo', prefix: '', descriptions: false, level: 0 }) +// getSchemaInstantiation(schema, module, options = {type: 'params' | 'result' | 'event' | 'callback'}) let types = { getMethodSignature: ()=>null, getMethodSignatureParams: ()=>null, getSchemaShape: ()=>null, getSchemaType: ()=>null, - getJsonType: ()=>null + getJsonType: ()=>null, + getSchemaInstantiation: ()=>null } let config = { @@ -1048,6 +1050,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, {instantiationType: 'params'}) + const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' } ) let seeAlso = '' if (isPolymorphicPullMethod(methodObj) && pullsForType) { @@ -1080,6 +1084,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\.context\}(.*?)\$\{end\.if\.context\}/gms, event.params.length ? '$1' : '') + .replace(/\$\{method\.params\.serialization\}/g, serializedParams) // Typed signature stuff .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination, section: state.section })) @@ -1105,9 +1110,11 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .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, title: true, asPath: false, destination: state.destination })) //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result.schema, json, {name: result.name, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name : result.name })) + .replace(/\$\{method\.result\.instantiation\}/g, resultInst) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) .replace(/\$\{method\.alternative.link\}/g, '#'+(method.alternative || "").toLowerCase()) @@ -1121,6 +1128,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{method\.setter\}/g, setterTemplate) // must be last!! .replace(/\$\{method\.subscriber\}/g, subscriberTemplate) // must be last!! + if (method.deprecated) { template = template.replace(/\$\{if\.deprecated\}(.*?)\$\{end\.if\.deprecated\}/gms, '$1') } diff --git a/src/shared/typescript.mjs b/src/shared/typescript.mjs index 79c3e022..5982137e 100644 --- a/src/shared/typescript.mjs +++ b/src/shared/typescript.mjs @@ -346,10 +346,14 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, return acc } + function getSchemaInstantiation(schema, module, { instantiationType }) { + return '' + } export default { getMethodSignature, getMethodSignatureParams, getSchemaShape, getSchemaType, - getJsonType + getJsonType, + getSchemaInstantiation } \ No newline at end of file From 8e716e58d923960854bd3198d5897e9b0d1ad3eb Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 22 Jun 2023 08:25:31 +0530 Subject: [PATCH 044/137] Add support to keep original file permissions of template/sdk files (#99) --- languages/c/language.config.json | 5 ++- src/macrofier/index.mjs | 22 +++++++++-- src/sdk/index.mjs | 3 +- src/shared/filesystem.mjs | 63 +++++++++++++++++++++----------- 4 files changed, 66 insertions(+), 27 deletions(-) diff --git a/languages/c/language.config.json b/languages/c/language.config.json index 185b0370..97e90519 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -10,5 +10,6 @@ "/include/Common/Module.h", "/src/Module_Common.cpp", "/src/JsonData_Module.h" - ] -} \ No newline at end of file + ], + "persistPermission": true +} diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index f8acada8..b1d61ee4 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -18,7 +18,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { emptyDir, readDir, readFiles, readJson, writeFiles, writeText } from '../shared/filesystem.mjs' +import { emptyDir, readDir, readFiles, readFilesPermissions, readJson, + writeFiles, writeFilesPermissions, writeText } from '../shared/filesystem.mjs' import { getTemplate, getTemplateForModule } from '../shared/template.mjs' import { getModule, hasPublicAPIs } from '../shared/modules.mjs' import { logHeader, logSuccess } from '../shared/io.mjs' @@ -42,6 +43,7 @@ const macrofy = async ( staticContent, templatesPerModule, templatesPerSchema, + persistPermission, createModuleDirectories, copySchemasIntoModules, aggregateFile, @@ -87,6 +89,12 @@ const macrofy = async ( const sharedTemplateList = await readDir(sharedTemplates, { recursive: true }) const templates = Object.assign(await readFiles(sharedTemplateList, sharedTemplates), await readFiles(sdkTemplateList, template)) // sdkTemplates are second so they win ties + let templatesPermission = {} + if (persistPermission) { + templatesPermission = Object.assign(await readFilesPermissions(sharedTemplateList, sharedTemplates), + await readFilesPermissions(sdkTemplateList, template)) + } + const exampleTemplates = {} for (var i=0; i chmodSync(ref, mode) + const readText = ref => readFile(ref) .then(resp => resp.toString()) @@ -39,6 +41,34 @@ const readDir = async (ref, options) => { return results.sort() } +const getIndex = (refs, base) => { + let index = base ? base.length : 0 + if (base && !refs[0].startsWith(base)) { + refs = refs.map(v => path.relative(base, v)) + index = 0 + } + else if (index === 0 && refs.length !== 1) { + // find the common prefix of all the files + while ((new Set(refs.map(r => r[index]))).size === 1) { + index++ + } + // back up one dirctory from the common prefix + index = path.join(path.join(refs[0].substring(0, index)), '..').length + } + return index +} + +const readFilesPermissions = (refs, base) => Promise.all(refs.map(ref => stat(ref))) + .then(permissions => { + if (!refs || refs.length === 0) { + return Promise.resolve({}) + } + const results = refs.map(v => [v.substring(getIndex(refs, base)), null]) + for (let i=0; i Promise.all(refs.map(ref => readFile(ref))) if (!refs || refs.length === 0) { return Promise.resolve({}) } - - let index = base ? base.length : 0 - if (base && !refs[0].startsWith(base)) { - refs = refs.map(v => path.relative(base, v)) - index = 0 - } - else if (index === 0 && refs.length !== 1) { - // find the common prefix of all the files - while ((new Set(refs.map(r => r[index]))).size === 1) { - index++ - } - - // back up one dirctory from the common prefix - index = path.join(path.join(refs[0].substring(0, index)), '..').length - } - - const results = refs.map(v => [v.substring(index), null]) + const results = refs.map(v => [v.substring(getIndex(refs, base)), null]) for (let i=0; i refs[i].endsWith(suffix))) { results[i][1] = contents[i] @@ -83,6 +97,11 @@ const writeFiles = (files) => { .map( ([file, contents]) => writeText(file, contents))) } +const writeFilesPermissions = (files) => { + return Promise.all(Object.entries(files) + .map( ([file, mode]) => setPermission(file, mode))) +} + export { readText, writeText, @@ -91,5 +110,7 @@ export { readDir, readFiles, writeFiles, - emptyDir -} \ No newline at end of file + emptyDir, + readFilesPermissions, + writeFilesPermissions +} From 8d9ac144d6d5bc5e708aadbe47eeaf7e3e42f80c Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 22 Jun 2023 08:25:52 +0530 Subject: [PATCH 045/137] Event template implementation added (#101) --- languages/c/Types.mjs | 92 ++++++------ languages/c/src/types/ImplHelpers.mjs | 132 +++++++++++++++++- languages/c/src/types/NativeHelpers.mjs | 13 +- languages/c/templates/declarations/event.c | 4 + languages/c/templates/methods/default.c | 2 +- languages/c/templates/methods/event.c | 26 ++++ languages/c/templates/methods/property.c | 13 +- languages/c/templates/modules/src/Module.cpp | 1 + .../c/templates/schemas/src/Module_Common.cpp | 1 + src/macrofier/engine.mjs | 59 +++++--- 10 files changed, 260 insertions(+), 83 deletions(-) create mode 100644 languages/c/templates/declarations/event.c create mode 100644 languages/c/templates/methods/event.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 0886d3dc..72912930 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -18,8 +18,8 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' -import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature } from './src/types/NativeHelpers.mjs' -import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation } from './src/types/ImplHelpers.mjs' +import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' +import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation, getCallbackParametersInstantiation, getCallbackResultInstantiation, getCallbackResponseInstantiation } from './src/types/ImplHelpers.mjs' import { getJsonContainerDefinition, getJsonDataStructName } from './src/types/JSONHelpers.mjs' const getSdkNameSpace = () => 'FireboltSDK' @@ -170,44 +170,50 @@ const hasTag = (method, tag) => { return method.tags && method.tags.filter(t => t.name === tag).length > 0 } -function getMethodSignature(method, module, { destination, isInterface = false }) { - - let signature = '' +function getParamList(schema, module) { let paramList = [] - if(hasTag(method, 'property') || hasTag(method, 'property:readonly') || hasTag(method, 'property:immutable')) { - - method.params.map(param => { + if (schema.params.length > 0) { + schema.params.map(p => { /* - paramList = [{name='', nativeType='', jsonType='', required=boolean}] + param = {name='', nativeType='', jsonType='', required=boolean} */ - paramList['nativeType'] = getSchemaType(param.schema, module, { title: true, name: param.name }) - paramList['jsonType'] = getJsonType(param.schema, module, {name: param.name}) - paramList['name'] = param.name - paramList['required'] = param.required - + let param = {} + param['nativeType'] = getSchemaType(p.schema, module, { title: true, name: p.name }) + param['jsonType'] = getJsonType(p.schema, module, {name: p.name}) + param['name'] = p.name + param['required'] = p.required + paramList.push(param) }) + } + return paramList +} + +function getMethodSignature(method, module, { destination, isInterface = false }) { + + let signature = '' + if (hasTag(method, 'property') || hasTag(method, 'property:readonly') || hasTag(method, 'property:immutable')) { + let paramList = getParamList(method, module) let resultType = method.result && getSchemaType(method.result.schema, module, { title: true, name: method.result.name, resultSchema: true}) || '' signature = getPropertyGetterSignature(method, module, resultType, paramList) + ';\n\n' - if(hasTag(method, 'property') || hasTag(method, 'property:readonly')) { - signature += getPropertyEventCallbackSignature(method, module, resultType, paramList) + ';\n\n' - signature += getPropertyEventRegisterSignature(method, module, paramList) + ';\n\n' - signature += getPropertyEventUnregisterSignature(method, module) + ';\n\n' - } - - if(hasTag(method, 'property')) { + if (hasTag(method, 'property')) { signature += getPropertySetterSignature(method, module, resultType, paramList) + ';\n\n' } } return signature } +function getMethodSignatureParams(method, module, { destination, callback= false } = {}) { -function getMethodSignatureParams(method, module, { destination }) { - - return method.params.map(param => getSchemaType(param.schema, module, { name: param.name, title: true, destination }) + (!param.required ? '* ' : ' ') + param.name ).join(', ') + return method.params.map(param => { + let type = getSchemaType(param.schema, module, { name: param.name, title: true, destination }) + if ((callback === true) && (type === 'char*')) { + type = getFireboltStringType() + } + return type + (!param.required ? '* ' : ' ') + param.name + }).join(', ') } const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop @@ -723,34 +729,32 @@ const enumReducer = (acc, val, i, arr) => { function getSchemaInstantiation(schema, module, name, { instantiationType = '' } = {}) { - if(instantiationType === 'params') { - if (schema.params.length > 0) { - let paramList = [] - schema.params.map(param => { - /* - paramList = [{name='', nativeType='', jsonType='', required=boolean}] - */ - const parameter = {} - parameter['nativeType'] = getSchemaType(param.schema, module, { title: true, name: param.name }) - parameter['jsonType'] = getJsonType(param.schema, module, {name: param.name}) - parameter['name'] = param.name - parameter['required'] = param.required - paramList.push(parameter) - - }) - return getParameterInstantiation(paramList) - } - } else if(instantiationType === 'result') { + if (instantiationType === 'params') { + return getParameterInstantiation(getParamList(schema, module)) + } + else if (instantiationType === 'result') { let resultType = getSchemaType(schema, module, { title: true, name: name, resultSchema: true}) || '' let resultJsonType = getJsonType(schema, module, {name: name}) || '' - return getResultInstantiation(name, resultType, resultJsonType) } + else if (instantiationType === 'callback.params') { + let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + return getCallbackParametersInstantiation(getParamList(schema, module), resultJsonType) + } + else if (instantiationType === 'callback.result') { + let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + return getCallbackResultInstantiation(resultType, resultJsonType) + } + else if (instantiationType === 'callback.response') { + let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + return getCallbackResponseInstantiation(getParamList(schema, module), resultType, resultJsonType) + } return '' } - export default { getMethodSignature, getMethodSignatureParams, diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index a39af0b6..6509375a 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -1,10 +1,9 @@ -import { capitalize } from "./NativeHelpers.mjs" +import { capitalize, getFireboltStringType } from "./NativeHelpers.mjs" const Indent = '\t' const getSdkNameSpace = () => 'FireboltSDK' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' -const getFireboltStringType = () => 'FireboltTypes_StringHandle' const getObjectHandleManagementImpl = (varName, jsonDataName) => { @@ -320,12 +319,138 @@ function getParameterInstantiation(paramList, container = '') { impl += ` jsonParameters.Set(_T("${param.name}"), ${capitalize(param.name)});\n` impl += ` }` } + impl += '\n' } }) return impl } +const isNativeType = (type) => (type === 'float' || type === 'char*' || type === 'int32_t' || type === 'bool') + +function getCallbackParametersInstantiation(paramList, container = '') { + + let impl = '' + + if (paramList.length > 0) { + paramList.forEach(param => { + if (param.required !== undefined) { + if (param.nativeType !== 'char*') { + impl += ` ${param.nativeType} ${param.name};\n` + if (param.required === false) { + impl += ` ${param.nativeType}* ${param.name}Ptr = nullptr;\n` + } + } + else { + impl += ` ${getFireboltStringType()} ${param.name};\n` + } + } + }) + impl += `\n WPEFramework::Core::ProxyType<${container}>* jsonResponse;\n` + impl += ` WPEFramework::Core::ProxyType& var = *(static_cast*>(response)); + + ASSERT(var.IsValid() == true); + if (var.IsValid() == true) { + WPEFramework::Core::JSON::VariantContainer::Iterator elements = var->Variants(); + + while (elements.Next()) { + if (strcmp(elements.Label(), "value") == 0) { + + jsonResponse = new WPEFramework::Core::ProxyType<${container}>(); + string objectStr; + elements.Current().Object().ToString(objectStr); + (*jsonResponse)->FromString(objectStr); + } else if (strcmp(elements.Label(), "context") == 0) { + + WPEFramework::Core::JSON::VariantContainer::Iterator params = elements.Current().Object().Variants(); + while (params.Next()) {\n` + let contextParams = '' + + paramList.forEach(param => { + if (param.required !== undefined) { + if (isNativeType(param.nativeType) === true) { + if (contextParams.length > 0) { + contextParams += ` else if (strcmp(elements.Label(), "${param.name}") == 0) {\n` + } + else { + contextParams += ` if (strcmp(elements.Label(), "${param.name}") == 0) {\n` + } + if (param.nativeType === 'char*') { + contextParams += ` ${getSdkNameSpace()}::JSON::String* ${param.name}Value = new ${getSdkNameSpace()}::JSON::String(); + *${param.name}Value = elements.Current().Value().c_str(); + ${param.name} = ${param.name}Value;\n` + } + else if (param.nativeType === 'bool') { + contextParams += ` ${param.name} = elements.Current().Boolean();\n` + } + else if ((param.nativeType === 'float') || (param.nativeType === 'int32_t')) { + contextParams += ` ${param.name} = elements.Current().Number();\n` + } + if ((param.nativeType !== 'char*') && (param.required === false)) { + contextParams += ` ${param.name}Ptr = &${param.name};\n` + } + contextParams += ` }\n` + } + } + }) + impl += contextParams + impl += ` } + } else { + ASSERT(false); + } + } + }\n` + } else { + + impl +=` WPEFramework::Core::ProxyType<${container}>* jsonResponse = static_cast*>(response);\n` + } + + return impl +} + +function getCallbackResultInstantiation(nativeType, container = '') { + let impl = '' + if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + impl +=` + ${container}* jsonStrResponse = new ${container}(); + *jsonStrResponse = *(*jsonResponse); + jsonResponse->Release();` + '\n' + } + return impl +} + +function getCallbackResponseInstantiation(paramList, nativeType, container = '') { + let impl = '' + + if (paramList.length > 0) { + paramList.forEach(param => { + if (param.required !== undefined) { + if (param.nativeType === 'char*') { + impl += `static_cast<${getFireboltStringType()}>(${param.name}), ` + } + else if (param.required === true) { + impl += `${param.name}, ` + } + else if (param.required === false) { + impl += `${param.name}Ptr, ` + } + } + }) + } + + if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + impl += `static_cast<${nativeType}>(jsonStrResponse)` + } + else if (nativeType.includes('Handle')) { + impl += `static_cast<${nativeType}>(jsonResponse)` + } + else { + impl += `static_cast<${nativeType}>((*jsonResponse)->Value())` + } + + return impl +} + function getResultInstantiation (name, nativeType, container, indentLevel = 3) { let impl = '' @@ -353,5 +478,8 @@ export { getObjectHandleManagementImpl, getPropertyAccessorsImpl, getParameterInstantiation, + getCallbackParametersInstantiation, + getCallbackResultInstantiation, + getCallbackResponseInstantiation, getResultInstantiation } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 65a78443..022437e8 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -120,7 +120,7 @@ const getNativeType = (json, stringAsHandle = false) => { let jsonType = json.const ? typeof json.const : json.type if (jsonType === 'string') { type = 'char*' - if(stringAsHandle) { + if (stringAsHandle) { type = getFireboltStringType() } } @@ -140,7 +140,6 @@ const getNativeType = (json, stringAsHandle = false) => { return type } - const getObjectHandleManagement = varName => { let result = `typedef void* ${varName}Handle; @@ -229,13 +228,16 @@ function getPropertyGetterSignature(property, module, propType, paramList = []) let contextParams = '' contextParams = getContextParams(paramList) - return `uint32_t ${capitalize(getModuleName(module))}_Get${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType}* ${property.result.name || property.name})` + return `uint32_t ${capitalize(getModuleName(module))}_Get${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType}* ${property.result.name || property.name} )` } function getPropertySetterSignature(property, module, propType, paramList = []) { let contextParams = '' contextParams = getContextParams(paramList) - return `uint32_t ${capitalize(getModuleName(module))}_Set${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType} ${property.result.name || property.name})` + if (propType === getFireboltStringType()) { + propType = 'char*' + } + return `uint32_t ${capitalize(getModuleName(module))}_Set${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType} ${property.result.name || property.name} )` } function getPropertyEventCallbackSignature(property, module, propType, paramList = []) { @@ -288,5 +290,6 @@ export { getPropertyAccessors, isOptional, generateEnum, - getArrayElementSchema + getArrayElementSchema, + getFireboltStringType } diff --git a/languages/c/templates/declarations/event.c b/languages/c/templates/declarations/event.c new file mode 100644 index 00000000..45e4b608 --- /dev/null +++ b/languages/c/templates/declarations/event.c @@ -0,0 +1,4 @@ +/* ${method.name} - ${method.description} */ +typedef void (*${info.Title}${method.Name}Callback)( const void* userData, ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${event.result.type} ); +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 ); +uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 49f76ce1..6a023534 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -21,4 +21,4 @@ uint32_t ${info.title}_${method.Name}(${method.params.list}${if.params}, ${end.i } return status; -} \ No newline at end of file +} diff --git a/languages/c/templates/methods/event.c b/languages/c/templates/methods/event.c new file mode 100644 index 00000000..ec868cd5 --- /dev/null +++ b/languages/c/templates/methods/event.c @@ -0,0 +1,26 @@ +/* ${method.name} - ${method.description} */ +static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) +{ +${event.callback.params.serialization} + ASSERT(jsonResponse->IsValid() == true); + if (jsonResponse->IsValid() == true) { +${event.callback.result.instantiation} + ${info.Title}${method.Name}Callback callback = reinterpret_cast<${info.Title}${method.Name}Callback>(userCB); + callback(userData, ${event.callback.response.instantiation}); + } +} +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}"); + uint32_t status = FireboltSDKErrorNone; + + if (userCB != nullptr) { + ${event.params.serialization} + status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${info.Title}${method.Name}InnerCallback, reinterpret_cast(userCB), userData); + } + return status; +} +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(userCB)); +} diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 0b2843a8..c7510da9 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -2,14 +2,10 @@ 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}"); - JsonObject jsonParameters; - ${if.params} -${method.params.serialization} - ${end.if.params} - +${if.params}${method.params.serialization}${end.if.params} ${method.result.json} jsonResult; - - uint32_t status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult); + ${if.params}uint32_t status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult);${end.if.params} + ${if.params.empty}uint32_t status = FireboltSDK::Properties::Get(method, jsonResult);${end.if.params.empty} if (status == FireboltSDKErrorNone) { if (${method.result.name} != nullptr) { ${method.result.instantiation} @@ -17,5 +13,4 @@ uint32_t ${info.title}_Get${method.Name}( ${method.signature.params}${if.params} } return status; } - -${method.setter} \ No newline at end of file +${method.setter} diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index d34c1da5..65721f1e 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -35,6 +35,7 @@ extern "C" { /* ${ACCESSORS} */ /* ${METHODS} */ +/* ${EVENTS} */ #ifdef __cplusplus } diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/Module_Common.cpp index e2389d50..0ccdfc28 100644 --- a/languages/c/templates/schemas/src/Module_Common.cpp +++ b/languages/c/templates/schemas/src/Module_Common.cpp @@ -28,6 +28,7 @@ extern "C" { /* ${ACCESSORS} */ /* ${METHODS} */ + /* ${EVENTS} */ #ifdef __cplusplus } diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 50c10667..85cb67e2 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -47,7 +47,7 @@ const _inspector = obj => { // getSchemaType(schema, module, options = { destination: 'file.txt', title: true }) // getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) // getJsonType(schema, module, options = { name: 'Foo', prefix: '', descriptions: false, level: 0 }) -// getSchemaInstantiation(schema, module, options = {type: 'params' | 'result' | 'event' | 'callback'}) +// getSchemaInstantiation(schema, module, options = {type: 'params' | 'result' | 'callback.params'| 'callback.result' | 'callback.response'}) let types = { getMethodSignature: ()=>null, @@ -70,6 +70,19 @@ const state = { const capitalize = str => str[0].toUpperCase() + str.substr(1) const hasMethodsSchema = (json, options) => json.methods && json.methods.length +const indent = (str, padding) => { + let first = true + return str.split('\n').map(line => { + if (first) { + first = false + return line + } + else { + return padding + line + } + }).join('\n') +} + const setTyper = (t) => { types = t } @@ -1022,9 +1035,9 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const capabilities = getTemplate('/sections/capabilities', templates) + insertCapabilityMacros(getTemplate('/capabilities/default', templates), methodObj.tags.find(t => t.name === "capabilities"), methodObj, json) const result = JSON.parse(JSON.stringify(methodObj.result)) - const event = JSON.parse(JSON.stringify(methodObj)) + const event = isEventMethod(methodObj) ? JSON.parse(JSON.stringify(methodObj)) : '' - if (isEventMethod(methodObj)) { + if (event) { result.schema = JSON.parse(JSON.stringify(getPayloadFromEvent(methodObj))) event.result.schema = getPayloadFromEvent(event) event.params = event.params.filter(p => p.name !== 'listen') @@ -1052,6 +1065,12 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, {instantiationType: 'params'}) const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' } ) + const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'params'}), ' ') : '' + const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.params'}) : '' + const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.result'}) : '' + const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.response'}) : '' + const resultType = result.schema ? types.getSchemaType(result.schema, json, { name: result.name }) : '' + const resultJsonType = result.schema ? types.getJsonType(result.schema, json, { name: result.name }) : '' let seeAlso = '' if (isPolymorphicPullMethod(methodObj) && pullsForType) { @@ -1083,8 +1102,9 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{method\.params\.array\}/g, JSON.stringify(methodObj.params.map(p => p.name))) .replace(/\$\{method\.params\.count}/g, methodObj.params ? methodObj.params.length : 0) .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/gms, method.params.length ? '$1' : '') - .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event.params.length ? '$1' : '') - .replace(/\$\{method\.params\.serialization\}/g, serializedParams) + .replace(/\$\{if\.params.empty\}(.*?)\$\{end\.if\.params.empty\}/gms, method.params.length === 0 ? '$1' : '') + .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event && event.params.length ? '$1' : '') + .replace(/\$\{method\.params\.serialization\}/g, serializedParams) // Typed signature stuff .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination, section: state.section })) @@ -1095,8 +1115,15 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{event\.name\}/g, method.name.toLowerCase()[2] + method.name.substr(3)) .replace(/\$\{event\.params\}/g, eventParams) .replace(/\$\{event\.params\.table\.rows\}/g, eventParamsRows) - .replace(/\$\{event\.signature\.params\}/g, types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section })) + .replace(/\$\{if\.event\.params\}(.*?)\$\{end\.if\.event\.params\}/gms, event && event.params.length ? '$1' : '') + .replace(/\$\{event\.signature\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section }) : '') + .replace(/\$\{event\.signature\.callback\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section, callback: true }) : '') + .replace(/\$\{event\.params\.serialization\}/g, serializedEventParams) + .replace(/\$\{event\.callback\.params\.serialization\}/g, callbackSerializedParams) + .replace(/\$\{event\.callback\.result\.instantiation\}/g, callbackResultInst) + .replace(/\$\{event\.callback\.response\.instantiation\}/g, callbackResponseInst) .replace(/\$\{info\.title\}/g, info.title) + .replace(/\$\{info\.Title\}/g, capitalize(info.title)) .replace(/\$\{info\.TITLE\}/g, info.title.toUpperCase()) .replace(/\$\{method\.property\.immutable\}/g, hasTag(methodObj, 'property:immutable')) .replace(/\$\{method\.property\.readonly\}/g, !getSetterFor(methodObj.name, json)) @@ -1112,9 +1139,10 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .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, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, baseUrl: options.baseUrl .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') + .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name : result.name })) - .replace(/\$\{method\.result\.instantiation\}/g, resultInst) + .replace(/\$\{method\.result\.instantiation\}/g, resultInst) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) .replace(/\$\{method\.alternative.link\}/g, '#'+(method.alternative || "").toLowerCase()) @@ -1408,19 +1436,6 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te while (match = template.match(regex)) { let methodsBlock = '' - const indent = (str, padding) => { - let first = true - return str.split('\n').map(line => { - if (first) { - first = false - return line - } - else { - return padding + line - } - }).join('\n') - } - let i = 1 iface.forEach(method => { @@ -1489,7 +1504,7 @@ export { generateMacros, insertMacros, generateAggregateMacros, - insertAggregateMacros, + insertAggregateMacros } export default { From db4c7fecd9d7227c628d04044a64868651267b5f Mon Sep 17 00:00:00 2001 From: sramani-metro <71630728+sramani-metro@users.noreply.github.com> Date: Thu, 22 Jun 2023 12:19:00 +0530 Subject: [PATCH 046/137] Template for Polymorphic pull method (#102) * feat: Add method templates for properties * feat: Property setters using templates * fix: Macro name correction * feat: Add template for polymorphic-pull --- .../methods/polymorphic-pull-event.c | 0 .../c/templates/methods/polymorphic-pull.c | 21 +++++++++++++++++++ .../c/templates/methods/polymorphic-reducer.c | 11 ---------- 3 files changed, 21 insertions(+), 11 deletions(-) create mode 100644 languages/c/templates/methods/polymorphic-pull-event.c create mode 100644 languages/c/templates/methods/polymorphic-pull.c diff --git a/languages/c/templates/methods/polymorphic-pull-event.c b/languages/c/templates/methods/polymorphic-pull-event.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/methods/polymorphic-pull.c b/languages/c/templates/methods/polymorphic-pull.c new file mode 100644 index 00000000..553b2946 --- /dev/null +++ b/languages/c/templates/methods/polymorphic-pull.c @@ -0,0 +1,21 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.title}_Push${method.Name}(${method.signature.params}) +{ + uint32_t status = FireboltSDKErrorUnavailable; + ${if.params} +${method.params.serialization} + ${end.if.params} + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + WPEFramework::Core::JSON::Boolean jsonResult; + status = transport->Invoke(_T("${info.title}.${method.name}"), jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; + } + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; +} diff --git a/languages/c/templates/methods/polymorphic-reducer.c b/languages/c/templates/methods/polymorphic-reducer.c index db07747f..e69de29b 100644 --- a/languages/c/templates/methods/polymorphic-reducer.c +++ b/languages/c/templates/methods/polymorphic-reducer.c @@ -1,11 +0,0 @@ - -function ${method.name}(${method.params.list}) { - const transforms = ${method.transforms} - - if (arguments.length === 1 && Array.isArray(arguments[0])) { - return Transport.send('${info.title}', '${method.name}', arguments[0], transforms) - } - else { - return Transport.send('${info.title}', '${method.name}', { ${method.params.list} }, transforms) - } -} \ No newline at end of file From 014e4fbb3c1c0d74b633e26715b7d3e7eb066a6f Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 5 Jul 2023 14:54:52 -0400 Subject: [PATCH 047/137] fix: Promote and name sub-schemas in one place --- src/macrofier/engine.mjs | 549 ++++++++++++++++++++------------------- src/macrofier/index.mjs | 6 +- 2 files changed, 281 insertions(+), 274 deletions(-) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 85cb67e2..b167f4d4 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -50,16 +50,17 @@ const _inspector = obj => { // getSchemaInstantiation(schema, module, options = {type: 'params' | 'result' | 'callback.params'| 'callback.result' | 'callback.response'}) let types = { - getMethodSignature: ()=>null, - getMethodSignatureParams: ()=>null, - getSchemaShape: ()=>null, - getSchemaType: ()=>null, - getJsonType: ()=>null, - getSchemaInstantiation: ()=>null + getMethodSignature: () => null, + getMethodSignatureParams: () => null, + getSchemaShape: () => null, + getSchemaType: () => null, + getJsonType: () => null, + getSchemaInstantiation: () => null } let config = { - copySchemasIntoModules: false + copySchemasIntoModules: false, + extractSubSchemas: false } const state = { @@ -68,7 +69,6 @@ const state = { } const capitalize = str => str[0].toUpperCase() + str.substr(1) -const hasMethodsSchema = (json, options) => json.methods && json.methods.length const indent = (str, padding) => { let first = true @@ -129,21 +129,21 @@ const getLinkForSchema = (schema, json, { name = '' } = {}) => { return `#\$\{LINK:schema:${type}\}` } else { - const [group, schema] = Object.entries(json['x-schemas']).find( ([key, value]) => json['x-schemas'][key] && json['x-schemas'][key][type]) || [null, null] - if (group && schema) { - if (copySchemasIntoModules) { - return `#\$\{LINK:schema:${type}\}` + const [group, schema] = Object.entries(json['x-schemas']).find(([key, value]) => json['x-schemas'][key] && json['x-schemas'][key][type]) || [null, null] + if (group && schema) { + if (copySchemasIntoModules) { + return `#\$\{LINK:schema:${type}\}` + } + else { + const base = dirs ? '..' : '.' + if (dirs) { + return `${base}/${group}/schemas/#${type}` } else { - const base = dirs ? '..' : '.' - if (dirs) { - return `${base}/${group}/schemas/#${type}` - } - else { - return `${base}/schemas/${group}.md#${type}` - } + return `${base}/schemas/${group}.md#${type}` } } + } } return '#' @@ -348,14 +348,74 @@ const generateAggregateMacros = (openrpc, modules, templates, library) => Object library: library }) +const addContentDescriptorSubSchema = (descriptor, prefix, obj) => { + const title = prefix.charAt(0).toUpperCase() + prefix.substring(1) + descriptor.name.charAt(0).toUpperCase() + descriptor.name.substring(1) + if (obj.components.schemas[title]) { + throw 'Generated name `' + title + '` already exists...' + } + obj.components.schemas[title] = descriptor.schema + obj.components.schemas[title].title = title + descriptor.schema = { + $ref: "#/components/schemas/" + title + } +} + +// only consider sub-objects and sub enums to be sub-schemas +const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) + +const promoteAndNameSubSchemas = (obj) => { + // make a copy so we don't polute our inputs + obj = JSON.parse(JSON.stringify(obj)) + // find anonymous method param or result schemas and name/promote them + obj.methods && obj.methods.forEach(method => { + method.params && method.params.forEach(param => { + if (isSubSchema(param.schema)) { + addContentDescriptorSubSchema(param, method.name, obj) + } + }) + if (isSubSchema(method.result.schema)) { + addContentDescriptorSubSchema(method.result, method.name, obj) + } + }) + + // find non-primative sub-schemas of components.schemas and name/promote them + if (obj.components && obj.components.schemas) { + let more = true + while (more) { + more = false + Object.entries(obj.components.schemas).forEach(([key, schema]) => { + if (schema.type === "object" && schema.properties) { + Object.entries(schema.properties).forEach(([name, propSchema]) => { + if (isSubSchema(propSchema)) { + more = true + const descriptor = { + name: name, + schema: propSchema + } + addContentDescriptorSubSchema(descriptor, key, obj) + schema.properties[name] = descriptor.schema + } + }) + } + }) + } + } + + return obj +} + const generateMacros = (obj, templates, languages, options = {}) => { + // for languages that don't support nested schemas, let's promote them to first-class schemas w/ titles + if (config.extractSubSchemas) { + obj = promoteAndNameSubSchemas(obj) + } // grab the options so we don't have to pass them from method to method Object.assign(state, options) - const imports = generateImports(obj, templates, { destination : (options.destination ? options.destination : '') }) + const imports = generateImports(obj, templates, { destination: (options.destination ? options.destination : '') }) const initialization = generateInitialization(obj, templates) - const enums = generateEnums(obj, templates, { destination : (options.destination ? options.destination : '') }) + const enums = generateEnums(obj, templates, { destination: (options.destination ? options.destination : '') }) const eventsEnum = generateEvents(obj, templates) const examples = generateExamples(obj, templates, languages) @@ -367,10 +427,6 @@ const generateMacros = (obj, templates, languages, options = {}) => { const declarations = declarationsArray.length ? getTemplate('/sections/declarations', templates).replace(/\$\{declaration\.list\}/g, declarationsArray.map(m => m.declaration).join('\n')) : '' 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 methodTypesArray = generateSchemas(obj, templates, { baseUrl: '', section: 'methods_schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) - const methodTypes = methodTypesArray.length ? getTemplate('/sections/methods_types', templates).replace(/\$\{schema.list\}/g, methodTypesArray.map(s => s.body).filter(body => body).join('\n')) : '' - const methodAccessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'methods_accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) - const methodAccessors = methodAccessorsArray.length ? getTemplate('/sections/methods_accessors', templates).replace(/\$\{schema.list\}/g, methodAccessorsArray.map(s => s.body).filter(body => body).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')) : '' @@ -380,9 +436,9 @@ const generateMacros = (obj, templates, languages, options = {}) => { const accessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).filter(body => body).join('\n')) : '' const typesArray = schemasArray.length ? schemasArray.filter(x => !x.enum) : [] - const types = (typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodTypes + const types = (typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).filter(body => body).join('\n')) : '') - const accessors = (accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodAccessors + const accessors = (accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).filter(body => body).join('\n')) : '') const module = getTemplate('/codeblocks/module', templates) const macros = { @@ -425,7 +481,7 @@ const insertMacros = (fContents = '', macros = {}) => { if (macros.append) { fContents += '\n' + macros.module } - + const quote = config.operators ? config.operators.stringQuotation : '"' const or = config.operators ? config.operators.or : ' | ' @@ -453,7 +509,7 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{info\.TITLE\}/g, macros.title.toUpperCase()) fContents = fContents.replace(/\$\{info\.description\}/g, macros.description) fContents = fContents.replace(/\$\{info\.version\}/g, macros.version.readable) - + if (macros.public) { fContents = fContents.replace(/\$\{if\.public\}(.*?)\$\{end\.if\.public\}/gms, '$1') } @@ -498,7 +554,7 @@ function insertTableofContents(content) { count[slug] = 0 } const link = '#' + slug + (count[slug] ? `-${count[slug]}` : '') - toc += ' ' + ' '.repeat(level-1) + `- [${title}](${link})\n` + toc += ' ' + ' '.repeat(level - 1) + `- [${title}](${link})\n` } } }).join('\n') @@ -511,7 +567,7 @@ function insertTableofContents(content) { const index = candidates.findIndex(line => line.indexOf(`- [${match[2]}](`) >= 0) let extra = '' - + // add '-1' to schemas when there's more than once match if (index > 0 && match[1] === 'schema') { extra = '-1' @@ -525,51 +581,14 @@ function insertTableofContents(content) { return content } -const isEnumType = x => x.type !== 'undefined' && x.type === 'string' && Array.isArray(x.enum) - -const getProperties = x => { - return Array.isArray(x.properties) ? x.properties[0] : x.properties -} - -const isEnumProperties = schema => compose( - getProperties, - filter(enm => enm), - map(filter(enm => enm)), - map(props => props.map(([k, v]) => ((v.type === 'object') ? isEnumProperties(v) : ((v.type === 'array') ? isEnumType(v.items[0] ? v.items[0] : v.items): isEnumType(v))))), - map(Object.entries), - filter(schema => isObject(schema)) -)(schema) - -const getEnumProperties = schema => compose( - getProperties, - filter(enm => enm), - map(filter(isEnumType)), - map(props => props.map(([k, v]) => { - let enm = v - if (isEnumType(v) == true) { - enm = Object.assign({}, v) - enm.title = k - } else if (v.type === 'object') { - enm = getEnumProperties(v) - } else if (v.type === 'array') { - enm = Object.assign({}, (v.items[0] ? v.items[0] : v.items)) - enm.title = k - } - return enm - })), - map(Object.entries), - filter(schema => isObject(schema)) -)(schema) - -const convertEnumTemplate = (sch, templateName, templates) => { +const convertEnumTemplate = (schema, templateName, templates) => { const template = getTemplate(templateName, templates).split('\n') - let schema = isEnumType(sch) ? sch : getEnumProperties(sch) for (var i = 0; i < template.length; i++) { if (template[i].indexOf('${key}') >= 0) { template[i] = schema.enum.map(value => { const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() return template[i].replace(/\$\{key\}/g, safeName) - .replace(/\$\{value\}/g, value) + .replace(/\$\{value\}/g, value) }).join('\n') if (!templateName.includes(".cpp")) { template[i] = template[i].replace(/,*$/, ''); @@ -577,14 +596,14 @@ const convertEnumTemplate = (sch, templateName, templates) => { } } return template.join('\n') - .replace(/\$\{title\}/g, capitalize(schema.title)) - .replace(/\$\{description\}/g, schema.description ? ('- ' + schema.description) : '') - .replace(/\$\{name\}/g, schema.title) - .replace(/\$\{NAME\}/g, schema.title.toUpperCase()) + .replace(/\$\{title\}/g, capitalize(schema.title)) + .replace(/\$\{description\}/g, schema.description ? ('- ' + schema.description) : '') + .replace(/\$\{name\}/g, schema.title) + .replace(/\$\{NAME\}/g, schema.title.toUpperCase()) } const enumFinder = compose( - filter(x => ((isEnumType(x) && x.title) || isEnumProperties(x))), + filter(x => isEnum(x)), map(([_, val]) => val), filter(([_key, val]) => isObject(val)) ) @@ -659,24 +678,24 @@ const isEnum = x => x.type && x.type === 'string' && Array.isArray(x.enum) && x. function generateSchemas(json, templates, options) { let results = [] - const schemas = (options.section.includes('methods') ? (hasMethodsSchema(json) ? json.methods : '') : (json.definitions || (json.components && json.components.schemas) || {})) + const schemas = JSON.parse(JSON.stringify(json.definitions || (json.components && json.components.schemas) || {})) const generate = (name, schema, uri, { prefix = '' } = {}) => { // these are internal schemas used by the firebolt-openrpc tooling, and not meant to be used in code/doc generation if (['ListenResponse', 'ProviderRequest', 'ProviderResponse', 'FederatedResponse', 'FederatedRequest'].includes(name)) { return - } + } let content = getTemplate('/schemas/default', templates) if (!schema.examples || schema.examples.length === 0) { - content = content.replace(/\$\{if\.examples\}.*?\{end\.if\.examples\}/gms, '') + content = content.replace(/\$\{if\.examples\}.*?\{end\.if\.examples\}/gms, '') } else { content = content.replace(/\$\{if\.examples\}(.*?)\{end\.if\.examples\}/gms, '$1') } if (!schema.description) { - content = content.replace(/\$\{if\.description\}.*?\{end\.if\.description\}/gms, '') + content = content.replace(/\$\{if\.description\}.*?\{end\.if\.description\}/gms, '') } else { content = content.replace(/\$\{if\.description\}(.*?)\{end\.if\.description\}/gms, '$1') @@ -684,20 +703,20 @@ function generateSchemas(json, templates, options) { const schemaShape = types.getSchemaShape(schema, json, { name, prefix, destination: state.destination, section: options.section }) content = content - .replace(/\$\{schema.title\}/, (schema.title || name)) - .replace(/\$\{schema.description\}/, schema.description || '') - .replace(/\$\{schema.shape\}/, schemaShape) + .replace(/\$\{schema.title\}/, (schema.title || name)) + .replace(/\$\{schema.description\}/, schema.description || '') + .replace(/\$\{schema.shape\}/, schemaShape) if (schema.examples) { - content = content.replace(/\$\{schema.example\}/, schema.examples.map(ex => JSON.stringify(ex, null, ' ')).join('\n\n')) + content = content.replace(/\$\{schema.example\}/, schema.examples.map(ex => JSON.stringify(ex, null, ' ')).join('\n\n')) } let seeAlso = getRelatedSchemaLinks(schema, json, templates, options) if (seeAlso) { - content = content.replace(/\$\{schema.seeAlso\}/, '\n\n' + seeAlso) + content = content.replace(/\$\{schema.seeAlso\}/, '\n\n' + seeAlso) } else { - content = content.replace(/.*\$\{schema.seeAlso\}/, '') + content = content.replace(/.*\$\{schema.seeAlso\}/, '') } content = content.trim().length ? content.trimEnd() : content.trim() @@ -720,30 +739,18 @@ function generateSchemas(json, templates, options) { const list = [] // schemas may be 1 or 2 levels deeps - Object.entries(schemas).forEach( ([name, schema]) => { + Object.entries(schemas).forEach(([name, schema]) => { if (isSchema(schema)) { list.push([name, schema]) } - else if (schema.tags) { - if (!isDeprecatedMethod(schema)) { - schema.params.forEach(param => { - if (param.schema && (param.schema.type === 'object')) { - list.push([param.name, param.schema, '', { prefix : schema.name }]) - } - }) - if (schema.result.schema && (schema.result.schema.type === 'object')) { - list.push([schema.result.name, schema.result.schema, '', { prefix : schema.name }]) - } - } - } }) list.sort((a, b) => { const aInB = isDefinitionReferencedBySchema('#/components/schemas/' + a[0], b[1]) const bInA = isDefinitionReferencedBySchema('#/components/schemas/' + b[0], a[1]) - if(isEnum(a[1]) || (aInB && !bInA)) { + if (isEnum(a[1]) || (aInB && !bInA)) { return -1 - } else if(isEnum(b[1]) || (!aInB && bInA)) { + } else if (isEnum(b[1]) || (!aInB && bInA)) { return 1 } return 0; @@ -762,14 +769,14 @@ function getRelatedSchemaLinks(schema = {}, json = {}, templates = {}, options = // - convert them to the $ref value (which are paths to other schema files), instead of the path to the ref node itself // - convert those into markdown links of the form [Schema](Schema#/link/to/element) let links = getLinkedSchemaPaths(schema) - .map(path => getPathOr(null, path, schema)) - .filter(path => seen.hasOwnProperty(path) ? false : (seen[path] = true)) - .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, 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') + .map(path => getPathOr(null, path, schema)) + .filter(path => seen.hasOwnProperty(path) ? false : (seen[path] = true)) + .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, 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') return links } @@ -882,13 +889,13 @@ function generateExamples(json = {}, mainTemplates = {}, languages = {}) { examples[method.name] = method.examples.map(example => ({ json: example, value: example.result.value, - languages: Object.fromEntries(Object.entries(languages).map( ([lang, templates]) => ([lang, { + languages: Object.fromEntries(Object.entries(languages).map(([lang, templates]) => ([lang, { langcode: templates['__config'].langcode, code: getTemplateForExample(method, templates) - .replace(/\$\{rpc\.example\.params\}/g, JSON.stringify(Object.fromEntries(example.params.map(param => [param.name, param.value])))), + .replace(/\$\{rpc\.example\.params\}/g, JSON.stringify(Object.fromEntries(example.params.map(param => [param.name, param.value])))), result: getTemplateForExampleResult(method, templates) - .replace(/\$\{example\.result\}/g, JSON.stringify(example.result.value, null, '\t')) - .replace(/\$\{example\.result\.item\}/g, Array.isArray(example.result.value) ? JSON.stringify(example.result.value[0], null, '\t') : ''), + .replace(/\$\{example\.result\}/g, JSON.stringify(example.result.value, null, '\t')) + .replace(/\$\{example\.result\.item\}/g, Array.isArray(example.result.value) ? JSON.stringify(example.result.value[0], null, '\t') : ''), template: lang === 'JSON-RPC' ? getTemplate('/examples/jsonrpc', mainTemplates) : getTemplateForExample(method, mainTemplates) // getTemplate('/examples/default', mainTemplates) }]))) })) @@ -898,7 +905,7 @@ function generateExamples(json = {}, mainTemplates = {}, languages = {}) { examples[method.name] = examples[method.name].map(example => ({ json: example.json, value: example.value, - languages: Object.fromEntries(Object.entries(example.languages).filter( ([k, v]) => k === 'JSON-RPC')) + languages: Object.fromEntries(Object.entries(example.languages).filter(([k, v]) => k === 'JSON-RPC')) })) } @@ -909,7 +916,7 @@ function generateExamples(json = {}, mainTemplates = {}, languages = {}) { example.languages['JSON-RPC'].code = JSON.stringify(JSON.parse(example.languages['JSON-RPC'].code), null, '\t') example.languages['JSON-RPC'].result = JSON.stringify(JSON.parse(example.languages['JSON-RPC'].result), null, '\t') } - catch (error) {} + catch (error) { } } }) }) @@ -974,12 +981,12 @@ function generateMethods(json = {}, examples = {}, templates = {}) { body: getTemplate('/methods/once', templates), declaration: getTemplate('/declarations/once', templates) }) - + results.push({ name: "clear", body: getTemplate('/methods/clear', templates), declaration: getTemplate('/declarations/clear', templates) - }) + }) } results.sort((a, b) => a.name.localeCompare(b.name)) @@ -988,7 +995,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, examples = {}) { const moduleName = getModuleName(json) const info = { @@ -1036,12 +1043,12 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const result = JSON.parse(JSON.stringify(methodObj.result)) const event = isEventMethod(methodObj) ? JSON.parse(JSON.stringify(methodObj)) : '' - + if (event) { result.schema = JSON.parse(JSON.stringify(getPayloadFromEvent(methodObj))) event.result.schema = getPayloadFromEvent(event) event.params = event.params.filter(p => p.name !== 'listen') - } + } const eventParams = event.params && event.params.length ? getTemplate('/sections/parameters', templates) + event.params.map(p => insertParameterMacros(getTemplate('/parameters/default', templates), p, event, json)).join('') : '' const eventParamsRows = event.params && event.params.length ? event.params.map(p => insertParameterMacros(getTemplate('/parameters/default', templates), p, event, json)).join('') : '' @@ -1059,16 +1066,16 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const subscriberTemplate = (subscriber ? insertMethodMacros(getTemplate('/codeblocks/subscriber', templates), subscriber, json, templates, 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 + const pullsParams = (puller || pullsFor) ? localizeDependencies(getPayloadFromEvent(puller || methodObj), json, null, { mergeAllOfs: true }).properties.parameters : null const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) - const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) - const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' - const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, {instantiationType: 'params'}) - const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' } ) - const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'params'}), ' ') : '' - const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.params'}) : '' - const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.result'}) : '' - const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.response'}) : '' + const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) + const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, { instantiationType: 'params' }) + const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' }) + const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'params' }), ' ') : '' + const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.params' }) : '' + const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.result' }) : '' + const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.response' }) : '' const resultType = result.schema ? types.getSchemaType(result.schema, json, { name: result.name }) : '' const resultJsonType = result.schema ? types.getJsonType(result.schema, json, { name: result.name }) : '' @@ -1082,9 +1089,9 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { } if (isTemporalSetMethod(methodObj)) { - itemName = result.schema.items.title || 'item' - itemName = itemName.charAt(0).toLowerCase() + itemName.substring(1) - itemType = types.getSchemaType(result.schema.items, json, { destination: state.destination, section: state.section }) + itemName = result.schema.items.title || 'item' + itemName = itemName.charAt(0).toLowerCase() + itemName.substring(1) + itemType = types.getSchemaType(result.schema.items, json, { destination: state.destination, section: state.section }) } template = insertExampleMacros(template, examples[methodObj.name] || [], methodObj, json, templates) @@ -1092,7 +1099,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { template = template.replace(/\$\{method\.name\}/g, method.name) .replace(/\$\{method\.summary\}/g, methodObj.summary) .replace(/\$\{method\.description\}/g, methodObj.description - || methodObj.summary) + || methodObj.summary) // Parameter stuff .replace(/\$\{method\.params\}/g, params) .replace(/\$\{method\.params\.table\.rows\}/g, paramsRows) @@ -1106,8 +1113,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event && event.params.length ? '$1' : '') .replace(/\$\{method\.params\.serialization\}/g, serializedParams) // Typed signature stuff - .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) - .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination, section: state.section })) + .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) + .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(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\.deprecation\}/g, deprecation) @@ -1116,7 +1123,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{event\.params\}/g, eventParams) .replace(/\$\{event\.params\.table\.rows\}/g, eventParamsRows) .replace(/\$\{if\.event\.params\}(.*?)\$\{end\.if\.event\.params\}/gms, event && event.params.length ? '$1' : '') - .replace(/\$\{event\.signature\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section }) : '') + .replace(/\$\{event\.signature\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section }) : '') .replace(/\$\{event\.signature\.callback\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section, callback: true }) : '') .replace(/\$\{event\.params\.serialization\}/g, serializedEventParams) .replace(/\$\{event\.callback\.params\.serialization\}/g, callbackSerializedParams) @@ -1136,22 +1143,22 @@ 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, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') + .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, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) - .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name : result.name })) + .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) .replace(/\$\{method\.result\.instantiation\}/g, resultInst) - .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) + .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) - .replace(/\$\{method\.alternative.link\}/g, '#'+(method.alternative || "").toLowerCase()) - .replace(/\$\{method\.pulls\.for\}/g, pullsFor ? pullsFor.name : '' ) + .replace(/\$\{method\.alternative.link\}/g, '#' + (method.alternative || "").toLowerCase()) + .replace(/\$\{method\.pulls\.for\}/g, pullsFor ? pullsFor.name : '') .replace(/\$\{method\.pulls\.type\}/g, pullsForType) .replace(/\$\{method\.pulls\.result\}/g, pullsResultType) .replace(/\$\{method\.pulls\.params.type\}/g, pullsParams ? pullsParams.title : '') .replace(/\$\{method\.pulls\.params\}/g, pullsParamsType) - .replace(/\$\{method\.setter\.for\}/g, setterFor ) + .replace(/\$\{method\.setter\.for\}/g, setterFor) .replace(/\$\{method\.puller\}/g, pullerTemplate) // must be last!! .replace(/\$\{method\.setter\}/g, setterTemplate) // must be last!! .replace(/\$\{method\.subscriber\}/g, subscriberTemplate) // must be last!! @@ -1171,7 +1178,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { template = template.replace(/\$\{method\.params\[([0-9]+)\]\.type\}/g, types.getSchemaType(methodObj.params[index].schema, json, { destination: state.destination })) template = template.replace(/\$\{method\.params\[([0-9]+)\]\.name\}/g, methodObj.params[index].name) }) - + // Note that we do this twice to ensure all recursive macros are resolved template = insertExampleMacros(template, examples[methodObj.name] || [], methodObj, json, templates) @@ -1209,38 +1216,38 @@ function insertExampleMacros(template, examples, method, json, templates) { let indent = ' '.repeat(json.info.title.length + method.name.length + 2) let params = formatParams(method.params, ', ') if (params.length + indent > 80) { - params = formatParams(method.params, ',\n', true) - params = params.split('\n') - let first = params.shift() - params = params.map(p => indent + p) - params.unshift(first) - params = params.join('\n') + params = formatParams(method.params, ',\n', true) + params = params.split('\n') + let first = params.shift() + params = params.map(p => indent + p) + params.unshift(first) + params = params.join('\n') } languageContent = languageContent - .replace(/\$\{example\.code\}/g, language.code) - .replace(/\$\{example\.name\}/g, example.json.name) - .replace(/\$\{example\.language\}/g, name) - .replace(/\$\{example\.langcode\}/g, language.langcode) - - .replace(/\$\{method\.result\.name\}/g, method.result.name) - .replace(/\$\{method\.name\}/g, method.name) - .replace(/\$\{example\.params\}/g, params) - .replace(/\$\{example\.result\}/g, language.result) - .replace(/\$\{example\.result\.item\}/g, Array.isArray(example.json.result.value) ? JSON.stringify(example.json.result.value[0], null, '\t') : '') - .replace(/\$\{module\}/g, json.info.title) + .replace(/\$\{example\.code\}/g, language.code) + .replace(/\$\{example\.name\}/g, example.json.name) + .replace(/\$\{example\.language\}/g, name) + .replace(/\$\{example\.langcode\}/g, language.langcode) + + .replace(/\$\{method\.result\.name\}/g, method.result.name) + .replace(/\$\{method\.name\}/g, method.name) + .replace(/\$\{example\.params\}/g, params) + .replace(/\$\{example\.result\}/g, language.result) + .replace(/\$\{example\.result\.item\}/g, Array.isArray(example.json.result.value) ? JSON.stringify(example.json.result.value[0], null, '\t') : '') + .replace(/\$\{module\}/g, json.info.title) const matches = [...languageContent.matchAll(/\$\{method\.params\[([0-9]+)\]\.example\.value\}/g)] matches.forEach(match => { const paramIndex = parseInt(match[1]) let indent = 0 - while (match.index-indent >= 0 && match.input[match.index-indent] !== '\n') { + while (match.index - indent >= 0 && match.input[match.index - indent] !== '\n') { indent++ } - const value = JSON.stringify(method.examples[index].params[paramIndex].value, null, '\t').split('\n').map( (line, i) => i > 0 ? ' '.repeat(indent) + line : line).join('\n') + const value = JSON.stringify(method.examples[index].params[paramIndex].value, null, '\t').split('\n').map((line, i) => i > 0 ? ' '.repeat(indent) + line : line).join('\n') languageContent = languageContent.replace(/\$\{method\.params\[([0-9]+)\]\.example\.value\}/g, value) }) - + if (originator) { const originalExample = originator.examples.length > index ? originator.examples[index] : originator.examples[0] @@ -1248,10 +1255,10 @@ function insertExampleMacros(template, examples, method, json, templates) { matches.forEach(match => { const paramIndex = parseInt(match[1]) let indent = 0 - while (match.index-indent >= 0 && match.input[match.index-indent] !== '\n') { + while (match.index - indent >= 0 && match.input[match.index - indent] !== '\n') { indent++ } - const value = JSON.stringify(originalExample.params[paramIndex].value, null, '\t').split('\n').map( (line, i) => i > 0 ? ' '.repeat(indent) + line : line).join('\n') + const value = JSON.stringify(originalExample.params[paramIndex].value, null, '\t').split('\n').map((line, i) => i > 0 ? ' '.repeat(indent) + line : line).join('\n') languageContent = languageContent.replace(/\$\{originator\.params\[([0-9]+)\]\.example\.value\}/g, value) }) } @@ -1273,12 +1280,12 @@ function insertExampleMacros(template, examples, method, json, templates) { function generateResult(result, json, templates, { name = '' } = {}) { - const type = types.getSchemaType(result, json, { name: name, destination: state.destination, section: state.section }) + const type = types.getSchemaType(result, json, { name: name, destination: state.destination, section: state.section }) if (result.type === 'object' && result.properties) { let content = getTemplate('/types/object', templates).split('\n') - for (var i=0; i= 0) { content[i] = Object.entries(result.properties).map(([title, property]) => insertSchemaMacros(content[i], title, property, json)).join('\n') } @@ -1290,17 +1297,17 @@ 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, { name: name }) // if we get a real link use it if (link !== '#') { - return `[${types.getSchemaType(result, json, { destination: state.destination, section: state.section })}](${link})` + return `[${types.getSchemaType(result, json, { destination: state.destination, section: state.section })}](${link})` } // otherwise this was a schema with no title, and we'll just copy it here else { const schema = localizeDependencies(result, json) return getTemplate('/types/default', templates) - .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { name: result.$ref.split("/").pop() })) + .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { name: result.$ref.split("/").pop() })) } } else { @@ -1310,15 +1317,15 @@ function generateResult(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, destination: state.destination, section: state.section, code: false })) - .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module, { name: title })) - .replace(/\$\{description\}/g, schema.description || '') - .replace(/\$\{name\}/g, title || '') + .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { name: title, destination: state.destination, section: state.section, code: false })) + .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module, { name: title })) + .replace(/\$\{description\}/g, schema.description || '') + .replace(/\$\{name\}/g, title || '') } function insertParameterMacros(template, param, method, module) { -//| `${method.param.name}` | ${method.param.type} | ${method.param.required} | ${method.param.summary} ${method.param.constraints} | + //| `${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, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl @@ -1326,18 +1333,18 @@ function insertParameterMacros(template, param, method, module) { let jsonType = types.getJsonType(param.schema, module, { name: param.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) if (constraints && type) { - constraints = '
' + constraints + constraints = '
' + constraints } return template - .replace(/\$\{method.param.name\}/g, param.name) - .replace(/\$\{method.param.Name\}/g, param.name[0].toUpperCase() + param.name.substring(1)) - .replace(/\$\{method.param.summary\}/g, param.summary || '') - .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.constraints\}/g, constraints) //getType(param)) + .replace(/\$\{method.param.name\}/g, param.name) + .replace(/\$\{method.param.Name\}/g, param.name[0].toUpperCase() + param.name.substring(1)) + .replace(/\$\{method.param.summary\}/g, param.summary || '') + .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.constraints\}/g, constraints) //getType(param)) } function insertCapabilityMacros(template, capabilities, method, module) { @@ -1347,18 +1354,18 @@ function insertCapabilityMacros(template, capabilities, method, module) { roles.forEach(role => { if (capabilities[role] && capabilities[role].length) { content.push(template.replace(/\$\{role\}/g, role.split('-').pop()) - .replace(/\$\{capability\}/g, capabilities[role].join('
'))) // Warning, hack! + .replace(/\$\{capability\}/g, capabilities[role].join('
'))) // Warning, hack! } }) if (capabilities['x-provides']) { content.push(template.replace(/\$\{role\}/g, 'provides') - .replace(/\$\{capability\}/g, capabilities['x-provides'])) -} + .replace(/\$\{capability\}/g, capabilities['x-provides'])) + } return content.join() } - + function generateProviderInterfaces(json, templates) { const interfaces = getProvidedCapabilities(json) let template = getTemplate('/sections/provider-interfaces', templates) @@ -1384,83 +1391,83 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te let interfaceShape = getTemplate('/codeblocks/interface', templates) interfaceShape = interfaceShape.replace(/\$\{name\}/g, name) - .replace(/\$\{capability\}/g, capability) - .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => `\t${types.getMethodSignature(method, moduleJson, { destination: state.destination, section: state.section, isInterface: true })}`).join('\n') + '\n') + .replace(/\$\{capability\}/g, capability) + .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => `\t${types.getMethodSignature(method, moduleJson, { destination: state.destination, section: state.section, isInterface: true })}`).join('\n') + '\n') if (iface.length === 0) { - template = template.replace(/\$\{provider\.methods\}/gms, '') + template = template.replace(/\$\{provider\.methods\}/gms, '') } else { - let regex = /\$\{provider\.methods\}/gms - let match = template.match(regex) + let regex = /\$\{provider\.methods\}/gms + let match = template.match(regex) + + let methodsBlock = '' + + // insert the standard method templates for each provider + if (match) { + iface.forEach(method => { + // add a tag to pick the correct template + method.tags.unshift({ + name: 'provider' + }) + const parametersSchema = method.params[0].schema + const parametersShape = types.getSchemaShape(parametersSchema, moduleJson, { destination: state.destination, section: state.section }) + let methodBlock = insertMethodMacros(getTemplateForMethod(method, templates), method, moduleJson, templates) + methodBlock = methodBlock.replace(/\${parameters\.shape\}/g, parametersShape) + const hasProviderParameters = parametersSchema && parametersSchema.properties && Object.keys(parametersSchema.properties).length > 0 + if (hasProviderParameters) { + const lines = methodBlock.split('\n') + for (let i = lines.length - 1; i >= 0; i--) { + if (lines[i].match(/\$\{provider\.param\.[a-zA-Z]+\}/)) { + let line = lines[i] + lines.splice(i, 1) + line = insertProviderParameterMacros(line, method.params[0].schema, moduleJson) + lines.splice(i++, 0, line) + } + } + methodBlock = lines.join('\n') + } + else { + methodBlock = methodBlock.replace(/\$\{if\.provider\.params\}.*?\$\{end\.if\.provider\.params\}/gms, '') + } + methodsBlock += methodBlock + }) + + match = template.match(regex) + template = template.replace(regex, methodsBlock) + } + regex = /\$\{provider\.interface\.start\}.*?\$\{provider\.interface\.end\}/s + + // insert the granular method details for any ${provider.method.start} loops + while (match = template.match(regex)) { let methodsBlock = '' - - // insert the standard method templates for each provider - if (match) { - iface.forEach(method => { - // add a tag to pick the correct template - method.tags.unshift({ - name: 'provider' - }) - const parametersSchema = method.params[0].schema - const parametersShape = types.getSchemaShape(parametersSchema, moduleJson, { destination: state.destination, section: state.section }) - let methodBlock = insertMethodMacros(getTemplateForMethod(method, templates), method, moduleJson, templates) - methodBlock = methodBlock.replace(/\${parameters\.shape\}/g, parametersShape) - const hasProviderParameters = parametersSchema && parametersSchema.properties && Object.keys(parametersSchema.properties).length > 0 - if (hasProviderParameters) { - const lines = methodBlock.split('\n') - for (let i = lines.length - 1; i >= 0; i--) { - if (lines[i].match(/\$\{provider\.param\.[a-zA-Z]+\}/)) { - let line = lines[i] - lines.splice(i, 1) - line = insertProviderParameterMacros(line, method.params[0].schema, moduleJson) - lines.splice(i++, 0, line) - } - } - methodBlock = lines.join('\n') - } - else { - methodBlock = methodBlock.replace(/\$\{if\.provider\.params\}.*?\$\{end\.if\.provider\.params\}/gms, '') - } - methodsBlock += methodBlock - }) - match = template.match(regex) - template = template.replace(regex, methodsBlock) - } + let i = 1 + iface.forEach(method => { - regex = /\$\{provider\.interface\.start\}.*?\$\{provider\.interface\.end\}/s - - // insert the granular method details for any ${provider.method.start} loops - while (match = template.match(regex)) { - let methodsBlock = '' - - let i = 1 - iface.forEach(method => { - - methodsBlock += match[0].replace(/\$\{provider\.interface\.name\}/g, method.name) - .replace(/\$\{provider\.interface\.Name\}/g, method.name.charAt(0).toUpperCase() + method.name.substr(1)) - - // first check for indented lines, and do the fancy indented replacement - .replace(/^([ \t]+)(.*?)\$\{provider\.interface\.example\.result\}/gm, '$1$2' + indent(JSON.stringify(method.examples[0].result.value, null, ' '), '$1')) - .replace(/^([ \t]+)(.*?)\$\{provider\.interface\.example\.parameters\}/gm, '$1$2' + indent(JSON.stringify(method.examples[0].params[0].value, null, ' '), '$1')) - // okay now just do the basic replacement (a single regex for both was not fun) - .replace(/\$\{provider\.interface\.example\.result\}/g, JSON.stringify(method.examples[0].result.value)) - .replace(/\$\{provider\.interface\.example\.parameters\}/g, JSON.stringify(method.examples[0].params[0].value)) - - .replace(/\$\{provider\.interface\.example\.correlationId\}/g, JSON.stringify(method.examples[0].params[1].value.correlationId)) - - // a set of up to three RPC "id" values for generating intersting examples with matching ids - .replace(/\$\{provider\.interface\.i\}/g, i) - .replace(/\$\{provider\.interface\.j\}/g, (i+iface.length)) - .replace(/\$\{provider\.interface\.k\}/g, (i+2*iface.length)) - - i++ - }) - methodsBlock = methodsBlock.replace(/\$\{provider\.interface\.[a-zA-Z]+\}/g, '') - template = template.replace(regex, methodsBlock) - } + methodsBlock += match[0].replace(/\$\{provider\.interface\.name\}/g, method.name) + .replace(/\$\{provider\.interface\.Name\}/g, method.name.charAt(0).toUpperCase() + method.name.substr(1)) + + // first check for indented lines, and do the fancy indented replacement + .replace(/^([ \t]+)(.*?)\$\{provider\.interface\.example\.result\}/gm, '$1$2' + indent(JSON.stringify(method.examples[0].result.value, null, ' '), '$1')) + .replace(/^([ \t]+)(.*?)\$\{provider\.interface\.example\.parameters\}/gm, '$1$2' + indent(JSON.stringify(method.examples[0].params[0].value, null, ' '), '$1')) + // okay now just do the basic replacement (a single regex for both was not fun) + .replace(/\$\{provider\.interface\.example\.result\}/g, JSON.stringify(method.examples[0].result.value)) + .replace(/\$\{provider\.interface\.example\.parameters\}/g, JSON.stringify(method.examples[0].params[0].value)) + + .replace(/\$\{provider\.interface\.example\.correlationId\}/g, JSON.stringify(method.examples[0].params[1].value.correlationId)) + + // a set of up to three RPC "id" values for generating intersting examples with matching ids + .replace(/\$\{provider\.interface\.i\}/g, i) + .replace(/\$\{provider\.interface\.j\}/g, (i + iface.length)) + .replace(/\$\{provider\.interface\.k\}/g, (i + 2 * iface.length)) + + i++ + }) + methodsBlock = methodsBlock.replace(/\$\{provider\.interface\.[a-zA-Z]+\}/g, '') + template = template.replace(regex, methodsBlock) + } } // TODO: JSON-RPC examples need to use ${provider.interface} macros, but we're replacing them globally instead of each block @@ -1476,25 +1483,25 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te function insertProviderParameterMacros(data = '', parameters, module = {}, options = {}) { if (!parameters || !parameters.properties) { - return '' + return '' } let result = '' Object.entries(parameters.properties).forEach(([name, param]) => { - let constraints = getSchemaConstraints(param, module) - let type = types.getSchemaType(param, module, { destination: state.destination, section: state.section, code: true, link: true, title: true, asPath: options.asPath, baseUrl: options.baseUrl }) + let constraints = getSchemaConstraints(param, module) + let type = types.getSchemaType(param, module, { destination: state.destination, section: state.section, code: true, link: true, title: true, asPath: options.asPath, baseUrl: options.baseUrl }) - if (constraints && type) { - constraints = '
' + constraints - } + if (constraints && type) { + constraints = '
' + constraints + } - result += data - .replace(/\$\{provider.param.name\}/, name) - .replace(/\$\{provider.param.summary\}/, param.description || '') - .replace(/\$\{provider.param.required\}/, (parameters.required && parameters.required.includes(name)) || 'false') - .replace(/\$\{provider.param.type\}/, type) - .replace(/\$\{provider.param.constraints\}/, constraints) + '\n' + result += data + .replace(/\$\{provider.param.name\}/, name) + .replace(/\$\{provider.param.summary\}/, param.description || '') + .replace(/\$\{provider.param.required\}/, (parameters.required && parameters.required.includes(name)) || 'false') + .replace(/\$\{provider.param.type\}/, type) + .replace(/\$\{provider.param.constraints\}/, constraints) + '\n' }) return result diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index b1d61ee4..58a9e7e2 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -46,6 +46,7 @@ const macrofy = async ( persistPermission, createModuleDirectories, copySchemasIntoModules, + extractSubSchemas = true, aggregateFile, operators, hidePrivate = true, @@ -63,8 +64,6 @@ const macrofy = async ( return new Promise( async (resolve, reject) => { const openrpc = await readJson(input) - - logHeader(`Generating ${headline} for version ${openrpc.info.title} ${openrpc.info.version}`) let typer @@ -81,6 +80,7 @@ const macrofy = async ( engine.setConfig({ copySchemasIntoModules, createModuleDirectories, + extractSubSchemas, operators }) @@ -277,7 +277,7 @@ const macrofy = async ( await writeFiles(outputFiles) if (persistPermission) { - await writeFilesPermissions(templatesPermission) + //await writeFilesPermissions(templatesPermission) } logSuccess(`Wrote ${Object.keys(outputFiles).length} files.`) From 044e52871b08d9e650db985c93f0ddefde90ff17 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 5 Jul 2023 15:32:58 -0400 Subject: [PATCH 048/137] fix: Add extractSubSchemas flag to C language --- languages/c/language.config.json | 1 + src/macrofier/index.mjs | 2 +- src/sdk/index.mjs | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/languages/c/language.config.json b/languages/c/language.config.json index 97e90519..77cde389 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -2,6 +2,7 @@ "name": "C", "langcode": "c", "createModuleDirectories": false, + "extractSubSchemas": true, "templatesPerModule": [ "/include/Module.h", "/src/Module.cpp" diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 58a9e7e2..0012d86a 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -46,7 +46,7 @@ const macrofy = async ( persistPermission, createModuleDirectories, copySchemasIntoModules, - extractSubSchemas = true, + extractSubSchemas, aggregateFile, operators, hidePrivate = true, diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index c5727cfc..7e85fab9 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -61,6 +61,7 @@ const run = async ({ operators: config.operators, createModuleDirectories: config.createModuleDirectories, copySchemasIntoModules: config.copySchemasIntoModules, + extractSubSchemas: config.extractSubSchemas, staticModuleNames: staticModuleNames, hideExcluded: true, aggregateFile: config.aggregateFile, From 45280e0051f3c2128733077be72b2728921bac93 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 5 Jul 2023 15:39:25 -0400 Subject: [PATCH 049/137] fix: Uncomment writeFilePermissions --- src/macrofier/index.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 0012d86a..3db5d17a 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -277,7 +277,7 @@ const macrofy = async ( await writeFiles(outputFiles) if (persistPermission) { - //await writeFilesPermissions(templatesPermission) + await writeFilesPermissions(templatesPermission) } logSuccess(`Wrote ${Object.keys(outputFiles).length} files.`) From d3ef7f36878493734af447dfb1c46f451e1ede84 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 10 Jul 2023 10:12:50 +0530 Subject: [PATCH 050/137] polymorphic-pull: method and event implementation added (#107) --- languages/c/Types.mjs | 26 ++++++--- .../declarations/polymorphic-pull-event.c | 4 ++ .../templates/declarations/polymorphic-pull.c | 2 + .../methods/polymorphic-pull-event.c | 54 +++++++++++++++++++ .../c/templates/methods/polymorphic-pull.c | 12 ++--- src/macrofier/engine.mjs | 16 ++++-- 6 files changed, 97 insertions(+), 17 deletions(-) create mode 100644 languages/c/templates/declarations/polymorphic-pull-event.c create mode 100644 languages/c/templates/declarations/polymorphic-pull.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 72912930..edf817c9 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -205,15 +205,21 @@ function getMethodSignature(method, module, { destination, isInterface = false } return signature } -function getMethodSignatureParams(method, module, { destination, callback= false } = {}) { - - return method.params.map(param => { +function getMethodSignatureParams(method, module, { destination, callback = false } = {}) { + let signatureParams = '' + let polymorphicPull = method.tags.find(t => t.name === 'polymorphic-pull') + method.params.map(param => { + if (polymorphicPull && (param.name === 'correlationId')) { + return + } + signatureParams += (signatureParams.length > 0) ? ', ' : '' let type = getSchemaType(param.schema, module, { name: param.name, title: true, destination }) if ((callback === true) && (type === 'char*')) { type = getFireboltStringType() } - return type + (!param.required ? '* ' : ' ') + param.name - }).join(', ') + signatureParams += type + (!param.required ? '* ' : ' ') + param.name + }) + return signatureParams } const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop @@ -738,19 +744,23 @@ function getSchemaInstantiation(schema, module, name, { instantiationType = '' } return getResultInstantiation(name, resultType, resultJsonType) } else if (instantiationType === 'callback.params') { - let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' return getCallbackParametersInstantiation(getParamList(schema, module), resultJsonType) } else if (instantiationType === 'callback.result') { let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' - let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' return getCallbackResultInstantiation(resultType, resultJsonType) } else if (instantiationType === 'callback.response') { let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' - let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' return getCallbackResponseInstantiation(getParamList(schema, module), resultType, resultJsonType) } + else if (instantiationType === 'pull.param.name') { + let resultJsonType = getJsonType(schema, module, { name: name }) || '' + return resultJsonType && resultJsonType[0].split('_')[1] || '' + } return '' } diff --git a/languages/c/templates/declarations/polymorphic-pull-event.c b/languages/c/templates/declarations/polymorphic-pull-event.c new file mode 100644 index 00000000..26f1f1c4 --- /dev/null +++ b/languages/c/templates/declarations/polymorphic-pull-event.c @@ -0,0 +1,4 @@ +/* ${method.name} - ${method.description} */ +typedef void* (*${info.Title}${method.Name}Callback)( const void* userData, ${method.pulls.param.type} ); +uint32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callback userCB, const void* userData ); +uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); diff --git a/languages/c/templates/declarations/polymorphic-pull.c b/languages/c/templates/declarations/polymorphic-pull.c new file mode 100644 index 00000000..fbf74697 --- /dev/null +++ b/languages/c/templates/declarations/polymorphic-pull.c @@ -0,0 +1,2 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ); diff --git a/languages/c/templates/methods/polymorphic-pull-event.c b/languages/c/templates/methods/polymorphic-pull-event.c index e69de29b..d2f5ef4c 100644 --- a/languages/c/templates/methods/polymorphic-pull-event.c +++ b/languages/c/templates/methods/polymorphic-pull-event.c @@ -0,0 +1,54 @@ +/* ${method.name} - ${method.description} */ +static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) +{ +${event.callback.params.serialization} + ASSERT(jsonResponse->IsValid() == true); + if (jsonResponse->IsValid() == true) { + + ${info.Title}${method.Name}Callback callback = reinterpret_cast<${info.Title}${method.Name}Callback>(userCB); + + WPEFramework::Core::ProxyType<${method.pulls.param.json.type}>* requestParam = new WPEFramework::Core::ProxyType<${method.pulls.param.json.type}>(); + *requestParam = WPEFramework::Core::ProxyType<${method.pulls.param.json.type}>::Create(); + *(*requestParam) = (*jsonResponse)->${event.pulls.param.name}Parameters; + + ${method.pulls.type} result = reinterpret_cast<${method.pulls.type}>(callback(userData, reinterpret_cast<${method.pulls.param.type}>(requestParam))); + + JsonObject jsonParameters; + WPEFramework::Core::JSON::Variant CorrelationId = (*jsonResponse)->CorrelationId.Value(); + jsonParameters.Set(_T("correlationId"), CorrelationId); + + ${method.pulls.json.type}& resultObj = *(*(reinterpret_cast*>(result))); + string resultStr; + resultObj.ToString(resultStr); + WPEFramework::Core::JSON::VariantContainer resultContainer(resultStr); + WPEFramework::Core::JSON::Variant Result = resultContainer; + jsonParameters.Set(_T("result"), Result); + + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + 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(), "${info.Title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; + } + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport"); + } + } +} +uint32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callback userCB, const void* userData ) +{ + const string eventName = _T("${info.title}.${method.name}"); + uint32_t status = FireboltSDKErrorNone; + + if (userCB != nullptr) { + ${event.params.serialization} + status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${info.Title}${method.Name}InnerCallback, reinterpret_cast(userCB), userData); + } + return status; +} +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(userCB)); +} diff --git a/languages/c/templates/methods/polymorphic-pull.c b/languages/c/templates/methods/polymorphic-pull.c index 553b2946..ec052e64 100644 --- a/languages/c/templates/methods/polymorphic-pull.c +++ b/languages/c/templates/methods/polymorphic-pull.c @@ -1,20 +1,20 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_Push${method.Name}(${method.signature.params}) +uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ) { uint32_t status = FireboltSDKErrorUnavailable; - ${if.params} + + string correlationId = ""; ${method.params.serialization} - ${end.if.params} FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); - if (transport != nullptr) { + if (transport != nullptr) { WPEFramework::Core::JSON::Boolean jsonResult; status = transport->Invoke(_T("${info.title}.${method.name}"), jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; } } else { - FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport"); } return status; diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index b167f4d4..770d890e 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -1068,10 +1068,16 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) 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 const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) - const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) - const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) + + const pullsForJsonType = pullsResult ? types.getJsonType(pullsResult, json, { name: pullsResult.name }) : '' + const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const pullsForParamType = pullsParams ? types.getSchemaType(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const pullsForParamJsonType = pullsParams ? types.getJsonType(pullsParams, json, { name: pullsParams.title }) : '' + const pullsEventParamName = event ? types.getSchemaInstantiation(event.result, json, event.name, { instantiationType: 'pull.param.name' }) : '' + const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, { instantiationType: 'params' }) - const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' }) + const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' } ) const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'params' }), ' ') : '' const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.params' }) : '' const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.result' }) : '' @@ -1148,6 +1154,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) + .replace(/\$\{event\.pulls\.param\.name\}/g, pullsEventParamName) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) .replace(/\$\{method\.result\.instantiation\}/g, resultInst) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) @@ -1155,9 +1162,12 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.alternative.link\}/g, '#' + (method.alternative || "").toLowerCase()) .replace(/\$\{method\.pulls\.for\}/g, pullsFor ? pullsFor.name : '') .replace(/\$\{method\.pulls\.type\}/g, pullsForType) + .replace(/\$\{method\.pulls\.json\.type\}/g, pullsForJsonType) .replace(/\$\{method\.pulls\.result\}/g, pullsResultType) .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\.setter\.for\}/g, setterFor) .replace(/\$\{method\.puller\}/g, pullerTemplate) // must be last!! .replace(/\$\{method\.setter\}/g, setterTemplate) // must be last!! From 968703378fe419a2206fca94a53c86a7f446dd5f Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 10 Jul 2023 10:13:28 +0530 Subject: [PATCH 051/137] SchemaSorting: logic updated to consider all schemas (#106) --- src/macrofier/engine.mjs | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 770d890e..18091b7e 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -673,6 +673,24 @@ function generateDefaults(json = {}, templates) { return reducer(json) } +function sortSchemasByReference(schemas = []) { + let indexA = 0; + while (indexA < schemas.length) { + + let swapped = false + for (let indexB = indexA + 1; indexB < schemas.length; ++indexB) { + const bInA = isDefinitionReferencedBySchema('#/components/schemas/' + schemas[indexB][0], schemas[indexA][1]) + if ((isEnum(schemas[indexB][1]) && !isEnum(schemas[indexA][1])) || (bInA === true)) { + [schemas[indexA], schemas[indexB]] = [schemas[indexB], schemas[indexA]] + swapped = true + break + } + } + indexA = swapped ? indexA : ++indexA + } + return schemas +} + const isEnum = x => x.type && x.type === 'string' && Array.isArray(x.enum) && x.title function generateSchemas(json, templates, options) { @@ -736,7 +754,7 @@ function generateSchemas(json, templates, options) { results.push(result) } - const list = [] + let list = [] // schemas may be 1 or 2 levels deeps Object.entries(schemas).forEach(([name, schema]) => { @@ -745,17 +763,7 @@ function generateSchemas(json, templates, options) { } }) - list.sort((a, b) => { - const aInB = isDefinitionReferencedBySchema('#/components/schemas/' + a[0], b[1]) - const bInA = isDefinitionReferencedBySchema('#/components/schemas/' + b[0], a[1]) - if (isEnum(a[1]) || (aInB && !bInA)) { - return -1 - } else if (isEnum(b[1]) || (!aInB && bInA)) { - return 1 - } - return 0; - }) - + list = sortSchemasByReference(list) list.forEach(item => generate(...item)) return results From 5a15e169df652fa7e1746d41243f39df1d2016de Mon Sep 17 00:00:00 2001 From: sramani-metro <71630728+sramani-metro@users.noreply.github.com> Date: Tue, 11 Jul 2023 13:23:11 +0530 Subject: [PATCH 052/137] fix: Fix the reentrancy of methods from callback (#105) --- languages/c/templates/sdk/src/Transport/Transport.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/languages/c/templates/sdk/src/Transport/Transport.h b/languages/c/templates/sdk/src/Transport/Transport.h index 2aff350d..d12312a5 100644 --- a/languages/c/templates/sdk/src/Transport/Transport.h +++ b/languages/c/templates/sdk/src/Transport/Transport.h @@ -668,15 +668,15 @@ namespace FireboltSDK { } result = WPEFramework::Core::ERROR_NONE; + _adminLock.Unlock(); } else { - + _adminLock.Unlock(); string eventName; if (IsEvent(inbound->Id.Value(), eventName)) { _eventHandler->Dispatch(eventName, inbound); } } - _adminLock.Unlock(); } return (result); From daf6ec6b86148320e983094750985da9d282488e Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Tue, 11 Jul 2023 21:58:32 +0530 Subject: [PATCH 053/137] Default template implementation added (#103) Default template implementation added --- languages/c/Types.mjs | 62 ++++++++++++-------- languages/c/src/types/ImplHelpers.mjs | 26 ++++---- languages/c/src/types/NativeHelpers.mjs | 4 +- languages/c/templates/codeblocks/setter.c | 6 +- languages/c/templates/declarations/default.c | 3 + languages/c/templates/methods/default.c | 33 +++++------ languages/c/templates/methods/property.c | 2 +- src/macrofier/engine.mjs | 6 +- 8 files changed, 83 insertions(+), 59 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index edf817c9..2a8f5aa0 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -170,6 +170,9 @@ const hasTag = (method, tag) => { return method.tags && method.tags.filter(t => t.name === tag).length > 0 } +const IsResultConstNullSuccess = (schema, name) => (name === 'success' && !schema.const && !schema.type) +const IsResultBooleanSuccess = (schema, name) => (name === 'success' && schema.type === 'boolean') + function getParamList(schema, module) { let paramList = [] if (schema.params.length > 0) { @@ -229,13 +232,13 @@ function getSchemaType(schema, module, { name, prefix = '', destination, resultS return info.type } -function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = {level: 0, descriptions: true, title: false, resultSchema: false, event: false}) { +function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = { level: 0, descriptions: true, title: false, resultSchema: false, event: false}) { if (json.schema) { json = json.schema } - let stringAsHandle = options.resultSchema || options.event + let fireboltString = options.resultSchema || options.event let structure = {} structure["type"] = '' @@ -263,7 +266,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref } } else if (json.const) { - structure.type = getNativeType(json, stringAsHandle) + structure.type = getNativeType(json, fireboltString) structure.json = json return structure } @@ -320,7 +323,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref return getSchemaTypeInfo(module, union, '', schemas, '', options) } else if (json.oneOf) { - structure.type = 'char*' + structure.type = fireboltString ? getFireboltStringType() : 'char*' structure.json.type = 'string' return structure } @@ -337,7 +340,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref structure.namespace = (json.namespace ? json.namespace : getModuleName(module)) } else { - structure.type = 'char*' + structure.type = fireboltString ? getFireboltStringType() : 'char*' } if (name) { structure.name = capitalize(name) @@ -346,14 +349,14 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref return structure } else if (json.type) { - structure.type = getNativeType(json, stringAsHandle) - structure.json = json - if (name || json.title) { - structure.name = capitalize(name || json.title) + if (!IsResultBooleanSuccess(json, name) && !IsResultConstNullSuccess(json, name)) { + structure.type = getNativeType(json, fireboltString) + structure.json = json + if (name || json.title) { + structure.name = capitalize(name || json.title) + } + structure.namespace = getModuleName(module) } - structure.namespace = getModuleName(module) - - return structure } return structure } @@ -377,13 +380,12 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' if (json['$ref'][0] === '#') { //Ref points to local schema //Get Path to ref in this module and getSchemaType - const schema = getPath(json['$ref'], module, schemas) - const tname = schema.title || json['$ref'].split('/').pop() + let schema = getPath(json['$ref'], module, schemas) + const tName = schema.title || json['$ref'].split('/').pop() if (json['$ref'].includes('x-schemas')) { schema = (getRefModule(json['$ref'].split('/')[2])) } - - shape = getSchemaShapeInfo(schema, module, schemas, { name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) + shape = getSchemaShapeInfo(schema, module, schemas, { name: tName, prefix, merged, level, title, summary, descriptions, destination, section, enums }) } } //If the schema is a const, @@ -429,7 +431,6 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' let info = getSchemaTypeInfo(module, items, items.name || pname, schemas, prefix, {level : level, descriptions: descriptions, title: true}) if (info.type && info.type.length > 0) { let objName = tName + '_' + capitalize(prop.title || pname) - let moduleName = info.namespace info.json.namespace = info.namespace let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) let prefixName = ((prefix.length > 0) && items['$ref']) ? '' : prefix @@ -539,10 +540,14 @@ 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(name) + capitalize(type.type) - let objName = getTypeName(info.namespace, arrayName, prefix) + let arrayName = capitalize(info.name) + capitalize(type.type) + let namespace = info.namespace + if (type && type.type === 'object') { + namespace = getModuleName(module) + } + let objName = getTypeName(namespace, arrayName, prefix) let tName = objName + 'Array' - let moduleName = info.namespace + info.json.namespace = info.namespace let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) let subModuleProperty = getJsonTypeInfo(module, j, j.title, schemas, prefix) @@ -712,6 +717,9 @@ function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '' structure.type = getJsonNativeType(json) return structure } + else { + structure.type = 'JsonObject' + } return structure } @@ -739,9 +747,17 @@ function getSchemaInstantiation(schema, module, name, { instantiationType = '' } return getParameterInstantiation(getParamList(schema, module)) } else if (instantiationType === 'result') { - let resultType = getSchemaType(schema, module, { title: true, name: name, resultSchema: true}) || '' - let resultJsonType = getJsonType(schema, module, {name: name}) || '' - return getResultInstantiation(name, resultType, resultJsonType) + let result = '' + + if (!IsResultConstNullSuccess(schema, name)) { + let resultJsonType = getJsonType(schema, module, {name: name}) || '' + let resultType = '' + if (!IsResultBooleanSuccess(schema, name)) { + resultType = getSchemaType(schema, module, { title: true, name: name, resultSchema: true}) || '' + } + result = getResultInstantiation(name, resultType, resultJsonType) + } + return result } else if (instantiationType === 'callback.params') { let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index 6509375a..3d5403d4 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -455,16 +455,22 @@ function getResultInstantiation (name, nativeType, container, indentLevel = 3) { let impl = '' - if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { - impl += `${' '.repeat(indentLevel)}${container}* strResult = new ${container}(jsonResult);` + '\n' - impl += `${' '.repeat(indentLevel)}*${name} = static_cast<${getFireboltStringType()}>(strResult);` - } else if (nativeType.includes('Handle')) { - impl += `${' '.repeat(indentLevel)}WPEFramework::Core::ProxyType<${container}>* resultPtr = new WPEFramework::Core::ProxyType<${container}>();\n` - impl += `${' '.repeat(indentLevel)}*resultPtr = WPEFramework::Core::ProxyType<${container}>::Create();\n` - impl += `${' '.repeat(indentLevel)}*(*resultPtr) = jsonResult;\n` - impl += `${' '.repeat(indentLevel)}*${name} = static_cast<${nativeType}>(resultPtr);` - } else { - impl += `${' '.repeat(indentLevel)}*${name} = jsonResult.Value();` + if (nativeType) { + impl += `${' '.repeat(indentLevel)}if (${name} != nullptr) {` + '\n' + if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + impl += `${' '.repeat(indentLevel + 1)}${container}* strResult = new ${container}(jsonResult);` + '\n' + impl += `${' '.repeat(indentLevel + 1)}*${name} = static_cast<${getFireboltStringType()}>(strResult);` + } else if (nativeType.includes('Handle')) { + impl += `${' '.repeat(indentLevel + 1)}WPEFramework::Core::ProxyType<${container}>* resultPtr = new WPEFramework::Core::ProxyType<${container}>();\n` + impl += `${' '.repeat(indentLevel + 1)}*resultPtr = WPEFramework::Core::ProxyType<${container}>::Create();\n` + impl += `${' '.repeat(indentLevel + 1)}*(*resultPtr) = jsonResult;\n` + impl += `${' '.repeat(indentLevel + 1)}*${name} = static_cast<${nativeType}>(resultPtr);` + } else { + impl += `${' '.repeat(indentLevel + 1)}*${name} = jsonResult.Value();` + } + impl += `${' '.repeat(indentLevel)}}` + '\n' + } else if (name === 'success') { + impl += `${' '.repeat(indentLevel)}status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported;` } return impl diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 022437e8..1460e22e 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -115,12 +115,12 @@ const getArrayElementSchema = (json, module, schemas = {}, name) => { return result } -const getNativeType = (json, stringAsHandle = false) => { +const getNativeType = (json, fireboltString = false) => { let type let jsonType = json.const ? typeof json.const : json.type if (jsonType === 'string') { type = 'char*' - if (stringAsHandle) { + if (fireboltString) { type = getFireboltStringType() } } diff --git a/languages/c/templates/codeblocks/setter.c b/languages/c/templates/codeblocks/setter.c index 9f496543..342a98d6 100644 --- a/languages/c/templates/codeblocks/setter.c +++ b/languages/c/templates/codeblocks/setter.c @@ -1,9 +1,7 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_${method.Name}( ${method.signature.params} ) +uint32_t ${info.Title}_${method.Name}( ${method.signature.params} ) { const string method = _T("${info.title}.${method.name}"); - ${if.params} -${method.params.serialization} - ${end.if.params} +${if.params}${method.params.serialization}${end.if.params} return FireboltSDK::Properties::Set(method, jsonParameters); } diff --git a/languages/c/templates/declarations/default.c b/languages/c/templates/declarations/default.c index e69de29b..ac4e7f78 100644 --- a/languages/c/templates/declarations/default.c +++ b/languages/c/templates/declarations/default.c @@ -0,0 +1,3 @@ +/* ${method.name} - ${method.description} +${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation}${end.if.deprecated} */ +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} ); diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 6a023534..6fbca47e 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -1,24 +1,21 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_${method.Name}(${method.params.list}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { - uint32_t status = FireboltSDKErrorUnavailable; - FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); - if (transport != nullptr) { - - JsonObject jsonParameters; +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} ) { - ${if.params} -${method.params.json} - ${end.if.params} + uint32_t status = FireboltSDKErrorUnavailable; + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { - WPEFramework::Core::JSON::Boolean jsonResult; - status = transport->Invoke("${info.title}.${method.name}", jsonParameters, jsonResult); - if (status == FireboltSDKErrorNone) { - *success = jsonResult.Value(); - } + ${method.params.serialization.with.indent} + ${method.result.json.type} jsonResult; + status = transport->Invoke("${info.title}.${method.name}", jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully invoked"); +${method.result.instantiation} + } - } else { - FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); - } + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } - return status; + return status; } diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index c7510da9..9a92dce4 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,5 +1,5 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_Get${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name} ) +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}"); ${if.params}${method.params.serialization}${end.if.params} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 18091b7e..b4f4f9c8 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -1123,9 +1123,12 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.params\.array\}/g, JSON.stringify(methodObj.params.map(p => p.name))) .replace(/\$\{method\.params\.count}/g, methodObj.params ? methodObj.params.length : 0) .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/gms, method.params.length ? '$1' : '') - .replace(/\$\{if\.params.empty\}(.*?)\$\{end\.if\.params.empty\}/gms, method.params.length === 0 ? '$1' : '') + .replace(/\$\{if\.result\}(.*?)\$\{end\.if\.result\}/gms, resultType ? '$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' : '') .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event && event.params.length ? '$1' : '') .replace(/\$\{method\.params\.serialization\}/g, serializedParams) + .replace(/\$\{method\.params\.serialization\.with\.indent\}/g, indent(serializedParams, ' ')) // Typed signature stuff .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination, section: state.section })) @@ -1164,6 +1167,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{event\.pulls\.param\.name\}/g, pullsEventParamName) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) + .replace(/\$\{method\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{method\.result\.instantiation\}/g, resultInst) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) From 161b347e4ea0ee123b47085004d57ad8246e23ea Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Wed, 12 Jul 2023 09:16:41 +0530 Subject: [PATCH 054/137] Naming + void* to struct* changes based on sky review, removed redundant code, array handling fix (#109) Naming + void* to struct* changes based on sky review, removed redundant code, array handling fix --- languages/c/Types.mjs | 34 ++- languages/c/language.config.json | 10 +- languages/c/src/types/ImplHelpers.mjs | 141 +++++++------ languages/c/src/types/JSONHelpers.mjs | 3 +- languages/c/src/types/NativeHelpers.mjs | 74 ++----- languages/c/templates/imports/default.cpp | 2 +- languages/c/templates/imports/default.h | 2 +- .../c/templates/imports/default.jsondata | 2 +- .../modules/include/{Module.h => module.h} | 6 +- .../modules/src/{Module.cpp => module.cpp} | 4 +- .../{Common/Module.h => common/module.h} | 6 +- .../{JsonData_Module.h => jsondata_module.h} | 4 +- .../{Module_Common.cpp => module_common.cpp} | 2 +- .../sdk/include/{Error.h => error.h} | 6 +- .../sdk/include/{Firebolt.h => firebolt.h} | 10 +- .../sdk/include/{Types.h => types.h} | 12 +- languages/c/templates/sdk/scripts/build.sh | 42 +++- languages/c/templates/sdk/src/CMakeLists.txt | 5 - languages/c/templates/sdk/src/FireboltSDK.h | 2 +- .../c/templates/sdk/src/Logger/Logger.cpp | 2 +- languages/c/templates/sdk/src/Logger/Logger.h | 2 +- .../c/templates/sdk/src/Transport/Transport.h | 2 +- languages/c/templates/sdk/src/Types.cpp | 10 +- .../sdk/src/{Firebolt.cpp => firebolt.cpp} | 0 languages/c/templates/sdk/test/CMakeLists.txt | 2 +- languages/c/templates/sdk/test/Main.c | 1 + languages/c/templates/sdk/test/Module.h | 1 - .../c/templates/sdk/test/OpenRPCCTests.h | 11 +- .../c/templates/sdk/test/OpenRPCTests.cpp | 199 ++++++++++++++---- languages/c/templates/sdk/test/OpenRPCTests.h | 23 +- languages/c/templates/sdk/test/TestUtils.h | 10 +- languages/c/templates/types/enum.cpp | 4 +- languages/c/templates/types/enum.h | 2 +- src/macrofier/engine.mjs | 7 +- src/macrofier/index.mjs | 4 +- 35 files changed, 392 insertions(+), 255 deletions(-) rename languages/c/templates/modules/include/{Module.h => module.h} (92%) rename languages/c/templates/modules/src/{Module.cpp => module.cpp} (93%) rename languages/c/templates/schemas/include/{Common/Module.h => common/module.h} (90%) rename languages/c/templates/schemas/src/{JsonData_Module.h => jsondata_module.h} (91%) rename languages/c/templates/schemas/src/{Module_Common.cpp => module_common.cpp} (94%) rename languages/c/templates/sdk/include/{Error.h => error.h} (93%) rename languages/c/templates/sdk/include/{Firebolt.h => firebolt.h} (93%) rename languages/c/templates/sdk/include/{Types.h => types.h} (73%) rename languages/c/templates/sdk/src/{Firebolt.cpp => firebolt.cpp} (100%) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 2a8f5aa0..1ed84940 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -20,7 +20,7 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation, getCallbackParametersInstantiation, getCallbackResultInstantiation, getCallbackResponseInstantiation } from './src/types/ImplHelpers.mjs' -import { getJsonContainerDefinition, getJsonDataStructName } from './src/types/JSONHelpers.mjs' +import { getJsonContainerDefinition, getJsonDataStructName, getJsonDataPrefix } from './src/types/JSONHelpers.mjs' const getSdkNameSpace = () => 'FireboltSDK' const getJsonNativeTypeForOpaqueString = () => getSdkNameSpace() + '::JSON::String' @@ -262,17 +262,14 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref structure.json = res.json structure.name = res.name structure.namespace = res.namespace - return structure } } else if (json.const) { structure.type = getNativeType(json, fireboltString) structure.json = json - return structure } else if (json['x-method']) { console.log(`WARNING UNHANDLED: x-method in ${name}`) - return structure //throw "x-methods not supported yet" } else if (json.type === 'string' && json.enum) { @@ -283,13 +280,12 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref structure.json = json structure.type = typeName structure.namespace = getModuleName(module) - return structure } else if (Array.isArray(json.type)) { let type = json.type.find(t => t !== 'null') let sch = JSON.parse(JSON.stringify(json)) sch.type = type - return getSchemaTypeInfo(module, sch, name, schemas, prefix, options) + structure = getSchemaTypeInfo(module, sch, name, schemas, prefix, options) } else if (json.type === 'array' && json.items && (validJsonObjectProperties(json) === true)) { let res = '' @@ -306,13 +302,11 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref res = getSchemaTypeInfo(module, json.items, json.items.name || name, schemas, prefix) } - let arrayName = capitalize(res.name) + capitalize(res.json.type) - let n = getTypeName(getModuleName(module), arrayName, prefix) + let n = getTypeName(getModuleName(module), capitalize(res.name), prefix) structure.name = res.name || name && (capitalize(name)) - structure.type = n + 'ArrayHandle' + structure.type = n + 'Array_t' structure.json = json structure.namespace = getModuleName(module) - return structure } else if (json.allOf) { let title = json.title ? json.title : name @@ -320,22 +314,21 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref union['title'] = title delete union['$ref'] - return getSchemaTypeInfo(module, union, '', schemas, '', options) + structure = getSchemaTypeInfo(module, union, '', schemas, '', options) } else if (json.oneOf) { structure.type = fireboltString ? getFireboltStringType() : 'char*' structure.json.type = 'string' - return structure } else if (json.anyOf) { let mergedSchema = getMergedSchema(module, json, name, schemas) let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) - return getSchemaTypeInfo(module, mergedSchema, '', schemas, prefixName, options) + structure = getSchemaTypeInfo(module, mergedSchema, '', schemas, prefixName, options) } else if (json.type === 'object') { structure.json = json if (hasProperties(json)) { - structure.type = getTypeName(getModuleName(module), json.title || name, prefix) + 'Handle' + structure.type = getTypeName(getModuleName(module), json.title || name, prefix) + '_t' structure.name = (json.name ? json.name : (json.title ? json.title : name)) structure.namespace = (json.namespace ? json.namespace : getModuleName(module)) } @@ -345,8 +338,6 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref if (name) { structure.name = capitalize(name) } - - return structure } else if (json.type) { if (!IsResultBooleanSuccess(json, name) && !IsResultConstNullSuccess(json, name)) { @@ -370,8 +361,9 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' let shape = '' if (destination && section) { - const isHeader = (destination.includes("JsonData_") !== true) && destination.endsWith(".h") - const isCPP = ((destination.endsWith(".cpp") || destination.includes("JsonData_")) && (section.includes('accessors') !== true)) + const isHeader = (destination.includes(getJsonDataPrefix().toLowerCase()) !== true) && destination.endsWith(".h") + const isCPP = ((destination.endsWith(".cpp") || destination.includes(getJsonDataPrefix().toLowerCase())) && (section.includes('accessors') !== true)) + json = JSON.parse(JSON.stringify(json)) name = json.title || name @@ -437,7 +429,7 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, schemas, prefix) let t = description(capitalize(info.name), json.description) + '\n' - t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + '_t'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) c_shape += '\n' + t props.push({name: `${pname}`, type: `WPEFramework::Core::JSON::ArrayType<${subModuleProperty.type}>`}) } @@ -556,7 +548,7 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' t += description(capitalize(info.name), json.description) + '\n' t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, moduleProperty.type)) } - t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, '', info.type, info.json)) + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + '_t'), subModuleProperty.type, '', info.type, info.json)) shape += '\n' + t } } @@ -775,7 +767,7 @@ function getSchemaInstantiation(schema, module, name, { instantiationType = '' } } else if (instantiationType === 'pull.param.name') { let resultJsonType = getJsonType(schema, module, { name: name }) || '' - return resultJsonType && resultJsonType[0].split('_')[1] || '' + return resultJsonType.length && resultJsonType[0].split('_')[1] || '' } return '' diff --git a/languages/c/language.config.json b/languages/c/language.config.json index 77cde389..ee3604d7 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -4,13 +4,13 @@ "createModuleDirectories": false, "extractSubSchemas": true, "templatesPerModule": [ - "/include/Module.h", - "/src/Module.cpp" + "/include/module.h", + "/src/module.cpp" ], "templatesPerSchema": [ - "/include/Common/Module.h", - "/src/Module_Common.cpp", - "/src/JsonData_Module.h" + "/include/common/module.h", + "/src/module_common.cpp", + "/src/jsondata_module.h" ], "persistPermission": true } diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index 3d5403d4..5b373377 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -4,35 +4,36 @@ const Indent = '\t' const getSdkNameSpace = () => 'FireboltSDK' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' +const camelcase = str => str[0].toLowerCase() + str.substr(1) const getObjectHandleManagementImpl = (varName, jsonDataName) => { - let result = `${varName}Handle ${varName}Handle_Create(void) + let result = `${varName}_t ${varName}Handle_Acquire(void) { WPEFramework::Core::ProxyType<${jsonDataName}>* type = new WPEFramework::Core::ProxyType<${jsonDataName}>(); *type = WPEFramework::Core::ProxyType<${jsonDataName}>::Create(); - return (static_cast<${varName}Handle>(type)); + return (reinterpret_cast<${varName}_t>(type)); } -void ${varName}Handle_Addref(${varName}Handle handle) +void ${varName}Handle_Addref(${varName}_t handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); var->AddRef(); } -void ${varName}Handle_Release(${varName}Handle handle) +void ${varName}Handle_Release(${varName}_t handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = reinterpret_cast*>(handle); var->Release(); if (var->IsValid() != true) { delete var; } } -bool ${varName}Handle_IsValid(${varName}Handle handle) +bool ${varName}Handle_IsValid(${varName}_t handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); return var->IsValid(); } @@ -42,17 +43,17 @@ bool ${varName}Handle_IsValid(${varName}Handle handle) const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, subPropertyName, accessorPropertyType, json = {}, options = {readonly:false, optional:false}) => { let result = '' - result += `${accessorPropertyType} ${objName}_Get_${subPropertyName}(${objName}Handle handle) + result += `${accessorPropertyType} ${objName}_Get_${subPropertyName}(${objName}_t handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ` + '\n' if ((json.type === 'object') && (accessorPropertyType !== 'char*')) { result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); *(*element) = (*var)->${subPropertyName}; - return (static_cast<${accessorPropertyType}>(element));` + '\n' + return (reinterpret_cast<${accessorPropertyType}>(element));` + '\n' } else { if ((typeof json.const === 'string') || (json.type === 'string' && !json.enum) || (accessorPropertyType === 'char*')) { @@ -66,14 +67,14 @@ const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, if (!options.readonly) { let type = (accessorPropertyType === getFireboltStringType()) ? 'char*' : accessorPropertyType - result += `void ${objName}_Set_${subPropertyName}(${objName}Handle handle, ${type} value)\n{ + result += `void ${objName}_Set_${subPropertyName}(${objName}_t handle, ${type} value)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ` + '\n' if (json.type === 'object' && (accessorPropertyType !== 'char*')) { - result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* object = static_cast*>(value); + result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* object = reinterpret_cast*>(value); (*var)->${subPropertyName} = *(*object);` + '\n' } else { @@ -83,16 +84,16 @@ const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, } if (options.optional === true) { - result += `bool ${objName}_Has_${subPropertyName}(${objName}Handle handle)\n{ + result += `bool ${objName}_Has_${subPropertyName}(${objName}_t handle)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); return ((*var)->${subPropertyName}.IsSet()); }` + '\n' - result += `void ${objName}_Clear_${subPropertyName}(${objName}Handle handle)\n{ + result += `void ${objName}_Clear_${subPropertyName}(${objName}_t handle)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ((*var)->${subPropertyName}.Clear()); }` + '\n' @@ -113,7 +114,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr let result = `uint32_t ${objName}Array_Size(${objHandleType} handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); return (${propertyName}.Length()); @@ -122,7 +123,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr result += `${accessorPropertyType} ${objName}Array_Get(${objHandleType} handle, uint32_t index) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid());` + '\n' if ((json.type === 'object') || (json.type === 'array')) { @@ -130,7 +131,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr *object = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); *(*object) = ${propertyName}.Get(index); - return (static_cast<${accessorPropertyType}>(object));` + '\n' + return (reinterpret_cast<${accessorPropertyType}>(object));` + '\n' } else { if ((typeof json.const === 'string') || (json.type === 'string' && !json.enum)) { @@ -146,23 +147,25 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr result += `void ${objName}Array_Add(${objHandleType} handle, ${type} value) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid());` + '\n' if ((json.type === 'object') || (json.type === 'array')) { - result += ` ${subPropertyType}& element = *(*(static_cast*>(value)));` + '\n' + result += ` ${subPropertyType} element; + element = *(*(reinterpret_cast*>(value)));` + '\n' } else { - result += ` ${subPropertyType} element(value);` + '\n' + result += ` ${subPropertyType} element;` + '\n' + result += ` element = value;` + '\n' } result += ` - ${propertyName}.Add(element); + ${propertyName}.Add() = element; }` + '\n' result += `void ${objName}Array_Clear(${objHandleType} handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ${propertyName}.Clear(); @@ -172,10 +175,10 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr } const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPropertyType, json = {}, options = {readonly:false, optional:false}) => { - let result = `uint32_t ${objName}_KeysCount(${objName}Handle handle) + let result = `uint32_t ${objName}_KeysCount(${objName}_t handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ${containerType}::Iterator elements = (*var)->Variants(); uint32_t count = 0; @@ -184,10 +187,10 @@ const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPr } return (count); }` + '\n' - result += `void ${objName}_AddKey(${objName}Handle handle, char* key, ${accessorPropertyType} value) + result += `void ${objName}_AddKey(${objName}_t handle, char* key, ${accessorPropertyType} value) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ` + '\n' let elementContainer = subPropertyType @@ -196,14 +199,14 @@ const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPr } if ((json.type === 'object') || (json.type === 'array' && json.items)) { if (containerType.includes('VariantContainer')) { - result += ` ${subPropertyType}& container = *(*(static_cast*>(value)));` + '\n' + result += ` ${subPropertyType}& container = *(*(reinterpret_cast*>(value)));` + '\n' result += ` string containerStr;` + '\n' result += ` element.ToString(containerStr);` + '\n' result += ` WPEFramework::Core::JSON::VariantContainer containerVariant(containerStr);` + '\n' result += ` WPEFramework::Core::JSON::Variant element = containerVariant;` + '\n' } else { - result += ` ${subPropertyType}& element = *(*(static_cast*>(value)));` + '\n' + result += ` ${subPropertyType}& element = *(*(reinterpret_cast*>(value)));` + '\n' } } else { result += ` ${elementContainer} element(value);` + '\n' @@ -211,19 +214,19 @@ const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPr result += ` (*var)->Set(const_cast(key), element); }` + '\n' - result += `void ${objName}_RemoveKey(${objName}Handle handle, char* key) + result += `void ${objName}_RemoveKey(${objName}_t handle, char* key) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); (*var)->Remove(key); }` + '\n' - result += `${accessorPropertyType} ${objName}_FindKey(${objName}Handle handle, char* key) + result += `${accessorPropertyType} ${objName}_FindKey(${objName}_t handle, char* key) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid());` + '\n' if ((json.type === 'object') || (json.type === 'array') || ((json.type === 'string' || (typeof json.const === 'string')) && !json.enum)) { @@ -249,14 +252,14 @@ const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPr *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); *(*element) = objectMap; - status = (static_cast<${accessorPropertyType}>(element));` + '\n' + status = (reinterpret_cast<${accessorPropertyType}>(element));` + '\n' } else if (json.type === 'array' && json.items) { result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); *(*element) = (*var)->Get(key).Array(); - status = (static_cast<${accessorPropertyType}>(element));` + '\n' + status = (reinterpret_cast<${accessorPropertyType}>(element));` + '\n' } else { if (json.type === 'string' || (typeof json.const === 'string')) { @@ -298,25 +301,41 @@ function getParameterInstantiation(paramList, container = '') { paramList.forEach(param => { impl += `\n` const jsonType = param.jsonType + const name = param.name if (jsonType.length) { if (param.required) { - if (param.nativeType.includes('FireboltTypes_StringHandle')) { - impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = *(static_cast<${jsonType}*>(${param.name}));\n` + if (param.nativeType.includes('FireboltTypes_String_t')) { + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = *(reinterpret_cast<${jsonType}*>(${name}));\n` + } + else if (param.nativeType.includes('_t')) { + impl += ` ${jsonType}& ${capitalize(name)}Container = *(*(reinterpret_cast*>(${camelcase(name)})));\n` + impl += ` string ${capitalize(name)}Str;\n` + impl += ` ${capitalize(name)}Container.ToString(${capitalize(name)}Str);\n` + impl += ` WPEFramework::Core::JSON::VariantContainer ${capitalize(name)}VariantContainer(${capitalize(name)}Str);\n` + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = ${capitalize(name)}VariantContainer;\n` } else { - impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = ${param.name};\n` + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = ${name};\n` } - impl += ` jsonParameters.Set(_T("${param.name}"), ${capitalize(param.name)});` + impl += ` jsonParameters.Set(_T("${name}"), ${capitalize(name)});` } else { - impl += ` if (${param.name} != nullptr) {\n` + + impl += ` if (${name} != nullptr) {\n` if (param.nativeType.includes('char*')) { - impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = ${param.name};\n` + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = ${name};\n` + } + else if (param.nativeType.includes('_t')) { + impl += ` ${jsonType}& ${capitalize(name)}Container = *(*(reinterpret_cast*>(${camelcase(name)})));\n` + impl += ` string ${capitalize(name)}Str;\n` + impl += ` ${capitalize(name)}Container.ToString(${capitalize(name)}Str);\n` + impl += ` WPEFramework::Core::JSON::VariantContainer ${capitalize(name)}VariantContainer(${capitalize(name)}Str);\n` + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = ${capitalize(name)}VariantContainer;\n` } else { - impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = *(${param.name});\n` + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = *(${name});\n` } - impl += ` jsonParameters.Set(_T("${param.name}"), ${capitalize(param.name)});\n` + impl += ` jsonParameters.Set(_T("${name}"), ${capitalize(name)});\n` impl += ` }` } impl += '\n' @@ -347,7 +366,7 @@ function getCallbackParametersInstantiation(paramList, container = '') { } }) impl += `\n WPEFramework::Core::ProxyType<${container}>* jsonResponse;\n` - impl += ` WPEFramework::Core::ProxyType& var = *(static_cast*>(response)); + impl += ` WPEFramework::Core::ProxyType& var = *(reinterpret_cast*>(response)); ASSERT(var.IsValid() == true); if (var.IsValid() == true) { @@ -378,7 +397,7 @@ function getCallbackParametersInstantiation(paramList, container = '') { if (param.nativeType === 'char*') { contextParams += ` ${getSdkNameSpace()}::JSON::String* ${param.name}Value = new ${getSdkNameSpace()}::JSON::String(); *${param.name}Value = elements.Current().Value().c_str(); - ${param.name} = ${param.name}Value;\n` + ${param.name} = reinterpret_cast<${getFireboltStringType()}>(${param.name}Value);\n` } else if (param.nativeType === 'bool') { contextParams += ` ${param.name} = elements.Current().Boolean();\n` @@ -402,7 +421,7 @@ function getCallbackParametersInstantiation(paramList, container = '') { }\n` } else { - impl +=` WPEFramework::Core::ProxyType<${container}>* jsonResponse = static_cast*>(response);\n` + impl +=` WPEFramework::Core::ProxyType<${container}>* jsonResponse = reinterpret_cast*>(response);\n` } return impl @@ -410,7 +429,7 @@ function getCallbackParametersInstantiation(paramList, container = '') { function getCallbackResultInstantiation(nativeType, container = '') { let impl = '' - if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + if (nativeType === 'char*' || nativeType === 'FireboltTypes_String_t') { impl +=` ${container}* jsonStrResponse = new ${container}(); *jsonStrResponse = *(*jsonResponse); @@ -426,7 +445,7 @@ function getCallbackResponseInstantiation(paramList, nativeType, container = '') paramList.forEach(param => { if (param.required !== undefined) { if (param.nativeType === 'char*') { - impl += `static_cast<${getFireboltStringType()}>(${param.name}), ` + impl += `reinterpret_cast<${getFireboltStringType()}>(${param.name}), ` } else if (param.required === true) { impl += `${param.name}, ` @@ -438,11 +457,11 @@ function getCallbackResponseInstantiation(paramList, nativeType, container = '') }) } - if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { - impl += `static_cast<${nativeType}>(jsonStrResponse)` + if (nativeType === 'char*' || nativeType === 'FireboltTypes_String_t') { + impl += `reinterpret_cast<${nativeType}>(jsonStrResponse)` } - else if (nativeType.includes('Handle')) { - impl += `static_cast<${nativeType}>(jsonResponse)` + else if (nativeType.includes('_t')) { + impl += `reinterpret_cast<${nativeType}>(jsonResponse)` } else { impl += `static_cast<${nativeType}>((*jsonResponse)->Value())` @@ -457,16 +476,16 @@ function getResultInstantiation (name, nativeType, container, indentLevel = 3) { if (nativeType) { impl += `${' '.repeat(indentLevel)}if (${name} != nullptr) {` + '\n' - if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + if (nativeType === 'char*' || nativeType === 'FireboltTypes_String_t') { impl += `${' '.repeat(indentLevel + 1)}${container}* strResult = new ${container}(jsonResult);` + '\n' - impl += `${' '.repeat(indentLevel + 1)}*${name} = static_cast<${getFireboltStringType()}>(strResult);` - } else if (nativeType.includes('Handle')) { + impl += `${' '.repeat(indentLevel + 1)}*${name} = reinterpret_cast<${getFireboltStringType()}>(strResult);` + '\n' + } else if (nativeType.includes('_t')) { impl += `${' '.repeat(indentLevel + 1)}WPEFramework::Core::ProxyType<${container}>* resultPtr = new WPEFramework::Core::ProxyType<${container}>();\n` impl += `${' '.repeat(indentLevel + 1)}*resultPtr = WPEFramework::Core::ProxyType<${container}>::Create();\n` impl += `${' '.repeat(indentLevel + 1)}*(*resultPtr) = jsonResult;\n` - impl += `${' '.repeat(indentLevel + 1)}*${name} = static_cast<${nativeType}>(resultPtr);` - } else { - impl += `${' '.repeat(indentLevel + 1)}*${name} = jsonResult.Value();` + impl += `${' '.repeat(indentLevel + 1)}*${name} = reinterpret_cast<${nativeType}>(resultPtr);` + '\n' + } else { + impl += `${' '.repeat(indentLevel + 1)}*${name} = jsonResult.Value();` + '\n' } impl += `${' '.repeat(indentLevel)}}` + '\n' } else if (name === 'success') { diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index b2a260b5..cc31b14a 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -52,5 +52,6 @@ function getJsonContainerDefinition (schema, name, props) { export { getJsonContainerDefinition, - getJsonDataStructName + getJsonDataStructName, + getJsonDataPrefix } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 1460e22e..7bfef987 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -29,7 +29,7 @@ const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = pre const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' -const getFireboltStringType = () => 'FireboltTypes_StringHandle' +const getFireboltStringType = () => 'FireboltTypes_String_t' const getHeaderText = () => { return `/* @@ -42,40 +42,6 @@ const getHeaderText = () => { ` } -const getIncludeGuardOpen = (json, prefix=null) => { - prefix = prefix ? `${prefix.toUpperCase()}_` : '' - return ` -#ifndef _${prefix}${getModuleName(json).toUpperCase()}_H -#define _${prefix}${getModuleName(json).toUpperCase()}_H - -` -} - -const getStyleGuardOpen = () => { - return ` -#ifdef __cplusplus -extern "C" { -#endif - -` -} - -const getStyleGuardClose = () => { - return ` - -#ifdef __cplusplus -} -#endif - -` -} - -const getIncludeGuardClose = () => { - return ` -#endif // Header Include Guard -` -} - const capitalize = str => str[0].toUpperCase() + str.substr(1) const description = (title, str='') => '/* ' + title + (str.length > 0 ? ' - ' + str : '') + ' */' const isOptional = (prop, json) => (!json.required || !json.required.includes(prop)) @@ -142,26 +108,26 @@ const getNativeType = (json, fireboltString = false) => { const getObjectHandleManagement = varName => { - let result = `typedef void* ${varName}Handle; -${varName}Handle ${varName}Handle_Create(void); -void ${varName}Handle_Addref(${varName}Handle handle); -void ${varName}Handle_Release(${varName}Handle handle); -bool ${varName}Handle_IsValid(${varName}Handle handle); + let result = `typedef struct ${varName}_s* ${varName}_t; +${varName}_t ${varName}Handle_Acquire(void); +void ${varName}Handle_Addref(${varName}_t handle); +void ${varName}Handle_Release(${varName}_t handle); +bool ${varName}Handle_IsValid(${varName}_t handle); ` return result } const getPropertyAccessors = (objName, propertyName, propertyType, options = {level:0, readonly:false, optional:false}) => { - let result = `${Indent.repeat(options.level)}${propertyType} ${objName}_Get_${propertyName}(${objName}Handle handle);` + '\n' + let result = `${Indent.repeat(options.level)}${propertyType} ${objName}_Get_${propertyName}(${objName}_t handle);` + '\n' if (!options.readonly) { let type = (propertyType === getFireboltStringType()) ? 'char*' : propertyType - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${type} ${propertyName.toLowerCase()});` + '\n' + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}_t handle, ${type} ${propertyName.toLowerCase()});` + '\n' } if (options.optional === true) { - result += `${Indent.repeat(options.level)}bool ${objName}_Has_${propertyName}(${objName}Handle handle);` + '\n' - result += `${Indent.repeat(options.level)}void ${objName}_Clear_${propertyName}(${objName}Handle handle);` + '\n' + result += `${Indent.repeat(options.level)}bool ${objName}_Has_${propertyName}(${objName}_t handle);` + '\n' + result += `${Indent.repeat(options.level)}void ${objName}_Clear_${propertyName}(${objName}_t handle);` + '\n' } return result @@ -171,10 +137,10 @@ const getMapAccessors = (typeName, accessorPropertyType, level = 0) => { let res - res = `${Indent.repeat(level)}uint32_t ${typeName}_KeysCount(${typeName}Handle handle);` + '\n' - res += `${Indent.repeat(level)}void ${typeName}_AddKey(${typeName}Handle handle, char* key, ${accessorPropertyType} value);` + '\n' - res += `${Indent.repeat(level)}void ${typeName}_RemoveKey(${typeName}Handle handle, char* key);` + '\n' - res += `${Indent.repeat(level)}${accessorPropertyType} ${typeName}_FindKey(${typeName}Handle handle, char* key);` + '\n' + res = `${Indent.repeat(level)}uint32_t ${typeName}_KeysCount(${typeName}_t handle);` + '\n' + res += `${Indent.repeat(level)}void ${typeName}_AddKey(${typeName}_t handle, char* key, ${accessorPropertyType} value);` + '\n' + res += `${Indent.repeat(level)}void ${typeName}_RemoveKey(${typeName}_t handle, char* key);` + '\n' + res += `${Indent.repeat(level)}${accessorPropertyType} ${typeName}_FindKey(${typeName}_t handle, char* key);` + '\n' return res } @@ -193,10 +159,10 @@ const getTypeName = (moduleName, varName, prefix = '', upperCase = false, capita const getArrayAccessors = (arrayName, propertyType, valueType) => { - let res = `uint32_t ${arrayName}Array_Size(${propertyType}Handle handle);` + '\n' - res += `${valueType} ${arrayName}Array_Get(${propertyType}Handle handle, uint32_t index);` + '\n' - res += `void ${arrayName}Array_Add(${propertyType}Handle handle, ${valueType} value);` + '\n' - res += `void ${arrayName}Array_Clear(${propertyType}Handle handle);` + '\n' + let res = `uint32_t ${arrayName}Array_Size(${propertyType}_t handle);` + '\n' + res += `${valueType} ${arrayName}Array_Get(${propertyType}_t handle, uint32_t index);` + '\n' + res += `void ${arrayName}Array_Add(${propertyType}_t handle, ${valueType} value);` + '\n' + res += `void ${arrayName}Array_Clear(${propertyType}_t handle);` + '\n' return res } @@ -270,10 +236,6 @@ function getPropertyEventUnregisterSignature(property, module) { export { getHeaderText, - getIncludeGuardOpen, - getStyleGuardOpen, - getStyleGuardClose, - getIncludeGuardClose, getNativeType, getModuleName, getPropertyGetterSignature, diff --git a/languages/c/templates/imports/default.cpp b/languages/c/templates/imports/default.cpp index 69e241f9..caf84bc9 100644 --- a/languages/c/templates/imports/default.cpp +++ b/languages/c/templates/imports/default.cpp @@ -1 +1 @@ -#include "JsonData_${info.title}.h" +#include "jsondata_${info.title.lowercase}.h" diff --git a/languages/c/templates/imports/default.h b/languages/c/templates/imports/default.h index a38b58ef..56a97a40 100644 --- a/languages/c/templates/imports/default.h +++ b/languages/c/templates/imports/default.h @@ -1 +1 @@ -#include "Common/${info.title}.h" +#include "common/${info.title.lowercase}.h" diff --git a/languages/c/templates/imports/default.jsondata b/languages/c/templates/imports/default.jsondata index 69e241f9..caf84bc9 100644 --- a/languages/c/templates/imports/default.jsondata +++ b/languages/c/templates/imports/default.jsondata @@ -1 +1 @@ -#include "JsonData_${info.title}.h" +#include "jsondata_${info.title.lowercase}.h" diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/module.h similarity index 92% rename from languages/c/templates/modules/include/Module.h rename to languages/c/templates/modules/include/module.h index a202f643..00c5d595 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/module.h @@ -16,10 +16,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _${info.TITLE}_H -#define _${info.TITLE}_H +#ifndef ${info.TITLE}_H +#define ${info.TITLE}_H -#include "Firebolt.h" +#include /* ${IMPORTS} */ #ifdef __cplusplus diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/module.cpp similarity index 93% rename from languages/c/templates/modules/src/Module.cpp rename to languages/c/templates/modules/src/module.cpp index 65721f1e..2b467ae1 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/module.cpp @@ -18,10 +18,10 @@ #include "FireboltSDK.h" /* ${IMPORTS} */ -#include "${info.title}.h" +#include "${info.title.lowercase}.h" namespace FireboltSDK { - namespace ${info.title} { + namespace ${info.Title} { // Types /* ${TYPES} */ } diff --git a/languages/c/templates/schemas/include/Common/Module.h b/languages/c/templates/schemas/include/common/module.h similarity index 90% rename from languages/c/templates/schemas/include/Common/Module.h rename to languages/c/templates/schemas/include/common/module.h index ff037fba..939b3988 100644 --- a/languages/c/templates/schemas/include/Common/Module.h +++ b/languages/c/templates/schemas/include/common/module.h @@ -16,10 +16,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _COMMON_${info.TITLE}_H -#define _COMMON_${info.TITLE}_H +#ifndef COMMON_${info.TITLE}_H +#define COMMON_${info.TITLE}_H -#include "Firebolt.h" +#include /* ${IMPORTS} */ #ifdef __cplusplus diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/jsondata_module.h similarity index 91% rename from languages/c/templates/schemas/src/JsonData_Module.h rename to languages/c/templates/schemas/src/jsondata_module.h index d0ecbbac..f80be03e 100644 --- a/languages/c/templates/schemas/src/JsonData_Module.h +++ b/languages/c/templates/schemas/src/jsondata_module.h @@ -19,10 +19,10 @@ #pragma once /* ${IMPORTS} */ -#include "Common/${info.title}.h" +#include "common/${info.title.lowercase}.h" namespace FireboltSDK { - namespace ${info.title} { + namespace ${info.Title} { // Types /* ${SCHEMAS} */ diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/module_common.cpp similarity index 94% rename from languages/c/templates/schemas/src/Module_Common.cpp rename to languages/c/templates/schemas/src/module_common.cpp index 0ccdfc28..0d8c74d2 100644 --- a/languages/c/templates/schemas/src/Module_Common.cpp +++ b/languages/c/templates/schemas/src/module_common.cpp @@ -18,7 +18,7 @@ #include "FireboltSDK.h" /* ${IMPORTS} */ -#include "JsonData_${info.title}.h" +#include "jsondata_${info.title.lowercase}.h" /* ${ENUMS} */ diff --git a/languages/c/templates/sdk/include/Error.h b/languages/c/templates/sdk/include/error.h similarity index 93% rename from languages/c/templates/sdk/include/Error.h rename to languages/c/templates/sdk/include/error.h index 87cda9dd..07d6268a 100644 --- a/languages/c/templates/sdk/include/Error.h +++ b/languages/c/templates/sdk/include/error.h @@ -16,8 +16,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _FIREBOLT_ERROR_H -#define _FIREBOLT_ERROR_H +#ifndef FIREBOLT_ERROR_H +#define FIREBOLT_ERROR_H #ifdef __cplusplus extern "C" { @@ -38,4 +38,4 @@ typedef enum FireboltSDKError { } #endif -#endif // _FIREBOLT_ERROR_H +#endif // FIREBOLT_ERROR_H diff --git a/languages/c/templates/sdk/include/Firebolt.h b/languages/c/templates/sdk/include/firebolt.h similarity index 93% rename from languages/c/templates/sdk/include/Firebolt.h rename to languages/c/templates/sdk/include/firebolt.h index 2223bad3..0957973f 100644 --- a/languages/c/templates/sdk/include/Firebolt.h +++ b/languages/c/templates/sdk/include/firebolt.h @@ -16,11 +16,11 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _FIREBOLT_H -#define _FIREBOLT_H +#ifndef FIREBOLT_H +#define FIREBOLT_H -#include "Error.h" -#include "Types.h" +#include "error.h" +#include "types.h" #ifdef __cplusplus extern "C" { @@ -62,4 +62,4 @@ uint32_t FireboltSDK_Deinitialize(void); #endif -#endif // _FIREBOLT_H +#endif // FIREBOLT_H diff --git a/languages/c/templates/sdk/include/Types.h b/languages/c/templates/sdk/include/types.h similarity index 73% rename from languages/c/templates/sdk/include/Types.h rename to languages/c/templates/sdk/include/types.h index 4fd16256..26efc54f 100644 --- a/languages/c/templates/sdk/include/Types.h +++ b/languages/c/templates/sdk/include/types.h @@ -16,8 +16,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _FIREBOLT_TYPES_H -#define _FIREBOLT_TYPES_H +#ifndef FIREBOLT_TYPES_H +#define FIREBOLT_TYPES_H #include #include @@ -26,12 +26,12 @@ extern "C" { #endif -typedef void* FireboltTypes_StringHandle; -const char* FireboltTypes_String(FireboltTypes_StringHandle handle); -void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle); +typedef struct FireboltTypes_String_s* FireboltTypes_String_t; +const char* FireboltTypes_String(FireboltTypes_String_t handle); +void FireboltTypes_StringHandle_Release(FireboltTypes_String_t handle); #ifdef __cplusplus } #endif -#endif // _FIREBOLT_TYPES_H +#endif // FIREBOLT_TYPES_H diff --git a/languages/c/templates/sdk/scripts/build.sh b/languages/c/templates/sdk/scripts/build.sh index e9b01f20..d50295a6 100755 --- a/languages/c/templates/sdk/scripts/build.sh +++ b/languages/c/templates/sdk/scripts/build.sh @@ -1,11 +1,37 @@ #!/bin/bash -SDK_PATH="." -if [ "$1" != "" ] +usage() +{ + echo "options:" + echo " -p sdk path" + echo " -s sysroot path" + echo " -t enable test" + echo " -c clear build" + echo " -h : help" + echo + echo "usage: " + echo " ./build.sh -p path -tc" +} + +SdkPath="." +EnableTest="OFF" +SysrootPath=${SYSROOT_PATH} +ClearBuild="N" +while getopts p:s:tch flag +do + case "${flag}" in + p) SdkPath="${OPTARG}";; + s) SysrootPath="${OPTARG}";; + t) EnableTest="ON";; + c) ClearBuild="Y";; + h) usage && exit 1;; + esac +done + +if [ "${ClearBuild}" == "Y" ]; then - SDK_PATH=$1 - echo "inside ${1}" + rm -rf ${SdkPath}/build fi -echo ${SDK_PATH} -rm -rf ${SDK_PATH}/build -cmake -B${SDK_PATH}/build -S${SDK_PATH} -DSYSROOT_PATH=${SYSROOT_PATH} -cmake --build ${SDK_PATH}/build + +cmake -B${SdkPath}/build -S${SdkPath} -DSYSROOT_PATH=${SysrootPath} -DENABLE_TESTS=${EnableTest} +cmake --build ${SdkPath}/build +cmake --install ${SdkPath}/build --prefix=${SdkPath}/build/Firebolt diff --git a/languages/c/templates/sdk/src/CMakeLists.txt b/languages/c/templates/sdk/src/CMakeLists.txt index 2f00bdf1..b565d6b1 100644 --- a/languages/c/templates/sdk/src/CMakeLists.txt +++ b/languages/c/templates/sdk/src/CMakeLists.txt @@ -20,7 +20,6 @@ project(FireboltSDK) project_version(1.0.0) set(TARGET ${PROJECT_NAME}) message("Setup ${TARGET} v${PROJECT_VERSION}") -file(GLOB GENERATED_SOURCES "${GENERATED_CODE_PATH}/src/*.cpp") file(GLOB SOURCES *.cpp) add_library(${TARGET} ${FIREBOLT_LIBRARY_TYPE} @@ -41,8 +40,6 @@ target_link_libraries(${TARGET} target_include_directories(${TARGET} PRIVATE - $ - $ $ $ ) @@ -64,8 +61,6 @@ install( ) InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION ${FIREBOLT_NAMESPACE}SDK) -InstallHeaders(TARGET ${TARGET} EXCLUDE_ROOT_DIR HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} - SOURCE ${GENERATED_CODE_PATH}/include DESTINATION ${FIREBOLT_NAMESPACE}/generated) InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../include DESTINATION ${FIREBOLT_NAMESPACE}) diff --git a/languages/c/templates/sdk/src/FireboltSDK.h b/languages/c/templates/sdk/src/FireboltSDK.h index 19946126..d78687dc 100644 --- a/languages/c/templates/sdk/src/FireboltSDK.h +++ b/languages/c/templates/sdk/src/FireboltSDK.h @@ -23,4 +23,4 @@ #include "Accessor/Accessor.h" #include "Logger/Logger.h" #include "TypesPriv.h" -#include "Types.h" +#include "types.h" diff --git a/languages/c/templates/sdk/src/Logger/Logger.cpp b/languages/c/templates/sdk/src/Logger/Logger.cpp index 0e49dfce..a9750a6e 100644 --- a/languages/c/templates/sdk/src/Logger/Logger.cpp +++ b/languages/c/templates/sdk/src/Logger/Logger.cpp @@ -17,7 +17,7 @@ */ #include "Module.h" -#include "Error.h" +#include "error.h" #include "Logger.h" namespace WPEFramework { diff --git a/languages/c/templates/sdk/src/Logger/Logger.h b/languages/c/templates/sdk/src/Logger/Logger.h index cffeff54..2c864c7b 100644 --- a/languages/c/templates/sdk/src/Logger/Logger.h +++ b/languages/c/templates/sdk/src/Logger/Logger.h @@ -18,7 +18,7 @@ #pragma once -#include "Types.h" +#include "types.h" namespace FireboltSDK { diff --git a/languages/c/templates/sdk/src/Transport/Transport.h b/languages/c/templates/sdk/src/Transport/Transport.h index d12312a5..109e2431 100644 --- a/languages/c/templates/sdk/src/Transport/Transport.h +++ b/languages/c/templates/sdk/src/Transport/Transport.h @@ -19,7 +19,7 @@ #pragma once #include "Module.h" -#include "Error.h" +#include "error.h" namespace FireboltSDK { diff --git a/languages/c/templates/sdk/src/Types.cpp b/languages/c/templates/sdk/src/Types.cpp index f19cfe63..b9620436 100644 --- a/languages/c/templates/sdk/src/Types.cpp +++ b/languages/c/templates/sdk/src/Types.cpp @@ -17,7 +17,7 @@ */ #include "Module.h" -#include "Types.h" +#include "types.h" #include "TypesPriv.h" #ifdef __cplusplus @@ -25,14 +25,14 @@ extern "C" { #endif // String Type Handler Interfaces -const char* FireboltTypes_String(FireboltTypes_StringHandle handle) +const char* FireboltTypes_String(FireboltTypes_String_t handle) { - return ((static_cast(handle))->Value().c_str()); + return ((reinterpret_cast(handle))->Value().c_str()); } -void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle) +void FireboltTypes_StringHandle_Release(FireboltTypes_String_t handle) { - delete static_cast(handle); + delete reinterpret_cast(handle); } #ifdef __cplusplus diff --git a/languages/c/templates/sdk/src/Firebolt.cpp b/languages/c/templates/sdk/src/firebolt.cpp similarity index 100% rename from languages/c/templates/sdk/src/Firebolt.cpp rename to languages/c/templates/sdk/src/firebolt.cpp diff --git a/languages/c/templates/sdk/test/CMakeLists.txt b/languages/c/templates/sdk/test/CMakeLists.txt index a56ca20a..21ee1f55 100644 --- a/languages/c/templates/sdk/test/CMakeLists.txt +++ b/languages/c/templates/sdk/test/CMakeLists.txt @@ -57,7 +57,7 @@ install( InstallCMakeConfig(TARGETS ${TESTLIB}) InstallCMakeConfigs(TARGET ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) InstallHeaders(TARGET ${TESTLIB} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION FireboltTest) -InstallLibraries(TARGET ${TESTLIB} LIBRARIES ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallLibraries(TARGET ${TESTLIB} STATIC LIBRARIES ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) set(TESTAPP "FireboltSDKTestApp") diff --git a/languages/c/templates/sdk/test/Main.c b/languages/c/templates/sdk/test/Main.c index 7c4c94a5..6161792e 100644 --- a/languages/c/templates/sdk/test/Main.c +++ b/languages/c/templates/sdk/test/Main.c @@ -35,6 +35,7 @@ int main() EXECUTE("test_properties_set", test_properties_set); EXECUTE("test_eventregister_by_providing_callback", test_eventregister_by_providing_callback); EXECUTE("test_eventregister", test_eventregister); + EXECUTE("test_eventregister_with_same_callback", test_eventregister_with_same_callback); EXECUTE("test_string_set_get_value", test_string_set_get_value); test_firebolt_dispose_instance(); diff --git a/languages/c/templates/sdk/test/Module.h b/languages/c/templates/sdk/test/Module.h index d5340b68..a147ff75 100644 --- a/languages/c/templates/sdk/test/Module.h +++ b/languages/c/templates/sdk/test/Module.h @@ -23,7 +23,6 @@ #endif #include -#include #undef EXTERNAL #define EXTERNAL diff --git a/languages/c/templates/sdk/test/OpenRPCCTests.h b/languages/c/templates/sdk/test/OpenRPCCTests.h index 7f2fb59e..4fe5eb5b 100644 --- a/languages/c/templates/sdk/test/OpenRPCCTests.h +++ b/languages/c/templates/sdk/test/OpenRPCCTests.h @@ -16,8 +16,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _OPENRPC_C_TESTS_H -#define _OPENRPC_C_TESTS_H +#ifndef OPENRPC_C_TESTS_H +#define OPENRPC_C_TESTS_H #include "TestUtils.h" @@ -25,13 +25,14 @@ extern "C" { #endif -uint32_t test_firebolt_create_instance(); -uint32_t test_firebolt_dispose_instance(); +void test_firebolt_create_instance(); +void test_firebolt_dispose_instance(); uint32_t test_firebolt_main(); uint32_t test_properties_get_device_id(); uint32_t test_properties_set(); uint32_t test_eventregister(); +uint32_t test_eventregister_with_same_callback(); uint32_t test_eventregister_by_providing_callback(); uint32_t test_string_set_get_value(); @@ -39,4 +40,4 @@ uint32_t test_string_set_get_value(); } #endif -#endif // _OPENRPC_C_TESTS_H +#endif // OPENRPC_C_TESTS_H diff --git a/languages/c/templates/sdk/test/OpenRPCTests.cpp b/languages/c/templates/sdk/test/OpenRPCTests.cpp index cf9ea5a0..b74f17ae 100644 --- a/languages/c/templates/sdk/test/OpenRPCTests.cpp +++ b/languages/c/templates/sdk/test/OpenRPCTests.cpp @@ -38,11 +38,20 @@ ENUM_CONVERSION_BEGIN(TestEnum) { TestEnum::Test4, _TXT("Test4ValueCheck") }, ENUM_CONVERSION_END(TestEnum) } + +typedef void (*OnNotifyDeviceNameChanged)(const void* userData, const char* data); +static void NotifyEvent(const void* userData, const char* data) +{ + printf("NotifyEvent data : %s\n", data); +} + namespace FireboltSDK { Tests::Tests() { _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEventWithMultipleCallback"), std::forward_as_tuple(&SubscribeEventWithMultipleCallback)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEventwithSameCallback"), + std::forward_as_tuple(&SubscribeEventwithSameCallback)); _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEvent"), std::forward_as_tuple(&SubscribeEvent)); @@ -147,25 +156,55 @@ namespace FireboltSDK { return status; } - static void deviceNameChangeCallback(const void* userData, void* response) + static void deviceNameChangeCallback(void* userCB, const void* userData, void* response) { - WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + WPEFramework::Core::ProxyType& jsonResponse = *(reinterpret_cast*>(response)); FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Received a new event: %s", jsonResponse->Value().c_str()); - jsonResponse.Release(); FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + OnNotifyDeviceNameChanged notifyDeviceNameChanged = reinterpret_cast(userCB); + notifyDeviceNameChanged(userData, jsonResponse->Value().c_str()); eventControl->NotifyEvent(); + jsonResponse.Release(); } /* static */ uint32_t Tests::SubscribeEvent() { - FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl("EventControl"); const string eventName = _T("device.Name"); const void* userdata = static_cast(eventControl); - uint32_t id = 0; + eventControl->ResetEvent(); + + JsonObject jsonParameters; + uint32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), + "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered successfully, Waiting for event...", __func__); + + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + delete eventControl; + + return status; + } + + /* static */ uint32_t Tests::SubscribeEventwithSameCallback() + { + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl("EventControl"); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); eventControl->ResetEvent(); - uint32_t status = Properties::Subscribe(eventName, deviceNameChangeCallback, userdata, id); + + JsonObject jsonParameters; + uint32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -174,40 +213,71 @@ namespace FireboltSDK { } else { FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "%s Yes registered successfully", __func__); - eventControl->WaitForEvent(WPEFramework::Core::infinite); + + status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback, reinterpret_cast(NotifyEvent), userdata); + EXPECT_EQ(status, FireboltSDKErrorInUse); + if (status == FireboltSDKErrorInUse) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes this device.name event is already registered with same callback", __func__); + } + status = ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone : status); } - EXPECT_EQ(Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); delete eventControl; return status; } + + static void NotifyEvent1(const void* userData, const char* data) + { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent1 data : %s", data); + if (userData) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent1 userData : %s\n", reinterpret_cast(userData)->Name().c_str()); + } + } + static void NotifyEvent2(const void* userData, const char* data) + { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent2 data : %s", data); + if (userData) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent2 userData : %s\n", reinterpret_cast(userData)->Name().c_str()); + } + } + template - /* static */ uint32_t Tests::SubscribeEventForC(const string& eventName, CALLBACK& callbackFunc, const void* userdata, uint32_t& id) + /* static */ uint32_t Tests::SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata) { - return Properties::Subscribe(eventName, callbackFunc, userdata, id);; + return Properties::Subscribe(eventName, jsonParameters, callbackFunc, usercb, userdata); } - static void deviceNameChangeMultipleCallback(const void* userData, void* response) + static void deviceNameChangeMultipleCallback(void* userCB, const void* userData, void* response) { - WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + WPEFramework::Core::ProxyType& jsonResponse = *(reinterpret_cast*>(response)); FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Received a new event from deviceNameChangeMultipleCallback: %s", jsonResponse->Value().c_str()); - jsonResponse.Release(); FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + OnNotifyDeviceNameChanged notifyDeviceNameChanged = reinterpret_cast(userCB); + notifyDeviceNameChanged(userData, jsonResponse->Value().c_str()); + eventControl->NotifyEvent(); + jsonResponse.Release(); } /* static */ uint32_t Tests::SubscribeEventWithMultipleCallback() { - FireboltSDK::Tests::EventControl* eventControl1 = new FireboltSDK::Tests::EventControl(); + FireboltSDK::Tests::EventControl* eventControl1 = new FireboltSDK::Tests::EventControl("EventControl1"); const string eventName = _T("device.Name"); const void* userdata = static_cast(eventControl1); - uint32_t id1 = 0, id2 = 0; eventControl1->ResetEvent(); - uint32_t status = Properties::Subscribe(eventName, deviceNameChangeCallback, userdata, id1); + + JsonObject jsonParameters; + uint32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent1), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -215,28 +285,33 @@ namespace FireboltSDK { "Set %s status = %d", eventName.c_str(), status); } else { FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), - "%s Yes registered successfully", __func__); + "%s Yes registered successfully, Waiting for event...", __func__); } if (status == FireboltSDKErrorNone) { - FireboltSDK::Tests::EventControl* eventControl2 = new FireboltSDK::Tests::EventControl(); + FireboltSDK::Tests::EventControl* eventControl2 = new FireboltSDK::Tests::EventControl("EventControl2"); userdata = static_cast(eventControl2); - status = Properties::Subscribe(eventName, deviceNameChangeMultipleCallback, userdata, id2); + status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent2), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", eventName.c_str(), status); } else { + status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent2), userdata); + EXPECT_EQ(status, FireboltSDKErrorInUse); + status = ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone : status); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), - "%s Yes registered second callback also successfully", __func__); + "%s Yes registered second callback also successfully, waiting for events...\n", __func__); + eventControl1->WaitForEvent(WPEFramework::Core::infinite); eventControl2->WaitForEvent(WPEFramework::Core::infinite); } - EXPECT_EQ(Properties::Unsubscribe(eventName, id1), FireboltSDKErrorNone); + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent2)), FireboltSDKErrorNone); delete eventControl2; } - EXPECT_EQ(Properties::Unsubscribe(eventName, id2), FireboltSDKErrorNone); + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent1)), FireboltSDKErrorNone); delete eventControl1; return status; @@ -248,12 +323,21 @@ namespace FireboltSDK { extern "C" { #endif -uint32_t test_firebolt_create_instance() +void test_firebolt_create_instance() { - FireboltSDK::Accessor::Instance(); + 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); } -uint32_t test_firebolt_dispose_instance() +void test_firebolt_dispose_instance() { FireboltSDK::Accessor::Dispose(); } @@ -297,28 +381,27 @@ uint32_t test_properties_set() return status; } -static void deviceNameChangeCallbackForC(const void* userData, void* response) +static void deviceNameChangeCallbackForC(void* userCB, const void* userData, void* response) { - WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + WPEFramework::Core::ProxyType& jsonResponse = *(reinterpret_cast*>(response)); FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", "Received a new event--->: %s", jsonResponse->Value().c_str()); - jsonResponse.Release(); FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); eventControl->NotifyEvent(); + jsonResponse.Release(); } uint32_t test_eventregister() { FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); - JsonObject parameters; - const string eventName = _T("device.Name"); const void* userdata = static_cast(eventControl); - uint32_t id = 0; eventControl->ResetEvent(); - uint32_t status = FireboltSDK::Properties::Subscribe(eventName, deviceNameChangeCallbackForC, userdata, id); + + JsonObject jsonParameters; + uint32_t status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -326,26 +409,60 @@ uint32_t test_eventregister() "%s Set %s status = %d", __func__, eventName.c_str(), status); } else { FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "%s Yes registered successfully", __func__); + "%s Yes registered successfully, Waiting for event...", __func__); eventControl->WaitForEvent(WPEFramework::Core::infinite); } delete eventControl; - EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); return status; } +uint32_t test_eventregister_with_same_callback() +{ + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + + eventControl->ResetEvent(); + + JsonObject jsonParameters; + uint32_t status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Set %s status = %d", __func__, eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes registered successfully", __func__); + + status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); + EXPECT_EQ(status, FireboltSDKErrorInUse); + if (status == FireboltSDKErrorInUse) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes this device.name event is already registered with same callback", __func__); + } + status = ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone : status); + } + + delete eventControl; + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + + return status; +} uint32_t test_eventregister_by_providing_callback() { FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); const string eventName = _T("device.Name"); const void* userdata = static_cast(eventControl); - uint32_t id = 0; eventControl->ResetEvent(); - uint32_t status = FireboltSDK::Tests::SubscribeEventForC(eventName, deviceNameChangeCallbackForC, userdata, id); + + JsonObject jsonParameters; + uint32_t status = FireboltSDK::Tests::SubscribeEventForC(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -353,20 +470,22 @@ uint32_t test_eventregister_by_providing_callback() "%s Set %s status = %d", __func__, eventName.c_str(), status); } else { FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "%s Yes registered successfully", __func__); + "%s Yes registered successfully, Waiting for event...", __func__); eventControl->WaitForEvent(WPEFramework::Core::infinite); } delete eventControl; - EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + return status; } #include "TypesPriv.h" uint32_t test_string_set_get_value() { uint32_t status = FireboltSDKErrorNone; - FireboltSDK::String* str = new FireboltSDK::String("testString"); - void* handle = static_cast(str); + FireboltSDK::JSON::String* str = new FireboltSDK::JSON::String(); + WPEFramework::Core::JSON::String wpeJsonStr("TestString"); + FireboltTypes_String_t handle = reinterpret_cast(str); const char* value = FireboltTypes_String(handle); EXPECT_EQ(strncmp(value, str->Value().c_str(), str->Value().length()), 0); diff --git a/languages/c/templates/sdk/test/OpenRPCTests.h b/languages/c/templates/sdk/test/OpenRPCTests.h index 00abd364..e82665d0 100644 --- a/languages/c/templates/sdk/test/OpenRPCTests.h +++ b/languages/c/templates/sdk/test/OpenRPCTests.h @@ -18,8 +18,15 @@ #pragma once +#include "FireboltSDK.h" #include "TestUtils.h" -#include "Firebolt.h" + +typedef enum { + Test1, + Test2, + Test3, + Test4 +} TestEnum; namespace FireboltSDK { typedef uint32_t (*Func)(); @@ -30,6 +37,12 @@ namespace FireboltSDK { public: EventControl() : _event(false, true) + , _name("EventControl") + { + } + EventControl(string name) + : _event(false, true) + , _name(name) { } ~EventControl() = default; @@ -47,8 +60,13 @@ namespace FireboltSDK { { _event.ResetEvent(); } + string Name() const + { + return _name; + } private: WPEFramework::Core::Event _event; + string _name; }; private: @@ -84,10 +102,11 @@ namespace FireboltSDK { static uint32_t SetUnKnownMethod(); static uint32_t SubscribeEvent(); + static uint32_t SubscribeEventwithSameCallback(); static uint32_t SubscribeEventWithMultipleCallback(); template - static uint32_t SubscribeEventForC(const string& eventName, CALLBACK& callbackFunc, const void* userdata, uint32_t& id); + static uint32_t SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata); protected: static void PrintJsonObject(const JsonObject::Iterator& iterator); diff --git a/languages/c/templates/sdk/test/TestUtils.h b/languages/c/templates/sdk/test/TestUtils.h index 8c3cb732..c54db9f0 100644 --- a/languages/c/templates/sdk/test/TestUtils.h +++ b/languages/c/templates/sdk/test/TestUtils.h @@ -1,5 +1,5 @@ -#ifndef _TEST_UTILS_H -#define _TEST_UTILS_H +#ifndef TEST_UTILS_H +#define TEST_UTILS_H #include #include @@ -8,8 +8,8 @@ #define MAX(x, y) (((x) > (y)) ? (x) : (y)) #define MIN(x, y) (((x) < (y)) ? (x) : (y)) -#define _RESULT(expr, exprorig, result) if (expr) { printf(" SUCCESS: %s\n", #exprorig); __pass++; } else printf(" FAILED: %s, actual: %u\n", #exprorig, result) -#define _EVAL(result, expected, op) do { __cnt++; uint32_t resval = ((uint32_t)(result)); uint32_t expval = ((uint32_t)(expected)); _RESULT(resval op expval, result op expected, resval); } while(0) +#define _RESULT(expr, exprorig, result) if (expr) { printf("TestStatus: SUCCESS: %s\n", #exprorig); __pass++; } else printf("TestStatus: FAILED: %s, actual: %lu\n", #exprorig, result) +#define _EVAL(result, expected, op) do { __cnt++; long resval = ((long)(result)); long expval = ((long)(expected)); _RESULT(resval op expval, result op expected, resval); } while(0) #define _HEAD(name) printf("\n======== %s\n", name); __cnt = 0; __pass = 0 #define _FOOT(name) printf("\n======== %s - %i PASSED, %i FAILED\n", name, __pass, (__cnt - __pass)); TotalTests += __cnt; TotalTestsPassed += __pass; @@ -35,4 +35,4 @@ extern int TotalTestsPassed; } #endif -#endif // _TEST_UTILS_H +#endif // TEST_UTILS_H diff --git a/languages/c/templates/types/enum.cpp b/languages/c/templates/types/enum.cpp index ddda2ae9..9c98f888 100644 --- a/languages/c/templates/types/enum.cpp +++ b/languages/c/templates/types/enum.cpp @@ -1,4 +1,4 @@ /* ${title} ${description} */ - ENUM_CONVERSION_BEGIN(${info.title}_${name}) + ENUM_CONVERSION_BEGIN(${info.Title}_${name}) { ${info.TITLE}_${NAME}_${key}, _T("${value}") }, - ENUM_CONVERSION_END(${info.title}_${name}) + ENUM_CONVERSION_END(${info.Title}_${name}) diff --git a/languages/c/templates/types/enum.h b/languages/c/templates/types/enum.h index 6926fa77..906d908d 100644 --- a/languages/c/templates/types/enum.h +++ b/languages/c/templates/types/enum.h @@ -1,4 +1,4 @@ /* ${title} ${description} */ typedef enum { ${info.TITLE}_${NAME}_${key}, -} ${info.title}_${name}; +} ${info.Title}_${name}; diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index b4f4f9c8..bff898ca 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -506,6 +506,8 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{minor\}/g, macros.version.minor) fContents = fContents.replace(/\$\{patch\}/g, macros.version.patch) fContents = fContents.replace(/\$\{info\.title\}/g, macros.title) + fContents = fContents.replace(/\$\{info\.title\.lowercase\}/g, macros.title.toLowerCase()) + fContents = fContents.replace(/\$\{info\.Title\}/g, capitalize(macros.title)) fContents = fContents.replace(/\$\{info\.TITLE\}/g, macros.title.toUpperCase()) fContents = fContents.replace(/\$\{info\.description\}/g, macros.description) fContents = fContents.replace(/\$\{info\.version\}/g, macros.version.readable) @@ -828,12 +830,12 @@ const generateImports = (json, templates, options = { destination: '' }) => { } if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0 && !json.info['x-uri-titles']) { - imports += Object.keys(json['x-schemas']).map(shared => template.replace(/\$\{info.title\}/g, shared)).join('') + imports += Object.keys(json['x-schemas']).map(shared => template.replace(/\$\{info.title.lowercase\}/g, shared.toLowerCase())).join('') } let componentExternalSchema = getComponentExternalSchema(json) if (componentExternalSchema.length && json.info['x-uri-titles']) { - imports += componentExternalSchema.map(shared => template.replace(/\$\{info.title\}/g, shared)).join('') + imports += componentExternalSchema.map(shared => template.replace(/\$\{info.title.lowercase\}/g, shared.toLowerCase())).join('') } return imports } @@ -1146,6 +1148,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{event\.callback\.params\.serialization\}/g, callbackSerializedParams) .replace(/\$\{event\.callback\.result\.instantiation\}/g, callbackResultInst) .replace(/\$\{event\.callback\.response\.instantiation\}/g, callbackResponseInst) + .replace(/\$\{info\.title\.lowercase\}/g, info.title.toLowerCase()) .replace(/\$\{info\.title\}/g, info.title) .replace(/\$\{info\.Title\}/g, capitalize(info.title)) .replace(/\$\{info\.TITLE\}/g, info.title.toUpperCase()) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 3db5d17a..dc5f30e8 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -167,7 +167,7 @@ const macrofy = async ( content = engine.insertMacros(content, macros) content = engine.insertAggregateMacros(content, aggregateMacros) - const location = createModuleDirectories ? path.join(output, module.info.title, t) : path.join(output, t.replace(/Module/, module.info.title).replace(/index/, module.info.title)) + const location = createModuleDirectories ? path.join(output, module.info.title, t) : path.join(output, t.replace(/module/, module.info.title.toLowerCase()).replace(/index/, module.info.title)) outputFiles[location] = content logSuccess(`Generated macros for module ${path.relative(output, location)}`) @@ -262,7 +262,7 @@ const macrofy = async ( // NOTE: whichever insert is called first also needs to be called again last, so each phase can insert recursive macros from the other content = engine.insertMacros(content, macros) - const location = createModuleDirectories ? path.join(output, document.info.title, t) : path.join(output, t.replace(/Module/, document.info.title).replace(/index/, document.info.title)) + const location = createModuleDirectories ? path.join(output, document.info.title, t) : path.join(output, t.replace(/module/, document.info.title.toLowerCase()).replace(/index/, document.info.title)) outputFiles[location] = content logSuccess(`Generated macros for schema ${path.relative(output, location)}`) From 5f12311d57336b43cbdcfa96868c409ae53086cd Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 09:15:34 +0530 Subject: [PATCH 055/137] language-c: re-arrange files locations (#112) language-c: re-arrange files locations --- .../sdk => src/shared}/CMakeLists.txt | 0 .../shared}/cmake/HelperFunctions.cmake | 0 .../sdk => src/shared}/cmake/project.cmake.in | 0 .../sdk => src/shared}/include/error.h | 0 .../sdk => src/shared}/include/firebolt.h | 0 .../sdk => src/shared}/include/types.h | 0 .../shared}/src/Accessor/Accessor.cpp | 0 .../shared}/src/Accessor/Accessor.h | 0 .../shared}/src/Accessor/WorkerPool.h | 0 .../sdk => src/shared}/src/CMakeLists.txt | 0 .../sdk => src/shared}/src/Event/Event.cpp | 0 .../sdk => src/shared}/src/Event/Event.h | 0 .../shared}/src/FireboltSDK.conf.in | 0 .../sdk => src/shared}/src/FireboltSDK.h | 0 .../sdk => src/shared}/src/Logger/Logger.cpp | 0 .../sdk => src/shared}/src/Logger/Logger.h | 0 .../sdk => src/shared}/src/Module.cpp | 0 .../sdk => src/shared}/src/Module.h | 0 .../shared}/src/Properties/Properties.h | 0 .../shared}/src/Transport/Transport.cpp | 0 .../shared}/src/Transport/Transport.h | 0 .../sdk => src/shared}/src/Types.cpp | 0 .../sdk => src/shared}/src/TypesPriv.h | 0 .../sdk => src/shared}/src/firebolt.cpp | 0 .../sdk => src/shared}/test/CMakeLists.txt | 0 .../{templates/sdk => src/shared}/test/Main.c | 0 .../sdk => src/shared}/test/Module.cpp | 0 .../sdk => src/shared}/test/Module.h | 0 .../sdk => src/shared}/test/OpenRPCCTests.h | 0 .../sdk => src/shared}/test/OpenRPCTests.cpp | 0 .../sdk => src/shared}/test/OpenRPCTests.h | 0 .../sdk => src/shared}/test/TestUtils.h | 0 languages/c/templates/sdk/scripts/install.js | 32 --------- languages/c/templates/sdk/scripts/install.sh | 65 +++++++++++++++++++ 34 files changed, 65 insertions(+), 32 deletions(-) rename languages/c/{templates/sdk => src/shared}/CMakeLists.txt (100%) rename languages/c/{templates/sdk => src/shared}/cmake/HelperFunctions.cmake (100%) rename languages/c/{templates/sdk => src/shared}/cmake/project.cmake.in (100%) rename languages/c/{templates/sdk => src/shared}/include/error.h (100%) rename languages/c/{templates/sdk => src/shared}/include/firebolt.h (100%) rename languages/c/{templates/sdk => src/shared}/include/types.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Accessor/Accessor.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/Accessor/Accessor.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Accessor/WorkerPool.h (100%) rename languages/c/{templates/sdk => src/shared}/src/CMakeLists.txt (100%) rename languages/c/{templates/sdk => src/shared}/src/Event/Event.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/Event/Event.h (100%) rename languages/c/{templates/sdk => src/shared}/src/FireboltSDK.conf.in (100%) rename languages/c/{templates/sdk => src/shared}/src/FireboltSDK.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Logger/Logger.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/Logger/Logger.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Module.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/Module.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Properties/Properties.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Transport/Transport.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/Transport/Transport.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Types.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/TypesPriv.h (100%) rename languages/c/{templates/sdk => src/shared}/src/firebolt.cpp (100%) rename languages/c/{templates/sdk => src/shared}/test/CMakeLists.txt (100%) rename languages/c/{templates/sdk => src/shared}/test/Main.c (100%) rename languages/c/{templates/sdk => src/shared}/test/Module.cpp (100%) rename languages/c/{templates/sdk => src/shared}/test/Module.h (100%) rename languages/c/{templates/sdk => src/shared}/test/OpenRPCCTests.h (100%) rename languages/c/{templates/sdk => src/shared}/test/OpenRPCTests.cpp (100%) rename languages/c/{templates/sdk => src/shared}/test/OpenRPCTests.h (100%) rename languages/c/{templates/sdk => src/shared}/test/TestUtils.h (100%) delete mode 100644 languages/c/templates/sdk/scripts/install.js create mode 100755 languages/c/templates/sdk/scripts/install.sh diff --git a/languages/c/templates/sdk/CMakeLists.txt b/languages/c/src/shared/CMakeLists.txt similarity index 100% rename from languages/c/templates/sdk/CMakeLists.txt rename to languages/c/src/shared/CMakeLists.txt diff --git a/languages/c/templates/sdk/cmake/HelperFunctions.cmake b/languages/c/src/shared/cmake/HelperFunctions.cmake similarity index 100% rename from languages/c/templates/sdk/cmake/HelperFunctions.cmake rename to languages/c/src/shared/cmake/HelperFunctions.cmake diff --git a/languages/c/templates/sdk/cmake/project.cmake.in b/languages/c/src/shared/cmake/project.cmake.in similarity index 100% rename from languages/c/templates/sdk/cmake/project.cmake.in rename to languages/c/src/shared/cmake/project.cmake.in diff --git a/languages/c/templates/sdk/include/error.h b/languages/c/src/shared/include/error.h similarity index 100% rename from languages/c/templates/sdk/include/error.h rename to languages/c/src/shared/include/error.h diff --git a/languages/c/templates/sdk/include/firebolt.h b/languages/c/src/shared/include/firebolt.h similarity index 100% rename from languages/c/templates/sdk/include/firebolt.h rename to languages/c/src/shared/include/firebolt.h diff --git a/languages/c/templates/sdk/include/types.h b/languages/c/src/shared/include/types.h similarity index 100% rename from languages/c/templates/sdk/include/types.h rename to languages/c/src/shared/include/types.h diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.cpp b/languages/c/src/shared/src/Accessor/Accessor.cpp similarity index 100% rename from languages/c/templates/sdk/src/Accessor/Accessor.cpp rename to languages/c/src/shared/src/Accessor/Accessor.cpp diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.h b/languages/c/src/shared/src/Accessor/Accessor.h similarity index 100% rename from languages/c/templates/sdk/src/Accessor/Accessor.h rename to languages/c/src/shared/src/Accessor/Accessor.h diff --git a/languages/c/templates/sdk/src/Accessor/WorkerPool.h b/languages/c/src/shared/src/Accessor/WorkerPool.h similarity index 100% rename from languages/c/templates/sdk/src/Accessor/WorkerPool.h rename to languages/c/src/shared/src/Accessor/WorkerPool.h diff --git a/languages/c/templates/sdk/src/CMakeLists.txt b/languages/c/src/shared/src/CMakeLists.txt similarity index 100% rename from languages/c/templates/sdk/src/CMakeLists.txt rename to languages/c/src/shared/src/CMakeLists.txt diff --git a/languages/c/templates/sdk/src/Event/Event.cpp b/languages/c/src/shared/src/Event/Event.cpp similarity index 100% rename from languages/c/templates/sdk/src/Event/Event.cpp rename to languages/c/src/shared/src/Event/Event.cpp diff --git a/languages/c/templates/sdk/src/Event/Event.h b/languages/c/src/shared/src/Event/Event.h similarity index 100% rename from languages/c/templates/sdk/src/Event/Event.h rename to languages/c/src/shared/src/Event/Event.h diff --git a/languages/c/templates/sdk/src/FireboltSDK.conf.in b/languages/c/src/shared/src/FireboltSDK.conf.in similarity index 100% rename from languages/c/templates/sdk/src/FireboltSDK.conf.in rename to languages/c/src/shared/src/FireboltSDK.conf.in diff --git a/languages/c/templates/sdk/src/FireboltSDK.h b/languages/c/src/shared/src/FireboltSDK.h similarity index 100% rename from languages/c/templates/sdk/src/FireboltSDK.h rename to languages/c/src/shared/src/FireboltSDK.h diff --git a/languages/c/templates/sdk/src/Logger/Logger.cpp b/languages/c/src/shared/src/Logger/Logger.cpp similarity index 100% rename from languages/c/templates/sdk/src/Logger/Logger.cpp rename to languages/c/src/shared/src/Logger/Logger.cpp diff --git a/languages/c/templates/sdk/src/Logger/Logger.h b/languages/c/src/shared/src/Logger/Logger.h similarity index 100% rename from languages/c/templates/sdk/src/Logger/Logger.h rename to languages/c/src/shared/src/Logger/Logger.h diff --git a/languages/c/templates/sdk/src/Module.cpp b/languages/c/src/shared/src/Module.cpp similarity index 100% rename from languages/c/templates/sdk/src/Module.cpp rename to languages/c/src/shared/src/Module.cpp diff --git a/languages/c/templates/sdk/src/Module.h b/languages/c/src/shared/src/Module.h similarity index 100% rename from languages/c/templates/sdk/src/Module.h rename to languages/c/src/shared/src/Module.h diff --git a/languages/c/templates/sdk/src/Properties/Properties.h b/languages/c/src/shared/src/Properties/Properties.h similarity index 100% rename from languages/c/templates/sdk/src/Properties/Properties.h rename to languages/c/src/shared/src/Properties/Properties.h diff --git a/languages/c/templates/sdk/src/Transport/Transport.cpp b/languages/c/src/shared/src/Transport/Transport.cpp similarity index 100% rename from languages/c/templates/sdk/src/Transport/Transport.cpp rename to languages/c/src/shared/src/Transport/Transport.cpp diff --git a/languages/c/templates/sdk/src/Transport/Transport.h b/languages/c/src/shared/src/Transport/Transport.h similarity index 100% rename from languages/c/templates/sdk/src/Transport/Transport.h rename to languages/c/src/shared/src/Transport/Transport.h diff --git a/languages/c/templates/sdk/src/Types.cpp b/languages/c/src/shared/src/Types.cpp similarity index 100% rename from languages/c/templates/sdk/src/Types.cpp rename to languages/c/src/shared/src/Types.cpp diff --git a/languages/c/templates/sdk/src/TypesPriv.h b/languages/c/src/shared/src/TypesPriv.h similarity index 100% rename from languages/c/templates/sdk/src/TypesPriv.h rename to languages/c/src/shared/src/TypesPriv.h diff --git a/languages/c/templates/sdk/src/firebolt.cpp b/languages/c/src/shared/src/firebolt.cpp similarity index 100% rename from languages/c/templates/sdk/src/firebolt.cpp rename to languages/c/src/shared/src/firebolt.cpp diff --git a/languages/c/templates/sdk/test/CMakeLists.txt b/languages/c/src/shared/test/CMakeLists.txt similarity index 100% rename from languages/c/templates/sdk/test/CMakeLists.txt rename to languages/c/src/shared/test/CMakeLists.txt diff --git a/languages/c/templates/sdk/test/Main.c b/languages/c/src/shared/test/Main.c similarity index 100% rename from languages/c/templates/sdk/test/Main.c rename to languages/c/src/shared/test/Main.c diff --git a/languages/c/templates/sdk/test/Module.cpp b/languages/c/src/shared/test/Module.cpp similarity index 100% rename from languages/c/templates/sdk/test/Module.cpp rename to languages/c/src/shared/test/Module.cpp diff --git a/languages/c/templates/sdk/test/Module.h b/languages/c/src/shared/test/Module.h similarity index 100% rename from languages/c/templates/sdk/test/Module.h rename to languages/c/src/shared/test/Module.h diff --git a/languages/c/templates/sdk/test/OpenRPCCTests.h b/languages/c/src/shared/test/OpenRPCCTests.h similarity index 100% rename from languages/c/templates/sdk/test/OpenRPCCTests.h rename to languages/c/src/shared/test/OpenRPCCTests.h diff --git a/languages/c/templates/sdk/test/OpenRPCTests.cpp b/languages/c/src/shared/test/OpenRPCTests.cpp similarity index 100% rename from languages/c/templates/sdk/test/OpenRPCTests.cpp rename to languages/c/src/shared/test/OpenRPCTests.cpp diff --git a/languages/c/templates/sdk/test/OpenRPCTests.h b/languages/c/src/shared/test/OpenRPCTests.h similarity index 100% rename from languages/c/templates/sdk/test/OpenRPCTests.h rename to languages/c/src/shared/test/OpenRPCTests.h diff --git a/languages/c/templates/sdk/test/TestUtils.h b/languages/c/src/shared/test/TestUtils.h similarity index 100% rename from languages/c/templates/sdk/test/TestUtils.h rename to languages/c/src/shared/test/TestUtils.h diff --git a/languages/c/templates/sdk/scripts/install.js b/languages/c/templates/sdk/scripts/install.js deleted file mode 100644 index 5c332ceb..00000000 --- a/languages/c/templates/sdk/scripts/install.js +++ /dev/null @@ -1,32 +0,0 @@ -import { createRequire } from 'module'; -const require = createRequire(import.meta.url); -const fs = require('fs'); -const path = require('path'); - -var dest = process.env.NODE_INSTALL_PATH; -var src = 'src/native/build/' + process.env.TARGET_NAME; - -installFiles(src, dest); -function installFiles(src, dest) { - if (!fs.existsSync(dest)) { - fs.mkdirSync(dest); - } - - var entries = fs.readdirSync(src); - entries.forEach((entry) => { - const srcPath = path.join(src, entry); - const destPath = path.join(dest, entry); - const stat = fs.lstatSync(srcPath); - - if (stat.isFile()) { - fs.copyFileSync(srcPath, destPath); - } else if (stat.isDirectory()) { - installFiles(srcPath, destPath); - } else if (stat.isSymbolicLink()) { - if (fs.existsSync(destPath)) { - fs.unlinkSync(destPath); - } - fs.symlinkSync(fs.readlinkSync(srcPath), destPath); - } - }); -} diff --git a/languages/c/templates/sdk/scripts/install.sh b/languages/c/templates/sdk/scripts/install.sh new file mode 100755 index 00000000..69c2d66a --- /dev/null +++ b/languages/c/templates/sdk/scripts/install.sh @@ -0,0 +1,65 @@ +#!/bin/bash +usage() +{ + echo "options:" + echo " -i install path" + echo " -s sdk path" + echo " -t include test" + echo " -m module name. i.e, core/manage" + echo + echo "usage: " + echo " ./install.sh -p path" +} + +SdkPath=".." +InstallPath=".." +IncludeTest="OFF" +ModuleName="core" +while getopts i:s:m:th flag +do + case "${flag}" in + i) InstallPath="${OPTARG}";; + s) SdkPath="${OPTARG}";; + m) ModuleName="${OPTARG}";; + t) IncludeTest="ON";; + h) usage && exit 1;; + esac +done + +GetVersion() +{ + PackagePath=${SdkPath}/../../../../../../package-lock.json + InputKey="name\": \"@firebolt-js/openrpc" + LineNo="$(grep -n "${InputKey}" ${PackagePath} | head -n 1 | cut -d: -f1)" + VersionLine=$((LineNo++)) + eval "array=(`sed -n "${LineNo}p" < ${PackagePath} | sed 's/\"/\n/g'`)" + Version=${array[2]} +} + +Version=0.0 +GetVersion +ReleaseName=firebolt-${ModuleName}-native-sdk-${Version} +ReleasePath=${InstallPath}/${ReleaseName} + +rm -rf ${ReleasePath} +mkdir -p ${ReleasePath} +cp -ar ${SdkPath}/src ${ReleasePath} +cp -ar ${SdkPath}/include ${ReleasePath} +cp -ar ${SdkPath}/cmake ${ReleasePath} +cp -ar ${SdkPath}/scripts/build.sh ${ReleasePath} +cp -ar ${SdkPath}/CMakeLists.txt ${ReleasePath} + +if [ "${IncludeTest}" == "ON" ]; +then + cp -ar ${SdkPath}/ctest ${ReleasePath}/test +fi + +sed -i '/EnableTest="ON";;/d' ${ReleasePath}/build.sh +sed -i 's/getopts p:s:tch/getopts p:s:ch/g' ${ReleasePath}/build.sh +sed -i '/enable test/d' ${ReleasePath}/build.sh +sed -i '/EnableTest="OFF"/d' ${ReleasePath}/build.sh +sed -i 's/ -DENABLE_TESTS=${EnableTest}//g' ${ReleasePath}/build.sh + +cd ${ReleasePath}/../ +tar -cvzf ${ReleaseName}.tgz ${ReleaseName}/* +cd - From 923de607d75407a36a88067af8bfec26c8add7a2 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 09:16:03 +0530 Subject: [PATCH 056/137] fixes to generate array inside subschemas (#111) --- languages/c/Types.mjs | 35 ++++++++--------- languages/c/src/types/ImplHelpers.mjs | 4 +- languages/c/src/types/JSONHelpers.mjs | 2 +- languages/c/src/types/NativeHelpers.mjs | 48 +---------------------- languages/c/templates/codeblocks/export.c | 1 - src/macrofier/engine.mjs | 25 +++++++----- 6 files changed, 38 insertions(+), 77 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 1ed84940..d8cae205 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -18,7 +18,7 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' -import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' +import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation, getCallbackParametersInstantiation, getCallbackResultInstantiation, getCallbackResponseInstantiation } from './src/types/ImplHelpers.mjs' import { getJsonContainerDefinition, getJsonDataStructName, getJsonDataPrefix } from './src/types/JSONHelpers.mjs' @@ -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 } @@ -302,8 +303,10 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref res = getSchemaTypeInfo(module, json.items, json.items.name || name, schemas, prefix) } + + prefix = prefix ? prefix + name : name let n = getTypeName(getModuleName(module), capitalize(res.name), prefix) - structure.name = res.name || name && (capitalize(name)) + structure.name = name ? name + capitalize(res.name) : res.name structure.type = n + 'Array_t' structure.json = json structure.namespace = getModuleName(module) @@ -525,24 +528,19 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' else { j = json.items } - shape += getSchemaShapeInfo(j, module, schemas, { name: j.title || name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) if (!isCPP) { - let info = getSchemaTypeInfo(module, j, j.title || name, schemas, prefix, {level : level, descriptions: descriptions, title: true}) + let subPrefix = prefix ? prefix + name : name + let info = getSchemaTypeInfo(module, j, j.title || name, schemas, subPrefix, {level : level, descriptions: descriptions, title: true}) if (info.type && info.type.length > 0) { - let type = getArrayElementSchema(json, module, schemas, info.name) - let arrayName = capitalize(info.name) + capitalize(type.type) - let namespace = info.namespace - if (type && type.type === 'object') { - namespace = getModuleName(module) - } - let objName = getTypeName(namespace, arrayName, prefix) + let arrayName = capitalize(info.name); + let objName = getTypeName(getModuleName(module), arrayName, subPrefix) let tName = objName + 'Array' info.json.namespace = info.namespace let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) - let subModuleProperty = getJsonTypeInfo(module, j, j.title, schemas, prefix) + let subModuleProperty = getJsonTypeInfo(module, j, j.title || name, schemas, prefix) let t = '' if (level === 0) { t += description(capitalize(info.name), json.description) + '\n' @@ -666,6 +664,7 @@ function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '' items = json.items // grab the type for the non-array schema } + res = getJsonTypeInfo(module, items, items.name || name, schemas, prefix) structure.deps = res.deps structure.type.push(`WPEFramework::Core::JSON::ArrayType<${res.type}>`) @@ -733,7 +732,7 @@ const enumReducer = (acc, val, i, arr) => { return acc } -function getSchemaInstantiation(schema, module, name, { instantiationType = '' } = {}) { +function getSchemaInstantiation(schema, module, name, { instantiationType = '', prefix = '' } = {}) { if (instantiationType === 'params') { return getParameterInstantiation(getParamList(schema, module)) @@ -752,17 +751,17 @@ function getSchemaInstantiation(schema, module, name, { instantiationType = '' } return result } else if (instantiationType === 'callback.params') { - let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' + let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name, prefix }) || '' return getCallbackParametersInstantiation(getParamList(schema, module), resultJsonType) } else if (instantiationType === 'callback.result') { - let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' + let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, prefix, resultSchema: true}) || '' let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' return getCallbackResultInstantiation(resultType, resultJsonType) } else if (instantiationType === 'callback.response') { - let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' - let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' + let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, prefix, resultSchema: true}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name, prefix }) || '' return getCallbackResponseInstantiation(getParamList(schema, module), resultType, resultJsonType) } else if (instantiationType === 'pull.param.name') { diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index 5b373377..8dbe8f08 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -49,7 +49,7 @@ const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ` + '\n' - if ((json.type === 'object') && (accessorPropertyType !== 'char*')) { + if (((json.type === 'object') || (json.type === 'array')) && (accessorPropertyType !== 'char*')) { result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); *(*element) = (*var)->${subPropertyName}; @@ -73,7 +73,7 @@ const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, ASSERT(var->IsValid()); ` + '\n' - if (json.type === 'object' && (accessorPropertyType !== 'char*')) { + if (((json.type === 'object') || (json.type === 'array')) && (accessorPropertyType !== 'char*')) { result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* object = reinterpret_cast*>(value); (*var)->${subPropertyName} = *(*object);` + '\n' } diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index cc31b14a..009beb99 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -4,7 +4,7 @@ const getJsonDataPrefix = () => 'JsonData_' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' const getJsonDataStructName = (modName, name, prefix = '') => { - let result =((prefix.length > 0) && (!name.startsWith(prefix))) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}_${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` + let result =((prefix.length > 0) && (prefix !== name)) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` return ((result.includes(wpeJsonNameSpace()) === true) ? result : `${getSdkNameSpace()}::${result}`) } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 7bfef987..8d00199e 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -30,18 +30,7 @@ const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = pre const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' const getFireboltStringType = () => 'FireboltTypes_String_t' -const getHeaderText = () => { - return `/* -* Copyright 2022 Comcast -* -* Auto Generated using firebolt-openrpc tools. DO NOT EDIT. -* -*/ - -` -} - const capitalize = str => str[0].toUpperCase() + str.substr(1) const description = (title, str='') => '/* ' + title + (str.length > 0 ? ' - ' + str : '') + ' */' const isOptional = (prop, json) => (!json.required || !json.required.includes(prop)) @@ -50,37 +39,6 @@ const SdkTypesPrefix = 'Firebolt' const Indent = ' ' -const getArrayElementSchema = (json, module, schemas = {}, name) => { - let result = '' - if (json.type === 'array' && json.items) { - if (Array.isArray(json.items)) { - result = json.items[0] - } - else { - // grab the type for the non-array schema - result = json.items - } - if (result['$ref']) { - result = getPath(result['$ref'], module, schemas) - } - } - else if (json.type == 'object') { - if (json.properties) { - Object.entries(json.properties).every(([pname, prop]) => { - if (prop.type === 'array') { - result = getArrayElementSchema(prop, module, schemas) - if (name === capitalize(pname)) { - return false - } - } - return true - }) - } - } - - return result -} - const getNativeType = (json, fireboltString = false) => { let type let jsonType = json.const ? typeof json.const : json.type @@ -150,10 +108,10 @@ const getTypeName = (moduleName, varName, prefix = '', upperCase = false, capita let mName = upperCase ? moduleName.toUpperCase() : capitalize(moduleName) let vName = upperCase ? varName.toUpperCase() : capitalCase ? capitalize(varName) : varName if (prefix.length > 0) { - prefix = (!varName.startsWith(prefix)) ? (upperCase ? prefix.toUpperCase() : capitalize(prefix)) : '' + prefix = (prefix !== varName) ? (upperCase ? prefix.toUpperCase() : capitalize(prefix)) : '' } prefix = (prefix.length > 0) ?(upperCase ? prefix.toUpperCase() : capitalize(prefix)) : prefix - let name = (prefix.length > 0) ? `${mName}_${prefix}_${vName}` : `${mName}_${vName}` + let name = (prefix.length > 0) ? `${mName}_${prefix}${vName}` : `${mName}_${vName}` return name } @@ -235,7 +193,6 @@ function getPropertyEventUnregisterSignature(property, module) { export { - getHeaderText, getNativeType, getModuleName, getPropertyGetterSignature, @@ -252,6 +209,5 @@ export { getPropertyAccessors, isOptional, generateEnum, - getArrayElementSchema, getFireboltStringType } diff --git a/languages/c/templates/codeblocks/export.c b/languages/c/templates/codeblocks/export.c index c98498e4..e69de29b 100644 --- a/languages/c/templates/codeblocks/export.c +++ b/languages/c/templates/codeblocks/export.c @@ -1 +0,0 @@ -export { default as ${info.title} } from './${info.title}/index.mjs' \ No newline at end of file diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index bff898ca..61eebd3d 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -361,7 +361,7 @@ const addContentDescriptorSubSchema = (descriptor, prefix, obj) => { } // only consider sub-objects and sub enums to be sub-schemas -const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) +const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) || (schema.type === 'array' && schema.items) const promoteAndNameSubSchemas = (obj) => { // make a copy so we don't polute our inputs @@ -384,7 +384,7 @@ const promoteAndNameSubSchemas = (obj) => { while (more) { more = false Object.entries(obj.components.schemas).forEach(([key, schema]) => { - if (schema.type === "object" && schema.properties) { + if ((schema.type === "object") && schema.properties) { Object.entries(schema.properties).forEach(([name, propSchema]) => { if (isSubSchema(propSchema)) { more = true @@ -584,10 +584,11 @@ function insertTableofContents(content) { } const convertEnumTemplate = (schema, templateName, templates) => { + let enumSchema = isArraySchema(schema) ? schema.items : schema const template = getTemplate(templateName, templates).split('\n') for (var i = 0; i < template.length; i++) { if (template[i].indexOf('${key}') >= 0) { - template[i] = schema.enum.map(value => { + template[i] = enumSchema.enum.map(value => { const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() return template[i].replace(/\$\{key\}/g, safeName) .replace(/\$\{value\}/g, value) @@ -693,7 +694,12 @@ function sortSchemasByReference(schemas = []) { return schemas } -const isEnum = x => x.type && x.type === 'string' && Array.isArray(x.enum) && x.title +const isArraySchema = x => x.type && x.type === 'array' && x.items + +const isEnum = x => { + let schema = isArraySchema(x) ? x.items : x + return schema.type && schema.type === 'string' && Array.isArray(schema.enum) && x.title +} function generateSchemas(json, templates, options) { let results = [] @@ -1089,9 +1095,10 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, { instantiationType: 'params' }) const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' } ) const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'params' }), ' ') : '' - const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.params' }) : '' - const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.result' }) : '' - const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.response' }) : '' + const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.params', prefix: method.alternative }) : '' + const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.result', prefix: method.alternative }) : '' + const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.response', prefix: method.alternative }) : '' + const callbackResultJsonType = event && result.schema ? types.getJsonType(result.schema, json, { name: result.name, prefix: method.alternative }) : '' const resultType = result.schema ? types.getSchemaType(result.schema, json, { name: result.name }) : '' const resultJsonType = result.schema ? types.getJsonType(result.schema, json, { name: result.name }) : '' @@ -1166,8 +1173,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .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, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, baseUrl: options.baseUrl .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') - .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, prefix: method.alternative, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') + .replace(/\$\{event\.result\.json\.type\}/g, callbackResultJsonType) .replace(/\$\{event\.pulls\.param\.name\}/g, pullsEventParamName) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) .replace(/\$\{method\.result\.json\.type\}/g, resultJsonType) From 14dfca7cd949b0902cf4720e8605a218a22d1f4a Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 20:09:16 +0530 Subject: [PATCH 057/137] include test always (#113) --- languages/c/templates/sdk/scripts/install.sh | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/languages/c/templates/sdk/scripts/install.sh b/languages/c/templates/sdk/scripts/install.sh index 69c2d66a..15596524 100755 --- a/languages/c/templates/sdk/scripts/install.sh +++ b/languages/c/templates/sdk/scripts/install.sh @@ -4,24 +4,21 @@ usage() echo "options:" echo " -i install path" echo " -s sdk path" - echo " -t include test" echo " -m module name. i.e, core/manage" echo echo "usage: " - echo " ./install.sh -p path" + echo " ./install.sh -i path -s sdk path-m core" } SdkPath=".." InstallPath=".." -IncludeTest="OFF" ModuleName="core" -while getopts i:s:m:th flag +while getopts i:s:m:h flag do case "${flag}" in i) InstallPath="${OPTARG}";; s) SdkPath="${OPTARG}";; m) ModuleName="${OPTARG}";; - t) IncludeTest="ON";; h) usage && exit 1;; esac done @@ -48,11 +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} - -if [ "${IncludeTest}" == "ON" ]; -then - cp -ar ${SdkPath}/ctest ${ReleasePath}/test -fi +cp -ar ${SdkPath}/ctest ${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 From e7e9ebae840121202d38c2e7bd106a75557ace35 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 20:09:40 +0530 Subject: [PATCH 058/137] use String type if there is any issue with anyOf merge (#114) --- languages/c/Types.mjs | 27 ++++++++++++++++++------- languages/c/src/types/JSONHelpers.mjs | 2 +- languages/c/src/types/NativeHelpers.mjs | 6 +++--- 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index d8cae205..1ee99224 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -82,7 +82,7 @@ function union(schemas, module, commonSchemas) { //console.warn(`Ignoring "${key}" that is already present and same`) } else { console.warn(`ERROR "${key}" is not same -${JSON.stringify(result, null, 4)} ${key} ${result[key]} - ${value}`); - throw "ERROR: type is not same" + return {} } } else { //If the Key is a const then merge them into an enum @@ -325,8 +325,14 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref } else if (json.anyOf) { let mergedSchema = getMergedSchema(module, json, name, schemas) - let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) - structure = getSchemaTypeInfo(module, mergedSchema, '', schemas, prefixName, options) + if (mergedSchema.type) { + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + structure = getSchemaTypeInfo(module, mergedSchema, '', schemas, prefixName, options) + } + else { + structure.type = fireboltString ? getFireboltStringType() : 'char*' + structure.json.type = 'string' + } } else if (json.type === 'object') { structure.json = json @@ -499,8 +505,10 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' else if (json.anyOf) { if (level > 0) { let mergedSchema = getMergedSchema(module, json, name, schemas) - let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) - shape += getSchemaShapeInfo(mergedSchema, module, schemas, { name, prefix: prefixName, merged, level, title, summary, descriptions, destination, section, enums }) + if (mergedSchema.type) { + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + shape += getSchemaShapeInfo(mergedSchema, module, schemas, { name, prefix: prefixName, merged, level, title, summary, descriptions, destination, section, enums }) + } } } else if (json.oneOf) { @@ -689,8 +697,13 @@ function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '' } else if (json.anyOf) { let mergedSchema = getMergedSchema(module, json, name, schemas) - let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) - structure = getJsonTypeInfo(module, mergedSchema, name, schemas, prefixName, {descriptions, level}) + if (mergedSchema.type) { + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + structure = getJsonTypeInfo(module, mergedSchema, name, schemas, prefixName, {descriptions, level}) + } + else { + structure.type = getJsonNativeTypeForOpaqueString() + } } else if (json.type === 'object') { if (hasProperties(json) !== true) { diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index 009beb99..954ac50d 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -4,7 +4,7 @@ const getJsonDataPrefix = () => 'JsonData_' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' const getJsonDataStructName = (modName, name, prefix = '') => { - let result =((prefix.length > 0) && (prefix !== name)) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` + let result =((prefix && prefix.length > 0) && (prefix !== name)) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` return ((result.includes(wpeJsonNameSpace()) === true) ? result : `${getSdkNameSpace()}::${result}`) } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 8d00199e..3437c3f4 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -107,11 +107,11 @@ const getTypeName = (moduleName, varName, prefix = '', upperCase = false, capita let mName = upperCase ? moduleName.toUpperCase() : capitalize(moduleName) let vName = upperCase ? varName.toUpperCase() : capitalCase ? capitalize(varName) : varName - if (prefix.length > 0) { + if (prefix && prefix.length > 0) { prefix = (prefix !== varName) ? (upperCase ? prefix.toUpperCase() : capitalize(prefix)) : '' } - prefix = (prefix.length > 0) ?(upperCase ? prefix.toUpperCase() : capitalize(prefix)) : prefix - let name = (prefix.length > 0) ? `${mName}_${prefix}${vName}` : `${mName}_${vName}` + prefix = (prefix && prefix.length > 0) ?(upperCase ? prefix.toUpperCase() : capitalize(prefix)) : prefix + let name = (prefix && prefix.length > 0) ? `${mName}_${prefix}${vName}` : `${mName}_${vName}` return name } From 51f30430162b581643bd5c4d1d7a72c023a243a5 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 21:10:37 +0530 Subject: [PATCH 059/137] calls-metrics: support added (#115) --- languages/c/templates/declarations/rpc-only.c | 0 .../c/templates/imports/calls-metrics.cpp | 1 + languages/c/templates/methods/calls-metrics.c | 30 +++++++++++++++++++ languages/c/templates/methods/rpc-only.c | 0 src/macrofier/engine.mjs | 13 +++++++- src/shared/modules.mjs | 8 +++++ 6 files changed, 51 insertions(+), 1 deletion(-) delete mode 100644 languages/c/templates/declarations/rpc-only.c create mode 100644 languages/c/templates/imports/calls-metrics.cpp create mode 100644 languages/c/templates/methods/calls-metrics.c delete mode 100644 languages/c/templates/methods/rpc-only.c diff --git a/languages/c/templates/declarations/rpc-only.c b/languages/c/templates/declarations/rpc-only.c deleted file mode 100644 index e69de29b..00000000 diff --git a/languages/c/templates/imports/calls-metrics.cpp b/languages/c/templates/imports/calls-metrics.cpp new file mode 100644 index 00000000..4ba289b3 --- /dev/null +++ b/languages/c/templates/imports/calls-metrics.cpp @@ -0,0 +1 @@ +#include "metrics.h" diff --git a/languages/c/templates/methods/calls-metrics.c b/languages/c/templates/methods/calls-metrics.c new file mode 100644 index 00000000..91831a3c --- /dev/null +++ b/languages/c/templates/methods/calls-metrics.c @@ -0,0 +1,30 @@ +/* ${method.rpc.name} - ${method.description} */ +void Metrics_${method.Name}Dispatcher(const void*${if.result} result${end.if.result}) { + Metrics_${method.Name}(${if.result}(static_cast<${method.result.json.type}>(const_cast(result)))${end.if.result}); +} + +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; + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + + ${method.params.serialization.with.indent} + ${method.result.json.type} jsonResult; + status = transport->Invoke("${info.title}.${method.rpc.name}", jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); +${method.result.instantiation} + + void* result = nullptr; + ${if.result}result = static_cast(new ${method.result.json.type});${end.if.result} + WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(Metrics_${method.Name}Dispatcher, result)); + WPEFramework::Core::IWorkerPool::Instance().Submit(job); + } + + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; +} diff --git a/languages/c/templates/methods/rpc-only.c b/languages/c/templates/methods/rpc-only.c deleted file mode 100644 index e69de29b..00000000 diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 61eebd3d..9a2da33f 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -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, isCallsMetricsMethod, isExcludedMethod, hasMethodAttributes, getMethodAttributes, isEventMethodWithContext, getSemanticVersion, getSetterFor, getProvidedCapabilities, isPolymorphicPullMethod, hasPublicAPIs } from '../shared/modules.mjs' import isEmpty from 'crocks/core/isEmpty.js' import { getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies, isDefinitionReferencedBySchema } from '../shared/json-schema.mjs' @@ -282,6 +282,13 @@ const temporalSets = compose( getMethods ) +const callsMetrics = compose( + option([]), + map(filter(not(isExcludedMethod))), + map(filter(isCallsMetricsMethod)), + getMethods +) + const methodsWithXMethodsInResult = compose( option([]), map(filter(hasMethodAttributes)), @@ -830,6 +837,10 @@ const generateImports = (json, templates, options = { destination: '' }) => { const suffix = options.destination.split('.').pop() const prefix = options.destination.split('/').pop().split('_')[0].toLowerCase() + if (callsMetrics(json).length) { + imports += getTemplate(suffix ? `/imports/calls-metrics.${suffix}` : '/imports/calls-metrics', templates) + } + let template = prefix ? getTemplate(`/imports/default.${prefix}`, templates) : '' if (!template) { template = getTemplate(suffix ? `/imports/default.${suffix}` : '/imports/default', templates) diff --git a/src/shared/modules.mjs b/src/shared/modules.mjs index 386b9d6d..a91c076b 100644 --- a/src/shared/modules.mjs +++ b/src/shared/modules.mjs @@ -227,6 +227,13 @@ const isTemporalSetMethod = compose( getPath(['tags']) ) +const isCallsMetricsMethod = compose( + option(false), + map(_ => true), + chain(find(propEq('name', 'calls-metrics'))), + getPath(['tags']) +) + const getMethodAttributes = compose( option(null), map(props => props.reduce( (val, item) => { @@ -1148,6 +1155,7 @@ export { isPolymorphicReducer, isPolymorphicPullMethod, isTemporalSetMethod, + isCallsMetricsMethod, isExcludedMethod, isRPCOnlyMethod, isProviderInterfaceMethod, From 6a17ba253d3da01cc5c307f37daa3cd9d3181712 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 21:13:35 +0530 Subject: [PATCH 060/137] Generate polymorphci methods for anyOf param/result case (#110) --- languages/c/Types.mjs | 1 + languages/c/language.config.json | 3 +- languages/c/templates/codeblocks/setter.c | 4 +- languages/c/templates/methods/default.c | 6 +- languages/c/templates/methods/event.c | 6 +- .../methods/polymorphic-pull-event.c | 10 +- .../c/templates/methods/polymorphic-pull.c | 11 +- languages/c/templates/methods/property.c | 4 +- src/macrofier/engine.mjs | 20 ++- src/macrofier/index.mjs | 7 +- src/sdk/index.mjs | 1 + src/shared/modules.mjs | 137 +++++++++++++++++- 12 files changed, 182 insertions(+), 28 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 1ee99224..4c092a92 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -358,6 +358,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref structure.namespace = getModuleName(module) } } + return structure } diff --git a/languages/c/language.config.json b/languages/c/language.config.json index ee3604d7..b684e11b 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -12,5 +12,6 @@ "/src/module_common.cpp", "/src/jsondata_module.h" ], - "persistPermission": true + "persistPermission": true, + "createPolymorphicMethods": true } diff --git a/languages/c/templates/codeblocks/setter.c b/languages/c/templates/codeblocks/setter.c index 342a98d6..411d4542 100644 --- a/languages/c/templates/codeblocks/setter.c +++ b/languages/c/templates/codeblocks/setter.c @@ -1,7 +1,7 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.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.lowercase}.${method.rpc.name}"); ${if.params}${method.params.serialization}${end.if.params} return FireboltSDK::Properties::Set(method, jsonParameters); } diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 6fbca47e..881b592c 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -1,4 +1,4 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.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; @@ -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.lowercase}.${method.rpc.name}", jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully invoked"); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); ${method.result.instantiation} } diff --git a/languages/c/templates/methods/event.c b/languages/c/templates/methods/event.c index ec868cd5..c02e74c4 100644 --- a/languages/c/templates/methods/event.c +++ b/languages/c/templates/methods/event.c @@ -1,4 +1,4 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.name} - ${method.description} */ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) { ${event.callback.params.serialization} @@ -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.lowercase}.${method.rpc.name}"); uint32_t status = FireboltSDKErrorNone; if (userCB != nullptr) { @@ -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(userCB)); + return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); } diff --git a/languages/c/templates/methods/polymorphic-pull-event.c b/languages/c/templates/methods/polymorphic-pull-event.c index d2f5ef4c..7c833b71 100644 --- a/languages/c/templates/methods/polymorphic-pull-event.c +++ b/languages/c/templates/methods/polymorphic-pull-event.c @@ -1,4 +1,4 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.name} - ${method.description} */ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) { ${event.callback.params.serialization} @@ -27,9 +27,9 @@ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { WPEFramework::Core::JSON::Boolean jsonResult; - uint32_t status = transport->Invoke(_T("${info.title}.${method.pulls.for}"), jsonParameters, jsonResult); + uint32_t status = transport->Invoke(_T("${info.title.lowercase}.${method.pulls.for}"), jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully pushed with status as %d", jsonResult.Value()); status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; } } else { @@ -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.lowercase}.${method.rpc.name}"); uint32_t status = FireboltSDKErrorNone; if (userCB != nullptr) { @@ -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(userCB)); + return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); } diff --git a/languages/c/templates/methods/polymorphic-pull.c b/languages/c/templates/methods/polymorphic-pull.c index ec052e64..759b0ae9 100644 --- a/languages/c/templates/methods/polymorphic-pull.c +++ b/languages/c/templates/methods/polymorphic-pull.c @@ -1,16 +1,17 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.name} - ${method.description} */ uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ) { uint32_t status = FireboltSDKErrorUnavailable; - string correlationId = ""; -${method.params.serialization} FireboltSDK::Transport* 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.lowercase}.${method.rpc.name}"), jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully pushed with status as %d", jsonResult.Value()); status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; } } else { diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 9a92dce4..7fb5b148 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,7 +1,7 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.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.lowercase}.${method.rpc.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} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 9a2da33f..1ad8b6e6 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -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, isCallsMetricsMethod, isExcludedMethod, 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' @@ -416,6 +416,21 @@ const generateMacros = (obj, templates, languages, options = {}) => { if (config.extractSubSchemas) { obj = promoteAndNameSubSchemas(obj) } + if (options.createPolymorphicMethods) { + let methods = [] + obj.methods && obj.methods.forEach(method => { + let polymorphicMethods = createPolymorphicMethods(method, obj) + if (polymorphicMethods.length > 1) { + polymorphicMethods.forEach(polymorphicMethod => { + methods.push(polymorphicMethod) + }) + } + else { + methods.push(method) + } + }) + obj.methods = methods + } // grab the options so we don't have to pass them from method to method Object.assign(state, options) @@ -1022,7 +1037,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, examples={}) { const moduleName = getModuleName(json) const info = { @@ -1131,6 +1146,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\.rpc\.name\}/g, methodObj.title || methodObj.name) .replace(/\$\{method\.summary\}/g, methodObj.summary) .replace(/\$\{method\.description\}/g, methodObj.description || methodObj.summary) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index dc5f30e8..86483fad 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -44,6 +44,7 @@ const macrofy = async ( templatesPerModule, templatesPerSchema, persistPermission, + createPolymorphicMethods, createModuleDirectories, copySchemasIntoModules, extractSubSchemas, @@ -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 @@ -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) } @@ -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 diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index 7e85fab9..2e72ba9b 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -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, diff --git a/src/shared/modules.mjs b/src/shared/modules.mjs index a91c076b..927092c2 100644 --- a/src/shared/modules.mjs +++ b/src/shared/modules.mjs @@ -29,6 +29,7 @@ const { and, not } = logic import isString from 'crocks/core/isString.js' import predicates from 'crocks/predicates/index.js' import { getExternalSchemaPaths, isDefinitionReferencedBySchema, isNull, localizeDependencies, isSchema, getLocalSchemaPaths, replaceRef } from './json-schema.mjs' +import { getPath as getRefDefinition } from './json-schema.mjs' const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = predicates // util for visually debugging crocks ADTs @@ -861,6 +862,137 @@ const generateEventListenResponse = json => { return json } +const getAnyOfSchema = (inType, json) => { + let anyOfTypes = [] + let outType = localizeDependencies(inType, json) + if (outType.schema.anyOf) { + let definition = '' + if (inType.schema['$ref'] && (inType.schema['$ref'][0] === '#')) { + definition = getRefDefinition(inType.schema['$ref'], json, json['x-schemas']) + } + else { + definition = outType.schema + } + definition.anyOf.forEach(anyOf => { + anyOfTypes.push(anyOf) + }) + outType.schema.anyOf = anyOfTypes + } + return outType +} + +const generateAnyOfSchema = (anyOf, name, summary) => { + let anyOfType = {} + anyOfType["name"] = name[0].toLowerCase() + name.substr(1) + anyOfType["summary"] = summary + anyOfType["schema"] = anyOf + return anyOfType +} + +const generateParamsAnyOfSchema = (methodParams, anyOf, anyOfTypes, title, summary) => { + let params = [] + methodParams.forEach(p => { + if (p.schema.anyOf === anyOfTypes) { + let anyOfType = generateAnyOfSchema(anyOf, title, summary) + anyOfType.required = p.required + params.push(anyOfType) + } + else { + params.push(p) + } + }) + return params +} + +const generateResultAnyOfSchema = (method, methodResult, anyOf, anyOfTypes, title, summary) => { + let methodResultSchema = {} + if (methodResult.schema.anyOf === anyOfTypes) { + let anyOfType = generateAnyOfSchema(anyOf, title, summary) + let index = 0 + if (isEventMethod(method)) { + index = (method.result.schema.anyOf || method.result.schema.oneOf).indexOf(getPayloadFromEvent(method)) + } + else { + index = (method.result.schema.anyOf || method.result.schema.oneOf).indexOf(anyOfType) + } + if (method.result.schema.anyOf) { + methodResultSchema["anyOf"] = Object.assign([], method.result.schema.anyOf) + methodResultSchema.anyOf[index] = anyOfType.schema + } + else if (method.result.schema.oneOf) { + methodResultSchema["oneOf"] = Object.assign([], method.result.schema.oneOf) + methodResultSchema.oneOf[index] = anyOfType.schema + } + else { + methodResultSchema = anyOfType.schema + } + } + return methodResultSchema +} + +const createPolymorphicMethods = (method, json) => { + let anyOfTypes + let methodParams = [] + let methodResult = Object.assign({}, method.result) + method.params.forEach(p => { + if (p.schema) { + let param = getAnyOfSchema(p, json) + if (param.schema.anyOf && anyOfTypes) { + //anyOf is allowed with only one param in the params list + throw `WARNING anyOf is repeated with param:${p}` + } + else if (param.schema.anyOf) { + anyOfTypes = param.schema.anyOf + } + methodParams.push(param) + } + }) + let foundAnyOfParams = anyOfTypes ? true : false + + if (isEventMethod(method)) { + methodResult.schema = getPayloadFromEvent(method) + } + methodResult = getAnyOfSchema(methodResult, json) + let foundAnyOfResult = methodResult.schema.anyOf ? true : false + if (foundAnyOfParams === true && foundAnyOfResult === true) { + throw `WARNING anyOf is already with param schema, it is repeated with ${method.name} result too` + } + else if (foundAnyOfResult === true) { + anyOfTypes = methodResult.schema.anyOf + } + let polymorphicMethodSchemas = [] + //anyOfTypes will be allowed either in any one of the params or in result + if (anyOfTypes) { + let polymorphicMethodSchema = { + name: {}, + tags: {}, + summary: `${method.summary}`, + params: {}, + result: {}, + examples: {} + } + anyOfTypes.forEach(anyOf => { + + let localized = localizeDependencies(anyOf, json) + let title = localized.title || localized.name || '' + let summary = localized.summary || localized.description || '' + polymorphicMethodSchema.title = method.name + polymorphicMethodSchema.name = foundAnyOfParams ? `${method.name}With${title}` : `${method.name}${title}` + polymorphicMethodSchema.tags = method.tags + polymorphicMethodSchema.params = foundAnyOfParams ? generateParamsAnyOfSchema(methodParams, anyOf, anyOfTypes, title, summary) : methodParams + polymorphicMethodSchema.result = Object.assign({}, method.result) + polymorphicMethodSchema.result.schema = foundAnyOfResult ? generateResultAnyOfSchema(method, methodResult, anyOf, anyOfTypes, title, summary) : methodResult + polymorphicMethodSchema.examples = method.examples + polymorphicMethodSchemas.push(Object.assign({}, polymorphicMethodSchema)) + }) + } + else { + polymorphicMethodSchemas = method + } + + return polymorphicMethodSchemas +} + const getPathFromModule = (module, path) => { console.error("DEPRECATED: getPathFromModule") @@ -1183,5 +1315,6 @@ export { getSemanticVersion, addExternalMarkdown, addExternalSchemas, - getExternalMarkdownPaths -} \ No newline at end of file + getExternalMarkdownPaths, + createPolymorphicMethods +} From 934fcfd9f5c25a8499eb5ce47bca301e615257c6 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 24 Jul 2023 09:11:31 +0530 Subject: [PATCH 061/137] Create namespaces only if there is value to put (#117) --- languages/c/templates/modules/include/module.h | 7 ++++--- languages/c/templates/modules/src/module.cpp | 13 +++++++++---- .../c/templates/schemas/include/common/module.h | 6 +++--- languages/c/templates/schemas/src/jsondata_module.h | 4 ++-- languages/c/templates/schemas/src/module_common.cpp | 9 +++++++-- languages/c/templates/sections/accessors.c | 1 - languages/c/templates/sections/methods.c | 3 --- src/macrofier/engine.mjs | 11 ++++++++--- 8 files changed, 33 insertions(+), 21 deletions(-) diff --git a/languages/c/templates/modules/include/module.h b/languages/c/templates/modules/include/module.h index 00c5d595..176ff9c1 100644 --- a/languages/c/templates/modules/include/module.h +++ b/languages/c/templates/modules/include/module.h @@ -22,20 +22,21 @@ #include /* ${IMPORTS} */ -#ifdef __cplusplus +${if.declarations}#ifdef __cplusplus extern "C" { #endif // Enums - /* ${ENUMS} */ +// Accessors /* ${ACCESSORS} */ +// Methods & Events /* ${DECLARATIONS} */ #ifdef __cplusplus } -#endif +#endif${end.if.declarations} #endif // Header Include Guard diff --git a/languages/c/templates/modules/src/module.cpp b/languages/c/templates/modules/src/module.cpp index 2b467ae1..737d38df 100644 --- a/languages/c/templates/modules/src/module.cpp +++ b/languages/c/templates/modules/src/module.cpp @@ -20,23 +20,28 @@ /* ${IMPORTS} */ #include "${info.title.lowercase}.h" -namespace FireboltSDK { +${if.types}namespace FireboltSDK { namespace ${info.Title} { // Types /* ${TYPES} */ } -} +}${end.if.types} /* ${ENUMS} */ -#ifdef __cplusplus +${if.definitions}#ifdef __cplusplus extern "C" { #endif +// Accessors /* ${ACCESSORS} */ + +// Methods /* ${METHODS} */ + +// Events /* ${EVENTS} */ #ifdef __cplusplus } -#endif +#endif${end.if.definitions} diff --git a/languages/c/templates/schemas/include/common/module.h b/languages/c/templates/schemas/include/common/module.h index 939b3988..90f1f031 100644 --- a/languages/c/templates/schemas/include/common/module.h +++ b/languages/c/templates/schemas/include/common/module.h @@ -22,18 +22,18 @@ #include /* ${IMPORTS} */ -#ifdef __cplusplus +${if.declarations}#ifdef __cplusplus extern "C" { #endif // Enums - /* ${ENUMS} */ +// Types /* ${TYPES} */ #ifdef __cplusplus } -#endif +#endif${end.if.declarations} #endif // Header Include Guard diff --git a/languages/c/templates/schemas/src/jsondata_module.h b/languages/c/templates/schemas/src/jsondata_module.h index f80be03e..81084440 100644 --- a/languages/c/templates/schemas/src/jsondata_module.h +++ b/languages/c/templates/schemas/src/jsondata_module.h @@ -21,10 +21,10 @@ /* ${IMPORTS} */ #include "common/${info.title.lowercase}.h" -namespace FireboltSDK { +${if.schemas}namespace FireboltSDK { namespace ${info.Title} { // Types /* ${SCHEMAS} */ } -} +}${end.if.schemas} diff --git a/languages/c/templates/schemas/src/module_common.cpp b/languages/c/templates/schemas/src/module_common.cpp index 0d8c74d2..582a650b 100644 --- a/languages/c/templates/schemas/src/module_common.cpp +++ b/languages/c/templates/schemas/src/module_common.cpp @@ -22,14 +22,19 @@ /* ${ENUMS} */ -#ifdef __cplusplus +${if.definitions}#ifdef __cplusplus extern "C" { #endif + // Accessors /* ${ACCESSORS} */ + + // Methods /* ${METHODS} */ + + // Events /* ${EVENTS} */ #ifdef __cplusplus } -#endif +#endif${end.if.definitions} diff --git a/languages/c/templates/sections/accessors.c b/languages/c/templates/sections/accessors.c index 1c790810..9295133c 100644 --- a/languages/c/templates/sections/accessors.c +++ b/languages/c/templates/sections/accessors.c @@ -1,2 +1 @@ -// Accessors ${schema.list} diff --git a/languages/c/templates/sections/methods.c b/languages/c/templates/sections/methods.c index 3ab606c0..e8200eb0 100644 --- a/languages/c/templates/sections/methods.c +++ b/languages/c/templates/sections/methods.c @@ -1,4 +1 @@ - -// Methods - ${method.list} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 1ad8b6e6..ab3f9ee6 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -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, createPolymorphicMethods } from '../shared/modules.mjs' +import { isRPCOnlyMethod, isProviderInterfaceMethod, getProviderInterface, getPayloadFromEvent, providerHasNoParameters, isTemporalSetMethod, isCallsMetricsMethod, isExcludedMethod, 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' @@ -507,6 +507,11 @@ const insertMacros = (fContents = '', macros = {}) => { const quote = config.operators ? config.operators.stringQuotation : '"' const or = config.operators ? config.operators.or : ' | ' + fContents = fContents.replace(/\$\{if\.types\}(.*?)\$\{end\.if\.types\}/gms, macros.types.trim() ? '$1' : '') + fContents = fContents.replace(/\$\{if\.schemas\}(.*?)\$\{end\.if\.schemas\}/gms, macros.schemas.trim() ? '$1' : '') + fContents = fContents.replace(/\$\{if\.declarations\}(.*?)\$\{end\.if\.declarations\}/gms, (macros.accessors.trim() || macros.declarations.trim() || macros.enums.trim()) ? '$1' : '') + fContents = fContents.replace(/\$\{if\.definitions\}(.*?)\$\{end\.if\.definitions\}/gms, (macros.accessors.trim() || 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]*\/\* \$\{ACCESSORS\} \*\/[ \t]*\n/, macros.accessors) @@ -638,7 +643,7 @@ const generateEnums = (json, templates, options = { destination: '' }) => { return compose( option(''), map(val => { - let template = getTemplate(`/sections/enum.${suffix}`, templates) + let template = val ? getTemplate(`/sections/enum.${suffix}`, templates) : val return template ? template.replace(/\$\{schema.list\}/g, val.trimEnd()) : val }), map(reduce((acc, val) => acc.concat(val).concat('\n'), '')), @@ -1037,7 +1042,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, examples = {}) { const moduleName = getModuleName(json) const info = { From 6d43093021d65f0308c2ead74de2bd66e4437276 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 24 Jul 2023 09:12:21 +0530 Subject: [PATCH 062/137] Changes to avoid duplication of sub-array schema with same reference (#116) --- languages/c/Types.mjs | 2 ++ src/macrofier/engine.mjs | 23 +++++++++++++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 4c092a92..c4465bfe 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -304,6 +304,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref } + name = name.endsWith("_ArrayType") ? name.split('_ArrayType')[0] : name prefix = prefix ? prefix + name : name let n = getTypeName(getModuleName(module), capitalize(res.name), prefix) structure.name = name ? name + capitalize(res.name) : res.name @@ -539,6 +540,7 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' } if (!isCPP) { + name = name.endsWith("_ArrayType") ? name.split('_ArrayType')[0] : name let subPrefix = prefix ? prefix + name : name let info = getSchemaTypeInfo(module, j, j.title || name, schemas, subPrefix, {level : level, descriptions: descriptions, title: true}) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index ab3f9ee6..52641bdb 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -356,9 +356,24 @@ const generateAggregateMacros = (openrpc, modules, templates, library) => Object }) const addContentDescriptorSubSchema = (descriptor, prefix, obj) => { - const title = prefix.charAt(0).toUpperCase() + prefix.substring(1) + descriptor.name.charAt(0).toUpperCase() + descriptor.name.substring(1) - if (obj.components.schemas[title]) { - throw 'Generated name `' + title + '` already exists...' + let title = '' + if (descriptor.schema.type === 'array' && descriptor.schema.items && descriptor.schema.items['$ref']) { + let refName = descriptor.schema.items['$ref'].split('/').pop() + title = refName.charAt(0).toUpperCase() + refName.substring(1) + '_ArrayType' + if (obj.components.schemas[title]) { + descriptor.schema = { + $ref: "#/components/schemas/" + title + } + return + } + } + else { + let descriptorName = capitalize(descriptor.name) + let prefixName = capitalize(prefix) + title = (prefixName !== descriptorName) ? prefixName + descriptorName : descriptorName + if (obj.components.schemas[title]) { + throw 'Generated name `' + title + '` already exists...' + } } obj.components.schemas[title] = descriptor.schema obj.components.schemas[title].title = title @@ -367,7 +382,7 @@ const addContentDescriptorSubSchema = (descriptor, prefix, obj) => { } } -// only consider sub-objects and sub enums to be sub-schemas +// only consider sub-objects, sub-array and sub-enums to be sub-schemas const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) || (schema.type === 'array' && schema.items) const promoteAndNameSubSchemas = (obj) => { From 3a9472756d31aa3080a5df35d5a3ecb9c649a0c7 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Wed, 26 Jul 2023 09:19:20 +0530 Subject: [PATCH 063/137] =?UTF-8?q?detach=20setter=20declaration=20from=20?= =?UTF-8?q?property=20template=20and=20add=20setter=20templ=E2=80=A6=20(#1?= =?UTF-8?q?18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Detach setter declaration from property template and add setter template, remove unredundant warnings Cleanup changes, add separator between prefix and subSchema name generation Introduce excludeDeclarations flag to handle declaration exclusion specific to language Alignement changes + cleanup + OUT params support added to differentiate method signature parameters Update in static code --- languages/c/Types.mjs | 28 +++------ languages/c/language.config.json | 3 +- languages/c/src/shared/include/firebolt.h | 3 + languages/c/src/shared/include/types.h | 6 +- languages/c/src/shared/src/Logger/Logger.cpp | 7 ++- .../c/src/shared/src/Transport/Transport.h | 2 +- languages/c/src/shared/src/Types.cpp | 4 +- languages/c/src/shared/test/OpenRPCTests.cpp | 6 +- languages/c/src/types/ImplHelpers.mjs | 32 +++++------ languages/c/src/types/JSONHelpers.mjs | 2 +- languages/c/src/types/NativeHelpers.mjs | 57 +++---------------- languages/c/templates/declarations/default.c | 3 +- languages/c/templates/declarations/event.c | 1 + .../declarations/polymorphic-pull-event.c | 1 + .../templates/declarations/polymorphic-pull.c | 1 + languages/c/templates/declarations/setter.c | 2 + languages/c/templates/methods/calls-metrics.c | 6 +- languages/c/templates/methods/default.c | 5 +- languages/c/templates/methods/event.c | 1 + .../methods/polymorphic-pull-event.c | 1 + .../c/templates/methods/polymorphic-pull.c | 3 +- languages/c/templates/methods/property.c | 4 +- .../c/templates/modules/include/module.h | 2 + languages/c/templates/modules/src/module.cpp | 2 + .../c/templates/schemas/src/module_common.cpp | 14 +++-- languages/c/templates/sdk/scripts/install.sh | 2 +- src/macrofier/engine.mjs | 28 +++++---- src/macrofier/index.mjs | 2 + src/sdk/index.mjs | 1 + 29 files changed, 103 insertions(+), 126 deletions(-) create mode 100644 languages/c/templates/declarations/setter.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index c4465bfe..6c3c8311 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -18,8 +18,8 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' -import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' -import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation, getCallbackParametersInstantiation, getCallbackResultInstantiation, getCallbackResponseInstantiation } from './src/types/ImplHelpers.mjs' +import { getTypeName, getModuleName, description, getObjectManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getPropertyGetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' +import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation, getCallbackParametersInstantiation, getCallbackResultInstantiation, getCallbackResponseInstantiation } from './src/types/ImplHelpers.mjs' import { getJsonContainerDefinition, getJsonDataStructName, getJsonDataPrefix } from './src/types/JSONHelpers.mjs' const getSdkNameSpace = () => 'FireboltSDK' @@ -199,11 +199,7 @@ function getMethodSignature(method, module, { destination, isInterface = false } let paramList = getParamList(method, module) let resultType = method.result && getSchemaType(method.result.schema, module, { title: true, name: method.result.name, resultSchema: true}) || '' - signature = getPropertyGetterSignature(method, module, resultType, paramList) + ';\n\n' - - if (hasTag(method, 'property')) { - signature += getPropertySetterSignature(method, module, resultType, paramList) + ';\n\n' - } + signature = getPropertyGetterSignature(method, module, resultType, paramList) + ';\n' } return signature } @@ -408,10 +404,10 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' shape = '' } else if (json.properties && (validJsonObjectProperties(json) === true)) { - let c_shape = description(capitalize(name), json.description) + let c_shape = '\n' + description(capitalize(name), json.description) let cpp_shape = '' let tName = getTypeName(getModuleName(module), name, prefix) - c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(json, module, { name }))) + c_shape += '\n' + (isHeader ? getObjectManagement(tName) : getObjectManagementImpl(tName, getJsonType(json, module, { name }))) let props = [] let containerName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? (prefix + '_' + capitalize(name)) : capitalize(name) Object.entries(json.properties).forEach(([pname, prop]) => { @@ -461,9 +457,6 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' let property = getJsonType(prop, module, { name : pname, prefix }) props.push({name: `${pname}`, type: `${property}`}) } - else { - console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) - } } }) @@ -488,7 +481,7 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' } let tName = getTypeName(getModuleName(module), name, prefix) - let t = description(capitalize(name), json.description) + '\n' + let t = '\n' + description(capitalize(name), json.description) let containerType = 'WPEFramework::Core::JSON::VariantContainer' let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, module['x-schemas']) @@ -496,13 +489,10 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' // Handle Container generation here } - t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, containerType)) + t += '\n' + (isHeader ? getObjectManagement(tName) : getObjectManagementImpl(tName, containerType)) t += (isHeader ? getMapAccessors(tName, info.type, { descriptions: descriptions, level: level }) : getMapAccessorsImpl(tName, containerType, subModuleProperty.type, info.type, info.json, { readonly: true, optional: false })) shape += '\n' + t } - else if (json.patternProperties) { - console.log(`WARNING: patternProperties are not supported by Firebolt(inside getModuleName(module):${name})`) - } } else if (json.anyOf) { if (level > 0) { @@ -554,8 +544,8 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' let subModuleProperty = getJsonTypeInfo(module, j, j.title || name, schemas, prefix) let t = '' if (level === 0) { - t += description(capitalize(info.name), json.description) + '\n' - t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, moduleProperty.type)) + t += '\n' + description(capitalize(info.name), json.description) + t += '\n' + (isHeader ? getObjectManagement(tName) : getObjectManagementImpl(tName, moduleProperty.type)) } t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + '_t'), subModuleProperty.type, '', info.type, info.json)) shape += '\n' + t diff --git a/languages/c/language.config.json b/languages/c/language.config.json index b684e11b..b19eddb8 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -13,5 +13,6 @@ "/src/jsondata_module.h" ], "persistPermission": true, - "createPolymorphicMethods": true + "createPolymorphicMethods": true, + "excludeDeclarations":true } diff --git a/languages/c/src/shared/include/firebolt.h b/languages/c/src/shared/include/firebolt.h index 0957973f..565b363c 100644 --- a/languages/c/src/shared/include/firebolt.h +++ b/languages/c/src/shared/include/firebolt.h @@ -26,6 +26,9 @@ extern "C" { #endif +#define IN +#define OUT + /** * @brief Intitialize the Firebolt SDK * diff --git a/languages/c/src/shared/include/types.h b/languages/c/src/shared/include/types.h index 26efc54f..8333f0eb 100644 --- a/languages/c/src/shared/include/types.h +++ b/languages/c/src/shared/include/types.h @@ -26,9 +26,9 @@ extern "C" { #endif -typedef struct FireboltTypes_String_s* FireboltTypes_String_t; -const char* FireboltTypes_String(FireboltTypes_String_t handle); -void FireboltTypes_StringHandle_Release(FireboltTypes_String_t handle); +typedef struct Firebolt_String_s* Firebolt_String_t; +const char* Firebolt_String(Firebolt_String_t handle); +void Firebolt_String_Release(Firebolt_String_t handle); #ifdef __cplusplus } diff --git a/languages/c/src/shared/src/Logger/Logger.cpp b/languages/c/src/shared/src/Logger/Logger.cpp index a9750a6e..a16764f2 100644 --- a/languages/c/src/shared/src/Logger/Logger.cpp +++ b/languages/c/src/shared/src/Logger/Logger.cpp @@ -71,11 +71,14 @@ namespace FireboltSDK { char formattedMsg[Logger::MaxBufSize]; const string time = WPEFramework::Core::Time::Now().ToTimeOnly(true); const string categoryName = WPEFramework::Core::EnumerateType(category).Data(); +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-truncation" if (categoryName.empty() != true) { - sprintf(formattedMsg, "--->\033[1;32m[%s]:[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), categoryName.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); + snprintf(formattedMsg, sizeof(formattedMsg), "--->\033[1;32m[%s]:[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), categoryName.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); } else { - sprintf(formattedMsg, "--->\033[1;32m[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); + snprintf(formattedMsg, sizeof(formattedMsg), "--->\033[1;32m[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); } +#pragma GCC diagnostic pop LOG_MESSAGE(formattedMsg); } } diff --git a/languages/c/src/shared/src/Transport/Transport.h b/languages/c/src/shared/src/Transport/Transport.h index 109e2431..b3405b9c 100644 --- a/languages/c/src/shared/src/Transport/Transport.h +++ b/languages/c/src/shared/src/Transport/Transport.h @@ -254,7 +254,7 @@ namespace FireboltSDK { public: ChannelImpl(CommunicationChannel* parent, const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask) - : BaseClass(5, FactoryImpl::Instance(), path, _T("JSON"), query, "", false, mask, false, remoteNode.AnyInterface(), remoteNode, 1024 * 2, 1024 * 2) //TODO Relook this size issue + : BaseClass(5, FactoryImpl::Instance(), path, _T("JSON"), query, "", false, mask, false, remoteNode.AnyInterface(), remoteNode, 512, 512) , _parent(*parent) { } diff --git a/languages/c/src/shared/src/Types.cpp b/languages/c/src/shared/src/Types.cpp index b9620436..93f6a8d8 100644 --- a/languages/c/src/shared/src/Types.cpp +++ b/languages/c/src/shared/src/Types.cpp @@ -25,12 +25,12 @@ extern "C" { #endif // String Type Handler Interfaces -const char* FireboltTypes_String(FireboltTypes_String_t handle) +const char* Firebolt_String(Firebolt_String_t handle) { return ((reinterpret_cast(handle))->Value().c_str()); } -void FireboltTypes_StringHandle_Release(FireboltTypes_String_t handle) +void Firebolt_String_Release(Firebolt_String_t handle) { delete reinterpret_cast(handle); } diff --git a/languages/c/src/shared/test/OpenRPCTests.cpp b/languages/c/src/shared/test/OpenRPCTests.cpp index b74f17ae..11170c15 100644 --- a/languages/c/src/shared/test/OpenRPCTests.cpp +++ b/languages/c/src/shared/test/OpenRPCTests.cpp @@ -485,9 +485,9 @@ uint32_t test_string_set_get_value() uint32_t status = FireboltSDKErrorNone; FireboltSDK::JSON::String* str = new FireboltSDK::JSON::String(); WPEFramework::Core::JSON::String wpeJsonStr("TestString"); - FireboltTypes_String_t handle = reinterpret_cast(str); + Firebolt_String_t handle = reinterpret_cast(str); - const char* value = FireboltTypes_String(handle); + const char* value = Firebolt_String(handle); EXPECT_EQ(strncmp(value, str->Value().c_str(), str->Value().length()), 0); FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", " ---> type name = %s %s", str->Value().c_str(), value); @@ -495,7 +495,7 @@ uint32_t test_string_set_get_value() WPEFramework::Core::JSON::EnumType<::TestEnum> testEnum = Test4; FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", " EnumTest = %d %s", testEnum.Value(), testEnum.Data()); - FireboltTypes_StringHandle_Release(handle); + Firebolt_String_Release(handle); return status; } diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index 8dbe8f08..0ac77dd6 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -6,22 +6,22 @@ const getSdkNameSpace = () => 'FireboltSDK' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' const camelcase = str => str[0].toLowerCase() + str.substr(1) -const getObjectHandleManagementImpl = (varName, jsonDataName) => { +const getObjectManagementImpl = (varName, jsonDataName) => { - let result = `${varName}_t ${varName}Handle_Acquire(void) + let result = `${varName}_t ${varName}_Acquire(void) { WPEFramework::Core::ProxyType<${jsonDataName}>* type = new WPEFramework::Core::ProxyType<${jsonDataName}>(); *type = WPEFramework::Core::ProxyType<${jsonDataName}>::Create(); return (reinterpret_cast<${varName}_t>(type)); } -void ${varName}Handle_Addref(${varName}_t handle) +void ${varName}_Addref(${varName}_t handle) { ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${jsonDataName}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); var->AddRef(); } -void ${varName}Handle_Release(${varName}_t handle) +void ${varName}_Release(${varName}_t handle) { ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${jsonDataName}>* var = reinterpret_cast*>(handle); @@ -30,7 +30,7 @@ void ${varName}Handle_Release(${varName}_t handle) delete var; } } -bool ${varName}Handle_IsValid(${varName}_t handle) +bool ${varName}_IsValid(${varName}_t handle) { ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${jsonDataName}>* var = reinterpret_cast*>(handle); @@ -101,7 +101,7 @@ const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, return result } -const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPropertyType, subPropertyName, accessorPropertyType, json = {}) => { +const getArrayAccessorsImpl = (objName, modulePropertyType, objType, subPropertyType, subPropertyName, accessorPropertyType, json = {}) => { let propertyName if (subPropertyName) { @@ -112,7 +112,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr propertyName = '(*(*var))' } - let result = `uint32_t ${objName}Array_Size(${objHandleType} handle) { + let result = `uint32_t ${objName}Array_Size(${objType} handle) { ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); @@ -120,7 +120,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr return (${propertyName}.Length()); }` + '\n' - result += `${accessorPropertyType} ${objName}Array_Get(${objHandleType} handle, uint32_t index) + result += `${accessorPropertyType} ${objName}Array_Get(${objType} handle, uint32_t index) { ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); @@ -144,7 +144,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr result += `}` + '\n' let type = (accessorPropertyType === getFireboltStringType()) ? 'char*' : accessorPropertyType - result += `void ${objName}Array_Add(${objHandleType} handle, ${type} value) + result += `void ${objName}Array_Add(${objType} handle, ${type} value) { ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); @@ -162,7 +162,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr ${propertyName}.Add() = element; }` + '\n' - result += `void ${objName}Array_Clear(${objHandleType} handle) + result += `void ${objName}Array_Clear(${objType} handle) { ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); @@ -304,7 +304,7 @@ function getParameterInstantiation(paramList, container = '') { const name = param.name if (jsonType.length) { if (param.required) { - if (param.nativeType.includes('FireboltTypes_String_t')) { + if (param.nativeType.includes('Firebolt_String_t')) { impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = *(reinterpret_cast<${jsonType}*>(${name}));\n` } else if (param.nativeType.includes('_t')) { @@ -429,7 +429,7 @@ function getCallbackParametersInstantiation(paramList, container = '') { function getCallbackResultInstantiation(nativeType, container = '') { let impl = '' - if (nativeType === 'char*' || nativeType === 'FireboltTypes_String_t') { + if (nativeType === 'char*' || nativeType === 'Firebolt_String_t') { impl +=` ${container}* jsonStrResponse = new ${container}(); *jsonStrResponse = *(*jsonResponse); @@ -457,7 +457,7 @@ function getCallbackResponseInstantiation(paramList, nativeType, container = '') }) } - if (nativeType === 'char*' || nativeType === 'FireboltTypes_String_t') { + if (nativeType === 'char*' || nativeType === 'Firebolt_String_t') { impl += `reinterpret_cast<${nativeType}>(jsonStrResponse)` } else if (nativeType.includes('_t')) { @@ -470,13 +470,13 @@ function getCallbackResponseInstantiation(paramList, nativeType, container = '') return impl } -function getResultInstantiation (name, nativeType, container, indentLevel = 3) { +function getResultInstantiation (name, nativeType, container, indentLevel = 2) { let impl = '' if (nativeType) { impl += `${' '.repeat(indentLevel)}if (${name} != nullptr) {` + '\n' - if (nativeType === 'char*' || nativeType === 'FireboltTypes_String_t') { + if (nativeType === 'char*' || nativeType === 'Firebolt_String_t') { impl += `${' '.repeat(indentLevel + 1)}${container}* strResult = new ${container}(jsonResult);` + '\n' impl += `${' '.repeat(indentLevel + 1)}*${name} = reinterpret_cast<${getFireboltStringType()}>(strResult);` + '\n' } else if (nativeType.includes('_t')) { @@ -500,7 +500,7 @@ function getResultInstantiation (name, nativeType, container, indentLevel = 3) { export { getArrayAccessorsImpl, getMapAccessorsImpl, - getObjectHandleManagementImpl, + getObjectManagementImpl, getPropertyAccessorsImpl, getParameterInstantiation, getCallbackParametersInstantiation, diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index 954ac50d..1c5e3ea4 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -4,7 +4,7 @@ const getJsonDataPrefix = () => 'JsonData_' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' const getJsonDataStructName = (modName, name, prefix = '') => { - let result =((prefix && prefix.length > 0) && (prefix !== name)) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` + let result =((prefix && prefix.length > 0) && (prefix !== name)) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}_${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` return ((result.includes(wpeJsonNameSpace()) === true) ? result : `${getSdkNameSpace()}::${result}`) } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 3437c3f4..cc7ac662 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -29,7 +29,7 @@ const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = pre const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' -const getFireboltStringType = () => 'FireboltTypes_String_t' +const getFireboltStringType = () => 'Firebolt_String_t' const capitalize = str => str[0].toUpperCase() + str.substr(1) const description = (title, str='') => '/* ' + title + (str.length > 0 ? ' - ' + str : '') + ' */' @@ -64,13 +64,13 @@ const getNativeType = (json, fireboltString = false) => { return type } -const getObjectHandleManagement = varName => { +const getObjectManagement = varName => { let result = `typedef struct ${varName}_s* ${varName}_t; -${varName}_t ${varName}Handle_Acquire(void); -void ${varName}Handle_Addref(${varName}_t handle); -void ${varName}Handle_Release(${varName}_t handle); -bool ${varName}Handle_IsValid(${varName}_t handle); +${varName}_t ${varName}_Acquire(void); +void ${varName}_Addref(${varName}_t handle); +void ${varName}_Release(${varName}_t handle); +bool ${varName}_IsValid(${varName}_t handle); ` return result } @@ -111,7 +111,7 @@ const getTypeName = (moduleName, varName, prefix = '', upperCase = false, capita prefix = (prefix !== varName) ? (upperCase ? prefix.toUpperCase() : capitalize(prefix)) : '' } prefix = (prefix && prefix.length > 0) ?(upperCase ? prefix.toUpperCase() : capitalize(prefix)) : prefix - let name = (prefix && prefix.length > 0) ? `${mName}_${prefix}${vName}` : `${mName}_${vName}` + let name = (prefix && prefix.length > 0) ? `${mName}_${prefix}_${vName}` : `${mName}_${vName}` return name } @@ -155,57 +155,16 @@ function getPropertyGetterSignature(property, module, propType, paramList = []) return `uint32_t ${capitalize(getModuleName(module))}_Get${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType}* ${property.result.name || property.name} )` } -function getPropertySetterSignature(property, module, propType, paramList = []) { - let contextParams = '' - contextParams = getContextParams(paramList) - if (propType === getFireboltStringType()) { - propType = 'char*' - } - return `uint32_t ${capitalize(getModuleName(module))}_Set${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType} ${property.result.name || property.name} )` -} - -function getPropertyEventCallbackSignature(property, module, propType, paramList = []) { - - let contextParams = '' - contextParams = getContextParams(paramList) - return `/*Callback to listen to updates on ${property.Name} property*/\n` + - `typedef void (*On${capitalize(getModuleName(module))}${capitalize(property.name)}Changed)( ${contextParams}${contextParams.length > 0 ? ', ':''}const void* userData, ${propType} ${property.result.name || property.name})` -} - -function getPropertyEventInnerCallbackSignature(method, module, schemas) { - let signature = `static void ${capitalize(getModuleName(module)) + capitalize(method.name)}` -} - -function getPropertyEventRegisterSignature(property, module, paramList = []) { - let contextParams = '' - contextParams = getContextParams(paramList) - - return `/*Register to listen to updates on ${capitalize(property.name)} property*/\n` + - `uint32_t ${capitalize(getModuleName(module))}_Register_${capitalize(property.name)}Update( ${contextParams}${contextParams.length > 0 ? ', ':''}On${capitalize(getModuleName(module))}${capitalize(property.name)}Changed userCB, const void* userData )` - -} - -function getPropertyEventUnregisterSignature(property, module) { - return `/*Unregister to listen to updates on ${capitalize(property.name)} property*/\n` + - `uint32_t ${capitalize(getModuleName(module))}_Unregister_${capitalize(property.name)}Update( On${capitalize(getModuleName(module))}${capitalize(property.name)}Changed userCB )` - -} - - export { getNativeType, getModuleName, getPropertyGetterSignature, - getPropertySetterSignature, - getPropertyEventCallbackSignature, - getPropertyEventRegisterSignature, - getPropertyEventUnregisterSignature, getMapAccessors, getArrayAccessors, capitalize, description, getTypeName, - getObjectHandleManagement, + getObjectManagement, getPropertyAccessors, isOptional, generateEnum, diff --git a/languages/c/templates/declarations/default.c b/languages/c/templates/declarations/default.c index ac4e7f78..8879378d 100644 --- a/languages/c/templates/declarations/default.c +++ b/languages/c/templates/declarations/default.c @@ -1,3 +1,4 @@ /* ${method.name} - ${method.description} ${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation}${end.if.deprecated} */ -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 ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name}${end.if.result}${if.signature.empty}void${end.if.signature.empty} ); + diff --git a/languages/c/templates/declarations/event.c b/languages/c/templates/declarations/event.c index 45e4b608..4dc59c4a 100644 --- a/languages/c/templates/declarations/event.c +++ b/languages/c/templates/declarations/event.c @@ -2,3 +2,4 @@ typedef void (*${info.Title}${method.Name}Callback)( const void* userData, ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${event.result.type} ); 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 ); uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); + diff --git a/languages/c/templates/declarations/polymorphic-pull-event.c b/languages/c/templates/declarations/polymorphic-pull-event.c index 26f1f1c4..9b22619e 100644 --- a/languages/c/templates/declarations/polymorphic-pull-event.c +++ b/languages/c/templates/declarations/polymorphic-pull-event.c @@ -2,3 +2,4 @@ typedef void* (*${info.Title}${method.Name}Callback)( const void* userData, ${method.pulls.param.type} ); uint32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callback userCB, const void* userData ); uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); + diff --git a/languages/c/templates/declarations/polymorphic-pull.c b/languages/c/templates/declarations/polymorphic-pull.c index fbf74697..ca08d823 100644 --- a/languages/c/templates/declarations/polymorphic-pull.c +++ b/languages/c/templates/declarations/polymorphic-pull.c @@ -1,2 +1,3 @@ /* ${method.name} - ${method.description} */ uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ); + diff --git a/languages/c/templates/declarations/setter.c b/languages/c/templates/declarations/setter.c new file mode 100644 index 00000000..9fcd86a2 --- /dev/null +++ b/languages/c/templates/declarations/setter.c @@ -0,0 +1,2 @@ +/* ${method.rpc.name} - ${method.description} */ +uint32_t ${info.Title}_${method.Name}( ${method.signature.params} ); diff --git a/languages/c/templates/methods/calls-metrics.c b/languages/c/templates/methods/calls-metrics.c index 91831a3c..c8caa238 100644 --- a/languages/c/templates/methods/calls-metrics.c +++ b/languages/c/templates/methods/calls-metrics.c @@ -2,8 +2,7 @@ void Metrics_${method.Name}Dispatcher(const void*${if.result} result${end.if.result}) { Metrics_${method.Name}(${if.result}(static_cast<${method.result.json.type}>(const_cast(result)))${end.if.result}); } - -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 ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name}${end.if.result}${if.signature.empty}void${end.if.signature.empty} ) { uint32_t status = FireboltSDKErrorUnavailable; FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); @@ -14,7 +13,7 @@ uint32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${i status = transport->Invoke("${info.title}.${method.rpc.name}", jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); -${method.result.instantiation} + ${method.result.instantiation.with.indent} void* result = nullptr; ${if.result}result = static_cast(new ${method.result.json.type});${end.if.result} @@ -28,3 +27,4 @@ uint32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${i return status; } + diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 881b592c..d8f619c5 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -1,5 +1,5 @@ /* ${method.rpc.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 ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name}${end.if.result}${if.signature.empty}void${end.if.signature.empty} ) { uint32_t status = FireboltSDKErrorUnavailable; FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); @@ -10,7 +10,7 @@ uint32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${i status = transport->Invoke("${info.title.lowercase}.${method.rpc.name}", jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); -${method.result.instantiation} + ${method.result.instantiation.with.indent} } } else { @@ -19,3 +19,4 @@ uint32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${i return status; } + diff --git a/languages/c/templates/methods/event.c b/languages/c/templates/methods/event.c index c02e74c4..2a2de707 100644 --- a/languages/c/templates/methods/event.c +++ b/languages/c/templates/methods/event.c @@ -24,3 +24,4 @@ uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Cal { return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); } + diff --git a/languages/c/templates/methods/polymorphic-pull-event.c b/languages/c/templates/methods/polymorphic-pull-event.c index 7c833b71..5bf302b5 100644 --- a/languages/c/templates/methods/polymorphic-pull-event.c +++ b/languages/c/templates/methods/polymorphic-pull-event.c @@ -52,3 +52,4 @@ uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Cal { return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); } + diff --git a/languages/c/templates/methods/polymorphic-pull.c b/languages/c/templates/methods/polymorphic-pull.c index 759b0ae9..d543e3ce 100644 --- a/languages/c/templates/methods/polymorphic-pull.c +++ b/languages/c/templates/methods/polymorphic-pull.c @@ -5,7 +5,7 @@ uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ) FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { - string correlationId = ""; + string correlationId = ""; ${method.params.serialization.with.indent} WPEFramework::Core::JSON::Boolean jsonResult; @@ -20,3 +20,4 @@ uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ) return status; } + diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 7fb5b148..af6200c9 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,5 +1,5 @@ /* ${method.rpc.name} - ${method.description} */ -uint32_t ${info.Title}_Get${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name} ) +uint32_t ${info.Title}_Get${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name} ) { const string method = _T("${info.title.lowercase}.${method.rpc.name}"); ${if.params}${method.params.serialization}${end.if.params} @@ -7,9 +7,7 @@ uint32_t ${info.Title}_Get${method.Name}( ${method.signature.params}${if.params} ${if.params}uint32_t status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult);${end.if.params} ${if.params.empty}uint32_t status = FireboltSDK::Properties::Get(method, jsonResult);${end.if.params.empty} if (status == FireboltSDKErrorNone) { - if (${method.result.name} != nullptr) { ${method.result.instantiation} - } } return status; } diff --git a/languages/c/templates/modules/include/module.h b/languages/c/templates/modules/include/module.h index 176ff9c1..1c8d427b 100644 --- a/languages/c/templates/modules/include/module.h +++ b/languages/c/templates/modules/include/module.h @@ -32,6 +32,8 @@ extern "C" { // Accessors /* ${ACCESSORS} */ + + // Methods & Events /* ${DECLARATIONS} */ diff --git a/languages/c/templates/modules/src/module.cpp b/languages/c/templates/modules/src/module.cpp index 737d38df..19727924 100644 --- a/languages/c/templates/modules/src/module.cpp +++ b/languages/c/templates/modules/src/module.cpp @@ -36,6 +36,8 @@ extern "C" { // Accessors /* ${ACCESSORS} */ + + // Methods /* ${METHODS} */ diff --git a/languages/c/templates/schemas/src/module_common.cpp b/languages/c/templates/schemas/src/module_common.cpp index 582a650b..5bfa7719 100644 --- a/languages/c/templates/schemas/src/module_common.cpp +++ b/languages/c/templates/schemas/src/module_common.cpp @@ -26,14 +26,16 @@ extern "C" { #endif - // Accessors - /* ${ACCESSORS} */ +// Accessors +/* ${ACCESSORS} */ - // Methods - /* ${METHODS} */ - // Events - /* ${EVENTS} */ + +// Methods +/* ${METHODS} */ + +// Events +/* ${EVENTS} */ #ifdef __cplusplus } diff --git a/languages/c/templates/sdk/scripts/install.sh b/languages/c/templates/sdk/scripts/install.sh index 15596524..24bd1c4c 100755 --- a/languages/c/templates/sdk/scripts/install.sh +++ b/languages/c/templates/sdk/scripts/install.sh @@ -7,7 +7,7 @@ usage() echo " -m module name. i.e, core/manage" echo echo "usage: " - echo " ./install.sh -i path -s sdk path-m core" + echo " ./install.sh -i path -s sdk path -m core" } SdkPath=".." diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 52641bdb..527f8eeb 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -60,7 +60,8 @@ let types = { let config = { copySchemasIntoModules: false, - extractSubSchemas: false + extractSubSchemas: false, + excludeDeclarations: false } const state = { @@ -370,7 +371,7 @@ const addContentDescriptorSubSchema = (descriptor, prefix, obj) => { else { let descriptorName = capitalize(descriptor.name) let prefixName = capitalize(prefix) - title = (prefixName !== descriptorName) ? prefixName + descriptorName : descriptorName + title = (prefixName !== descriptorName) ? prefixName + '_' +descriptorName : descriptorName if (obj.components.schemas[title]) { throw 'Generated name `' + title + '` already exists...' } @@ -390,13 +391,15 @@ const promoteAndNameSubSchemas = (obj) => { obj = JSON.parse(JSON.stringify(obj)) // find anonymous method param or result schemas and name/promote them obj.methods && obj.methods.forEach(method => { - method.params && method.params.forEach(param => { - if (isSubSchema(param.schema)) { - addContentDescriptorSubSchema(param, method.name, obj) + if (!isExcludedMethod(method)) { + method.params && method.params.forEach(param => { + if (isSubSchema(param.schema)) { + addContentDescriptorSubSchema(param, method.name, obj) + } + }) + if (isSubSchema(method.result.schema)) { + addContentDescriptorSubSchema(method.result, method.name, obj) } - }) - if (isSubSchema(method.result.schema)) { - addContentDescriptorSubSchema(method.result, method.name, obj) } }) @@ -457,9 +460,9 @@ const generateMacros = (obj, templates, languages, options = {}) => { const examples = generateExamples(obj, templates, languages) const allMethodsArray = generateMethods(obj, examples, templates) - 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) + 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 declarations = declarationsArray.length ? getTemplate('/sections/declarations', templates).replace(/\$\{declaration\.list\}/g, declarationsArray.map(m => m.declaration).join('\n')) : '' const methods = methodsArray.length ? getTemplate('/sections/methods', templates).replace(/\$\{method.list\}/g, methodsArray.map(m => m.body).join('\n')) : '' @@ -529,7 +532,7 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{module.list\}/g, macros.module) fContents = fContents.replace(/[ \t]*\/\* \$\{METHODS\} \*\/[ \t]*\n/, macros.methods) - fContents = fContents.replace(/[ \t]*\/\* \$\{ACCESSORS\} \*\/[ \t]*\n/, macros.accessors) + fContents = fContents.replace(/[ \t]*\/\* \$\{ACCESSORS\} \*\/[ \t]*\n/, macros.accessors.trimStart('\n')) fContents = fContents.replace(/[ \t]*\/\* \$\{DECLARATIONS\} \*\/[ \t]*\n/, macros.declarations) fContents = fContents.replace(/[ \t]*\/\* \$\{METHOD_LIST\} \*\/[ \t]*\n/, macros.methodList.join(',\n')) fContents = fContents.replace(/[ \t]*\/\* \$\{EVENTS\} \*\/[ \t]*\n/, macros.events) @@ -1226,6 +1229,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) .replace(/\$\{method\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{method\.result\.instantiation\}/g, resultInst) + .replace(/\$\{method\.result\.instantiation\.with\.indent\}/g, indent(resultInst, ' ')) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) .replace(/\$\{method\.alternative.link\}/g, '#' + (method.alternative || "").toLowerCase()) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 86483fad..ce8d3d8d 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -48,6 +48,7 @@ const macrofy = async ( createModuleDirectories, copySchemasIntoModules, extractSubSchemas, + excludeDeclarations, aggregateFile, operators, hidePrivate = true, @@ -82,6 +83,7 @@ const macrofy = async ( copySchemasIntoModules, createModuleDirectories, extractSubSchemas, + excludeDeclarations, operators }) diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index 2e72ba9b..5d7effa2 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -63,6 +63,7 @@ const run = async ({ createModuleDirectories: config.createModuleDirectories, copySchemasIntoModules: config.copySchemasIntoModules, extractSubSchemas: config.extractSubSchemas, + excludeDeclarations: config.excludeDeclarations, staticModuleNames: staticModuleNames, hideExcluded: true, aggregateFile: config.aggregateFile, From 5fd33a49655fe86c1f619926c399b728099cea3c Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 7 Aug 2023 10:10:55 +0530 Subject: [PATCH 064/137] SubArray generation issue fix (#121) --- languages/c/Types.mjs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 6c3c8311..8b14f4c3 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -299,11 +299,12 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref res = getSchemaTypeInfo(module, json.items, json.items.name || name, schemas, prefix) } - name = name.endsWith("_ArrayType") ? name.split('_ArrayType')[0] : name - prefix = prefix ? prefix + name : name - let n = getTypeName(getModuleName(module), capitalize(res.name), prefix) - structure.name = name ? name + capitalize(res.name) : res.name + name = capitalize(name) + res.name = capitalize(res.name) + prefix = prefix ? prefix + ((name !== res.name) ? name : '') : name + let n = getTypeName(getModuleName(module), res.name, prefix) + structure.name = (name && (name !== res.name)) ? name + capitalize(res.name) : res.name structure.type = n + 'Array_t' structure.json = json structure.namespace = getModuleName(module) From 6c3b417e46bc5879a05a89b8534ae877ec124aa0 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 7 Aug 2023 10:11:35 +0530 Subject: [PATCH 065/137] cmake changes to install proper files (#119) --- languages/c/src/shared/CMakeLists.txt | 5 -- .../c/src/shared/cmake/HelperFunctions.cmake | 90 ++----------------- languages/c/src/shared/src/CMakeLists.txt | 28 +++--- languages/c/templates/sdk/scripts/build.sh | 13 +-- 4 files changed, 28 insertions(+), 108 deletions(-) diff --git a/languages/c/src/shared/CMakeLists.txt b/languages/c/src/shared/CMakeLists.txt index 5efcad1a..fe7a0085 100644 --- a/languages/c/src/shared/CMakeLists.txt +++ b/languages/c/src/shared/CMakeLists.txt @@ -23,11 +23,6 @@ set(FIREBOLT_LOGLEVEL "Info" CACHE STRING "Log level to be enabled") option(FIREBOLT_ENABLE_STATIC_LIB "Create Firebolt library as Static library" OFF) option(ENABLE_TESTS "Build openrpc native test" OFF) -if (NOT SYSROOT_PATH) - # Set sysroot to support PC builds, sysroot_path not configured case - set(SYSROOT_PATH "${CMAKE_SOURCE_DIR}/../../firebolt") -endif() - if (FIREBOLT_ENABLE_STATIC_LIB) set(FIREBOLT_LIBRARY_TYPE STATIC) else () diff --git a/languages/c/src/shared/cmake/HelperFunctions.cmake b/languages/c/src/shared/cmake/HelperFunctions.cmake index b3647c16..eb2ae296 100644 --- a/languages/c/src/shared/cmake/HelperFunctions.cmake +++ b/languages/c/src/shared/cmake/HelperFunctions.cmake @@ -56,89 +56,17 @@ function(InstallHeaders) list(APPEND subdirs ${directory}) foreach(subdir ${subdirs}) - set(dest ${destination}/${subdir}) - file(GLOB headers "${source}/${directory}/${subdir}/*.h") - if (headers) - add_custom_command( - TARGET ${Argument_TARGET} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_NAMESPACE}/usr/include/${dest} - COMMAND ${CMAKE_COMMAND} -E copy ${source}/${directory}/${subdir}/*.h ${CMAKE_BINARY_DIR}/${Argument_NAMESPACE}/usr/include/${dest} - ) + if (NOT subdir STREQUAL ".") + set(dest ${destination}/${subdir}) + file(GLOB headers "${source}/${directory}/${subdir}/*.h") + if (headers) + install( + DIRECTORY "${source}/${directory}/${subdir}" + DESTINATION include/${dest} + FILES_MATCHING PATTERN "*.h") + endif() endif() endforeach(subdir) endforeach(directory) endif() endfunction(InstallHeaders) - -function(InstallLibraries) - set(optionsArgs SHARED STATIC) - set(oneValueArgs TARGET DESTINATION LIBDIR) - set(multiValueArgs LIBRARIES) - - cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) - if (Argument_UNPARSED_ARGUMENTS) - message(FATAL_ERROR "Unknown keywords given to InstallLibraries(): \"${Argument_UNPARSED_ARGUMENTS}\"") - endif() - if (Argument_LIBRARIES) - add_custom_command( - TARGET ${Argument_TARGET} - POST_BUILD - COMMENT "=================== Installing Libraries ======================" - ) - foreach(LIBRARY ${Argument_LIBRARIES}) - if (Argument_SHARED) - add_custom_command( - TARGET ${Argument_TARGET} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_LIBDIR}/lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib - COMMAND ${CMAKE_COMMAND} -E create_symlink lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR} - COMMAND ${CMAKE_COMMAND} -E create_symlink lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/lib${LIBRARY}.so - ) - elseif (Argument_STATIC) - add_custom_command( - TARGET ${Argument_TARGET} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/lib${LIBRARY}.a ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib - ) - - endif() - endforeach(LIBRARY) - endif() -endfunction(InstallLibraries) - -function(InstallCMakeConfigs) - set(optionsArgs) - set(oneValueArgs TARGET DESTINATION) - set(multiValueArgs) - - cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) - if (Argument_UNPARSED_ARGUMENTS) - message(FATAL_ERROR "Unknown keywords given to InstallCMakeConfigs(): \"${Argument_UNPARSED_ARGUMENTS}\"") - endif() - if (Argument_TARGET) - if (${CMAKE_VERSION} VERSION_LESS "3.25.0") - set(EXPORT_CONFIG_PATH "lib/cmake/${Argument_TARGET}") - else () - set(EXPORT_CONFIG_PATH "*") - endif () - add_custom_command( - TARGET ${Argument_TARGET} - POST_BUILD - COMMENT "=================== Installing CMakeConfigs ======================" - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}Config*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Export/${EXPORT_CONFIG_PATH}/${Argument_TARGET}Targets*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} - ) - if (EXISTS ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}.pc) - add_custom_command( - TARGET ${Argument_TARGET} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/pkgconfig - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}.pc ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/pkgconfig - ) - endif() - endif() -endfunction(InstallCMakeConfigs) diff --git a/languages/c/src/shared/src/CMakeLists.txt b/languages/c/src/shared/src/CMakeLists.txt index b565d6b1..ecaf4efb 100644 --- a/languages/c/src/shared/src/CMakeLists.txt +++ b/languages/c/src/shared/src/CMakeLists.txt @@ -55,25 +55,19 @@ set_target_properties(${TARGET} PROPERTIES install( TARGETS ${TARGET} EXPORT ${TARGET}Targets - LIBRARY DESTINATION lib COMPONENT libs - PUBLIC_HEADER DESTINATION include/${TARGET} COMPONENT devel # headers for mac (note the different component -> different package) - INCLUDES DESTINATION include/${TARGET} # headers + ARCHIVE DESTINATION lib COMPONENT libs # static lib + LIBRARY DESTINATION lib COMPONENT libs # shared lib ) -InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION ${FIREBOLT_NAMESPACE}SDK) -InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} - SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../include DESTINATION ${FIREBOLT_NAMESPACE}) +install( + DIRECTORY ${CMAKE_SOURCE_DIR}/include/ + DESTINATION include/${FIREBOLT_NAMESPACE}SDK + FILES_MATCHING PATTERN "*.h") + +install( + FILES ${CMAKE_BINARY_DIR}/FireboltConfig.cmake + DESTINATION lib/cmake/${FIREBOLT_NAMESPACE}) -InstallLibraries(TARGET ${TARGET} ${FIREBOLT_LIBRARY_TYPE} LIBDIR ${LIBDIR} LIBRARIES ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION ${FIREBOLT_NAMESPACE}SDK) InstallCMakeConfig(TARGETS ${TARGET}) InstallPackageConfig(TARGETS ${TARGET} DESCRIPTION "Firebolt SDK Library") -InstallCMakeConfigs(TARGET ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) - -add_custom_command( - TARGET ${TARGET} - POST_BUILD - COMMENT "=================== Installing FireboltConfig & Helper CMakes ======================" - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/cmake/*.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} -) diff --git a/languages/c/templates/sdk/scripts/build.sh b/languages/c/templates/sdk/scripts/build.sh index d50295a6..149cd1ae 100755 --- a/languages/c/templates/sdk/scripts/build.sh +++ b/languages/c/templates/sdk/scripts/build.sh @@ -4,8 +4,9 @@ usage() echo "options:" echo " -p sdk path" echo " -s sysroot path" - echo " -t enable test" echo " -c clear build" + echo " -l enable static build" + echo " -t enable test" echo " -h : help" echo echo "usage: " @@ -16,13 +17,15 @@ SdkPath="." EnableTest="OFF" SysrootPath=${SYSROOT_PATH} ClearBuild="N" -while getopts p:s:tch flag +EnableStaticLib="OFF" +while getopts p:s:clth flag do case "${flag}" in p) SdkPath="${OPTARG}";; s) SysrootPath="${OPTARG}";; - t) EnableTest="ON";; c) ClearBuild="Y";; + l) EnableStaticLib="ON";; + t) EnableTest="ON";; h) usage && exit 1;; esac done @@ -32,6 +35,6 @@ then rm -rf ${SdkPath}/build fi -cmake -B${SdkPath}/build -S${SdkPath} -DSYSROOT_PATH=${SysrootPath} -DENABLE_TESTS=${EnableTest} +cmake -B${SdkPath}/build -S${SdkPath} -DSYSROOT_PATH=${SysrootPath} -DENABLE_TESTS=${EnableTest} -DHIDE_NON_EXTERNAL_SYMBOLS=OFF -DFIREBOLT_ENABLE_STATIC_LIB=${EnableStaticLib} cmake --build ${SdkPath}/build -cmake --install ${SdkPath}/build --prefix=${SdkPath}/build/Firebolt +cmake --install ${SdkPath}/build --prefix=${SdkPath}/build/Firebolt/usr From 37dd5a66febdde59f6d63979218dda56628291b7 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 26 Apr 2023 10:25:43 -0400 Subject: [PATCH 066/137] chore: Copy JS templates to C and create language.config.json --- languages/c/Types.mjs | 78 +++++++++++++++++++ languages/c/language.config.json | 14 ++++ languages/c/src/index.mjs | 19 +++++ languages/c/src/types/CommonCppTypes.mjs | 60 ++++++++++++++ languages/c/src/types/CommonHeaderTypes.mjs | 55 +++++++++++++ languages/c/src/types/CppTypes.mjs | 55 +++++++++++++ languages/c/src/types/HeaderTypes.mjs | 55 +++++++++++++ languages/c/src/types/JSONTypes.mjs | 56 +++++++++++++ languages/c/templates/codeblocks/export.mjs | 1 + .../c/templates/codeblocks/mock-import.mjs | 1 + .../c/templates/codeblocks/mock-parameter.mjs | 1 + languages/c/templates/codeblocks/module.mjs | 11 +++ languages/c/templates/declarations/clear.js | 0 languages/c/templates/declarations/default.js | 4 + languages/c/templates/declarations/listen.js | 0 languages/c/templates/declarations/once.js | 0 .../declarations/polymorphic-reducer.js | 6 ++ languages/c/templates/declarations/provide.js | 0 .../c/templates/declarations/rpc-only.js | 0 languages/c/templates/defaults/default.mjs | 1 + languages/c/templates/defaults/property.mjs | 1 + languages/c/templates/examples/default.md | 6 ++ languages/c/templates/examples/event.md | 5 ++ .../examples/polymorphic-pull-event.md | 9 +++ .../c/templates/examples/polymorphic-pull.md | 6 ++ languages/c/templates/examples/provider.md | 10 +++ languages/c/templates/examples/setter.md | 6 ++ languages/c/templates/examples/subscriber.md | 7 ++ languages/c/templates/examples/synchronous.md | 4 + .../c/templates/examples/temporal-set.md | 13 ++++ .../c/templates/imports/context-event.mjs | 1 + languages/c/templates/imports/event.mjs | 2 + languages/c/templates/imports/property.mjs | 1 + languages/c/templates/imports/provider.mjs | 2 + languages/c/templates/imports/rpc.mjs | 1 + .../c/templates/imports/temporal-set.mjs | 1 + languages/c/templates/imports/x-method.mjs | 1 + .../templates/initializations/deprecated.mjs | 1 + .../c/templates/initializations/event.mjs | 1 + .../c/templates/initializations/provider.mjs | 1 + languages/c/templates/methods/clear.js | 0 languages/c/templates/methods/default.js | 7 ++ languages/c/templates/methods/listen.js | 0 languages/c/templates/methods/once.js | 0 .../templates/methods/polymorphic-reducer.js | 11 +++ languages/c/templates/methods/provide.js | 3 + languages/c/templates/methods/rpc-only.js | 0 .../templates/modules/include/Common/Module.h | 23 ++++++ .../c/templates/modules/include/Module.h | 25 ++++++ .../c/templates/modules/src/JsonData_Module.h | 23 ++++++ languages/c/templates/modules/src/Module.cpp | 29 +++++++ .../c/templates/modules/src/Module_Common.cpp | 26 +++++++ languages/c/templates/parameters/default.js | 1 + languages/c/templates/schemas/default.js | 5 ++ .../templates/schemas/include/Common/Module.h | 25 ++++++ .../c/templates/schemas/include/Module.h | 23 ++++++ .../c/templates/schemas/src/JsonData_Module.h | 23 ++++++ languages/c/templates/schemas/src/Module.cpp | 29 +++++++ .../c/templates/schemas/src/Module_Common.cpp | 26 +++++++ languages/c/templates/sdk/main.cpp | 30 +++++++ .../c/templates/sections/declarations.js | 1 + languages/c/templates/sections/events.js | 1 + languages/c/templates/sections/methods.js | 3 + .../templates/sections/provider-interfaces.js | 11 +++ languages/c/templates/sections/schemas.js | 3 + languages/c/templates/types/enum.mjs | 3 + 66 files changed, 827 insertions(+) create mode 100644 languages/c/Types.mjs create mode 100644 languages/c/language.config.json create mode 100644 languages/c/src/index.mjs create mode 100644 languages/c/src/types/CommonCppTypes.mjs create mode 100644 languages/c/src/types/CommonHeaderTypes.mjs create mode 100644 languages/c/src/types/CppTypes.mjs create mode 100644 languages/c/src/types/HeaderTypes.mjs create mode 100644 languages/c/src/types/JSONTypes.mjs create mode 100644 languages/c/templates/codeblocks/export.mjs create mode 100644 languages/c/templates/codeblocks/mock-import.mjs create mode 100644 languages/c/templates/codeblocks/mock-parameter.mjs create mode 100644 languages/c/templates/codeblocks/module.mjs create mode 100644 languages/c/templates/declarations/clear.js create mode 100644 languages/c/templates/declarations/default.js create mode 100644 languages/c/templates/declarations/listen.js create mode 100644 languages/c/templates/declarations/once.js create mode 100644 languages/c/templates/declarations/polymorphic-reducer.js create mode 100644 languages/c/templates/declarations/provide.js create mode 100644 languages/c/templates/declarations/rpc-only.js create mode 100644 languages/c/templates/defaults/default.mjs create mode 100644 languages/c/templates/defaults/property.mjs create mode 100644 languages/c/templates/examples/default.md create mode 100644 languages/c/templates/examples/event.md create mode 100644 languages/c/templates/examples/polymorphic-pull-event.md create mode 100644 languages/c/templates/examples/polymorphic-pull.md create mode 100644 languages/c/templates/examples/provider.md create mode 100644 languages/c/templates/examples/setter.md create mode 100644 languages/c/templates/examples/subscriber.md create mode 100644 languages/c/templates/examples/synchronous.md create mode 100644 languages/c/templates/examples/temporal-set.md create mode 100644 languages/c/templates/imports/context-event.mjs create mode 100644 languages/c/templates/imports/event.mjs create mode 100644 languages/c/templates/imports/property.mjs create mode 100644 languages/c/templates/imports/provider.mjs create mode 100644 languages/c/templates/imports/rpc.mjs create mode 100644 languages/c/templates/imports/temporal-set.mjs create mode 100644 languages/c/templates/imports/x-method.mjs create mode 100644 languages/c/templates/initializations/deprecated.mjs create mode 100644 languages/c/templates/initializations/event.mjs create mode 100644 languages/c/templates/initializations/provider.mjs create mode 100644 languages/c/templates/methods/clear.js create mode 100644 languages/c/templates/methods/default.js create mode 100644 languages/c/templates/methods/listen.js create mode 100644 languages/c/templates/methods/once.js create mode 100644 languages/c/templates/methods/polymorphic-reducer.js create mode 100644 languages/c/templates/methods/provide.js create mode 100644 languages/c/templates/methods/rpc-only.js create mode 100644 languages/c/templates/modules/include/Common/Module.h create mode 100644 languages/c/templates/modules/include/Module.h create mode 100644 languages/c/templates/modules/src/JsonData_Module.h create mode 100644 languages/c/templates/modules/src/Module.cpp create mode 100644 languages/c/templates/modules/src/Module_Common.cpp create mode 100644 languages/c/templates/parameters/default.js create mode 100644 languages/c/templates/schemas/default.js create mode 100644 languages/c/templates/schemas/include/Common/Module.h create mode 100644 languages/c/templates/schemas/include/Module.h create mode 100644 languages/c/templates/schemas/src/JsonData_Module.h create mode 100644 languages/c/templates/schemas/src/Module.cpp create mode 100644 languages/c/templates/schemas/src/Module_Common.cpp create mode 100644 languages/c/templates/sdk/main.cpp create mode 100644 languages/c/templates/sections/declarations.js create mode 100644 languages/c/templates/sections/events.js create mode 100644 languages/c/templates/sections/methods.js create mode 100644 languages/c/templates/sections/provider-interfaces.js create mode 100644 languages/c/templates/sections/schemas.js create mode 100644 languages/c/templates/types/enum.mjs diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs new file mode 100644 index 00000000..31f48dd1 --- /dev/null +++ b/languages/c/Types.mjs @@ -0,0 +1,78 @@ +/* + * Copyright 2021 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 + */ + +import jsonTypes from './src/types/JSONTypes.mjs' +import commonTypes from './src/types/CommonCppTypes.mjs' +import headerCommonTypes from './src/types/CommonHeaderTypes.mjs' +import headerTypes from './src/types/HeaderTypes.mjs' +import cppTypes from './src/types/CppTypes.mjs' + +import path from "path" + +const isSynchronous = m => !m.tags ? false : m.tags.map(t => t.name).find(s => s === 'synchronous') + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return routeToDestination('getMethodSignature', arguments) +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return routeToDestination('getMethodSignatureParams', arguments) +} + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + return routeToDestination('getSchemaShape', arguments) +} + +function getSchemaType(schema, module, { destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + const value = routeToDestination('getSchemaType', arguments) + return value +} + +function routeToDestination(method, args) { + const destination = args[args.length-1].destination || '' + + if ( path.basename(destination) === 'JsonData_Module.h') { + return jsonTypes[method](...args) + } + else if (path.basename(destination) === 'Module.cpp') { + return cppTypes[method](...args) + } + else if (path.basename(destination) === 'Module_Common.cpp') { + return commonTypes[method](...args) + } + else if (path.basename(destination) === 'Module.h' && path.dirname(destination).endsWith(path.sep + 'Common')) { + return headerCommonTypes[method](...args) + } + else if (path.basename(destination) === 'Module.h') { + return headerTypes[method](...args) + } + + return '' +} + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/language.config.json b/languages/c/language.config.json new file mode 100644 index 00000000..185b0370 --- /dev/null +++ b/languages/c/language.config.json @@ -0,0 +1,14 @@ +{ + "name": "C", + "langcode": "c", + "createModuleDirectories": false, + "templatesPerModule": [ + "/include/Module.h", + "/src/Module.cpp" + ], + "templatesPerSchema": [ + "/include/Common/Module.h", + "/src/Module_Common.cpp", + "/src/JsonData_Module.h" + ] +} \ No newline at end of file diff --git a/languages/c/src/index.mjs b/languages/c/src/index.mjs new file mode 100644 index 00000000..51c547a1 --- /dev/null +++ b/languages/c/src/index.mjs @@ -0,0 +1,19 @@ +/* + * Copyright 2021 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 + */ + +export { default as Transport } from './shared/Transport/index.mjs' \ No newline at end of file diff --git a/languages/c/src/types/CommonCppTypes.mjs b/languages/c/src/types/CommonCppTypes.mjs new file mode 100644 index 00000000..863cd77b --- /dev/null +++ b/languages/c/src/types/CommonCppTypes.mjs @@ -0,0 +1,60 @@ +/* + * Copyright 2021 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 + */ + +// import deepmerge from 'deepmerge' +// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' +// import { getLinkFromRef } from '../../src/shared/markdown.mjs' +// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' + + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return `// Common CPP Signatures for ${module}_${method}` +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return `// Common CPP Signature Params for ${module}_${method}` +} + +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + + return { + dependencies: [], + code: `// Common CPP Schema Shape` + } + return `// Common CPP Schema Shape` +} + +function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + return `// Common CPP Schema Type` +} + + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/src/types/CommonHeaderTypes.mjs b/languages/c/src/types/CommonHeaderTypes.mjs new file mode 100644 index 00000000..9c40c084 --- /dev/null +++ b/languages/c/src/types/CommonHeaderTypes.mjs @@ -0,0 +1,55 @@ +/* + * Copyright 2021 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 + */ + +// import deepmerge from 'deepmerge' +// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' +// import { getLinkFromRef } from '../../src/shared/markdown.mjs' +// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' + + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return `// common .h Signatures for ${module}_${method}` +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return `// common .h Signature Params for ${module}_${method}` +} + +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + return `// common .h Schema Shape` +} + +function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + return `// common .h Schema Type` +} + + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/src/types/CppTypes.mjs b/languages/c/src/types/CppTypes.mjs new file mode 100644 index 00000000..4b6fa6a8 --- /dev/null +++ b/languages/c/src/types/CppTypes.mjs @@ -0,0 +1,55 @@ +/* + * Copyright 2021 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 + */ + +// import deepmerge from 'deepmerge' +// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' +// import { getLinkFromRef } from '../../src/shared/markdown.mjs' +// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' + + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return `// CPP Signatures for ${module}_${method}` +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return `// CPP Signature Params for ${module}_${method}` +} + +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + return `// CPP Schema Shape` +} + +function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + return `// CPP Schema Type` +} + + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/src/types/HeaderTypes.mjs b/languages/c/src/types/HeaderTypes.mjs new file mode 100644 index 00000000..9ce0155e --- /dev/null +++ b/languages/c/src/types/HeaderTypes.mjs @@ -0,0 +1,55 @@ +/* + * Copyright 2021 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 + */ + +// import deepmerge from 'deepmerge' +// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' +// import { getLinkFromRef } from '../../src/shared/markdown.mjs' +// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' + + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return `// .h Signatures for ${module.info.title}_${method.name}` +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return `// .h Signature Params for ${module.info.title}_${method.name}` +} + +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + return `// .h Schema Shape` +} + +function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + return `// .h Schema Type` +} + + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/src/types/JSONTypes.mjs b/languages/c/src/types/JSONTypes.mjs new file mode 100644 index 00000000..d2961794 --- /dev/null +++ b/languages/c/src/types/JSONTypes.mjs @@ -0,0 +1,56 @@ + +/* + * Copyright 2021 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 + */ + +// import deepmerge from 'deepmerge' +// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' +// import { getLinkFromRef } from '../../src/shared/markdown.mjs' +// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' + + +// getMethodSignature(method, module, options = { destination: 'file.txt' }) +// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) +// getSchemaType(schema, module, options = { destination: 'file.txt' }) +// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) + +function getMethodSignature(method, module, { destination = '' } = {}) { + return `// JSON Signatures for ${module}_${method}` +} + +function getMethodSignatureParams(method, module, { destination = '' } = {}) { + return `// JSON Signature Params for ${module}_${method}` +} + +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { + return `// JSON Schema Shape` +} + +function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + return `// JSON Schema Type` +} + + +export default { + getMethodSignature, + getMethodSignatureParams, + getSchemaShape, + getSchemaType, +} \ No newline at end of file diff --git a/languages/c/templates/codeblocks/export.mjs b/languages/c/templates/codeblocks/export.mjs new file mode 100644 index 00000000..c98498e4 --- /dev/null +++ b/languages/c/templates/codeblocks/export.mjs @@ -0,0 +1 @@ +export { default as ${info.title} } from './${info.title}/index.mjs' \ No newline at end of file diff --git a/languages/c/templates/codeblocks/mock-import.mjs b/languages/c/templates/codeblocks/mock-import.mjs new file mode 100644 index 00000000..5d22512a --- /dev/null +++ b/languages/c/templates/codeblocks/mock-import.mjs @@ -0,0 +1 @@ +import { default as _${info.title} } from './${info.title}/defaults.mjs' \ No newline at end of file diff --git a/languages/c/templates/codeblocks/mock-parameter.mjs b/languages/c/templates/codeblocks/mock-parameter.mjs new file mode 100644 index 00000000..63e63902 --- /dev/null +++ b/languages/c/templates/codeblocks/mock-parameter.mjs @@ -0,0 +1 @@ + ${info.title}: _${info.title}, \ No newline at end of file diff --git a/languages/c/templates/codeblocks/module.mjs b/languages/c/templates/codeblocks/module.mjs new file mode 100644 index 00000000..48f6d6bc --- /dev/null +++ b/languages/c/templates/codeblocks/module.mjs @@ -0,0 +1,11 @@ +// JEREMY + +export module ${info.title} { + + /* ${SCHEMAS} */ + + /* ${DECLARATIONS} */ + + /* ${PROVIDERS} */ + +} \ No newline at end of file diff --git a/languages/c/templates/declarations/clear.js b/languages/c/templates/declarations/clear.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/declarations/default.js b/languages/c/templates/declarations/default.js new file mode 100644 index 00000000..bd8b6fcf --- /dev/null +++ b/languages/c/templates/declarations/default.js @@ -0,0 +1,4 @@ + /** + * ${method.summary} + ${method.params} */ + ${method.signature} diff --git a/languages/c/templates/declarations/listen.js b/languages/c/templates/declarations/listen.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/declarations/once.js b/languages/c/templates/declarations/once.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/declarations/polymorphic-reducer.js b/languages/c/templates/declarations/polymorphic-reducer.js new file mode 100644 index 00000000..979832b2 --- /dev/null +++ b/languages/c/templates/declarations/polymorphic-reducer.js @@ -0,0 +1,6 @@ + /** + * ${method.summary} + ${method.params} */ + ${method.signature} + +// TODO: generate reducer signature \ No newline at end of file diff --git a/languages/c/templates/declarations/provide.js b/languages/c/templates/declarations/provide.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/declarations/rpc-only.js b/languages/c/templates/declarations/rpc-only.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/defaults/default.mjs b/languages/c/templates/defaults/default.mjs new file mode 100644 index 00000000..e29085d1 --- /dev/null +++ b/languages/c/templates/defaults/default.mjs @@ -0,0 +1 @@ + ${method.name}: ${method.example.value} \ No newline at end of file diff --git a/languages/c/templates/defaults/property.mjs b/languages/c/templates/defaults/property.mjs new file mode 100644 index 00000000..95ef20cf --- /dev/null +++ b/languages/c/templates/defaults/property.mjs @@ -0,0 +1 @@ + ${method.name}: function () { return MockProps.mock('${info.title}', '${method.name}', arguments, ${method.example.value}) } \ No newline at end of file diff --git a/languages/c/templates/examples/default.md b/languages/c/templates/examples/default.md new file mode 100644 index 00000000..ecc979ba --- /dev/null +++ b/languages/c/templates/examples/default.md @@ -0,0 +1,6 @@ +import { ${module} } from '${package.name}' + +${module}.${method.name}(${example.params}) + .then(${method.result.name} => { + console.log(${method.result.name}) + }) \ No newline at end of file diff --git a/languages/c/templates/examples/event.md b/languages/c/templates/examples/event.md new file mode 100644 index 00000000..7b78fe76 --- /dev/null +++ b/languages/c/templates/examples/event.md @@ -0,0 +1,5 @@ +import { ${module} } from '${package.name}' + +${module}.listen('${event.name}', ${method.result.name} => { + console.log(${method.result.name}) +}) \ No newline at end of file diff --git a/languages/c/templates/examples/polymorphic-pull-event.md b/languages/c/templates/examples/polymorphic-pull-event.md new file mode 100644 index 00000000..7bc2baa7 --- /dev/null +++ b/languages/c/templates/examples/polymorphic-pull-event.md @@ -0,0 +1,9 @@ +import { ${module} } from '${package.name}' + +${module}.${method.pulls.for}(function(parameters) { + console.log(parameters.entityId) + console.log(parameters.assetId) + return Promise.resolve(${originator.params[1].example.value}) +}).then(success => { + console.log(success) +}) \ No newline at end of file diff --git a/languages/c/templates/examples/polymorphic-pull.md b/languages/c/templates/examples/polymorphic-pull.md new file mode 100644 index 00000000..7c53080c --- /dev/null +++ b/languages/c/templates/examples/polymorphic-pull.md @@ -0,0 +1,6 @@ +import { ${module} } from '${package.name}' + +${module}.${method.name}(${method.params[1].example.value}) + .then(success => { + console.log(success) + }) \ No newline at end of file diff --git a/languages/c/templates/examples/provider.md b/languages/c/templates/examples/provider.md new file mode 100644 index 00000000..d2d16366 --- /dev/null +++ b/languages/c/templates/examples/provider.md @@ -0,0 +1,10 @@ +import { ${module} } from '${package.name}' + +class MyProvider { + async ${example.providerMethod}(${method.result.name}, responder) { + console.log(JSON.stringify(${method.result.name}, null, 2)) + responder(${example.providerResponse}) + } +} + +${module}.provide(new MyProvider()) \ No newline at end of file diff --git a/languages/c/templates/examples/setter.md b/languages/c/templates/examples/setter.md new file mode 100644 index 00000000..c258314a --- /dev/null +++ b/languages/c/templates/examples/setter.md @@ -0,0 +1,6 @@ +import { ${module} } from '${package.name}' + +${module}.${method.setter.for}(${example.params}) + .then(${method.result.name} => { + console.log(${method.result.name}) + }) \ No newline at end of file diff --git a/languages/c/templates/examples/subscriber.md b/languages/c/templates/examples/subscriber.md new file mode 100644 index 00000000..99c0516f --- /dev/null +++ b/languages/c/templates/examples/subscriber.md @@ -0,0 +1,7 @@ +import { ${module} } from '${package.name}' + +${method.alternative}(value => { + console.log(value) +}).then(listenerId => { + console.log(listenerId) +}) \ No newline at end of file diff --git a/languages/c/templates/examples/synchronous.md b/languages/c/templates/examples/synchronous.md new file mode 100644 index 00000000..6e8e1e82 --- /dev/null +++ b/languages/c/templates/examples/synchronous.md @@ -0,0 +1,4 @@ +import { ${module} } from '${package.name}' + +const ${method.result.name} = ${module}.${method.name}(${example.params}) +console.log(${method.result.name}) \ No newline at end of file diff --git a/languages/c/templates/examples/temporal-set.md b/languages/c/templates/examples/temporal-set.md new file mode 100644 index 00000000..4a8e94ea --- /dev/null +++ b/languages/c/templates/examples/temporal-set.md @@ -0,0 +1,13 @@ +import { ${module} } from '${package.name}' + +const process = ${module}.${method.name}(function(${example.params}${if.params},${end.if.params} + ${method.item} => { + console.log('Added to temporal set:') + console.dir(${method.item}) + }, + ${method.item} => { + console.log('Removed from temporal set:') + console.dir(${method.item}) + }) + +setTimeout( () => process.stop(), 10000) \ No newline at end of file diff --git a/languages/c/templates/imports/context-event.mjs b/languages/c/templates/imports/context-event.mjs new file mode 100644 index 00000000..fcd3186b --- /dev/null +++ b/languages/c/templates/imports/context-event.mjs @@ -0,0 +1 @@ +import { registerEventContext } from '../Events/index.mjs' diff --git a/languages/c/templates/imports/event.mjs b/languages/c/templates/imports/event.mjs new file mode 100644 index 00000000..bc019bca --- /dev/null +++ b/languages/c/templates/imports/event.mjs @@ -0,0 +1,2 @@ +import Events from '../Events/index.mjs' +import { registerEvents } from '../Events/index.mjs' diff --git a/languages/c/templates/imports/property.mjs b/languages/c/templates/imports/property.mjs new file mode 100644 index 00000000..7107a163 --- /dev/null +++ b/languages/c/templates/imports/property.mjs @@ -0,0 +1 @@ +import Prop from '../Prop/index.mjs' diff --git a/languages/c/templates/imports/provider.mjs b/languages/c/templates/imports/provider.mjs new file mode 100644 index 00000000..b3ea7b4f --- /dev/null +++ b/languages/c/templates/imports/provider.mjs @@ -0,0 +1,2 @@ +import ProvideManager from '../ProvideManager/index.mjs' +import { registerProviderInterface } from '../ProvideManager/index.mjs' diff --git a/languages/c/templates/imports/rpc.mjs b/languages/c/templates/imports/rpc.mjs new file mode 100644 index 00000000..af459a1e --- /dev/null +++ b/languages/c/templates/imports/rpc.mjs @@ -0,0 +1 @@ +import Transport from '../Transport/index.mjs' diff --git a/languages/c/templates/imports/temporal-set.mjs b/languages/c/templates/imports/temporal-set.mjs new file mode 100644 index 00000000..089d35b1 --- /dev/null +++ b/languages/c/templates/imports/temporal-set.mjs @@ -0,0 +1 @@ +import TemporalSet from '../TemporalSet/index.mjs' \ No newline at end of file diff --git a/languages/c/templates/imports/x-method.mjs b/languages/c/templates/imports/x-method.mjs new file mode 100644 index 00000000..42453ecb --- /dev/null +++ b/languages/c/templates/imports/x-method.mjs @@ -0,0 +1 @@ +import Results from '../Results/index.mjs' \ No newline at end of file diff --git a/languages/c/templates/initializations/deprecated.mjs b/languages/c/templates/initializations/deprecated.mjs new file mode 100644 index 00000000..737d1c25 --- /dev/null +++ b/languages/c/templates/initializations/deprecated.mjs @@ -0,0 +1 @@ +Transport.registerDeprecatedMethod('${info.title}', '${method.name}', 'Use ${method.alternative} instead.') diff --git a/languages/c/templates/initializations/event.mjs b/languages/c/templates/initializations/event.mjs new file mode 100644 index 00000000..c151f674 --- /dev/null +++ b/languages/c/templates/initializations/event.mjs @@ -0,0 +1 @@ +registerEvents('${info.title}', ${events.array}) diff --git a/languages/c/templates/initializations/provider.mjs b/languages/c/templates/initializations/provider.mjs new file mode 100644 index 00000000..b113d236 --- /dev/null +++ b/languages/c/templates/initializations/provider.mjs @@ -0,0 +1 @@ +registerProviderInterface('${capability}', '${info.title}', ${interface}) diff --git a/languages/c/templates/methods/clear.js b/languages/c/templates/methods/clear.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/methods/default.js b/languages/c/templates/methods/default.js new file mode 100644 index 00000000..0c7f799b --- /dev/null +++ b/languages/c/templates/methods/default.js @@ -0,0 +1,7 @@ + +function ${method.name}(${method.params.list}) { + + const transforms = ${method.transforms} + + return Transport.send('${info.title}', '${method.name}', { ${method.params.list} }, transforms) +} \ No newline at end of file diff --git a/languages/c/templates/methods/listen.js b/languages/c/templates/methods/listen.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/methods/once.js b/languages/c/templates/methods/once.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/methods/polymorphic-reducer.js b/languages/c/templates/methods/polymorphic-reducer.js new file mode 100644 index 00000000..db07747f --- /dev/null +++ b/languages/c/templates/methods/polymorphic-reducer.js @@ -0,0 +1,11 @@ + +function ${method.name}(${method.params.list}) { + const transforms = ${method.transforms} + + if (arguments.length === 1 && Array.isArray(arguments[0])) { + return Transport.send('${info.title}', '${method.name}', arguments[0], transforms) + } + else { + return Transport.send('${info.title}', '${method.name}', { ${method.params.list} }, transforms) + } +} \ No newline at end of file diff --git a/languages/c/templates/methods/provide.js b/languages/c/templates/methods/provide.js new file mode 100644 index 00000000..8cb48885 --- /dev/null +++ b/languages/c/templates/methods/provide.js @@ -0,0 +1,3 @@ +function provide(capability, provider) { + return ProvideManager.provide(capability, provider) +} diff --git a/languages/c/templates/methods/rpc-only.js b/languages/c/templates/methods/rpc-only.js new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/modules/include/Common/Module.h b/languages/c/templates/modules/include/Common/Module.h new file mode 100644 index 00000000..4cee1781 --- /dev/null +++ b/languages/c/templates/modules/include/Common/Module.h @@ -0,0 +1,23 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${DECLARATIONS} */ + +} diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h new file mode 100644 index 00000000..60a75f5f --- /dev/null +++ b/languages/c/templates/modules/include/Module.h @@ -0,0 +1,25 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${SCHEMAS} */ + + /* ${DECLARATIONS} */ + +} diff --git a/languages/c/templates/modules/src/JsonData_Module.h b/languages/c/templates/modules/src/JsonData_Module.h new file mode 100644 index 00000000..4cee1781 --- /dev/null +++ b/languages/c/templates/modules/src/JsonData_Module.h @@ -0,0 +1,23 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${DECLARATIONS} */ + +} diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp new file mode 100644 index 00000000..26a26050 --- /dev/null +++ b/languages/c/templates/modules/src/Module.cpp @@ -0,0 +1,29 @@ +/* + * 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 + */ + +/* ${IMPORTS} */ + + +namespace FireboltSDK { + + namespace ${info.title} { + + /* ${METHODS} */ + + } +} diff --git a/languages/c/templates/modules/src/Module_Common.cpp b/languages/c/templates/modules/src/Module_Common.cpp new file mode 100644 index 00000000..8460c52a --- /dev/null +++ b/languages/c/templates/modules/src/Module_Common.cpp @@ -0,0 +1,26 @@ +/* + * 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 + */ + +/* ${IMPORTS} */ + + +namespace FireboltSDK { + + /* ${METHODS} */ + +} diff --git a/languages/c/templates/parameters/default.js b/languages/c/templates/parameters/default.js new file mode 100644 index 00000000..916a8adf --- /dev/null +++ b/languages/c/templates/parameters/default.js @@ -0,0 +1 @@ +${method.params.list} \ No newline at end of file diff --git a/languages/c/templates/schemas/default.js b/languages/c/templates/schemas/default.js new file mode 100644 index 00000000..bc9ab873 --- /dev/null +++ b/languages/c/templates/schemas/default.js @@ -0,0 +1,5 @@ + /** + * ${schema.description} + */ + +${schema.shape} diff --git a/languages/c/templates/schemas/include/Common/Module.h b/languages/c/templates/schemas/include/Common/Module.h new file mode 100644 index 00000000..5582d8ea --- /dev/null +++ b/languages/c/templates/schemas/include/Common/Module.h @@ -0,0 +1,25 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${DECLARATIONS} */ + + /* ${SCHEMAS} */ + +} diff --git a/languages/c/templates/schemas/include/Module.h b/languages/c/templates/schemas/include/Module.h new file mode 100644 index 00000000..4cee1781 --- /dev/null +++ b/languages/c/templates/schemas/include/Module.h @@ -0,0 +1,23 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${DECLARATIONS} */ + +} diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/JsonData_Module.h new file mode 100644 index 00000000..4cee1781 --- /dev/null +++ b/languages/c/templates/schemas/src/JsonData_Module.h @@ -0,0 +1,23 @@ +/* + * 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 + */ + +namespace FireboltSDK { + + /* ${DECLARATIONS} */ + +} diff --git a/languages/c/templates/schemas/src/Module.cpp b/languages/c/templates/schemas/src/Module.cpp new file mode 100644 index 00000000..26a26050 --- /dev/null +++ b/languages/c/templates/schemas/src/Module.cpp @@ -0,0 +1,29 @@ +/* + * 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 + */ + +/* ${IMPORTS} */ + + +namespace FireboltSDK { + + namespace ${info.title} { + + /* ${METHODS} */ + + } +} diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/Module_Common.cpp new file mode 100644 index 00000000..8460c52a --- /dev/null +++ b/languages/c/templates/schemas/src/Module_Common.cpp @@ -0,0 +1,26 @@ +/* + * 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 + */ + +/* ${IMPORTS} */ + + +namespace FireboltSDK { + + /* ${METHODS} */ + +} diff --git a/languages/c/templates/sdk/main.cpp b/languages/c/templates/sdk/main.cpp new file mode 100644 index 00000000..a9f2f5ca --- /dev/null +++ b/languages/c/templates/sdk/main.cpp @@ -0,0 +1,30 @@ +/* + * Copyright 2021 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 + */ + +import { setMockResponses } from './Transport/MockTransport.mjs' + +/* ${MOCK_IMPORTS} */ + +setMockResponses({ + /* ${MOCK_OBJECTS} */ +}) + +/* ${EXPORTS} */ +export { default as Log } from './Log/index.mjs' +export { default as Events } from './Events/index.mjs' +export { default as Settings } from './Settings/index.mjs' diff --git a/languages/c/templates/sections/declarations.js b/languages/c/templates/sections/declarations.js new file mode 100644 index 00000000..b3ef974d --- /dev/null +++ b/languages/c/templates/sections/declarations.js @@ -0,0 +1 @@ +${declaration.list} diff --git a/languages/c/templates/sections/events.js b/languages/c/templates/sections/events.js new file mode 100644 index 00000000..5be10409 --- /dev/null +++ b/languages/c/templates/sections/events.js @@ -0,0 +1 @@ +${event.list} diff --git a/languages/c/templates/sections/methods.js b/languages/c/templates/sections/methods.js new file mode 100644 index 00000000..3f382a63 --- /dev/null +++ b/languages/c/templates/sections/methods.js @@ -0,0 +1,3 @@ + + // Methods +${method.list} diff --git a/languages/c/templates/sections/provider-interfaces.js b/languages/c/templates/sections/provider-interfaces.js new file mode 100644 index 00000000..418d7abf --- /dev/null +++ b/languages/c/templates/sections/provider-interfaces.js @@ -0,0 +1,11 @@ + // Provider Interfaces + + interface ProviderSession { + correlationId(): string // Returns the correlation id of the current provider session + } + + interface FocusableProviderSession extends ProviderSession { + focus(): Promise // Requests that the provider app be moved into focus to prevent a user experience + } + + ${providers.list} \ No newline at end of file diff --git a/languages/c/templates/sections/schemas.js b/languages/c/templates/sections/schemas.js new file mode 100644 index 00000000..a2d20dbb --- /dev/null +++ b/languages/c/templates/sections/schemas.js @@ -0,0 +1,3 @@ +// Types + +${schema.list} diff --git a/languages/c/templates/types/enum.mjs b/languages/c/templates/types/enum.mjs new file mode 100644 index 00000000..907fb37d --- /dev/null +++ b/languages/c/templates/types/enum.mjs @@ -0,0 +1,3 @@ +${name}: { + ${key}: '${value}', +}, From e4779e270a43829af081ccf2ac417cfb65ce5cd8 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 26 Apr 2023 14:42:31 -0400 Subject: [PATCH 067/137] feat(languages): Add support for a distinct JSON-type for each schema Also started tweaking C templates and adding a few useful macros. --- languages/c/Types.mjs | 73 ++- languages/c/src/types/NativeHelpers.mjs | 494 ++++++++++++++++++ languages/c/templates/methods/default.c | 24 + languages/c/templates/methods/default.js | 7 - languages/c/templates/methods/property.c | 12 + .../templates/modules/include/Common/Module.h | 15 +- .../c/templates/modules/include/Module.h | 14 +- .../c/templates/modules/src/JsonData_Module.h | 8 +- languages/c/templates/modules/src/Module.cpp | 17 +- .../c/templates/modules/src/Module_Common.cpp | 15 +- languages/c/templates/parameters/default.c | 1 + languages/c/templates/parameters/default.js | 1 - languages/c/templates/parameters/json.c | 3 + .../javascript/templates/methods/property.js | 2 +- src/macrofier/engine.mjs | 33 +- src/macrofier/index.mjs | 3 + src/shared/typescript.mjs | 11 +- 17 files changed, 687 insertions(+), 46 deletions(-) create mode 100644 languages/c/src/types/NativeHelpers.mjs create mode 100644 languages/c/templates/methods/default.c delete mode 100644 languages/c/templates/methods/default.js create mode 100644 languages/c/templates/methods/property.c create mode 100644 languages/c/templates/parameters/default.c delete mode 100644 languages/c/templates/parameters/default.js create mode 100644 languages/c/templates/parameters/json.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 31f48dd1..aa209ad4 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -21,6 +21,8 @@ import commonTypes from './src/types/CommonCppTypes.mjs' import headerCommonTypes from './src/types/CommonHeaderTypes.mjs' import headerTypes from './src/types/HeaderTypes.mjs' import cppTypes from './src/types/CppTypes.mjs' +import typeScriptTypes from '../../src/shared/typescript.mjs' +import { getNativeType } from './src/types/NativeHelpers.mjs' import path from "path" @@ -31,8 +33,13 @@ const isSynchronous = m => !m.tags ? false : m.tags.map(t => t.name).find(s => s // getSchemaType(schema, module, options = { destination: 'file.txt' }) // getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -function getMethodSignature(method, module, { destination = '' } = {}) { - return routeToDestination('getMethodSignature', arguments) +function getMethodSignature(method, module, { destination = '' } = {}) { + const returnType = getNativeType(method.result.schema) + const useHandle = !returnType + const extraParam = useHandle ? '${info.title}_${method.result.type}Handle* ${method.result.name}' : '' + + + return (returnType || 'uint32_t') + ' ${info.title}_Get${method.Name}(' + extraParam + ')' } function getMethodSignatureParams(method, module, { destination = '' } = {}) { @@ -44,8 +51,53 @@ function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', } function getSchemaType(schema, module, { destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - const value = routeToDestination('getSchemaType', arguments) - return value + let type = getNativeType(schema) + + if (!type) { + type = typeScriptTypes.getSchemaType(...arguments) + + const array = type.endsWith('[]') + + if (array) { + type = type.substring(0, type.length-2) + type = `${type}ObjectArrayHandle` + } + + type = `${module.info.title}_${type}` + } + return type +} + +function getJsonType(schema, module, { destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { + let type = getSchemaType(...arguments) + + // FireboltSDK::JSON::String&, etc. + // FireboltSDK::::& + // WPEFramework::Core::JSON::Boolean + + const array = type.endsWith('[]') + + if (array) { + type = type.substring(0, type.length-2) + } + + let jsonType + + if (type === 'string') { + jsonType = 'FireboltSDK::JSON::String' + } + else if (type === 'boolean') { + jsonType = 'WPEFramework::Core::JSON::Boolean' + } + else { + jsonType = `FireboltSDK::${module.info.title}::${getSchemaType(...arguments)}` + } + + if (array) { + jsonType = `WPEFramework::Core::JSON::ArrayType<${jsonType}>` + } + + return `${jsonType}&` } function routeToDestination(method, args) { @@ -70,9 +122,22 @@ function routeToDestination(method, args) { return '' } +function getPrimativeType(schema) { + if (schema.type === "boolean") { + return "bool" + } + else if (schema.type === "integer") { + return "uint32_t" + } + else if (schema.type === "number") { + return + } +} + export default { getMethodSignature, getMethodSignatureParams, getSchemaShape, getSchemaType, + getJsonType } \ No newline at end of file diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs new file mode 100644 index 00000000..e51c47d7 --- /dev/null +++ b/languages/c/src/types/NativeHelpers.mjs @@ -0,0 +1,494 @@ +/* + * Copyright 2021 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 + */ + +import helpers from 'crocks/helpers/index.js' +const { compose, getPathOr } = helpers +import safe from 'crocks/Maybe/safe.js' +import pointfree from 'crocks/pointfree/index.js' +const { chain, filter, reduce, option, map } = pointfree +import predicates from 'crocks/predicates/index.js' +import { getPath, getExternalSchemaPaths } from '../../../../src/shared/json-schema.mjs' +import deepmerge from 'deepmerge' + +const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = predicates + +const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' + +const getHeaderText = () => { + + return `/* +* Copyright 2022 Comcast +* +* Auto Generated using firebolt-openrpc tools. DO NOT EDIT. +* +*/ + +` +} + +const getIncludeGuardOpen = (json, prefix=null) => { + prefix = prefix ? `${prefix.toUpperCase()}_` : '' + return ` +#ifndef _${prefix}${getModuleName(json).toUpperCase()}_H +#define _${prefix}${getModuleName(json).toUpperCase()}_H + +` +} + +const getStyleGuardOpen = () => { + return ` +#ifdef __cplusplus +extern "C" { +#endif + +` +} + +const getStyleGuardClose = () => { + return ` + +#ifdef __cplusplus +} +#endif + +` +} + +const getIncludeGuardClose = () => { + return ` +#endif // Header Include Guard +` +} + +const capitalize = str => str[0].toUpperCase() + str.substr(1) +const description = (title, str='') => '/* ' + title + (str.length > 0 ? ' - ' + str : '') + ' */' +const isOptional = (prop, json) => (!json.required || !json.required.includes(prop)) + +const SdkTypesPrefix = 'Firebolt' + +const Indent = ' ' + +const getNativeType = json => { + let type + + if (json.const) { + if (typeof json.const === 'string') { + type = 'char*' + } + else if (typeof json.const === 'number') { + type = 'uint32_t' + if (json.const < 0) + type = 'int32_t' + } else if (typeof json.const === 'boolean'){ + type = 'bool' + } + } + else if (json.type === 'string') { + type = 'char*' + } + else if (json.type === 'number' || json.type === 'integer') { //Lets keep it simple for now + type = 'uint32_t' + if ((json.minimum && json.minimum < 0) + || (json.exclusiveMinimum && json.exclusiveMinimum < 0)) { + type = 'int32_t' + } + } + else if (json.type === 'boolean') { + type = 'bool' + } + return type +} + +const getObjectHandleManagement = varName => { + + let result = `typedef void* ${varName}Handle; +${varName}Handle ${varName}Handle_Create(void); +void ${varName}Handle_Addref(${varName}Handle handle); +void ${varName}Handle_Release(${varName}Handle handle); +bool ${varName}Handle_IsValid(${varName}Handle handle); +` + return result +} + +const getPropertyAccessors = (objName, propertyName, propertyType, options = {level:0, readonly:false, optional:false}) => { + + let result = `${Indent.repeat(options.level)}${propertyType} ${objName}_Get_${propertyName}(${objName}Handle handle);` + '\n' + + if (!options.readonly) { + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${propertyType} ${propertyName.toLowerCase()});` + '\n' + } + + if (options.optional === true) { + result += `${Indent.repeat(options.level)}bool ${objName}_has_${propertyName}(${objName}Handle handle);` + '\n' + result += `${Indent.repeat(options.level)}void ${objName}_clear_${propertyName}(${objName}Handle handle);` + '\n' + } + + return result +} + +const getMapAccessors = (typeName, nativeType, level=0) => { + + let res + + res = `${Indent.repeat(level)}uint32_t ${typeName}_KeysCount(${typeName}Handle handle);` + '\n' + res += `${Indent.repeat(level)}void ${typeName}_AddKey(${typeName}Handle handle, char* key, ${nativeType} value);` + '\n' + res += `${Indent.repeat(level)}void ${typeName}_RemoveKey(${typeName}Handle handle, char* key);` + '\n' + res += `${Indent.repeat(level)}${nativeType} ${typeName}_FindKey(${typeName}Handle handle, char* key);` + '\n' + + return res +} + +const getTypeName = (moduleName, varName, upperCase = false) => { + let mName = upperCase ? moduleName.toUpperCase() : capitalize(moduleName) + let vName = upperCase ? varName.toUpperCase() : capitalize(varName) + + return `${mName}_${vName}` +} + +const getArrayAccessors = (arrayName, valueType) => { + + let res = `uint32_t ${arrayName}_Size(${arrayName}Handle handle);` + '\n' + res += `${valueType} ${arrayName}_Get(${arrayName}Handle handle, uint32_t index);` + '\n' + res += `void ${arrayName}_Add(${arrayName}Handle handle, ${valueType} value);` + '\n' + res += `void ${arrayName}_Clear(${arrayName}Handle handle);` + '\n' + + return res +} + +const enumValue = (val,prefix) => { + const keyName = val.replace(/[\.\-:]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + return ` ${prefix.toUpperCase()}_${keyName.toUpperCase()}` +} + +const generateEnum = (schema, prefix)=> { + if (!schema.enum) { + return '' + } + else { + let str = `typedef enum {\n` + str += schema.enum.map(e => enumValue(e, prefix)).join(',\n') + str += `\n} ${prefix};\n` + return str + } +} + +const getIncludeDefinitions = (json = {}, jsonData = false) => { + return getExternalSchemaPaths(json) + .map(ref => { + const mod = ref.split('#')[0].split('/').pop() + let i = `#include "Common/${capitalize(mod)}.h"` + if(jsonData === true) { + i += '\n' + `#include "JsonData_${capitalize(mod)}.h"` + } + return i + }) + .filter((item, index, arr) => arr.indexOf(item) === index) + .concat([`#include "Firebolt/Types.h"`]) +} + +function getSchemaType(module = {}, json = {}, name = '', schemas = {}, options = {level: 0, descriptions: true, title: false}) { + if (json.schema) { + json = json.schema + } + + let structure = {} + structure["deps"] = new Set() //To avoid duplication of local ref definitions + structure["type"] = [] + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(json['$ref'], module, schemas) + let tName = definition.title || json['$ref'].split('/').pop() + const res = getSchemaType(module, definition, tName, schemas, {descriptions: options.descriptions, level: options.level}) + res.deps.forEach(dep => structure.deps.add(dep)) + structure.type = res.type + return structure + } + else { + // External dependency. + // e.g, "https://meta.comcast.com/firebolt/entertainment#/definitions/ProgramType" + + //Get the module of this definition + const schema = getPath(json['$ref'].split('#')[0], schemas) || module + + //Get the schema of the definition + const definition = getPath(json['$ref'], module, schemas) + let tName = definition.title || json['$ref'].split('/').pop() + const res = getSchemaType(schema, definition, tName, schemas, {descriptions: options.descriptions, level: options.level}) + //We are only interested in the type definition for external modules + structure.type = res.type + return structure + } + } + else if (json.const) { + structure.type = getNativeType(json) + return structure + } + else if (json['x-method']) { + console.log(`WARNING UNHANDLED: x-method in ${name}`) + return structure + //throw "x-methods not supported yet" + } + else if (json.type === 'string' && json.enum) { + //Enum + let typeName = getTypeName(getModuleName(module), name || json.title) + let res = description(capitalize(name || json.title), json.description) + '\n' + generateEnum(json, typeName) + structure.deps.add(res) + structure.type.push(typeName) + return structure + } + else if (Array.isArray(json.type)) { + let type = json.type.find(t => t !== 'null') + console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) + } + else if (json.type === 'array' && json.items) { + let res + if (Array.isArray(json.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(json.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getSchemaType(module, json.items[0],'',schemas) + } + else { + // grab the type for the non-array schema + res = getSchemaType(module, json.items, '', schemas) + } + + res.deps.forEach(dep => structure.deps.add(dep)) + let n = getTypeName(getModuleName(module), name || json.title) + let def = description(name || json.title, json.description) + '\n' + if (options.level === 0) { + def += getObjectHandleManagement(n + 'Array') + '\n' + } + def += getArrayAccessors(n + 'Array', res.type) + structure.deps.add(def) + structure.type.push(n + 'ArrayHandle') + return structure + } + else if (json.allOf) { + let union = deepmerge.all([...json.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)]) + if (json.title) { + union['title'] = json.title + } + else { + union['title'] = name + } + delete union['$ref'] + return getSchemaType(module, union, '',schemas, options) + } + else if (json.oneOf || json.anyOf) { + return structure + //TODO + } + else if (json.type === 'object') { + let res = getSchemaShape(module, json, schemas, json.title || name, {descriptions: options.descriptions, level: 0}) + res.deps.forEach(dep => structure.deps.add(dep)) + res.type.forEach(t => structure.deps.add(t)) + structure.type.push(getTypeName(getModuleName(module), json.title || name) + 'Handle') + return structure + //TODO + } + else if (json.type) { + structure.type = getNativeType(json) + return structure + } + return structure +} + +function getSchemaShape(moduleJson = {}, json = {}, schemas = {}, name = '', options = {level: 0, descriptions: true}) { + json = JSON.parse(JSON.stringify(json)) + let level = options.level + let descriptions = options.descriptions + + let structure = {} + structure["deps"] = new Set() //To avoid duplication of local ref definitions + structure["type"] = [] + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + + const schema = getPath(json['$ref'], module, schemas) + const tname = schema.title || json['$ref'].split('/').pop() + res = getSchemaShape(module, schema, schemas, tname, {descriptions: descriptions, level: level}) + res.deps.forEach(dep => structure.deps.add(dep)) + structure.type = res.type + } + else { + // External dependency. Return only type + // e.g, "https://meta.comcast.com/firebolt/entertainment#/definitions/ProgramType" + + //Get the module of this definition + const schema = getPath(json['$ref'].split('#')[0], schemas) || module + + //Get the schema of the definition + const definition = getPath(json['$ref'], schema, schemas) + const pname = (json.title || name) + (definition.title || json['$ref'].split('/').pop()) + + res = getSchemaShape(schema, definition, schemas, pname,{descriptions: descriptions, level: level}) + //We are only interested in the type definition for external modules + structure.type = res.type + } + } + //If the schema is a const, + else if (json.hasOwnProperty('const')) { + if (level > 0) { + + let t = description(name, json.description) + typeName = getTypeName(getModuleName(moduleJson), name) + t += getPropertyAccessors(typeName, capitalize(name), typeof json.const, {level: level, readonly:true, optional:false}) + structure.type.push(t) + } + } + else if (json.type === 'object') { + + if (json.properties) { + let tName = getTypeName(getModuleName(moduleJson), name) + let t = description(name, json.description) + t += '\n' + getObjectHandleManagement(tName) + Object.entries(json.properties).forEach(([pname, prop]) => { + t += '\n' + description(pname, prop.description) + let res + if (prop.type === 'array') { + if (Array.isArray(prop.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(prop.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getSchemaType(moduleJson, prop.items[0],pname, schemas, {level : options.level, descriptions: options.descriptions, title: true}) + } + else { + // grab the type for the non-array schema + res = getSchemaType(moduleJson, prop.items, pname, schemas, {level : options.level, descriptions: options.descriptions, title: true}) + } + if (res.type && res.type.length > 0) { + let n = tName + '_' + capitalize(pname || prop.title) + let def = getArrayAccessors(n + 'Array', res.type) + t += '\n' + def + } + else { + console.log(`WARNING: Type undetermined for ${name}:${pname}`) + } + } else { + res = getSchemaType(moduleJson, prop, pname,schemas, {descriptions: descriptions, level: level + 1, title: true}) + if (res.type && res.type.length > 0) { + t += '\n' + getPropertyAccessors(tName, capitalize(pname), res.type, {level: level, readonly:false, optional:isOptional(pname, json)}) + } + else { + console.log(`WARNING: Type undetermined for ${name}:${pname}`) + } + } + res.deps.forEach(dep => structure.deps.add(dep)) + }) + structure.type.push(t) + } + else if (json.propertyNames && json.propertyNames.enum) { + //propertyNames in object not handled yet + } + else if (json.additionalProperties && (typeof json.additionalProperties === 'object')) { + //This is a map of string to type in schema + //Get the Type + let type = getSchemaType(moduleJson, json.additionalProperties, name,schemas) + if (type.type && type.type.length > 0) { + let tName = getTypeName(getModuleName(moduleJson), name) + type.deps.forEach(dep => structure.deps.add(dep)) + let t = description(name, json.description) + t += '\n' + getObjectHandleManagement(tName) + '\n' + t += getMapAccessors(getTypeName(getModuleName(moduleJson), name), type.type,{descriptions: descriptions, level: level}) + structure.type.push(t) + } + else { + console.log(`WARNING: Type undetermined for ${name}`) + } + } + else if (json.patternProperties) { + throw "patternProperties are not supported by Firebolt" + } + } + else if (json.anyOf) { + + } + else if (json.oneOf) { + + } + else if (json.allOf) { + let union = deepmerge.all([...json.allOf.map(x => x['$ref'] ? getPath(x['$ref'], moduleJson, schemas) || x : x)], options) + if (json.title) { + union['title'] = json.title + } + else { + union['title'] = name + } + delete union['$ref'] + return getSchemaShape(moduleJson, union, schemas, name, options) + + } + else if (json.type === 'array') { + let res = getSchemaType(moduleJson, json, name, schemas, {level: 0, descriptions: descriptions}) + res.deps.forEach(dep => structure.deps.add(dep)) + } + else { + let res = getSchemaType(moduleJson, json, name, schemas, {level: level, descriptions: descriptions}) + res.deps.forEach(dep => structure.deps.add(dep)) + } + return structure + } + + function getPropertyGetterSignature(method, module, paramType) { + let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` + return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` + } + + function getPropertySetterSignature(method, module, paramType) { + let m = `${capitalize(getModuleName(module))}_Set${capitalize(method.name)}` + return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType} ${method.result.name || method.name} )` + } + + function getPropertyEventCallbackSignature(method, module, paramType) { + return `typedef void (*On${capitalize(method.name)}Changed)(${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType})` + } + + function getPropertyEventSignature(method, module) { + return `${description(method.name, 'Listen to updates')}\n` + `uint32_t ${capitalize(getModuleName(module))}_Listen${capitalize(method.name)}Update(On${capitalize(method.name)}Changed notification, uint16_t* listenerId)` + } + + export { + getHeaderText, + getIncludeGuardOpen, + getStyleGuardOpen, + getStyleGuardClose, + getIncludeGuardClose, + getNativeType, + getSchemaType, + getSchemaShape, + getModuleName, + getIncludeDefinitions, + getPropertyGetterSignature, + getPropertySetterSignature, + getPropertyEventCallbackSignature, + getPropertyEventSignature, + capitalize, + description, + getTypeName + } diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c new file mode 100644 index 00000000..7d10ba97 --- /dev/null +++ b/languages/c/templates/methods/default.c @@ -0,0 +1,24 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.title}_${method.Name}(${method.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { + uint32_t status = FireboltSDKErrorUnavailable; + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + + JsonObject jsonParameters; + + ${if.params} +${method.params.json} + ${end.if.params} + + WPEFramework::Core::JSON::Boolean jsonResult; + status = transport->Invoke("${info.title}.${method.name}", jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + *success = jsonResult.Value(); + } + + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; +} \ No newline at end of file diff --git a/languages/c/templates/methods/default.js b/languages/c/templates/methods/default.js deleted file mode 100644 index 0c7f799b..00000000 --- a/languages/c/templates/methods/default.js +++ /dev/null @@ -1,7 +0,0 @@ - -function ${method.name}(${method.params.list}) { - - const transforms = ${method.transforms} - - return Transport.send('${info.title}', '${method.name}', { ${method.params.list} }, transforms) -} \ No newline at end of file diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c new file mode 100644 index 00000000..8f301bea --- /dev/null +++ b/languages/c/templates/methods/property.c @@ -0,0 +1,12 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.title}_Get${method.Name}(${method.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { + const string method = _T("${info.title}.${method.name}"); + FireboltSDK::${info.title}::${method.result.type} jsonResult; + + uint32_t status = FireboltSDK::Properties::Get(method, jsonResult); + if (status == FireboltSDKErrorNone) { + WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); + *${method.result.name} = static_cast<${info.title}_${method.result.type}Handle>(resultPtr); + } + return status; +} diff --git a/languages/c/templates/modules/include/Common/Module.h b/languages/c/templates/modules/include/Common/Module.h index 4cee1781..22c25143 100644 --- a/languages/c/templates/modules/include/Common/Module.h +++ b/languages/c/templates/modules/include/Common/Module.h @@ -16,8 +16,19 @@ * SPDX-License-Identifier: Apache-2.0 */ -namespace FireboltSDK { +#ifndef _COMMON_${info.TITLE}_H +#define _COMMON_${info.TITLE}_H - /* ${DECLARATIONS} */ +#include "Firebolt.h" +#ifdef __cplusplus +extern "C" { +#endif + + /* ${SCHEMAS} */ + +#ifdef __cplusplus } +#endif + +#endif // Header Include Guard \ No newline at end of file diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h index 60a75f5f..92bab4f7 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/Module.h @@ -16,10 +16,22 @@ * SPDX-License-Identifier: Apache-2.0 */ -namespace FireboltSDK { +#ifndef _${info.TITLE}_H +#define _${info.TITLE}_H + +#include "Firebolt.h" +#include "Common/${info.title}.h" + +#ifdef __cplusplus +extern "C" { +#endif /* ${SCHEMAS} */ /* ${DECLARATIONS} */ +#ifdef __cplusplus } +#endif + +#endif // Header Include Guard \ No newline at end of file diff --git a/languages/c/templates/modules/src/JsonData_Module.h b/languages/c/templates/modules/src/JsonData_Module.h index 4cee1781..2c7ca8c8 100644 --- a/languages/c/templates/modules/src/JsonData_Module.h +++ b/languages/c/templates/modules/src/JsonData_Module.h @@ -16,8 +16,14 @@ * SPDX-License-Identifier: Apache-2.0 */ +#pragma once + +#include "Firebolt.h" + namespace FireboltSDK { + namespace ${info.title} { - /* ${DECLARATIONS} */ + /* ${SCHEMAS}} */ + } } diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 26a26050..2417f708 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -16,14 +16,17 @@ * SPDX-License-Identifier: Apache-2.0 */ -/* ${IMPORTS} */ +#include "FireboltSDK.h" +#include "${info.title}.h" +#include "Common/${info.title}.h" +#include "JsonData_${info.title}.h" +#ifdef __cplusplus +extern "C" { +#endif -namespace FireboltSDK { - - namespace ${info.title} { + /* ${METHODS} */ - /* ${METHODS} */ - - } +#ifdef __cplusplus } +#endif diff --git a/languages/c/templates/modules/src/Module_Common.cpp b/languages/c/templates/modules/src/Module_Common.cpp index 8460c52a..bce775ff 100644 --- a/languages/c/templates/modules/src/Module_Common.cpp +++ b/languages/c/templates/modules/src/Module_Common.cpp @@ -16,11 +16,16 @@ * SPDX-License-Identifier: Apache-2.0 */ -/* ${IMPORTS} */ - - -namespace FireboltSDK { +#include "FireboltSDK.h" +#include "Common/${info.title}.h" +#include "JsonData_${info.title}.h" +} +#ifdef __cplusplus +extern "C" { +#endif - /* ${METHODS} */ + /* ${SCHEMAS}} */ +#ifdef __cplusplus } +#endif \ No newline at end of file diff --git a/languages/c/templates/parameters/default.c b/languages/c/templates/parameters/default.c new file mode 100644 index 00000000..e6e3b8ba --- /dev/null +++ b/languages/c/templates/parameters/default.c @@ -0,0 +1 @@ +${method.param.type} ${method.param.name} \ No newline at end of file diff --git a/languages/c/templates/parameters/default.js b/languages/c/templates/parameters/default.js deleted file mode 100644 index 916a8adf..00000000 --- a/languages/c/templates/parameters/default.js +++ /dev/null @@ -1 +0,0 @@ -${method.params.list} \ No newline at end of file diff --git a/languages/c/templates/parameters/json.c b/languages/c/templates/parameters/json.c new file mode 100644 index 00000000..5ee36bec --- /dev/null +++ b/languages/c/templates/parameters/json.c @@ -0,0 +1,3 @@ + ${json.param.type} ${method.param.Name} = ${method.param.name}; + jsonParameters.Add("_T(${method.param.name})", &${method.param.Name}); + diff --git a/languages/javascript/templates/methods/property.js b/languages/javascript/templates/methods/property.js index df748ecd..0b1e1359 100644 --- a/languages/javascript/templates/methods/property.js +++ b/languages/javascript/templates/methods/property.js @@ -1,4 +1,4 @@ function ${method.name}(${method.params.list}) { const callbackOrValue = arguments[${method.params.count}] - return Prop.prop('${info.title}', '${method.name}', { ${method.params} }, callbackOrValue, ${method.property.immutable}, ${method.property.readonly}, ${method.params.count}) + return Prop.prop('${info.title}', '${method.name}', { ${method.params.list} }, callbackOrValue, ${method.property.immutable}, ${method.property.readonly}, ${method.params.count}) } \ No newline at end of file diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 39e97ea9..abde2ec0 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -51,7 +51,8 @@ let types = { getMethodSignature: ()=>null, getMethodSignatureParams: ()=>null, getSchemaShape: ()=>null, - getSchemaType: ()=>null + getSchemaType: ()=>null, + getJsonType: ()=>null } let config = { @@ -879,12 +880,15 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { } } + const paramDelimiter = config.operators ? config.operators.paramDelimiter : ', ' + const temporalItemName = isTemporalSetMethod(methodObj) ? methodObj.result.schema.items && methodObj.result.schema.items.title || 'Item' : '' const temporalAddName = isTemporalSetMethod(methodObj) ? `on${temporalItemName}Available` : '' const temporalRemoveName = isTemporalSetMethod(methodObj) ? `on${temporalItemName}Unvailable` : '' - const params = methodObj.params && methodObj.params.length ? getTemplate('/sections/parameters', templates) + methodObj.params.map(p => insertParameterMacros(getTemplate('/parameters/default', templates), p, methodObj, json)).join('') : '' + const params = methodObj.params && methodObj.params.length ? getTemplate('/sections/parameters', templates) + methodObj.params.map(p => insertParameterMacros(getTemplate('/parameters/default', templates), p, methodObj, json)).join(paramDelimiter) : '' const paramsRows = methodObj.params && methodObj.params.length ? methodObj.params.map(p => insertParameterMacros(getTemplate('/parameters/default', templates), p, methodObj, json)).join('') : '' const paramsAnnotations = methodObj.params && methodObj.params.length ? methodObj.params.map(p => insertParameterMacros(getTemplate('/parameters/annotations', templates), p, methodObj, json)).join('') : '' + const paramsJson = methodObj.params && methodObj.params.length ? methodObj.params.map(p => insertParameterMacros(getTemplate('/parameters/json', templates), p, methodObj, json)).join('') : '' const deprecated = methodObj.tags && methodObj.tags.find(t => t.name === 'deprecated') const deprecation = deprecated ? deprecated['x-since'] ? `since version ${deprecated['x-since']}` : '' : '' @@ -947,10 +951,11 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{method\.params\}/g, params) .replace(/\$\{method\.params\.table\.rows\}/g, paramsRows) .replace(/\$\{method\.params\.annotations\}/g, paramsAnnotations) + .replace(/\$\{method\.params\.json\}/g, paramsJson) .replace(/\$\{method\.params\.list\}/g, method.params) .replace(/\$\{method\.params\.array\}/g, JSON.stringify(methodObj.params.map(p => p.name))) .replace(/\$\{method\.params\.count}/g, methodObj.params ? methodObj.params.length : 0) - .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/g, method.params.length ? '$1' : '') + .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/gms, method.params.length ? '$1' : '') .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event.params.length ? '$1' : '') // Typed signature stuff .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination })) @@ -965,6 +970,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{event\.params\.table\.rows\}/g, eventParamsRows) .replace(/\$\{event\.signature\.params\}/g, types.getMethodSignatureParams(event, json, { destination: state.destination })) .replace(/\$\{info\.title\}/g, info.title) + .replace(/\$\{info\.TITLE\}/g, info.title.toUpperCase()) .replace(/\$\{method\.property\.immutable\}/g, hasTag(methodObj, 'property:immutable')) .replace(/\$\{method\.property\.readonly\}/g, !getSetterFor(methodObj.name, json)) .replace(/\$\{method\.temporalset\.add\}/g, temporalAddName) @@ -977,8 +983,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{method\.result\.name\}/g, result.name) .replace(/\$\{method\.result\.summary\}/g, result.summary) .replace(/\$\{method\.result\.link\}/g, getLinkForSchema(result, json)) //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result, json, {title: true, asPath: false, destination: state.destination })) //, baseUrl: options.baseUrl - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result, json, { destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result.schema, json, {title: true, asPath: false, destination: state.destination })) //, baseUrl: options.baseUrl + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates)) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) @@ -1156,20 +1162,23 @@ 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, module, { destination: state.destination, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl + let type = types.getSchemaType(param.schema, module, { destination: state.destination, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl let typeLink = getLinkForSchema(param, module) + let jsonType = types.getJsonType(param.schema, module, { destination: state.destination, code: false, link: false, title: true, asPath: false, expandEnums: false }) if (constraints && type) { constraints = '
' + constraints } return template - .replace(/\$\{method.param.name\}/, param.name) - .replace(/\$\{method.param.summary\}/, param.summary || '') - .replace(/\$\{method.param.required\}/, param.required || 'false') - .replace(/\$\{method.param.type\}/, type) //getType(param)) - .replace(/\$\{method.param.link\}/, getLinkForSchema(param, module)) //getType(param)) - .replace(/\$\{method.param.constraints\}/, constraints) //getType(param)) + .replace(/\$\{method.param.name\}/g, param.name) + .replace(/\$\{method.param.Name\}/g, param.name[0].toUpperCase() + param.name.substring(1)) + .replace(/\$\{method.param.summary\}/g, param.summary || '') + .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, module)) //getType(param)) + .replace(/\$\{method.param.constraints\}/g, constraints) //getType(param)) } function insertCapabilityMacros(template, capabilities, method, module) { diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 89c194e2..29cf7ba4 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -68,10 +68,13 @@ const macrofy = async ( let typer try { + console.log(path.join(sharedTemplates, '..', 'Types.mjs')) const typerModule = await import(path.join(sharedTemplates, '..', 'Types.mjs')) typer = typerModule.default } catch (_) { + console.log("Using default Typer") + console.dir(_) typer = (await import('../shared/typescript.mjs')).default } diff --git a/src/shared/typescript.mjs b/src/shared/typescript.mjs index aa6e21f5..e53747cd 100644 --- a/src/shared/typescript.mjs +++ b/src/shared/typescript.mjs @@ -199,10 +199,6 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, } function getSchemaType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - if (schema.schema) { - schema = schema.schema - } - const wrap = (str, wrapper) => wrapper + str + wrapper if (schema['$ref']) { @@ -327,6 +323,10 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, return wrap('void', code ? '`' : '') } } + + function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + return '' + } function getTypeScriptType(jsonType) { if (jsonType === 'integer') { @@ -350,5 +350,6 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, getMethodSignature, getMethodSignatureParams, getSchemaShape, - getSchemaType + getSchemaType, + getJsonType } \ No newline at end of file From f2cd1970af52fe6bcc8bbd0255f5b24042bb4dbb Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 26 Apr 2023 14:43:51 -0400 Subject: [PATCH 068/137] chore: Dropped debug logs --- src/macrofier/index.mjs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 29cf7ba4..89c194e2 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -68,13 +68,10 @@ const macrofy = async ( let typer try { - console.log(path.join(sharedTemplates, '..', 'Types.mjs')) const typerModule = await import(path.join(sharedTemplates, '..', 'Types.mjs')) typer = typerModule.default } catch (_) { - console.log("Using default Typer") - console.dir(_) typer = (await import('../shared/typescript.mjs')).default } From 38dc6332d24c1804112c9c2bdb8f4c25bc4704f1 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 26 Apr 2023 14:49:28 -0400 Subject: [PATCH 069/137] fix: Stop passing non-schemas in to getSchemaType --- src/macrofier/engine.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index abde2ec0..65156709 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -1010,7 +1010,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const matches = [...template.matchAll(/\$\{method\.params\[([0-9]+)\]\.type\}/g)] matches.forEach(match => { const index = parseInt(match[1]) - template = template.replace(/\$\{method\.params\[([0-9]+)\]\.type\}/g, types.getSchemaType(methodObj.params[index], json, { destination: state.destination })) + template = template.replace(/\$\{method\.params\[([0-9]+)\]\.type\}/g, types.getSchemaType(methodObj.params[index].schema, json, { destination: state.destination })) template = template.replace(/\$\{method\.params\[([0-9]+)\]\.name\}/g, methodObj.params[index].name) }) From 6cb39c3b39fb3884e6abd31c272805a4f70c2134 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Fri, 28 Apr 2023 12:44:35 -0400 Subject: [PATCH 070/137] feat(accessors): New macro section for schema property accessors --- languages/c/Types.mjs | 397 ++++++-- languages/c/src/types/CommonCppTypes.mjs | 60 -- languages/c/src/types/CommonHeaderTypes.mjs | 55 -- languages/c/src/types/CppTypes.mjs | 55 -- languages/c/src/types/HeaderTypes.mjs | 55 -- languages/c/src/types/ImplHelpers.mjs | 294 ++++++ languages/c/src/types/JSONHelpers.mjs | 61 ++ languages/c/src/types/JSONTypes.mjs | 56 -- languages/c/src/types/NativeHelpers.mjs | 264 +----- .../codeblocks/{export.mjs => export.c} | 0 .../{mock-import.mjs => mock-import.c} | 0 .../{mock-parameter.mjs => mock-parameter.c} | 0 .../clear.js => codeblocks/module.c} | 0 languages/c/templates/codeblocks/module.mjs | 11 - .../declarations/{listen.js => clear.c} | 0 .../declarations/{default.js => default.c} | 2 +- .../declarations/{once.js => listen.c} | 0 .../declarations/{provide.js => once.c} | 0 ...rphic-reducer.js => polymorphic-reducer.c} | 0 .../declarations/{rpc-only.js => provide.c} | 0 .../listen.js => declarations/rpc-only.c} | 0 .../defaults/{default.mjs => default.c} | 0 .../defaults/{property.mjs => property.c} | 0 languages/c/templates/examples/default.md | 6 - languages/c/templates/examples/event.md | 5 - .../examples/polymorphic-pull-event.md | 9 - .../c/templates/examples/polymorphic-pull.md | 6 - languages/c/templates/examples/provider.md | 10 - languages/c/templates/examples/setter.md | 6 - languages/c/templates/examples/subscriber.md | 7 - languages/c/templates/examples/synchronous.md | 4 - .../c/templates/examples/temporal-set.md | 13 - .../c/templates/imports/context-event.mjs | 1 - languages/c/templates/imports/default.c | 1 + languages/c/templates/imports/event.mjs | 2 - languages/c/templates/imports/property.mjs | 1 - languages/c/templates/imports/provider.mjs | 2 - languages/c/templates/imports/rpc.mjs | 1 - .../c/templates/imports/temporal-set.mjs | 1 - languages/c/templates/imports/x-method.mjs | 1 - .../templates/initializations/deprecated.mjs | 1 - .../c/templates/initializations/event.mjs | 1 - .../c/templates/initializations/provider.mjs | 1 - languages/c/templates/methods/default.c | 2 +- .../c/templates/methods/{once.js => listen.c} | 0 .../templates/methods/{rpc-only.js => once.c} | 0 ...rphic-reducer.js => polymorphic-reducer.c} | 0 .../methods/{provide.js => provide.c} | 0 languages/c/templates/methods/rpc-only.c | 0 .../templates/modules/include/Common/Module.h | 6 + .../c/templates/modules/include/Module.h | 3 +- languages/c/templates/modules/src/Module.cpp | 11 +- .../schemas/{default.js => default.c} | 0 .../templates/schemas/include/Common/Module.h | 21 +- .../c/templates/schemas/src/Module_Common.cpp | 14 +- languages/c/templates/sdk/CMakeLists.txt | 49 + .../c/templates/sdk/build/CMakeCache.txt | 407 ++++++++ .../CMakeFiles/3.25.3/CMakeCCompiler.cmake | 72 ++ .../CMakeFiles/3.25.3/CMakeCXXCompiler.cmake | 83 ++ .../3.25.3/CMakeDetermineCompilerABI_C.bin | Bin 0 -> 16999 bytes .../3.25.3/CMakeDetermineCompilerABI_CXX.bin | Bin 0 -> 16983 bytes .../build/CMakeFiles/3.25.3/CMakeSystem.cmake | 15 + .../3.25.3/CompilerIdC/CMakeCCompilerId.c | 868 +++++++++++++++++ .../3.25.3/CompilerIdC/CMakeCCompilerId.o | Bin 0 -> 1712 bytes .../CompilerIdCXX/CMakeCXXCompilerId.cpp | 857 +++++++++++++++++ .../3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o | Bin 0 -> 1712 bytes .../sdk/build/CMakeFiles/CMakeError.log | 0 .../sdk/build/CMakeFiles/CMakeOutput.log | 266 ++++++ .../sdk/build/CMakeFiles/cmake.check_cache | 1 + .../c/templates/sdk/cmake/CopySymlink.cmake | 17 + .../templates/sdk/cmake/HelperFunctions.cmake | 139 +++ .../c/templates/sdk/cmake/project.cmake.in | 30 + languages/c/templates/sdk/include/Error.h | 41 + languages/c/templates/sdk/include/Types.h | 43 + languages/c/templates/sdk/scripts/install.js | 32 + .../c/templates/sdk/src/Accessor/Accessor.cpp | 134 +++ .../c/templates/sdk/src/Accessor/Accessor.h | 79 ++ .../c/templates/sdk/src/Accessor/Config.h | 41 + .../c/templates/sdk/src/Accessor/WorkerPool.h | 72 ++ languages/c/templates/sdk/src/CMakeLists.txt | 93 ++ languages/c/templates/sdk/src/Config.cmake | 34 + languages/c/templates/sdk/src/Event/Event.cpp | 148 +++ languages/c/templates/sdk/src/Event/Event.h | 154 +++ languages/c/templates/sdk/src/Firebolt.h | 25 + .../c/templates/sdk/src/FireboltSDK.conf.in | 3 + .../c/templates/sdk/src/Logger/Logger.cpp | 84 ++ languages/c/templates/sdk/src/Logger/Logger.h | 85 ++ .../templates/{schemas => sdk}/src/Module.cpp | 12 +- .../templates/sdk/{main.cpp => src/Module.h} | 21 +- languages/c/templates/sdk/src/Params.config | 3 + .../templates/sdk/src/Properties/Properties.h | 90 ++ .../src/Transport/Transport.cpp} | 5 +- .../c/templates/sdk/src/Transport/Transport.h | 897 ++++++++++++++++++ languages/c/templates/sdk/src/Types.cpp | 41 + languages/c/templates/sdk/src/TypesPriv.h | 55 ++ .../templates/sdk/src/cmake/CopySymlink.cmake | 1 + languages/c/templates/sdk/test/CMakeLists.txt | 86 ++ languages/c/templates/sdk/test/Main.c | 44 + languages/c/templates/sdk/test/Module.cpp | 21 + .../Module_Common.cpp => sdk/test/Module.h} | 18 +- .../c/templates/sdk/test/OpenRPCCTests.h | 42 + .../c/templates/sdk/test/OpenRPCTests.cpp | 385 ++++++++ languages/c/templates/sdk/test/OpenRPCTests.h | 99 ++ languages/c/templates/sdk/test/TestUtils.h | 38 + languages/c/templates/sections/accessors.c | 3 + .../{declarations.js => declarations.c} | 0 .../sections/{events.js => events.c} | 0 .../sections/{methods.js => methods.c} | 0 ...er-interfaces.js => provider-interfaces.c} | 0 languages/c/templates/sections/schemas.c | 3 + .../sections/{schemas.js => types.c} | 0 languages/c/templates/types/enum.c | 3 + languages/c/templates/types/enum.mjs | 3 - src/macrofier/engine.mjs | 73 +- 114 files changed, 6485 insertions(+), 776 deletions(-) delete mode 100644 languages/c/src/types/CommonCppTypes.mjs delete mode 100644 languages/c/src/types/CommonHeaderTypes.mjs delete mode 100644 languages/c/src/types/CppTypes.mjs delete mode 100644 languages/c/src/types/HeaderTypes.mjs create mode 100644 languages/c/src/types/ImplHelpers.mjs create mode 100644 languages/c/src/types/JSONHelpers.mjs delete mode 100644 languages/c/src/types/JSONTypes.mjs rename languages/c/templates/codeblocks/{export.mjs => export.c} (100%) rename languages/c/templates/codeblocks/{mock-import.mjs => mock-import.c} (100%) rename languages/c/templates/codeblocks/{mock-parameter.mjs => mock-parameter.c} (100%) rename languages/c/templates/{declarations/clear.js => codeblocks/module.c} (100%) delete mode 100644 languages/c/templates/codeblocks/module.mjs rename languages/c/templates/declarations/{listen.js => clear.c} (100%) rename languages/c/templates/declarations/{default.js => default.c} (68%) rename languages/c/templates/declarations/{once.js => listen.c} (100%) rename languages/c/templates/declarations/{provide.js => once.c} (100%) rename languages/c/templates/declarations/{polymorphic-reducer.js => polymorphic-reducer.c} (100%) rename languages/c/templates/declarations/{rpc-only.js => provide.c} (100%) rename languages/c/templates/{methods/listen.js => declarations/rpc-only.c} (100%) rename languages/c/templates/defaults/{default.mjs => default.c} (100%) rename languages/c/templates/defaults/{property.mjs => property.c} (100%) delete mode 100644 languages/c/templates/examples/default.md delete mode 100644 languages/c/templates/examples/event.md delete mode 100644 languages/c/templates/examples/polymorphic-pull-event.md delete mode 100644 languages/c/templates/examples/polymorphic-pull.md delete mode 100644 languages/c/templates/examples/provider.md delete mode 100644 languages/c/templates/examples/setter.md delete mode 100644 languages/c/templates/examples/subscriber.md delete mode 100644 languages/c/templates/examples/synchronous.md delete mode 100644 languages/c/templates/examples/temporal-set.md delete mode 100644 languages/c/templates/imports/context-event.mjs create mode 100644 languages/c/templates/imports/default.c delete mode 100644 languages/c/templates/imports/event.mjs delete mode 100644 languages/c/templates/imports/property.mjs delete mode 100644 languages/c/templates/imports/provider.mjs delete mode 100644 languages/c/templates/imports/rpc.mjs delete mode 100644 languages/c/templates/imports/temporal-set.mjs delete mode 100644 languages/c/templates/imports/x-method.mjs delete mode 100644 languages/c/templates/initializations/deprecated.mjs delete mode 100644 languages/c/templates/initializations/event.mjs delete mode 100644 languages/c/templates/initializations/provider.mjs rename languages/c/templates/methods/{once.js => listen.c} (100%) rename languages/c/templates/methods/{rpc-only.js => once.c} (100%) rename languages/c/templates/methods/{polymorphic-reducer.js => polymorphic-reducer.c} (100%) rename languages/c/templates/methods/{provide.js => provide.c} (100%) create mode 100644 languages/c/templates/methods/rpc-only.c rename languages/c/templates/schemas/{default.js => default.c} (100%) create mode 100644 languages/c/templates/sdk/CMakeLists.txt create mode 100644 languages/c/templates/sdk/build/CMakeCache.txt create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake create mode 100755 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin create mode 100755 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_CXX.bin create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeSystem.cmake create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.c create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.cpp create mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o create mode 100644 languages/c/templates/sdk/build/CMakeFiles/CMakeError.log create mode 100644 languages/c/templates/sdk/build/CMakeFiles/CMakeOutput.log create mode 100644 languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache create mode 100644 languages/c/templates/sdk/cmake/CopySymlink.cmake create mode 100644 languages/c/templates/sdk/cmake/HelperFunctions.cmake create mode 100644 languages/c/templates/sdk/cmake/project.cmake.in create mode 100644 languages/c/templates/sdk/include/Error.h create mode 100644 languages/c/templates/sdk/include/Types.h create mode 100644 languages/c/templates/sdk/scripts/install.js create mode 100644 languages/c/templates/sdk/src/Accessor/Accessor.cpp create mode 100644 languages/c/templates/sdk/src/Accessor/Accessor.h create mode 100644 languages/c/templates/sdk/src/Accessor/Config.h create mode 100644 languages/c/templates/sdk/src/Accessor/WorkerPool.h create mode 100644 languages/c/templates/sdk/src/CMakeLists.txt create mode 100644 languages/c/templates/sdk/src/Config.cmake create mode 100644 languages/c/templates/sdk/src/Event/Event.cpp create mode 100644 languages/c/templates/sdk/src/Event/Event.h create mode 100644 languages/c/templates/sdk/src/Firebolt.h create mode 100644 languages/c/templates/sdk/src/FireboltSDK.conf.in create mode 100644 languages/c/templates/sdk/src/Logger/Logger.cpp create mode 100644 languages/c/templates/sdk/src/Logger/Logger.h rename languages/c/templates/{schemas => sdk}/src/Module.cpp (85%) rename languages/c/templates/sdk/{main.cpp => src/Module.h} (61%) create mode 100644 languages/c/templates/sdk/src/Params.config create mode 100644 languages/c/templates/sdk/src/Properties/Properties.h rename languages/c/templates/{schemas/include/Module.h => sdk/src/Transport/Transport.cpp} (96%) create mode 100644 languages/c/templates/sdk/src/Transport/Transport.h create mode 100644 languages/c/templates/sdk/src/Types.cpp create mode 100644 languages/c/templates/sdk/src/TypesPriv.h create mode 100644 languages/c/templates/sdk/src/cmake/CopySymlink.cmake create mode 100644 languages/c/templates/sdk/test/CMakeLists.txt create mode 100644 languages/c/templates/sdk/test/Main.c create mode 100644 languages/c/templates/sdk/test/Module.cpp rename languages/c/templates/{modules/src/Module_Common.cpp => sdk/test/Module.h} (79%) create mode 100644 languages/c/templates/sdk/test/OpenRPCCTests.h create mode 100644 languages/c/templates/sdk/test/OpenRPCTests.cpp create mode 100644 languages/c/templates/sdk/test/OpenRPCTests.h create mode 100644 languages/c/templates/sdk/test/TestUtils.h create mode 100644 languages/c/templates/sections/accessors.c rename languages/c/templates/sections/{declarations.js => declarations.c} (100%) rename languages/c/templates/sections/{events.js => events.c} (100%) rename languages/c/templates/sections/{methods.js => methods.c} (100%) rename languages/c/templates/sections/{provider-interfaces.js => provider-interfaces.c} (100%) create mode 100644 languages/c/templates/sections/schemas.c rename languages/c/templates/sections/{schemas.js => types.c} (100%) create mode 100644 languages/c/templates/types/enum.c delete mode 100644 languages/c/templates/types/enum.mjs diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index aa209ad4..e44b4a78 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -16,122 +16,367 @@ * SPDX-License-Identifier: Apache-2.0 */ -import jsonTypes from './src/types/JSONTypes.mjs' -import commonTypes from './src/types/CommonCppTypes.mjs' -import headerCommonTypes from './src/types/CommonHeaderTypes.mjs' -import headerTypes from './src/types/HeaderTypes.mjs' -import cppTypes from './src/types/CppTypes.mjs' -import typeScriptTypes from '../../src/shared/typescript.mjs' -import { getNativeType } from './src/types/NativeHelpers.mjs' - -import path from "path" - -const isSynchronous = m => !m.tags ? false : m.tags.map(t => t.name).find(s => s === 'synchronous') - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) - -function getMethodSignature(method, module, { destination = '' } = {}) { - const returnType = getNativeType(method.result.schema) - const useHandle = !returnType - const extraParam = useHandle ? '${info.title}_${method.result.type}Handle* ${method.result.name}' : '' - - - return (returnType || 'uint32_t') + ' ${info.title}_Get${method.Name}(' + extraParam + ')' -} +import deepmerge from 'deepmerge' +import { getPath } from '../../src/shared/json-schema.mjs' +import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors } from './src/types/NativeHelpers.mjs' +import { getObjectHandleManagementImpl, getPropertyAccessorsImpl } from './src/types/ImplHelpers.mjs' +import { getJsonContainerDefinition } from './src/types/JSONHelpers.mjs' + +function getMethodSignature(method, module, { destination, isInterface = false }) { + const extraParam = '${method.result.type}* ${method.result.name}' -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return routeToDestination('getMethodSignatureParams', arguments) + const prefix = method.tags.find(t => t.name.split(":")[0] === "property") ? "Get" : "" + + return 'uint32_t ${info.title}_' + prefix + '${method.Name}(' + extraParam + ')' } -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - return routeToDestination('getSchemaShape', arguments) +function getMethodSignatureParams(method, module, { destination }) { + return method.params.map(param => param.name + (!param.required ? '?' : '') + ': ' + getSchemaType(param.schema, module, { title: true, destination })).join(', ') } -function getSchemaType(schema, module, { destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - let type = getNativeType(schema) +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop + +function getSchemaType(schema, module, { name, destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + let type = '' + let theTitle = schema.title || name || ('UnamedSchema' + (Math.floor(Math.random() * 100))) - if (!type) { - type = typeScriptTypes.getSchemaType(...arguments) + if (schema['x-method']) { + console.log(`WARNING UNHANDLED: x-method in ${theTitle}`) + //throw "x-methods not supported yet" + } - const array = type.endsWith('[]') + if (schema['$ref']) { + if (schema['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(schema['$ref'], module) + let tName = definition.title || schema['$ref'].split('/').pop() + return getSchemaType(definition, module, { name: tName, destination, link, title, code, asPath, event, expandEnums, baseUrl }) + } + } + else if (schema.const) { + type = getNativeType(schema) + return type + } + else if (schema.type === 'string' && schema.enum) { + //Enum + let typeName = getTypeName(getModuleName(module), theTitle) + return typeName + } + else if (Array.isArray(schema.type)) { + let type = schema.type.find(t => t !== 'null') + console.log(`WARNING UNHANDLED: type is an array containing ${schema.type}`) + } + else if (schema.type === 'array' && schema.items) { + let res + if (Array.isArray(schema.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(schema.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getSchemaType(schema.items[0], module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) + } + else { + // grab the type for the non-array schema + res = getSchemaType(schema.items, module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) + } - if (array) { - type = type.substring(0, type.length-2) - type = `${type}ObjectArrayHandle` + if (!schema.title && !name) { + console.log(`WARNING: generated name for ${module.info.title} schema w/ no title: ${theTitle}`) + console.dir(schema) } - type = `${module.info.title}_${type}` + let n = getTypeName(getModuleName(module), theTitle) + return n + 'ArrayHandle' + } + else if (schema.allOf) { + let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x)]) + if (theTitle) { + union['title'] = theTitle + } + delete union['$ref'] + return getSchemaType(union, module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) + } + else if (schema.oneOf || schema.anyOf) { + return type + //TODO + } + else if (schema.type === 'object') { + if (!schema.title && !name) { + console.log(`WARNING: generated name for ${module.info.title} schema w/ no title: ${theTitle}`) + console.dir(schema) + } + return getTypeName(getModuleName(module), theTitle) + 'Handle' + //TODO + } + else if (schema.type) { + type = getNativeType(schema) + return type } + + // TODO: deal with dependencies return type } -function getJsonType(schema, module, { destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - let type = getSchemaType(...arguments) +//function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, summary, descriptions = true, destination, enums = true } = {}) +// function getSchemaType() +function getSchemaShape(schema, module, { name = '', level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { + const isHeader = destination.endsWith(".h") + const isCPP = (destination.endsWith(".cpp") && section !== 'accessors') + + schema = JSON.parse(JSON.stringify(schema)) - // FireboltSDK::JSON::String&, etc. - // FireboltSDK::::& - // WPEFramework::Core::JSON::Boolean + let shape = '' - const array = type.endsWith('[]') + name = schema.title || name - if (array) { - type = type.substring(0, type.length-2) + if (!name) { + console.log(`WARNING: schema without a name in ${module.info.title}`) + return shape } - let jsonType + if (schema['$ref']) { + if (schema['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType - if (type === 'string') { - jsonType = 'FireboltSDK::JSON::String' + const schema = getPath(schema['$ref'], module) + const tname = name || schema['$ref'].split('/').pop() + return getSchemaShape(schema, module, { name: tname, descriptions: descriptions, level: level }) + } } - else if (type === 'boolean') { - jsonType = 'WPEFramework::Core::JSON::Boolean' + //If the schema is a const, + else if (schema.hasOwnProperty('const') && !isCPP) { + if (level > 0) { + + let t = description(name, schema.description) + typeName = getTypeName(getModuleName(module), name) + t += (isHeader ? getPropertyAccessors(typeName, capitalize(name), typeof schema.const, { level: level, readonly: true, optional: false }) : getPropertyAccessorsImpl(typeName, capitalize(name), getJsonType(schema, module, { level, name }), typeof schema.const, { level: level, readonly: true, optional: false })) + shape += '\n' + t + } } - else { - jsonType = `FireboltSDK::${module.info.title}::${getSchemaType(...arguments)}` + else if (schema.type === 'object') { + if (!name) { + console.log(`WARNING: unnamed schema in ${module.info.title}.`) + console.dir(schema) + shape = '' + } + else if (schema.properties) { + let tName = getTypeName(getModuleName(module), name) + let c_shape = description(name, schema.description) + let cpp_shape = '' + c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(schema, module, { name }))) + Object.entries(schema.properties).forEach(([pname, prop]) => { + c_shape += '\n' + description(pname, prop.description) + let res + if (prop.type === 'array') { + if (Array.isArray(prop.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(prop.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getSchemaType(prop.items[0], module, { name: pname, level: level, descriptions: descriptions, title: true }) + } + else { + // grab the type for the non-array schema + res = getSchemaType(prop.items, module, { name: pname, level: level, descriptions: descriptions, title: true }) + } + if (res && res.length > 0) { + let n = tName + '_' + capitalize(pname || prop.title) + let def = getArrayAccessors(n + 'Array', res) + c_shape += '\n' + def + } + else { + console.log(`a. WARNING: Type undetermined for ${name}:${pname}`) + } + } else { + res = getSchemaType(prop, module, { name: pname, descriptions: descriptions, level: level + 1, title: true }) + if (res && res.length > 0) { + c_shape += '\n' + (isHeader ? getPropertyAccessors(tName, capitalize(pname), res, { level: level, readonly: false, optional: isOptional(pname, schema) }) : getPropertyAccessorsImpl(tName, capitalize(pname), getJsonType(prop, module, { level, name }), res, { level: level, readonly: false, optional: isOptional(pname, schema) })) + } + else { + console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) + } + } + }) + cpp_shape += getJsonContainerDefinition(tName, Object.entries(schema.properties).map(([name, prop]) => ({ name, type: getJsonType(prop, module) }))) + + if (isCPP) { + shape += '\n' + cpp_shape + } + else { + shape += '\n' + c_shape + } + } + else if (schema.propertyNames && schema.propertyNames.enum) { + //propertyNames in object not handled yet + } + else if (schema.additionalProperties && (typeof schema.additionalProperties === 'object') && !isCPP) { + //This is a map of string to type in schema + //Get the Type + let type = getSchemaType(schema.additionalProperties, module, { name: name }) + if (type && type.length > 0) { + let tName = getTypeName(getModuleName(module), name) + // type.deps.forEach(dep => structure.deps.add(dep)) + let t = description(name, schema.description) + t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(schema, module, { name }))) + t += getMapAccessors(getTypeName(getModuleName(module), name), type, { descriptions: descriptions, level: level }) + shape += '\n' + t + } + else { + console.log(`c. WARNING: Type undetermined for ${name}`) + } + } + else if (schema.patternProperties) { + console.log(`WARNING: patternProperties not supported yet...`) + // throw "patternProperties are not supported by Firebolt" + } + } + else if (schema.anyOf) { + } + else if (schema.oneOf) { - if (array) { - jsonType = `WPEFramework::Core::JSON::ArrayType<${jsonType}>` } + else if (schema.allOf) { + let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x)]) + if (name) { + union['title'] = name + } + delete union['$ref'] + return getSchemaShape(union, module, { name, level, title, summary, descriptions, destination, section, enums }) + + } + else if (schema.type === 'array') { + let res = getSchemaType(schema, module, { name, level: 0, descriptions: descriptions }) + // res.deps.forEach(dep => structure.deps.add(dep)) + } + else { + let res = getSchemaType(schema, module, { name, level: level, descriptions: descriptions }) + // res.deps.forEach(dep => structure.deps.add(dep)) + } + // console.dir(structure.deps) + return shape +} + +// function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - return `${jsonType}&` +const getJsonDataStructName = (modName, name) => `${capitalize(modName)}::${capitalize(name)}` + +const getJsonNativeType = json => { + let type + let jsonType = json.const ? typeof json.const : json.type + + if (jsonType === 'string') { + type = 'WPEFramework::Core::JSON::String' + } + else if (jsonType === 'number' || json.type === 'integer') { //Lets keep it simple for now + type = 'WPEFramework::Core::JSON::Number' + } + else if (jsonType === 'boolean') { + type = 'WPEFramework::Core::JSON::Boolean' + } + else { + throw 'Unknown JSON Native Type !!!' + } + return type } -function routeToDestination(method, args) { - const destination = args[args.length-1].destination || '' +function getJsonType(schema = {}, module = {}, { name = '', descriptions = false, level = 0 } = {}) { - if ( path.basename(destination) === 'JsonData_Module.h') { - return jsonTypes[method](...args) + let type = '' + + if (schema['$ref']) { + if (schema['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(schema['$ref'], module) + let tName = definition.title || schema['$ref'].split('/').pop() + return getJsonType(definition, module, { name: tName, descriptions: descriptions, level: level }) + } } - else if (path.basename(destination) === 'Module.cpp') { - return cppTypes[method](...args) + else if (schema.const) { + return getJsonNativeType(schema) } - else if (path.basename(destination) === 'Module_Common.cpp') { - return commonTypes[method](...args) + else if (schema['x-method']) { + console.log(`WARNING: x-methods are not supported yet...`) + return type + //throw "x-methods not supported yet" } - else if (path.basename(destination) === 'Module.h' && path.dirname(destination).endsWith(path.sep + 'Common')) { - return headerCommonTypes[method](...args) + else if (schema.type === 'string' && schema.enum) { + //Enum + let t = getSchemaType(schema, module, { name }) + return 'WPEFramework::Core::JSON::EnumType<::' + t + '>' } - else if (path.basename(destination) === 'Module.h') { - return headerTypes[method](...args) + else if (Array.isArray(schema.type)) { + let type = schema.type.find(t => t !== 'null') + console.log(`WARNING UNHANDLED: type is an array containing ${schema.type}`) } + else if (schema.type === 'array' && schema.items) { + let res + if (Array.isArray(schema.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(schema.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getJsonType(schema.items[0], module, { name: '' }) + } + else { + // grab the type for the non-array schema + res = getJsonType(schema.items, module, { name: '' }) + } - return '' + return `WPEFramework::Core::JSON::ArrayType<${res}>` + } + else if (schema.allOf) { + let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)]) + if (schema.title) { + union['title'] = schema.title + } + else { + union['title'] = name + } + delete union['$ref'] + return getJsonType(union, module, { name: '', level, descriptions }) + } + else if (schema.oneOf || schema.anyOf) { + return type + //TODO + } + else if (schema.type === 'object') { + if (!schema.title && !name) { + console.log(`WARNING: schema with no name`) + console.dir(schema) + return 'Unknown' + } + return getJsonDataStructName(getModuleName(module), schema.title || name) + //TODO + } + else if (schema.type) { + return getJsonNativeType(schema) + } + return type } -function getPrimativeType(schema) { - if (schema.type === "boolean") { - return "bool" +function getTypeScriptType(jsonType) { + if (jsonType === 'integer') { + return 'number' } - else if (schema.type === "integer") { - return "uint32_t" + else { + return jsonType } - else if (schema.type === "number") { - return +} + +const enumReducer = (acc, val, i, arr) => { + const keyName = val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + acc = acc + ` ${keyName} = '${val}'` + if (i < arr.length - 1) { + acc = acc.concat(',\n') } + return acc } export default { diff --git a/languages/c/src/types/CommonCppTypes.mjs b/languages/c/src/types/CommonCppTypes.mjs deleted file mode 100644 index 863cd77b..00000000 --- a/languages/c/src/types/CommonCppTypes.mjs +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2021 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 - */ - -// import deepmerge from 'deepmerge' -// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' -// import { getLinkFromRef } from '../../src/shared/markdown.mjs' -// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' - - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) - -function getMethodSignature(method, module, { destination = '' } = {}) { - return `// Common CPP Signatures for ${module}_${method}` -} - -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return `// Common CPP Signature Params for ${module}_${method}` -} - -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - - return { - dependencies: [], - code: `// Common CPP Schema Shape` - } - return `// Common CPP Schema Shape` -} - -function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - return `// Common CPP Schema Type` -} - - -export default { - getMethodSignature, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, -} \ No newline at end of file diff --git a/languages/c/src/types/CommonHeaderTypes.mjs b/languages/c/src/types/CommonHeaderTypes.mjs deleted file mode 100644 index 9c40c084..00000000 --- a/languages/c/src/types/CommonHeaderTypes.mjs +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2021 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 - */ - -// import deepmerge from 'deepmerge' -// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' -// import { getLinkFromRef } from '../../src/shared/markdown.mjs' -// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' - - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) - -function getMethodSignature(method, module, { destination = '' } = {}) { - return `// common .h Signatures for ${module}_${method}` -} - -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return `// common .h Signature Params for ${module}_${method}` -} - -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - return `// common .h Schema Shape` -} - -function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - return `// common .h Schema Type` -} - - -export default { - getMethodSignature, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, -} \ No newline at end of file diff --git a/languages/c/src/types/CppTypes.mjs b/languages/c/src/types/CppTypes.mjs deleted file mode 100644 index 4b6fa6a8..00000000 --- a/languages/c/src/types/CppTypes.mjs +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2021 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 - */ - -// import deepmerge from 'deepmerge' -// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' -// import { getLinkFromRef } from '../../src/shared/markdown.mjs' -// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' - - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) - -function getMethodSignature(method, module, { destination = '' } = {}) { - return `// CPP Signatures for ${module}_${method}` -} - -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return `// CPP Signature Params for ${module}_${method}` -} - -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - return `// CPP Schema Shape` -} - -function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - return `// CPP Schema Type` -} - - -export default { - getMethodSignature, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, -} \ No newline at end of file diff --git a/languages/c/src/types/HeaderTypes.mjs b/languages/c/src/types/HeaderTypes.mjs deleted file mode 100644 index 9ce0155e..00000000 --- a/languages/c/src/types/HeaderTypes.mjs +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2021 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 - */ - -// import deepmerge from 'deepmerge' -// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' -// import { getLinkFromRef } from '../../src/shared/markdown.mjs' -// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' - - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) - -function getMethodSignature(method, module, { destination = '' } = {}) { - return `// .h Signatures for ${module.info.title}_${method.name}` -} - -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return `// .h Signature Params for ${module.info.title}_${method.name}` -} - -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - return `// .h Schema Shape` -} - -function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - return `// .h Schema Type` -} - - -export default { - getMethodSignature, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, -} \ No newline at end of file diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs new file mode 100644 index 00000000..f3b39cbf --- /dev/null +++ b/languages/c/src/types/ImplHelpers.mjs @@ -0,0 +1,294 @@ +const Indent = '\t' + +const getObjectHandleManagementImpl = (varName, jsonDataName) => { + + let result = ` +${varName}Handle ${varName}Handle_Create(void) { + WPEFramework::Core::ProxyType<${jsonDataName}>* type = new WPEFramework::Core::ProxyType<${jsonDataName}>(); + *type = WPEFramework::Core::ProxyType<${jsonDataName}>::Create(); + return (static_cast<${varName}Handle>(type)); +} +void ${varName}Handle_Addref(${varName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + var->AddRef(); +} +void ${varName}Handle_Release(${varName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + var->Release(); + if(var->IsValid() != true) { + delete var; + } +} +bool ${varName}Handle_IsValid(${varName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + return var->IsValid(); +} +` + return result +} + +const getPropertyAccessorsImpl = (objName, propertyName, jsonDataName, propertyType, json = {}, options = {readonly:false, optional:false}) => { + + let result + if (json.type === 'object') { + result += `${objName}_${propertyName}Handle ${objName}_Get_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyName}>(); + *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); + *(*object) = (*var)->${propertyName}; + return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' + } else if (json.type === 'array') { + result += `${objName}_${propertyName}ArrayHandle ${objName}_Get_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + WPEFramework::Core::ProxyType>* object = new WPEFramework::Core::ProxyType>(); + *object = WPEFramework::Core::ProxyType>::Create(); + *(*object) = (*var)->${propertyName}.Element(); + return (static_cast<${objName}_${propertyType}ArrayHandle>(object));` + '\n' + } else if (json.enum) { + result += `${objName}_${propertyName} ${objName}_Get_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + return static_cast<${propertyType}>((*var)->${propertyName}.Value());` + '\n' + } else { + result += `${propertyType} ${objName}_Get_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid());` + '\n' + if (json.type === 'string') { + result += ` + return static_cast<${propertyType}>((*var)->${propertyName}.Value().c_str());` + '\n' + } else { + result += ` + return static_cast<${propertyType}>((*var)->${propertyName}.Value());` + '\n' + } + } + result += ` +}` + '\n' + if (!options.readonly) { + if (json.type === 'object') { + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName}Handle ${propertyName.toLowerCase()}) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* object = static_cast*>(${propertyName.toLowerCase()}); + (*var)->${propertyName} = *(*object);` + '\n' + } + if (json.type === 'array') { + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName}ArrayHandle ${propertyName.toLowerCase()}) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + WPEFramework::Core::ProxyType>* object = static_cast>*>(${propertyName.toLowerCase()}).Element(); + (*var)->${propertyName} = *(*object);` + '\n' + } if (json.enum) { + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName} ${propertyName.toLowerCase()}) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + (*var)->${propertyName} = static_cast<${propertyType}>(${propertyName.toLowerCase()});` + '\n' + } + else { + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${propertyType} ${propertyName.toLowerCase()}) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + (*var)->${propertyName} = static_cast<${propertyType}>(${propertyName.toLowerCase()});` + '\n' + } +result += `}` + '\n' + } + + if (options.optional === true) { + result += `${Indent.repeat(options.level)}bool ${objName}_has_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + return ((*var)->${propertyName}.IsSet()); +}` + '\n' + result += `${Indent.repeat(options.level)}void ${objName}_clear_${propertyName}(${objName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + ((*var)->${propertyName}.Clear()); +}` + '\n' + } + return result +} + +const getArrayAccessors = (objName, propertyName, propertyType, json = {}, options = {readonly:false, optional:false}) => { + let result = ` +uint32_t ${objName}_${propertyName}Array_Size(${objName}::${propertyName}ArrayHandle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + return ((*var)->Length()); +}` + '\n' + + if (json.type === 'object') { +result += `${objName}_${propertyType}Handle ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid()); + WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyType}>(); + *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); + *(*object) = (*var)->Get(index); + return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' + } else if (json.enum) { + result += `${objName}_${propertyType} ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid()); + + return (static_cast<${propertyType}>((*var)->Get(index)));` + '\n' + } else { + result += `${propertyType} ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid());` + '\n' + + if (json.type === 'string') { + result += `return (static_cast<${propertyType}>((*var)->Get(index).Value().c_str()));` + '\n' + } else { + result += `return (static_cast<${propertyType}>((*var)->Get(index)));` + '\n' + } + + } + result += `}` + '\n' + + if (json.type === 'object') { + result += `void ${objName}_${propertyName}Array_Add(${objName}_${propertyName}ArrayHandle handle, ${objName}_${propertyType}Handle value) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid()); + WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = static_cast*>(value); + + (*var)->Add(*(*object));` + '\n' + } else { + result += `void ${objName}_${propertyName}Array_Add(${objName}_${propertyName}ArrayHandle handle, ${propertyType} value) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid());` + '\n' + if (json.type === 'string') { + result += `WPEFramework::Core::JSON::String element(value);` + '\n' + } else if (json.type === 'number') { + result += `WPEFramework::Core::JSON::Number element(value);` + '\n' + } else if (json.enum) { + result += `WPEFramework::Core::JSON::EnumType<${propertyType}> element(value);` + '\n' + } + result += `(*var)->Add(element);` + '\n' + } + result += `}` + '\n' + + result += `void ${objName}_${propertyName}Array_Clear(${objName}_${propertyName}ArrayHandle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + ASSERT(var->IsValid()); + (*var)->Clear(); +}` + '\n' + + return result +} + +const getMapAccessors = (objName, propertyName, propertyType, json = {}, options = {readonly:false, optional:false}) => { + let result = `uint32_t ${objName}_${propertyName}_KeysCount(${objName}_${propertyName}Handle handle) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + return (*var)->Size()); + + }` + '\n' + result += `void ${objName}_${propertyName}_AddKey(${objName}_${propertyName}Handle handle, char* key, ${propertyType} value) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid());` + '\n' + + if (json.type === 'object') { + result += ` + (*var)->Add(key, value);` + '\n' + } else if (json.type === 'boolean') { + result += ` + WPEFramework::Core::JSON::Boolean element(value);` + } else if (json.type === 'string') { + result += ` + WPEFramework::Core::JSON::String element(value);` + } else if (json.type === 'number') { + result += ` + WPEFramework::Core::JSON::Number element(value);` + } else if (json.type === 'array') { + result += ` + WPEFramework::Core::JSON::ArrayType element(value);` + } else if (json.enum) { + result += ` + WPEFramework::Core::JSON::EnumType element(value); + (*var)->Add(key, element);` + '\n' + } + result += ` + }` + '\n' + result += `void ${objName}_${propertyName}_RemoveKey(${objName}_${propertyName}Handle handle, char* key) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + + (*var)->Remove(key); + }` + '\n' + + if (json.type === 'object') { + result += `${objName}_${propertyType}Handle ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyType}>(); + *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); + *(*object) = (*var)->Find(key); + return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' + + } else if (json.type === 'array') { + result += `${objName}_${propertyType}ArrayHandle ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid()); + WPEFramework::Core::ProxyType>* object = new WPEFramework::Core::ProxyType>(); + *object = WPEFramework::Core::ProxyType>::Create(); + *(*object) = (*var)->Find(key); + return (static_cast<${objName}_${propertyType}ArrayHandle>(object));` + '\n' + + } else { + result += `${propertyType} ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { + ASSERT(handle != NULL); + WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + ASSERT(var->IsValid());` + '\n' + + if (json.type === 'string') { + result += ` + return (static_cast<${propertyType}>((*var)->(Find(key).Value().c_str())));` + '\n' + } else { + result += ` + return (static_cast<${propertyType}>((*var)->(Find(key).Value())));` + '\n' + } + } + result += ` +}` + '\n' + + return result +} + +export { + getObjectHandleManagementImpl, + getPropertyAccessorsImpl +} diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs new file mode 100644 index 00000000..25d1ad3b --- /dev/null +++ b/languages/c/src/types/JSONHelpers.mjs @@ -0,0 +1,61 @@ +const capitalize = str => str[0].toUpperCase() + str.substr(1) + +function getJsonContainerDefinition (name, props) { + name = capitalize(name) + let c = ` class ${name}: public Core::JSON::Container { + public: + ${name}(const ${name}&) = delete; + ${name}& operator=(const ${name}&) = delete; + ~${name}() override = default; + + public: + ${name}() + : Core::JSON::Container() + {` + + props.forEach(prop => { + c += `\n Add(_T("${prop.name}"), &${capitalize(prop.name)});` + }) + + c += `\n }\n\n public:` + + props.forEach(prop => { + c += `\n ${prop.type} ${capitalize(prop.name)};` + }) + + c += '\n };' + return c + } + +/* + +ENUM_CONVERSION_BEGIN(Advertising_SkipRestriction) + { ADVERTISING_SKIPRESTRICTION_NONE, _T("none") }, + { ADVERTISING_SKIPRESTRICTION_ADS_UNWATCHED, _T("adsUnwatched") }, + { ADVERTISING_SKIPRESTRICTION_ADS_ALL, _T("adsAll") }, + { ADVERTISING_SKIPRESTRICTION_ALL, _T("all") }, +ENUM_CONVERSION_END(Advertising_SkipRestriction) + + +*/ + +// TODO - this should be a global function in the main /src/ directory... not part of a language pack +const keyName = val => val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + +function getJsonEnumConversion(schema, module, { name }) { + name = capitalize(schema.title || name) + let e = `ENUM_CONVERSION_BEGIN(${module.info.title}_${name})\n` + + schema.enum.forEach(value => { + e += `{ ${module.info.title.toUpperCase()}_${name.toUpperCase()}_${keyName(value)}, _T("${value}") },` + }) + + e += `ENUM_CONVERSION_END(${module.info.title}_${name})` + + return e +} + +export { + getJsonContainerDefinition, + getJsonEnumConversion +} diff --git a/languages/c/src/types/JSONTypes.mjs b/languages/c/src/types/JSONTypes.mjs deleted file mode 100644 index d2961794..00000000 --- a/languages/c/src/types/JSONTypes.mjs +++ /dev/null @@ -1,56 +0,0 @@ - -/* - * Copyright 2021 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 - */ - -// import deepmerge from 'deepmerge' -// import { getPath, getSchema, localizeDependencies } from '../../src/shared/json-schema.mjs' -// import { getLinkFromRef } from '../../src/shared/markdown.mjs' -// import { getProviderInterfaceMethods, getPayloadFromEvent } from '../../src/shared/modules.mjs' - - -// getMethodSignature(method, module, options = { destination: 'file.txt' }) -// getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) -// getSchemaType(schema, module, options = { destination: 'file.txt' }) -// getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) -// getProviderInterface(capability, module, options = { destination: 'file.txt' } ) - -function getMethodSignature(method, module, { destination = '' } = {}) { - return `// JSON Signatures for ${module}_${method}` -} - -function getMethodSignatureParams(method, module, { destination = '' } = {}) { - return `// JSON Signature Params for ${module}_${method}` -} - -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaShape(schema = {}, module = {}, { name = '', destination = '', level = 0, descriptions = true} = {}) { - return `// JSON Schema Shape` -} - -function getSchemaType(schema, module, { schemas = {}, destination = '', link = false, title = false, code = false, asPath = false, baseUrl = '' } = {}) { - return `// JSON Schema Type` -} - - -export default { - getMethodSignature, - getMethodSignatureParams, - getSchemaShape, - getSchemaType, -} \ No newline at end of file diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index e51c47d7..79242d1f 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -201,260 +201,6 @@ const getIncludeDefinitions = (json = {}, jsonData = false) => { .concat([`#include "Firebolt/Types.h"`]) } -function getSchemaType(module = {}, json = {}, name = '', schemas = {}, options = {level: 0, descriptions: true, title: false}) { - if (json.schema) { - json = json.schema - } - - let structure = {} - structure["deps"] = new Set() //To avoid duplication of local ref definitions - structure["type"] = [] - - if (json['$ref']) { - if (json['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType - let definition = getPath(json['$ref'], module, schemas) - let tName = definition.title || json['$ref'].split('/').pop() - const res = getSchemaType(module, definition, tName, schemas, {descriptions: options.descriptions, level: options.level}) - res.deps.forEach(dep => structure.deps.add(dep)) - structure.type = res.type - return structure - } - else { - // External dependency. - // e.g, "https://meta.comcast.com/firebolt/entertainment#/definitions/ProgramType" - - //Get the module of this definition - const schema = getPath(json['$ref'].split('#')[0], schemas) || module - - //Get the schema of the definition - const definition = getPath(json['$ref'], module, schemas) - let tName = definition.title || json['$ref'].split('/').pop() - const res = getSchemaType(schema, definition, tName, schemas, {descriptions: options.descriptions, level: options.level}) - //We are only interested in the type definition for external modules - structure.type = res.type - return structure - } - } - else if (json.const) { - structure.type = getNativeType(json) - return structure - } - else if (json['x-method']) { - console.log(`WARNING UNHANDLED: x-method in ${name}`) - return structure - //throw "x-methods not supported yet" - } - else if (json.type === 'string' && json.enum) { - //Enum - let typeName = getTypeName(getModuleName(module), name || json.title) - let res = description(capitalize(name || json.title), json.description) + '\n' + generateEnum(json, typeName) - structure.deps.add(res) - structure.type.push(typeName) - return structure - } - else if (Array.isArray(json.type)) { - let type = json.type.find(t => t !== 'null') - console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) - } - else if (json.type === 'array' && json.items) { - let res - if (Array.isArray(json.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(json.items)) { - throw 'Heterogenous Arrays not supported yet' - } - res = getSchemaType(module, json.items[0],'',schemas) - } - else { - // grab the type for the non-array schema - res = getSchemaType(module, json.items, '', schemas) - } - - res.deps.forEach(dep => structure.deps.add(dep)) - let n = getTypeName(getModuleName(module), name || json.title) - let def = description(name || json.title, json.description) + '\n' - if (options.level === 0) { - def += getObjectHandleManagement(n + 'Array') + '\n' - } - def += getArrayAccessors(n + 'Array', res.type) - structure.deps.add(def) - structure.type.push(n + 'ArrayHandle') - return structure - } - else if (json.allOf) { - let union = deepmerge.all([...json.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)]) - if (json.title) { - union['title'] = json.title - } - else { - union['title'] = name - } - delete union['$ref'] - return getSchemaType(module, union, '',schemas, options) - } - else if (json.oneOf || json.anyOf) { - return structure - //TODO - } - else if (json.type === 'object') { - let res = getSchemaShape(module, json, schemas, json.title || name, {descriptions: options.descriptions, level: 0}) - res.deps.forEach(dep => structure.deps.add(dep)) - res.type.forEach(t => structure.deps.add(t)) - structure.type.push(getTypeName(getModuleName(module), json.title || name) + 'Handle') - return structure - //TODO - } - else if (json.type) { - structure.type = getNativeType(json) - return structure - } - return structure -} - -function getSchemaShape(moduleJson = {}, json = {}, schemas = {}, name = '', options = {level: 0, descriptions: true}) { - json = JSON.parse(JSON.stringify(json)) - let level = options.level - let descriptions = options.descriptions - - let structure = {} - structure["deps"] = new Set() //To avoid duplication of local ref definitions - structure["type"] = [] - - if (json['$ref']) { - if (json['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType - - const schema = getPath(json['$ref'], module, schemas) - const tname = schema.title || json['$ref'].split('/').pop() - res = getSchemaShape(module, schema, schemas, tname, {descriptions: descriptions, level: level}) - res.deps.forEach(dep => structure.deps.add(dep)) - structure.type = res.type - } - else { - // External dependency. Return only type - // e.g, "https://meta.comcast.com/firebolt/entertainment#/definitions/ProgramType" - - //Get the module of this definition - const schema = getPath(json['$ref'].split('#')[0], schemas) || module - - //Get the schema of the definition - const definition = getPath(json['$ref'], schema, schemas) - const pname = (json.title || name) + (definition.title || json['$ref'].split('/').pop()) - - res = getSchemaShape(schema, definition, schemas, pname,{descriptions: descriptions, level: level}) - //We are only interested in the type definition for external modules - structure.type = res.type - } - } - //If the schema is a const, - else if (json.hasOwnProperty('const')) { - if (level > 0) { - - let t = description(name, json.description) - typeName = getTypeName(getModuleName(moduleJson), name) - t += getPropertyAccessors(typeName, capitalize(name), typeof json.const, {level: level, readonly:true, optional:false}) - structure.type.push(t) - } - } - else if (json.type === 'object') { - - if (json.properties) { - let tName = getTypeName(getModuleName(moduleJson), name) - let t = description(name, json.description) - t += '\n' + getObjectHandleManagement(tName) - Object.entries(json.properties).forEach(([pname, prop]) => { - t += '\n' + description(pname, prop.description) - let res - if (prop.type === 'array') { - if (Array.isArray(prop.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(prop.items)) { - throw 'Heterogenous Arrays not supported yet' - } - res = getSchemaType(moduleJson, prop.items[0],pname, schemas, {level : options.level, descriptions: options.descriptions, title: true}) - } - else { - // grab the type for the non-array schema - res = getSchemaType(moduleJson, prop.items, pname, schemas, {level : options.level, descriptions: options.descriptions, title: true}) - } - if (res.type && res.type.length > 0) { - let n = tName + '_' + capitalize(pname || prop.title) - let def = getArrayAccessors(n + 'Array', res.type) - t += '\n' + def - } - else { - console.log(`WARNING: Type undetermined for ${name}:${pname}`) - } - } else { - res = getSchemaType(moduleJson, prop, pname,schemas, {descriptions: descriptions, level: level + 1, title: true}) - if (res.type && res.type.length > 0) { - t += '\n' + getPropertyAccessors(tName, capitalize(pname), res.type, {level: level, readonly:false, optional:isOptional(pname, json)}) - } - else { - console.log(`WARNING: Type undetermined for ${name}:${pname}`) - } - } - res.deps.forEach(dep => structure.deps.add(dep)) - }) - structure.type.push(t) - } - else if (json.propertyNames && json.propertyNames.enum) { - //propertyNames in object not handled yet - } - else if (json.additionalProperties && (typeof json.additionalProperties === 'object')) { - //This is a map of string to type in schema - //Get the Type - let type = getSchemaType(moduleJson, json.additionalProperties, name,schemas) - if (type.type && type.type.length > 0) { - let tName = getTypeName(getModuleName(moduleJson), name) - type.deps.forEach(dep => structure.deps.add(dep)) - let t = description(name, json.description) - t += '\n' + getObjectHandleManagement(tName) + '\n' - t += getMapAccessors(getTypeName(getModuleName(moduleJson), name), type.type,{descriptions: descriptions, level: level}) - structure.type.push(t) - } - else { - console.log(`WARNING: Type undetermined for ${name}`) - } - } - else if (json.patternProperties) { - throw "patternProperties are not supported by Firebolt" - } - } - else if (json.anyOf) { - - } - else if (json.oneOf) { - - } - else if (json.allOf) { - let union = deepmerge.all([...json.allOf.map(x => x['$ref'] ? getPath(x['$ref'], moduleJson, schemas) || x : x)], options) - if (json.title) { - union['title'] = json.title - } - else { - union['title'] = name - } - delete union['$ref'] - return getSchemaShape(moduleJson, union, schemas, name, options) - - } - else if (json.type === 'array') { - let res = getSchemaType(moduleJson, json, name, schemas, {level: 0, descriptions: descriptions}) - res.deps.forEach(dep => structure.deps.add(dep)) - } - else { - let res = getSchemaType(moduleJson, json, name, schemas, {level: level, descriptions: descriptions}) - res.deps.forEach(dep => structure.deps.add(dep)) - } - return structure - } - function getPropertyGetterSignature(method, module, paramType) { let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` @@ -480,15 +226,19 @@ function getSchemaShape(moduleJson = {}, json = {}, schemas = {}, name = '', opt getStyleGuardClose, getIncludeGuardClose, getNativeType, - getSchemaType, - getSchemaShape, getModuleName, getIncludeDefinitions, getPropertyGetterSignature, getPropertySetterSignature, getPropertyEventCallbackSignature, getPropertyEventSignature, + getMapAccessors, + getArrayAccessors, capitalize, description, - getTypeName + getTypeName, + getObjectHandleManagement, + getPropertyAccessors, + isOptional, + generateEnum } diff --git a/languages/c/templates/codeblocks/export.mjs b/languages/c/templates/codeblocks/export.c similarity index 100% rename from languages/c/templates/codeblocks/export.mjs rename to languages/c/templates/codeblocks/export.c diff --git a/languages/c/templates/codeblocks/mock-import.mjs b/languages/c/templates/codeblocks/mock-import.c similarity index 100% rename from languages/c/templates/codeblocks/mock-import.mjs rename to languages/c/templates/codeblocks/mock-import.c diff --git a/languages/c/templates/codeblocks/mock-parameter.mjs b/languages/c/templates/codeblocks/mock-parameter.c similarity index 100% rename from languages/c/templates/codeblocks/mock-parameter.mjs rename to languages/c/templates/codeblocks/mock-parameter.c diff --git a/languages/c/templates/declarations/clear.js b/languages/c/templates/codeblocks/module.c similarity index 100% rename from languages/c/templates/declarations/clear.js rename to languages/c/templates/codeblocks/module.c diff --git a/languages/c/templates/codeblocks/module.mjs b/languages/c/templates/codeblocks/module.mjs deleted file mode 100644 index 48f6d6bc..00000000 --- a/languages/c/templates/codeblocks/module.mjs +++ /dev/null @@ -1,11 +0,0 @@ -// JEREMY - -export module ${info.title} { - - /* ${SCHEMAS} */ - - /* ${DECLARATIONS} */ - - /* ${PROVIDERS} */ - -} \ No newline at end of file diff --git a/languages/c/templates/declarations/listen.js b/languages/c/templates/declarations/clear.c similarity index 100% rename from languages/c/templates/declarations/listen.js rename to languages/c/templates/declarations/clear.c diff --git a/languages/c/templates/declarations/default.js b/languages/c/templates/declarations/default.c similarity index 68% rename from languages/c/templates/declarations/default.js rename to languages/c/templates/declarations/default.c index bd8b6fcf..72fbf14f 100644 --- a/languages/c/templates/declarations/default.js +++ b/languages/c/templates/declarations/default.c @@ -1,4 +1,4 @@ /** * ${method.summary} ${method.params} */ - ${method.signature} + ${method.signature}; diff --git a/languages/c/templates/declarations/once.js b/languages/c/templates/declarations/listen.c similarity index 100% rename from languages/c/templates/declarations/once.js rename to languages/c/templates/declarations/listen.c diff --git a/languages/c/templates/declarations/provide.js b/languages/c/templates/declarations/once.c similarity index 100% rename from languages/c/templates/declarations/provide.js rename to languages/c/templates/declarations/once.c diff --git a/languages/c/templates/declarations/polymorphic-reducer.js b/languages/c/templates/declarations/polymorphic-reducer.c similarity index 100% rename from languages/c/templates/declarations/polymorphic-reducer.js rename to languages/c/templates/declarations/polymorphic-reducer.c diff --git a/languages/c/templates/declarations/rpc-only.js b/languages/c/templates/declarations/provide.c similarity index 100% rename from languages/c/templates/declarations/rpc-only.js rename to languages/c/templates/declarations/provide.c diff --git a/languages/c/templates/methods/listen.js b/languages/c/templates/declarations/rpc-only.c similarity index 100% rename from languages/c/templates/methods/listen.js rename to languages/c/templates/declarations/rpc-only.c diff --git a/languages/c/templates/defaults/default.mjs b/languages/c/templates/defaults/default.c similarity index 100% rename from languages/c/templates/defaults/default.mjs rename to languages/c/templates/defaults/default.c diff --git a/languages/c/templates/defaults/property.mjs b/languages/c/templates/defaults/property.c similarity index 100% rename from languages/c/templates/defaults/property.mjs rename to languages/c/templates/defaults/property.c diff --git a/languages/c/templates/examples/default.md b/languages/c/templates/examples/default.md deleted file mode 100644 index ecc979ba..00000000 --- a/languages/c/templates/examples/default.md +++ /dev/null @@ -1,6 +0,0 @@ -import { ${module} } from '${package.name}' - -${module}.${method.name}(${example.params}) - .then(${method.result.name} => { - console.log(${method.result.name}) - }) \ No newline at end of file diff --git a/languages/c/templates/examples/event.md b/languages/c/templates/examples/event.md deleted file mode 100644 index 7b78fe76..00000000 --- a/languages/c/templates/examples/event.md +++ /dev/null @@ -1,5 +0,0 @@ -import { ${module} } from '${package.name}' - -${module}.listen('${event.name}', ${method.result.name} => { - console.log(${method.result.name}) -}) \ No newline at end of file diff --git a/languages/c/templates/examples/polymorphic-pull-event.md b/languages/c/templates/examples/polymorphic-pull-event.md deleted file mode 100644 index 7bc2baa7..00000000 --- a/languages/c/templates/examples/polymorphic-pull-event.md +++ /dev/null @@ -1,9 +0,0 @@ -import { ${module} } from '${package.name}' - -${module}.${method.pulls.for}(function(parameters) { - console.log(parameters.entityId) - console.log(parameters.assetId) - return Promise.resolve(${originator.params[1].example.value}) -}).then(success => { - console.log(success) -}) \ No newline at end of file diff --git a/languages/c/templates/examples/polymorphic-pull.md b/languages/c/templates/examples/polymorphic-pull.md deleted file mode 100644 index 7c53080c..00000000 --- a/languages/c/templates/examples/polymorphic-pull.md +++ /dev/null @@ -1,6 +0,0 @@ -import { ${module} } from '${package.name}' - -${module}.${method.name}(${method.params[1].example.value}) - .then(success => { - console.log(success) - }) \ No newline at end of file diff --git a/languages/c/templates/examples/provider.md b/languages/c/templates/examples/provider.md deleted file mode 100644 index d2d16366..00000000 --- a/languages/c/templates/examples/provider.md +++ /dev/null @@ -1,10 +0,0 @@ -import { ${module} } from '${package.name}' - -class MyProvider { - async ${example.providerMethod}(${method.result.name}, responder) { - console.log(JSON.stringify(${method.result.name}, null, 2)) - responder(${example.providerResponse}) - } -} - -${module}.provide(new MyProvider()) \ No newline at end of file diff --git a/languages/c/templates/examples/setter.md b/languages/c/templates/examples/setter.md deleted file mode 100644 index c258314a..00000000 --- a/languages/c/templates/examples/setter.md +++ /dev/null @@ -1,6 +0,0 @@ -import { ${module} } from '${package.name}' - -${module}.${method.setter.for}(${example.params}) - .then(${method.result.name} => { - console.log(${method.result.name}) - }) \ No newline at end of file diff --git a/languages/c/templates/examples/subscriber.md b/languages/c/templates/examples/subscriber.md deleted file mode 100644 index 99c0516f..00000000 --- a/languages/c/templates/examples/subscriber.md +++ /dev/null @@ -1,7 +0,0 @@ -import { ${module} } from '${package.name}' - -${method.alternative}(value => { - console.log(value) -}).then(listenerId => { - console.log(listenerId) -}) \ No newline at end of file diff --git a/languages/c/templates/examples/synchronous.md b/languages/c/templates/examples/synchronous.md deleted file mode 100644 index 6e8e1e82..00000000 --- a/languages/c/templates/examples/synchronous.md +++ /dev/null @@ -1,4 +0,0 @@ -import { ${module} } from '${package.name}' - -const ${method.result.name} = ${module}.${method.name}(${example.params}) -console.log(${method.result.name}) \ No newline at end of file diff --git a/languages/c/templates/examples/temporal-set.md b/languages/c/templates/examples/temporal-set.md deleted file mode 100644 index 4a8e94ea..00000000 --- a/languages/c/templates/examples/temporal-set.md +++ /dev/null @@ -1,13 +0,0 @@ -import { ${module} } from '${package.name}' - -const process = ${module}.${method.name}(function(${example.params}${if.params},${end.if.params} - ${method.item} => { - console.log('Added to temporal set:') - console.dir(${method.item}) - }, - ${method.item} => { - console.log('Removed from temporal set:') - console.dir(${method.item}) - }) - -setTimeout( () => process.stop(), 10000) \ No newline at end of file diff --git a/languages/c/templates/imports/context-event.mjs b/languages/c/templates/imports/context-event.mjs deleted file mode 100644 index fcd3186b..00000000 --- a/languages/c/templates/imports/context-event.mjs +++ /dev/null @@ -1 +0,0 @@ -import { registerEventContext } from '../Events/index.mjs' diff --git a/languages/c/templates/imports/default.c b/languages/c/templates/imports/default.c new file mode 100644 index 00000000..a38b58ef --- /dev/null +++ b/languages/c/templates/imports/default.c @@ -0,0 +1 @@ +#include "Common/${info.title}.h" diff --git a/languages/c/templates/imports/event.mjs b/languages/c/templates/imports/event.mjs deleted file mode 100644 index bc019bca..00000000 --- a/languages/c/templates/imports/event.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import Events from '../Events/index.mjs' -import { registerEvents } from '../Events/index.mjs' diff --git a/languages/c/templates/imports/property.mjs b/languages/c/templates/imports/property.mjs deleted file mode 100644 index 7107a163..00000000 --- a/languages/c/templates/imports/property.mjs +++ /dev/null @@ -1 +0,0 @@ -import Prop from '../Prop/index.mjs' diff --git a/languages/c/templates/imports/provider.mjs b/languages/c/templates/imports/provider.mjs deleted file mode 100644 index b3ea7b4f..00000000 --- a/languages/c/templates/imports/provider.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import ProvideManager from '../ProvideManager/index.mjs' -import { registerProviderInterface } from '../ProvideManager/index.mjs' diff --git a/languages/c/templates/imports/rpc.mjs b/languages/c/templates/imports/rpc.mjs deleted file mode 100644 index af459a1e..00000000 --- a/languages/c/templates/imports/rpc.mjs +++ /dev/null @@ -1 +0,0 @@ -import Transport from '../Transport/index.mjs' diff --git a/languages/c/templates/imports/temporal-set.mjs b/languages/c/templates/imports/temporal-set.mjs deleted file mode 100644 index 089d35b1..00000000 --- a/languages/c/templates/imports/temporal-set.mjs +++ /dev/null @@ -1 +0,0 @@ -import TemporalSet from '../TemporalSet/index.mjs' \ No newline at end of file diff --git a/languages/c/templates/imports/x-method.mjs b/languages/c/templates/imports/x-method.mjs deleted file mode 100644 index 42453ecb..00000000 --- a/languages/c/templates/imports/x-method.mjs +++ /dev/null @@ -1 +0,0 @@ -import Results from '../Results/index.mjs' \ No newline at end of file diff --git a/languages/c/templates/initializations/deprecated.mjs b/languages/c/templates/initializations/deprecated.mjs deleted file mode 100644 index 737d1c25..00000000 --- a/languages/c/templates/initializations/deprecated.mjs +++ /dev/null @@ -1 +0,0 @@ -Transport.registerDeprecatedMethod('${info.title}', '${method.name}', 'Use ${method.alternative} instead.') diff --git a/languages/c/templates/initializations/event.mjs b/languages/c/templates/initializations/event.mjs deleted file mode 100644 index c151f674..00000000 --- a/languages/c/templates/initializations/event.mjs +++ /dev/null @@ -1 +0,0 @@ -registerEvents('${info.title}', ${events.array}) diff --git a/languages/c/templates/initializations/provider.mjs b/languages/c/templates/initializations/provider.mjs deleted file mode 100644 index b113d236..00000000 --- a/languages/c/templates/initializations/provider.mjs +++ /dev/null @@ -1 +0,0 @@ -registerProviderInterface('${capability}', '${info.title}', ${interface}) diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 7d10ba97..49f76ce1 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -1,5 +1,5 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_${method.Name}(${method.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { +uint32_t ${info.title}_${method.Name}(${method.params.list}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { uint32_t status = FireboltSDKErrorUnavailable; FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { diff --git a/languages/c/templates/methods/once.js b/languages/c/templates/methods/listen.c similarity index 100% rename from languages/c/templates/methods/once.js rename to languages/c/templates/methods/listen.c diff --git a/languages/c/templates/methods/rpc-only.js b/languages/c/templates/methods/once.c similarity index 100% rename from languages/c/templates/methods/rpc-only.js rename to languages/c/templates/methods/once.c diff --git a/languages/c/templates/methods/polymorphic-reducer.js b/languages/c/templates/methods/polymorphic-reducer.c similarity index 100% rename from languages/c/templates/methods/polymorphic-reducer.js rename to languages/c/templates/methods/polymorphic-reducer.c diff --git a/languages/c/templates/methods/provide.js b/languages/c/templates/methods/provide.c similarity index 100% rename from languages/c/templates/methods/provide.js rename to languages/c/templates/methods/provide.c diff --git a/languages/c/templates/methods/rpc-only.c b/languages/c/templates/methods/rpc-only.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/modules/include/Common/Module.h b/languages/c/templates/modules/include/Common/Module.h index 22c25143..2834b997 100644 --- a/languages/c/templates/modules/include/Common/Module.h +++ b/languages/c/templates/modules/include/Common/Module.h @@ -25,6 +25,12 @@ extern "C" { #endif + // Enums + + /* ${ENUMS}} */ + + // Schemas + /* ${SCHEMAS} */ #ifdef __cplusplus diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h index 92bab4f7..e24c869f 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/Module.h @@ -20,7 +20,7 @@ #define _${info.TITLE}_H #include "Firebolt.h" -#include "Common/${info.title}.h" +/* ${IMPORTS} */ #ifdef __cplusplus extern "C" { @@ -28,6 +28,7 @@ extern "C" { /* ${SCHEMAS} */ + /* ${ACCESSORS} */ /* ${DECLARATIONS} */ #ifdef __cplusplus diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 2417f708..0783b416 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -16,17 +16,22 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "FireboltSDK.h" +#include "Firebolt.h" #include "${info.title}.h" -#include "Common/${info.title}.h" #include "JsonData_${info.title}.h" +/* ${IMPORTS} */ + + #ifdef __cplusplus extern "C" { #endif - /* ${METHODS} */ +/* ${TYPES} */ #ifdef __cplusplus } #endif + +/* ${ACCESSORS} */ +/* ${METHODS} */ diff --git a/languages/c/templates/schemas/default.js b/languages/c/templates/schemas/default.c similarity index 100% rename from languages/c/templates/schemas/default.js rename to languages/c/templates/schemas/default.c diff --git a/languages/c/templates/schemas/include/Common/Module.h b/languages/c/templates/schemas/include/Common/Module.h index 5582d8ea..50ef1fd9 100644 --- a/languages/c/templates/schemas/include/Common/Module.h +++ b/languages/c/templates/schemas/include/Common/Module.h @@ -16,10 +16,25 @@ * SPDX-License-Identifier: Apache-2.0 */ -namespace FireboltSDK { +#ifndef _COMMON_${info.TITLE}_H +#define _COMMON_${info.TITLE}_H - /* ${DECLARATIONS} */ +#include "Firebolt.h" - /* ${SCHEMAS} */ +#ifdef __cplusplus +extern "C" { +#endif + // Enums + + /* ${ENUMS} */ + + // Types + + /* ${TYPES} */ + +#ifdef __cplusplus } +#endif + +#endif // Header Include Guard \ No newline at end of file diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/Module_Common.cpp index 8460c52a..632f38d6 100644 --- a/languages/c/templates/schemas/src/Module_Common.cpp +++ b/languages/c/templates/schemas/src/Module_Common.cpp @@ -16,11 +16,19 @@ * SPDX-License-Identifier: Apache-2.0 */ -/* ${IMPORTS} */ +#include "Firebolt.h" +#include "${info.title}.h" +#include "Common/${info.title}.h" +#include "JsonData_${info.title}.h" +#ifdef __cplusplus +extern "C" { +#endif -namespace FireboltSDK { - + /* ${TYPES} */ + /* ${ACCESSORS} */ /* ${METHODS} */ +#ifdef __cplusplus } +#endif diff --git a/languages/c/templates/sdk/CMakeLists.txt b/languages/c/templates/sdk/CMakeLists.txt new file mode 100644 index 00000000..a29658f7 --- /dev/null +++ b/languages/c/templates/sdk/CMakeLists.txt @@ -0,0 +1,49 @@ +# 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 + +cmake_minimum_required(VERSION 3.3) + +project(Firebolt) + +set(FIREBOLT_TRANSPORT_WAITTIME 1000 CACHE STRING "Maximum time to wait for Transport layer to get response") +set(FIREBOLT_LOGLEVEL "Info" CACHE STRING "Log level to be enabled") + +option(ENABLE_TESTS "Build openrpc native test" OFF) + +list(APPEND CMAKE_MODULE_PATH + "${CMAKE_SOURCE_DIR}/cmake" + "${SYSROOT_PATH}/usr/lib/cmake" + "${SYSROOT_PATH}/tools/cmake") +include(HelperFunctions) + +if (NOT DEFINED CMAKE_PREFIX_PATH) + set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) +endif() + +set(FIREBOLT_NAMESPACE ${PROJECT_NAME} CACHE STRING "Namespace of the project") + +find_package(WPEFramework CONFIG REQUIRED) + +add_subdirectory(src) + +if (ENABLE_TESTS) + add_subdirectory(test) +endif() + +# make sure others can make use cmake settings of Firebolt OpenRPC +configure_file( "${CMAKE_SOURCE_DIR}/cmake/project.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake" + @ONLY) diff --git a/languages/c/templates/sdk/build/CMakeCache.txt b/languages/c/templates/sdk/build/CMakeCache.txt new file mode 100644 index 00000000..f10d476d --- /dev/null +++ b/languages/c/templates/sdk/build/CMakeCache.txt @@ -0,0 +1,407 @@ +# This is the CMakeCache file. +# For build in directory: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build +# It was generated by CMake: /opt/homebrew/Cellar/cmake/3.25.3/bin/cmake +# You can edit this file to change values found and used by cmake. +# If you do not want to change any of the values, simply exit the editor. +# If you do want to change a value, simply edit, save, and exit the editor. +# The syntax for the file is as follows: +# KEY:TYPE=VALUE +# KEY is the name of a variable in the cache. +# TYPE is a hint to GUIs for the type of VALUE, DO NOT EDIT TYPE!. +# VALUE is the current value for the KEY. + +######################## +# EXTERNAL cache entries +######################## + +//Path to a program. +CMAKE_ADDR2LINE:FILEPATH=CMAKE_ADDR2LINE-NOTFOUND + +//Path to a program. +CMAKE_AR:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ar + +//Choose the type of build, options are: None Debug Release RelWithDebInfo +// MinSizeRel ... +CMAKE_BUILD_TYPE:STRING=Release + +//Enable/Disable color output during build. +CMAKE_COLOR_MAKEFILE:BOOL=ON + +//CXX compiler +CMAKE_CXX_COMPILER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/c++ + +//Flags used by the CXX compiler during all build types. +CMAKE_CXX_FLAGS:STRING=-D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION + +//Flags used by the CXX compiler during DEBUG builds. +CMAKE_CXX_FLAGS_DEBUG:STRING=-g + +//Flags used by the CXX compiler during MINSIZEREL builds. +CMAKE_CXX_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG + +//Flags used by the CXX compiler during RELEASE builds. +CMAKE_CXX_FLAGS_RELEASE:STRING=-O3 -DNDEBUG + +//Flags used by the CXX compiler during RELWITHDEBINFO builds. +CMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG + +//C compiler +CMAKE_C_COMPILER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/cc + +//Flags used by the C compiler during all build types. +CMAKE_C_FLAGS:STRING= + +//Flags used by the C compiler during DEBUG builds. +CMAKE_C_FLAGS_DEBUG:STRING=-g + +//Flags used by the C compiler during MINSIZEREL builds. +CMAKE_C_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG + +//Flags used by the C compiler during RELEASE builds. +CMAKE_C_FLAGS_RELEASE:STRING=-O3 -DNDEBUG + +//Flags used by the C compiler during RELWITHDEBINFO builds. +CMAKE_C_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG + +//Path to a program. +CMAKE_DLLTOOL:FILEPATH=CMAKE_DLLTOOL-NOTFOUND + +//Flags used by the linker during all build types. +CMAKE_EXE_LINKER_FLAGS:STRING= + +//Flags used by the linker during DEBUG builds. +CMAKE_EXE_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during MINSIZEREL builds. +CMAKE_EXE_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during RELEASE builds. +CMAKE_EXE_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during RELWITHDEBINFO builds. +CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//Enable/Disable output of compile commands during generation. +CMAKE_EXPORT_COMPILE_COMMANDS:BOOL= + +//Value Computed by CMake. +CMAKE_FIND_PACKAGE_REDIRECTS_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/pkgRedirects + +//Path to a program. +CMAKE_INSTALL_NAME_TOOL:FILEPATH=/usr/bin/install_name_tool + +//Install path prefix, prepended onto install directories. +CMAKE_INSTALL_PREFIX:PATH=/usr + +//No help, variable specified on the command line. +CMAKE_JS_INC:UNINITIALIZED=/Users/JLaciv000/.cmake-js/node-arm64/v19.6.1/include/node + +//No help, variable specified on the command line. +CMAKE_JS_SRC:UNINITIALIZED= + +//No help, variable specified on the command line. +CMAKE_JS_VERSION:UNINITIALIZED=undefined + +//No help, variable specified on the command line. +CMAKE_LIBRARY_OUTPUT_DIRECTORY:UNINITIALIZED=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/Release + +//Path to a program. +CMAKE_LINKER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ld + +//Path to a program. +CMAKE_MAKE_PROGRAM:FILEPATH=/usr/bin/make + +//Flags used by the linker during the creation of modules during +// all build types. +CMAKE_MODULE_LINKER_FLAGS:STRING= + +//Flags used by the linker during the creation of modules during +// DEBUG builds. +CMAKE_MODULE_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during the creation of modules during +// MINSIZEREL builds. +CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during the creation of modules during +// RELEASE builds. +CMAKE_MODULE_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during the creation of modules during +// RELWITHDEBINFO builds. +CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//No help, variable specified on the command line. +CMAKE_MSVC_RUNTIME_LIBRARY:UNINITIALIZED=MultiThreaded$<$:Debug> + +//Path to a program. +CMAKE_NM:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/nm + +//Path to a program. +CMAKE_OBJCOPY:FILEPATH=CMAKE_OBJCOPY-NOTFOUND + +//Path to a program. +CMAKE_OBJDUMP:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/objdump + +//Build architectures for OSX +CMAKE_OSX_ARCHITECTURES:STRING=arm64 + +//Minimum OS X version to target for deployment (at runtime); newer +// APIs weak linked. Set to empty string for default value. +CMAKE_OSX_DEPLOYMENT_TARGET:STRING= + +//The product will be built against the headers and libraries located +// inside the indicated SDK. +CMAKE_OSX_SYSROOT:PATH=/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk + +//Value Computed by CMake +CMAKE_PROJECT_DESCRIPTION:STATIC= + +//Value Computed by CMake +CMAKE_PROJECT_HOMEPAGE_URL:STATIC= + +//Value Computed by CMake +CMAKE_PROJECT_NAME:STATIC=Firebolt + +//Path to a program. +CMAKE_RANLIB:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ranlib + +//Path to a program. +CMAKE_READELF:FILEPATH=CMAKE_READELF-NOTFOUND + +//Flags used by the linker during the creation of shared libraries +// during all build types. +CMAKE_SHARED_LINKER_FLAGS:STRING=-undefined dynamic_lookup + +//Flags used by the linker during the creation of shared libraries +// during DEBUG builds. +CMAKE_SHARED_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during the creation of shared libraries +// during MINSIZEREL builds. +CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during the creation of shared libraries +// during RELEASE builds. +CMAKE_SHARED_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during the creation of shared libraries +// during RELWITHDEBINFO builds. +CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//If set, runtime paths are not added when installing shared libraries, +// but are added when building. +CMAKE_SKIP_INSTALL_RPATH:BOOL=NO + +//If set, runtime paths are not added when using shared libraries. +CMAKE_SKIP_RPATH:BOOL=NO + +//Flags used by the linker during the creation of static libraries +// during all build types. +CMAKE_STATIC_LINKER_FLAGS:STRING= + +//Flags used by the linker during the creation of static libraries +// during DEBUG builds. +CMAKE_STATIC_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during the creation of static libraries +// during MINSIZEREL builds. +CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during the creation of static libraries +// during RELEASE builds. +CMAKE_STATIC_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during the creation of static libraries +// during RELWITHDEBINFO builds. +CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//Path to a program. +CMAKE_STRIP:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/strip + +//If this value is on, makefiles will be generated without the +// .SILENT directive, and all commands will be echoed to the console +// during the make. This is useful for debugging only. With Visual +// Studio IDE projects all commands are done without /nologo. +CMAKE_VERBOSE_MAKEFILE:BOOL=FALSE + +//Build openrpc native test +ENABLE_TESTS:BOOL=OFF + +//Log level to be enabled +FIREBOLT_LOGLEVEL:STRING=Info + +//Namespace of the project +FIREBOLT_NAMESPACE:STRING=Firebolt + +//Maximum time to wait for Transport layer to get response +FIREBOLT_TRANSPORT_WAITTIME:STRING=1000 + +//Value Computed by CMake +Firebolt_BINARY_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build + +//Value Computed by CMake +Firebolt_IS_TOP_LEVEL:STATIC=ON + +//Value Computed by CMake +Firebolt_SOURCE_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native + +//No help, variable specified on the command line. +GENERATED_CODE_PATH:UNINITIALIZED=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/build/sdk/native-c + +//No help, variable specified on the command line. +NODE_ARCH:UNINITIALIZED=arm64 + +//No help, variable specified on the command line. +NODE_RUNTIME:UNINITIALIZED=node + +//No help, variable specified on the command line. +NODE_RUNTIMEVERSION:UNINITIALIZED=19.6.1 + +//The directory containing a CMake configuration file for WPEFramework. +WPEFramework_DIR:PATH=WPEFramework_DIR-NOTFOUND + + +######################## +# INTERNAL cache entries +######################## + +//ADVANCED property for variable: CMAKE_ADDR2LINE +CMAKE_ADDR2LINE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_AR +CMAKE_AR-ADVANCED:INTERNAL=1 +//This is the directory where this CMakeCache.txt was created +CMAKE_CACHEFILE_DIR:INTERNAL=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build +//Major version of cmake used to create the current loaded cache +CMAKE_CACHE_MAJOR_VERSION:INTERNAL=3 +//Minor version of cmake used to create the current loaded cache +CMAKE_CACHE_MINOR_VERSION:INTERNAL=25 +//Patch version of cmake used to create the current loaded cache +CMAKE_CACHE_PATCH_VERSION:INTERNAL=3 +//ADVANCED property for variable: CMAKE_COLOR_MAKEFILE +CMAKE_COLOR_MAKEFILE-ADVANCED:INTERNAL=1 +//Path to CMake executable. +CMAKE_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake +//Path to cpack program executable. +CMAKE_CPACK_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/cpack +//Path to ctest program executable. +CMAKE_CTEST_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/ctest +//ADVANCED property for variable: CMAKE_CXX_COMPILER +CMAKE_CXX_COMPILER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS +CMAKE_CXX_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_DEBUG +CMAKE_CXX_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_MINSIZEREL +CMAKE_CXX_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELEASE +CMAKE_CXX_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELWITHDEBINFO +CMAKE_CXX_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_COMPILER +CMAKE_C_COMPILER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS +CMAKE_C_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_DEBUG +CMAKE_C_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_MINSIZEREL +CMAKE_C_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_RELEASE +CMAKE_C_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_RELWITHDEBINFO +CMAKE_C_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_DLLTOOL +CMAKE_DLLTOOL-ADVANCED:INTERNAL=1 +//Path to cache edit program executable. +CMAKE_EDIT_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/ccmake +//Executable file format +CMAKE_EXECUTABLE_FORMAT:INTERNAL=MACHO +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS +CMAKE_EXE_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_DEBUG +CMAKE_EXE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_MINSIZEREL +CMAKE_EXE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELEASE +CMAKE_EXE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXPORT_COMPILE_COMMANDS +CMAKE_EXPORT_COMPILE_COMMANDS-ADVANCED:INTERNAL=1 +//Name of external makefile project generator. +CMAKE_EXTRA_GENERATOR:INTERNAL= +//Name of generator. +CMAKE_GENERATOR:INTERNAL=Unix Makefiles +//Generator instance identifier. +CMAKE_GENERATOR_INSTANCE:INTERNAL= +//Name of generator platform. +CMAKE_GENERATOR_PLATFORM:INTERNAL= +//Name of generator toolset. +CMAKE_GENERATOR_TOOLSET:INTERNAL= +//Source directory with the top level CMakeLists.txt file for this +// project +CMAKE_HOME_DIRECTORY:INTERNAL=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native +//ADVANCED property for variable: CMAKE_INSTALL_NAME_TOOL +CMAKE_INSTALL_NAME_TOOL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_LINKER +CMAKE_LINKER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MAKE_PROGRAM +CMAKE_MAKE_PROGRAM-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS +CMAKE_MODULE_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_DEBUG +CMAKE_MODULE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL +CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELEASE +CMAKE_MODULE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_NM +CMAKE_NM-ADVANCED:INTERNAL=1 +//number of local generators +CMAKE_NUMBER_OF_MAKEFILES:INTERNAL=1 +//ADVANCED property for variable: CMAKE_OBJCOPY +CMAKE_OBJCOPY-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_OBJDUMP +CMAKE_OBJDUMP-ADVANCED:INTERNAL=1 +//Platform information initialized +CMAKE_PLATFORM_INFO_INITIALIZED:INTERNAL=1 +CMAKE_PREFIX_PATH:INTERNAL=/usr/lib/cmake +//ADVANCED property for variable: CMAKE_RANLIB +CMAKE_RANLIB-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_READELF +CMAKE_READELF-ADVANCED:INTERNAL=1 +//Path to CMake installation. +CMAKE_ROOT:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/share/cmake +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS +CMAKE_SHARED_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_DEBUG +CMAKE_SHARED_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL +CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELEASE +CMAKE_SHARED_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SKIP_INSTALL_RPATH +CMAKE_SKIP_INSTALL_RPATH-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SKIP_RPATH +CMAKE_SKIP_RPATH-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS +CMAKE_STATIC_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_DEBUG +CMAKE_STATIC_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL +CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELEASE +CMAKE_STATIC_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STRIP +CMAKE_STRIP-ADVANCED:INTERNAL=1 +//uname command +CMAKE_UNAME:INTERNAL=/usr/bin/uname +//ADVANCED property for variable: CMAKE_VERBOSE_MAKEFILE +CMAKE_VERBOSE_MAKEFILE-ADVANCED:INTERNAL=1 + diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake new file mode 100644 index 00000000..dc7a67f2 --- /dev/null +++ b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake @@ -0,0 +1,72 @@ +set(CMAKE_C_COMPILER "/Library/Developer/CommandLineTools/usr/bin/cc") +set(CMAKE_C_COMPILER_ARG1 "") +set(CMAKE_C_COMPILER_ID "AppleClang") +set(CMAKE_C_COMPILER_VERSION "13.1.6.13160021") +set(CMAKE_C_COMPILER_VERSION_INTERNAL "") +set(CMAKE_C_COMPILER_WRAPPER "") +set(CMAKE_C_STANDARD_COMPUTED_DEFAULT "17") +set(CMAKE_C_EXTENSIONS_COMPUTED_DEFAULT "ON") +set(CMAKE_C_COMPILE_FEATURES "c_std_90;c_function_prototypes;c_std_99;c_restrict;c_variadic_macros;c_std_11;c_static_assert;c_std_17;c_std_23") +set(CMAKE_C90_COMPILE_FEATURES "c_std_90;c_function_prototypes") +set(CMAKE_C99_COMPILE_FEATURES "c_std_99;c_restrict;c_variadic_macros") +set(CMAKE_C11_COMPILE_FEATURES "c_std_11;c_static_assert") +set(CMAKE_C17_COMPILE_FEATURES "c_std_17") +set(CMAKE_C23_COMPILE_FEATURES "c_std_23") + +set(CMAKE_C_PLATFORM_ID "Darwin") +set(CMAKE_C_SIMULATE_ID "") +set(CMAKE_C_COMPILER_FRONTEND_VARIANT "") +set(CMAKE_C_SIMULATE_VERSION "") + + + + +set(CMAKE_AR "/Library/Developer/CommandLineTools/usr/bin/ar") +set(CMAKE_C_COMPILER_AR "") +set(CMAKE_RANLIB "/Library/Developer/CommandLineTools/usr/bin/ranlib") +set(CMAKE_C_COMPILER_RANLIB "") +set(CMAKE_LINKER "/Library/Developer/CommandLineTools/usr/bin/ld") +set(CMAKE_MT "") +set(CMAKE_COMPILER_IS_GNUCC ) +set(CMAKE_C_COMPILER_LOADED 1) +set(CMAKE_C_COMPILER_WORKS TRUE) +set(CMAKE_C_ABI_COMPILED TRUE) + +set(CMAKE_C_COMPILER_ENV_VAR "CC") + +set(CMAKE_C_COMPILER_ID_RUN 1) +set(CMAKE_C_SOURCE_FILE_EXTENSIONS c;m) +set(CMAKE_C_IGNORE_EXTENSIONS h;H;o;O;obj;OBJ;def;DEF;rc;RC) +set(CMAKE_C_LINKER_PREFERENCE 10) + +# Save compiler ABI information. +set(CMAKE_C_SIZEOF_DATA_PTR "8") +set(CMAKE_C_COMPILER_ABI "") +set(CMAKE_C_BYTE_ORDER "LITTLE_ENDIAN") +set(CMAKE_C_LIBRARY_ARCHITECTURE "") + +if(CMAKE_C_SIZEOF_DATA_PTR) + set(CMAKE_SIZEOF_VOID_P "${CMAKE_C_SIZEOF_DATA_PTR}") +endif() + +if(CMAKE_C_COMPILER_ABI) + set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_C_COMPILER_ABI}") +endif() + +if(CMAKE_C_LIBRARY_ARCHITECTURE) + set(CMAKE_LIBRARY_ARCHITECTURE "") +endif() + +set(CMAKE_C_CL_SHOWINCLUDES_PREFIX "") +if(CMAKE_C_CL_SHOWINCLUDES_PREFIX) + set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_C_CL_SHOWINCLUDES_PREFIX}") +endif() + + + + + +set(CMAKE_C_IMPLICIT_INCLUDE_DIRECTORIES "/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include") +set(CMAKE_C_IMPLICIT_LINK_LIBRARIES "") +set(CMAKE_C_IMPLICIT_LINK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib") +set(CMAKE_C_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks") diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake new file mode 100644 index 00000000..67dc227a --- /dev/null +++ b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake @@ -0,0 +1,83 @@ +set(CMAKE_CXX_COMPILER "/Library/Developer/CommandLineTools/usr/bin/c++") +set(CMAKE_CXX_COMPILER_ARG1 "") +set(CMAKE_CXX_COMPILER_ID "AppleClang") +set(CMAKE_CXX_COMPILER_VERSION "13.1.6.13160021") +set(CMAKE_CXX_COMPILER_VERSION_INTERNAL "") +set(CMAKE_CXX_COMPILER_WRAPPER "") +set(CMAKE_CXX_STANDARD_COMPUTED_DEFAULT "98") +set(CMAKE_CXX_EXTENSIONS_COMPUTED_DEFAULT "ON") +set(CMAKE_CXX_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters;cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates;cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates;cxx_std_17;cxx_std_20;cxx_std_23") +set(CMAKE_CXX98_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters") +set(CMAKE_CXX11_COMPILE_FEATURES "cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates") +set(CMAKE_CXX14_COMPILE_FEATURES "cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates") +set(CMAKE_CXX17_COMPILE_FEATURES "cxx_std_17") +set(CMAKE_CXX20_COMPILE_FEATURES "cxx_std_20") +set(CMAKE_CXX23_COMPILE_FEATURES "cxx_std_23") + +set(CMAKE_CXX_PLATFORM_ID "Darwin") +set(CMAKE_CXX_SIMULATE_ID "") +set(CMAKE_CXX_COMPILER_FRONTEND_VARIANT "") +set(CMAKE_CXX_SIMULATE_VERSION "") + + + + +set(CMAKE_AR "/Library/Developer/CommandLineTools/usr/bin/ar") +set(CMAKE_CXX_COMPILER_AR "") +set(CMAKE_RANLIB "/Library/Developer/CommandLineTools/usr/bin/ranlib") +set(CMAKE_CXX_COMPILER_RANLIB "") +set(CMAKE_LINKER "/Library/Developer/CommandLineTools/usr/bin/ld") +set(CMAKE_MT "") +set(CMAKE_COMPILER_IS_GNUCXX ) +set(CMAKE_CXX_COMPILER_LOADED 1) +set(CMAKE_CXX_COMPILER_WORKS TRUE) +set(CMAKE_CXX_ABI_COMPILED TRUE) + +set(CMAKE_CXX_COMPILER_ENV_VAR "CXX") + +set(CMAKE_CXX_COMPILER_ID_RUN 1) +set(CMAKE_CXX_SOURCE_FILE_EXTENSIONS C;M;c++;cc;cpp;cxx;m;mm;mpp;CPP;ixx;cppm) +set(CMAKE_CXX_IGNORE_EXTENSIONS inl;h;hpp;HPP;H;o;O;obj;OBJ;def;DEF;rc;RC) + +foreach (lang C OBJC OBJCXX) + if (CMAKE_${lang}_COMPILER_ID_RUN) + foreach(extension IN LISTS CMAKE_${lang}_SOURCE_FILE_EXTENSIONS) + list(REMOVE_ITEM CMAKE_CXX_SOURCE_FILE_EXTENSIONS ${extension}) + endforeach() + endif() +endforeach() + +set(CMAKE_CXX_LINKER_PREFERENCE 30) +set(CMAKE_CXX_LINKER_PREFERENCE_PROPAGATES 1) + +# Save compiler ABI information. +set(CMAKE_CXX_SIZEOF_DATA_PTR "8") +set(CMAKE_CXX_COMPILER_ABI "") +set(CMAKE_CXX_BYTE_ORDER "LITTLE_ENDIAN") +set(CMAKE_CXX_LIBRARY_ARCHITECTURE "") + +if(CMAKE_CXX_SIZEOF_DATA_PTR) + set(CMAKE_SIZEOF_VOID_P "${CMAKE_CXX_SIZEOF_DATA_PTR}") +endif() + +if(CMAKE_CXX_COMPILER_ABI) + set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_CXX_COMPILER_ABI}") +endif() + +if(CMAKE_CXX_LIBRARY_ARCHITECTURE) + set(CMAKE_LIBRARY_ARCHITECTURE "") +endif() + +set(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX "") +if(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX) + set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_CXX_CL_SHOWINCLUDES_PREFIX}") +endif() + + + + + +set(CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1;/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include") +set(CMAKE_CXX_IMPLICIT_LINK_LIBRARIES "c++") +set(CMAKE_CXX_IMPLICIT_LINK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib") +set(CMAKE_CXX_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks") diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin new file mode 100755 index 0000000000000000000000000000000000000000..9b3e67d1d3825990645b4978d3a1e9da0ed43128 GIT binary patch literal 16999 zcmeI3Uuau(6vt1J4mw-bDPw=A+wvq%M%!73vA8vv&DOh>G+QHv1^Joe-nN%DNljAM zl(`jkY7xOI!Vn*PvJ@tW2r~~t@nOEH-NO_gw8E4Y8SKRe>sb7r-@Ug@j7;$P960yf zbI$K~a?a=G^?bX2`(8Vdk05^Nc4#O-beV#9BiaKUgenz}oQR%{o*Cw7qv*?xp(c;( zgm6%)L^PRbOzZpM#u&N&7KB;Rk`|@P)^yo*VE$R}&QWI=?+E)m*M_vv?8ZA@l*$(J zCGT`|J+t4b=e6wl^)>3>m72<*xAUg5^P>e_zj59#+QD&^VNZ&#>~h z;4}Y6w&79`ivJvSPnC+@6LzNCtW22jSvsNI$NH7x4Rex!tKWiOSUF)2!VyE|=*7+mzTkW;b zYDc)*>f743TAy1(u3}IBYc74XDYt?e_^tV+fVyeKjt}>h>=~;ts?5o9G1U`#o+xGv zAJ6oaE6OSsEHhO!j;Rx|s4)CVfjdF!HA3a*weJh$P*jJqFy()F*nK40$e zIUC+Q`%d-|^!D+w?~S}OJLiMg>~HQ(Z{;_1rF6GWd=t0I*kj7dn|3-+O}PoXT%NGJ zG=8gI)_-bW0>NE~aT_c<5JRWF0Qp;Z>6}N&LX(_?VE;T45Bl{=yc4VM6Pqn++5DY9SA;OK&E`)@a62ozG~Gg3vqrwOy?1(}Yo+U07k`F$ z7?Bt+1c@g+5Q2z4kcE(VVk9IUWCXE^ga;BL=A8RyyHz3a>YU`pZ)-|0EOudnCf zw+}yx7_%`DJ7_Uz)WO(6Ccuud$)NS1oHx4HdYU~O8t^n*w9DB?ITq$|K_KUTPr#q; z*6xehXUwoi!7(b7qzUIKr6Xk+u>6|u<4V05GX!nyYgqDF*YF-ToJSJzHZwXmpS()X zXO?W*)*RM7=k4*GYFy@Oyd|OK&+hl8kq?=opq*8pemwjg;qR4v>pgXnS%_#n8myWa zYm<=-nOfgv5o2BBFc9Kgu+$i~3+yVe@!BNN?O-GCURXO|Ed*@@MZq^f#aN8_7a0qe z1W@?TvC8(gWMxbZSIX&_3^qy`DAwVeb!t!?td8y9F?eTu;g@JNoC%I$f4{hdd)E zeq*{VrL>Y5g-CY zfCvx)B0vO)01+SpM1Tko0U|&IhyW2F0z`la5CI}U1c(3;AOb{y2oM1xKm>>Y5g-CY zfCvx)B0vO)01+SpM1Tko0U|&IhyW2F0z}}yA~1A-^$pEnnf@}Cd0EK54mnw7psXtc zGrC9fdsg%mr~|HdPBD{jD=2(t^$mb8t#xUfhTRpuF{#5dIGs{>A}K4$pjYzyy&mrI z)k$t2_;F--s_}Bx6=#}p<{9R_HC14~90hHhmBy**aoTM#1bqZrfGy5MqoP>Hk@fj% z{XFYy<1hnm=dDq$bSRN_C^V{spi(xoHKfMbY%IjVKJGRynH#KiEcnbhdYD7k>`u#^ zJ^D`=Hl}gfa8g>YYl3F$Jz|{#Oz`K{z_l7UZ}u)+f`j>_B0ZR-(lxt1=jV$0r_me)L)enUEBe|6e9e#*%eORpTb7ZmQE>poLc zH~P}0y%($?}6|C|5qI)^f8eSKp>24 & 0x00FF) +# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) +# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) + +#elif defined(__BORLANDC__) +# define COMPILER_ID "Borland" + /* __BORLANDC__ = 0xVRR */ +# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) +# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) + +#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 +# define COMPILER_ID "Watcom" + /* __WATCOMC__ = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__WATCOMC__) +# define COMPILER_ID "OpenWatcom" + /* __WATCOMC__ = VVRP + 1100 */ +# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__SUNPRO_C) +# define COMPILER_ID "SunPro" +# if __SUNPRO_C >= 0x5100 + /* __SUNPRO_C = 0xVRRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>12) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xFF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) +# else + /* __SUNPRO_CC = 0xVRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>8) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) +# endif + +#elif defined(__HP_cc) +# define COMPILER_ID "HP" + /* __HP_cc = VVRRPP */ +# define COMPILER_VERSION_MAJOR DEC(__HP_cc/10000) +# define COMPILER_VERSION_MINOR DEC(__HP_cc/100 % 100) +# define COMPILER_VERSION_PATCH DEC(__HP_cc % 100) + +#elif defined(__DECC) +# define COMPILER_ID "Compaq" + /* __DECC_VER = VVRRTPPPP */ +# define COMPILER_VERSION_MAJOR DEC(__DECC_VER/10000000) +# define COMPILER_VERSION_MINOR DEC(__DECC_VER/100000 % 100) +# define COMPILER_VERSION_PATCH DEC(__DECC_VER % 10000) + +#elif defined(__IBMC__) && defined(__COMPILER_VER__) +# define COMPILER_ID "zOS" + /* __IBMC__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) + +#elif defined(__open_xl__) && defined(__clang__) +# define COMPILER_ID "IBMClang" +# define COMPILER_VERSION_MAJOR DEC(__open_xl_version__) +# define COMPILER_VERSION_MINOR DEC(__open_xl_release__) +# define COMPILER_VERSION_PATCH DEC(__open_xl_modification__) +# define COMPILER_VERSION_TWEAK DEC(__open_xl_ptf_fix_level__) + + +#elif defined(__ibmxl__) && defined(__clang__) +# define COMPILER_ID "XLClang" +# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) +# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) +# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) +# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) + + +#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ >= 800 +# define COMPILER_ID "XL" + /* __IBMC__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) + +#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ < 800 +# define COMPILER_ID "VisualAge" + /* __IBMC__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) + +#elif defined(__NVCOMPILER) +# define COMPILER_ID "NVHPC" +# define COMPILER_VERSION_MAJOR DEC(__NVCOMPILER_MAJOR__) +# define COMPILER_VERSION_MINOR DEC(__NVCOMPILER_MINOR__) +# if defined(__NVCOMPILER_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__NVCOMPILER_PATCHLEVEL__) +# endif + +#elif defined(__PGI) +# define COMPILER_ID "PGI" +# define COMPILER_VERSION_MAJOR DEC(__PGIC__) +# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) +# if defined(__PGIC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) +# endif + +#elif defined(_CRAYC) +# define COMPILER_ID "Cray" +# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) +# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) + +#elif defined(__TI_COMPILER_VERSION__) +# define COMPILER_ID "TI" + /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ +# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) +# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) +# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) + +#elif defined(__CLANG_FUJITSU) +# define COMPILER_ID "FujitsuClang" +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# define COMPILER_VERSION_INTERNAL_STR __clang_version__ + + +#elif defined(__FUJITSU) +# define COMPILER_ID "Fujitsu" +# if defined(__FCC_version__) +# define COMPILER_VERSION __FCC_version__ +# elif defined(__FCC_major__) +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# endif +# if defined(__fcc_version) +# define COMPILER_VERSION_INTERNAL DEC(__fcc_version) +# elif defined(__FCC_VERSION) +# define COMPILER_VERSION_INTERNAL DEC(__FCC_VERSION) +# endif + + +#elif defined(__ghs__) +# define COMPILER_ID "GHS" +/* __GHS_VERSION_NUMBER = VVVVRP */ +# ifdef __GHS_VERSION_NUMBER +# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) +# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) +# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) +# endif + +#elif defined(__TASKING__) +# define COMPILER_ID "Tasking" + # define COMPILER_VERSION_MAJOR DEC(__VERSION__/1000) + # define COMPILER_VERSION_MINOR DEC(__VERSION__ % 100) +# define COMPILER_VERSION_INTERNAL DEC(__VERSION__) + +#elif defined(__TINYC__) +# define COMPILER_ID "TinyCC" + +#elif defined(__BCC__) +# define COMPILER_ID "Bruce" + +#elif defined(__SCO_VERSION__) +# define COMPILER_ID "SCO" + +#elif defined(__ARMCC_VERSION) && !defined(__clang__) +# define COMPILER_ID "ARMCC" +#if __ARMCC_VERSION >= 1000000 + /* __ARMCC_VERSION = VRRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#else + /* __ARMCC_VERSION = VRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#endif + + +#elif defined(__clang__) && defined(__apple_build_version__) +# define COMPILER_ID "AppleClang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif +# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) + +#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) +# define COMPILER_ID "ARMClang" + # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) +# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) + +#elif defined(__clang__) +# define COMPILER_ID "Clang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif + +#elif defined(__LCC__) && (defined(__GNUC__) || defined(__GNUG__) || defined(__MCST__)) +# define COMPILER_ID "LCC" +# define COMPILER_VERSION_MAJOR DEC(1) +# if defined(__LCC__) +# define COMPILER_VERSION_MINOR DEC(__LCC__- 100) +# endif +# if defined(__LCC_MINOR__) +# define COMPILER_VERSION_PATCH DEC(__LCC_MINOR__) +# endif +# if defined(__GNUC__) && defined(__GNUC_MINOR__) +# define SIMULATE_ID "GNU" +# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) +# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) +# if defined(__GNUC_PATCHLEVEL__) +# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif +# endif + +#elif defined(__GNUC__) +# define COMPILER_ID "GNU" +# define COMPILER_VERSION_MAJOR DEC(__GNUC__) +# if defined(__GNUC_MINOR__) +# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) +# endif +# if defined(__GNUC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif + +#elif defined(_MSC_VER) +# define COMPILER_ID "MSVC" + /* _MSC_VER = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) +# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) +# if defined(_MSC_FULL_VER) +# if _MSC_VER >= 1400 + /* _MSC_FULL_VER = VVRRPPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) +# else + /* _MSC_FULL_VER = VVRRPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) +# endif +# endif +# if defined(_MSC_BUILD) +# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) +# endif + +#elif defined(_ADI_COMPILER) +# define COMPILER_ID "ADSP" +#if defined(__VERSIONNUM__) + /* __VERSIONNUM__ = 0xVVRRPPTT */ +# define COMPILER_VERSION_MAJOR DEC(__VERSIONNUM__ >> 24 & 0xFF) +# define COMPILER_VERSION_MINOR DEC(__VERSIONNUM__ >> 16 & 0xFF) +# define COMPILER_VERSION_PATCH DEC(__VERSIONNUM__ >> 8 & 0xFF) +# define COMPILER_VERSION_TWEAK DEC(__VERSIONNUM__ & 0xFF) +#endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# define COMPILER_ID "IAR" +# if defined(__VER__) && defined(__ICCARM__) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) +# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) +# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__) || defined(__ICCSTM8__)) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) +# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) +# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# endif + +#elif defined(__SDCC_VERSION_MAJOR) || defined(SDCC) +# define COMPILER_ID "SDCC" +# if defined(__SDCC_VERSION_MAJOR) +# define COMPILER_VERSION_MAJOR DEC(__SDCC_VERSION_MAJOR) +# define COMPILER_VERSION_MINOR DEC(__SDCC_VERSION_MINOR) +# define COMPILER_VERSION_PATCH DEC(__SDCC_VERSION_PATCH) +# else + /* SDCC = VRP */ +# define COMPILER_VERSION_MAJOR DEC(SDCC/100) +# define COMPILER_VERSION_MINOR DEC(SDCC/10 % 10) +# define COMPILER_VERSION_PATCH DEC(SDCC % 10) +# endif + + +/* These compilers are either not known or too old to define an + identification macro. Try to identify the platform and guess that + it is the native compiler. */ +#elif defined(__hpux) || defined(__hpua) +# define COMPILER_ID "HP" + +#else /* unknown compiler */ +# define COMPILER_ID "" +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; +#ifdef SIMULATE_ID +char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; +#endif + +#ifdef __QNXNTO__ +char const* qnxnto = "INFO" ":" "qnxnto[]"; +#endif + +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) +char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; +#endif + +#define STRINGIFY_HELPER(X) #X +#define STRINGIFY(X) STRINGIFY_HELPER(X) + +/* Identify known platforms by name. */ +#if defined(__linux) || defined(__linux__) || defined(linux) +# define PLATFORM_ID "Linux" + +#elif defined(__MSYS__) +# define PLATFORM_ID "MSYS" + +#elif defined(__CYGWIN__) +# define PLATFORM_ID "Cygwin" + +#elif defined(__MINGW32__) +# define PLATFORM_ID "MinGW" + +#elif defined(__APPLE__) +# define PLATFORM_ID "Darwin" + +#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) +# define PLATFORM_ID "Windows" + +#elif defined(__FreeBSD__) || defined(__FreeBSD) +# define PLATFORM_ID "FreeBSD" + +#elif defined(__NetBSD__) || defined(__NetBSD) +# define PLATFORM_ID "NetBSD" + +#elif defined(__OpenBSD__) || defined(__OPENBSD) +# define PLATFORM_ID "OpenBSD" + +#elif defined(__sun) || defined(sun) +# define PLATFORM_ID "SunOS" + +#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) +# define PLATFORM_ID "AIX" + +#elif defined(__hpux) || defined(__hpux__) +# define PLATFORM_ID "HP-UX" + +#elif defined(__HAIKU__) +# define PLATFORM_ID "Haiku" + +#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) +# define PLATFORM_ID "BeOS" + +#elif defined(__QNX__) || defined(__QNXNTO__) +# define PLATFORM_ID "QNX" + +#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) +# define PLATFORM_ID "Tru64" + +#elif defined(__riscos) || defined(__riscos__) +# define PLATFORM_ID "RISCos" + +#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) +# define PLATFORM_ID "SINIX" + +#elif defined(__UNIX_SV__) +# define PLATFORM_ID "UNIX_SV" + +#elif defined(__bsdos__) +# define PLATFORM_ID "BSDOS" + +#elif defined(_MPRAS) || defined(MPRAS) +# define PLATFORM_ID "MP-RAS" + +#elif defined(__osf) || defined(__osf__) +# define PLATFORM_ID "OSF1" + +#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) +# define PLATFORM_ID "SCO_SV" + +#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) +# define PLATFORM_ID "ULTRIX" + +#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) +# define PLATFORM_ID "Xenix" + +#elif defined(__WATCOMC__) +# if defined(__LINUX__) +# define PLATFORM_ID "Linux" + +# elif defined(__DOS__) +# define PLATFORM_ID "DOS" + +# elif defined(__OS2__) +# define PLATFORM_ID "OS2" + +# elif defined(__WINDOWS__) +# define PLATFORM_ID "Windows3x" + +# elif defined(__VXWORKS__) +# define PLATFORM_ID "VxWorks" + +# else /* unknown platform */ +# define PLATFORM_ID +# endif + +#elif defined(__INTEGRITY) +# if defined(INT_178B) +# define PLATFORM_ID "Integrity178" + +# else /* regular Integrity */ +# define PLATFORM_ID "Integrity" +# endif + +# elif defined(_ADI_COMPILER) +# define PLATFORM_ID "ADSP" + +#else /* unknown platform */ +# define PLATFORM_ID + +#endif + +/* For windows compilers MSVC and Intel we can determine + the architecture of the compiler being used. This is because + the compilers do not have flags that can change the architecture, + but rather depend on which compiler is being used +*/ +#if defined(_WIN32) && defined(_MSC_VER) +# if defined(_M_IA64) +# define ARCHITECTURE_ID "IA64" + +# elif defined(_M_ARM64EC) +# define ARCHITECTURE_ID "ARM64EC" + +# elif defined(_M_X64) || defined(_M_AMD64) +# define ARCHITECTURE_ID "x64" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# elif defined(_M_ARM64) +# define ARCHITECTURE_ID "ARM64" + +# elif defined(_M_ARM) +# if _M_ARM == 4 +# define ARCHITECTURE_ID "ARMV4I" +# elif _M_ARM == 5 +# define ARCHITECTURE_ID "ARMV5I" +# else +# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) +# endif + +# elif defined(_M_MIPS) +# define ARCHITECTURE_ID "MIPS" + +# elif defined(_M_SH) +# define ARCHITECTURE_ID "SHx" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__WATCOMC__) +# if defined(_M_I86) +# define ARCHITECTURE_ID "I86" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# if defined(__ICCARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__ICCRX__) +# define ARCHITECTURE_ID "RX" + +# elif defined(__ICCRH850__) +# define ARCHITECTURE_ID "RH850" + +# elif defined(__ICCRL78__) +# define ARCHITECTURE_ID "RL78" + +# elif defined(__ICCRISCV__) +# define ARCHITECTURE_ID "RISCV" + +# elif defined(__ICCAVR__) +# define ARCHITECTURE_ID "AVR" + +# elif defined(__ICC430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__ICCV850__) +# define ARCHITECTURE_ID "V850" + +# elif defined(__ICC8051__) +# define ARCHITECTURE_ID "8051" + +# elif defined(__ICCSTM8__) +# define ARCHITECTURE_ID "STM8" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__ghs__) +# if defined(__PPC64__) +# define ARCHITECTURE_ID "PPC64" + +# elif defined(__ppc__) +# define ARCHITECTURE_ID "PPC" + +# elif defined(__ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__x86_64__) +# define ARCHITECTURE_ID "x64" + +# elif defined(__i386__) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__TI_COMPILER_VERSION__) +# if defined(__TI_ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__MSP430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__TMS320C28XX__) +# define ARCHITECTURE_ID "TMS320C28x" + +# elif defined(__TMS320C6X__) || defined(_TMS320C6X) +# define ARCHITECTURE_ID "TMS320C6x" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +# elif defined(__ADSPSHARC__) +# define ARCHITECTURE_ID "SHARC" + +# elif defined(__ADSPBLACKFIN__) +# define ARCHITECTURE_ID "Blackfin" + +#elif defined(__TASKING__) + +# if defined(__CTC__) || defined(__CPTC__) +# define ARCHITECTURE_ID "TriCore" + +# elif defined(__CMCS__) +# define ARCHITECTURE_ID "MCS" + +# elif defined(__CARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__CARC__) +# define ARCHITECTURE_ID "ARC" + +# elif defined(__C51__) +# define ARCHITECTURE_ID "8051" + +# elif defined(__CPCP__) +# define ARCHITECTURE_ID "PCP" + +# else +# define ARCHITECTURE_ID "" +# endif + +#else +# define ARCHITECTURE_ID +#endif + +/* Convert integer to decimal digit literals. */ +#define DEC(n) \ + ('0' + (((n) / 10000000)%10)), \ + ('0' + (((n) / 1000000)%10)), \ + ('0' + (((n) / 100000)%10)), \ + ('0' + (((n) / 10000)%10)), \ + ('0' + (((n) / 1000)%10)), \ + ('0' + (((n) / 100)%10)), \ + ('0' + (((n) / 10)%10)), \ + ('0' + ((n) % 10)) + +/* Convert integer to hex digit literals. */ +#define HEX(n) \ + ('0' + ((n)>>28 & 0xF)), \ + ('0' + ((n)>>24 & 0xF)), \ + ('0' + ((n)>>20 & 0xF)), \ + ('0' + ((n)>>16 & 0xF)), \ + ('0' + ((n)>>12 & 0xF)), \ + ('0' + ((n)>>8 & 0xF)), \ + ('0' + ((n)>>4 & 0xF)), \ + ('0' + ((n) & 0xF)) + +/* Construct a string literal encoding the version number. */ +#ifdef COMPILER_VERSION +char const* info_version = "INFO" ":" "compiler_version[" COMPILER_VERSION "]"; + +/* Construct a string literal encoding the version number components. */ +#elif defined(COMPILER_VERSION_MAJOR) +char const info_version[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', + COMPILER_VERSION_MAJOR, +# ifdef COMPILER_VERSION_MINOR + '.', COMPILER_VERSION_MINOR, +# ifdef COMPILER_VERSION_PATCH + '.', COMPILER_VERSION_PATCH, +# ifdef COMPILER_VERSION_TWEAK + '.', COMPILER_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct a string literal encoding the internal version number. */ +#ifdef COMPILER_VERSION_INTERNAL +char const info_version_internal[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', + 'i','n','t','e','r','n','a','l','[', + COMPILER_VERSION_INTERNAL,']','\0'}; +#elif defined(COMPILER_VERSION_INTERNAL_STR) +char const* info_version_internal = "INFO" ":" "compiler_version_internal[" COMPILER_VERSION_INTERNAL_STR "]"; +#endif + +/* Construct a string literal encoding the version number components. */ +#ifdef SIMULATE_VERSION_MAJOR +char const info_simulate_version[] = { + 'I', 'N', 'F', 'O', ':', + 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', + SIMULATE_VERSION_MAJOR, +# ifdef SIMULATE_VERSION_MINOR + '.', SIMULATE_VERSION_MINOR, +# ifdef SIMULATE_VERSION_PATCH + '.', SIMULATE_VERSION_PATCH, +# ifdef SIMULATE_VERSION_TWEAK + '.', SIMULATE_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; +char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; + + + +#if !defined(__STDC__) && !defined(__clang__) +# if defined(_MSC_VER) || defined(__ibmxl__) || defined(__IBMC__) +# define C_VERSION "90" +# else +# define C_VERSION +# endif +#elif __STDC_VERSION__ > 201710L +# define C_VERSION "23" +#elif __STDC_VERSION__ >= 201710L +# define C_VERSION "17" +#elif __STDC_VERSION__ >= 201000L +# define C_VERSION "11" +#elif __STDC_VERSION__ >= 199901L +# define C_VERSION "99" +#else +# define C_VERSION "90" +#endif +const char* info_language_standard_default = + "INFO" ":" "standard_default[" C_VERSION "]"; + +const char* info_language_extensions_default = "INFO" ":" "extensions_default[" +#if (defined(__clang__) || defined(__GNUC__) || defined(__xlC__) || \ + defined(__TI_COMPILER_VERSION__)) && \ + !defined(__STRICT_ANSI__) + "ON" +#else + "OFF" +#endif +"]"; + +/*--------------------------------------------------------------------------*/ + +#ifdef ID_VOID_MAIN +void main() {} +#else +# if defined(__CLASSIC_C__) +int main(argc, argv) int argc; char *argv[]; +# else +int main(int argc, char* argv[]) +# endif +{ + int require = 0; + require += info_compiler[argc]; + require += info_platform[argc]; + require += info_arch[argc]; +#ifdef COMPILER_VERSION_MAJOR + require += info_version[argc]; +#endif +#ifdef COMPILER_VERSION_INTERNAL + require += info_version_internal[argc]; +#endif +#ifdef SIMULATE_ID + require += info_simulate[argc]; +#endif +#ifdef SIMULATE_VERSION_MAJOR + require += info_simulate_version[argc]; +#endif +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) + require += info_cray[argc]; +#endif + require += info_language_standard_default[argc]; + require += info_language_extensions_default[argc]; + (void)argv; + return require; +} +#endif diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o new file mode 100644 index 0000000000000000000000000000000000000000..537fbf261a76f93972038901b25169a2bbc47274 GIT binary patch literal 1712 zcmb_cJ!n%=6uz;wrbZJ52c@6^7pIWdlqyOfp;1&q+aW_FlnbM8Iw+;_kGKK=Uf`-Bi7 z0i(w>M)3$9aSYfwjIS!I=z&L%dbCZ%s}_<rdz)YvA0HYv+3-?QBs2c#UYr|Wo}&rIo+0dl*8pp+HUHwP5`=CXzCkY{+GmpJqe z^{C`F`qO(H&ZhmA8*Xd3;mQ8ix!yHi)SKvUv=;ePuiiAvzHGbqZMPz2J~uk&HP?%C zFpj>cWEaS(u`SOdcNQbasV}Tn(j%)}% za%=g<%2hfV+p)Y-w%K&7CC7AYYeHq3j_Fq$UcHnvJscZHO|QIOV!!2^ZpHK}vSL-u zw&RzK%bdY|vD}so84YqP%WHr6vB&z8_biVJmXgYhR3dPahISScM#@-BCg+Wb7peOc zS66bZgO^}XPkuYV^b_Do@J9iro4^>j6JVM&1pVam0j3v#QSfAdY0@6FmOm3y4i@8<*X7~Z$a`P`qk_SaKIb%|g!jTF5YI&NLI#U*ukag2`Ii@wwl*BF^ czusKnN(nfiDNW&k&T9$>)X)?TD9J>24 & 0x00FF) +# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) +# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) + +#elif defined(__BORLANDC__) +# define COMPILER_ID "Borland" + /* __BORLANDC__ = 0xVRR */ +# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) +# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) + +#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 +# define COMPILER_ID "Watcom" + /* __WATCOMC__ = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__WATCOMC__) +# define COMPILER_ID "OpenWatcom" + /* __WATCOMC__ = VVRP + 1100 */ +# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__SUNPRO_CC) +# define COMPILER_ID "SunPro" +# if __SUNPRO_CC >= 0x5100 + /* __SUNPRO_CC = 0xVRRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>12) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xFF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) +# else + /* __SUNPRO_CC = 0xVRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>8) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) +# endif + +#elif defined(__HP_aCC) +# define COMPILER_ID "HP" + /* __HP_aCC = VVRRPP */ +# define COMPILER_VERSION_MAJOR DEC(__HP_aCC/10000) +# define COMPILER_VERSION_MINOR DEC(__HP_aCC/100 % 100) +# define COMPILER_VERSION_PATCH DEC(__HP_aCC % 100) + +#elif defined(__DECCXX) +# define COMPILER_ID "Compaq" + /* __DECCXX_VER = VVRRTPPPP */ +# define COMPILER_VERSION_MAJOR DEC(__DECCXX_VER/10000000) +# define COMPILER_VERSION_MINOR DEC(__DECCXX_VER/100000 % 100) +# define COMPILER_VERSION_PATCH DEC(__DECCXX_VER % 10000) + +#elif defined(__IBMCPP__) && defined(__COMPILER_VER__) +# define COMPILER_ID "zOS" + /* __IBMCPP__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) + +#elif defined(__open_xl__) && defined(__clang__) +# define COMPILER_ID "IBMClang" +# define COMPILER_VERSION_MAJOR DEC(__open_xl_version__) +# define COMPILER_VERSION_MINOR DEC(__open_xl_release__) +# define COMPILER_VERSION_PATCH DEC(__open_xl_modification__) +# define COMPILER_VERSION_TWEAK DEC(__open_xl_ptf_fix_level__) + + +#elif defined(__ibmxl__) && defined(__clang__) +# define COMPILER_ID "XLClang" +# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) +# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) +# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) +# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) + + +#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ >= 800 +# define COMPILER_ID "XL" + /* __IBMCPP__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) + +#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ < 800 +# define COMPILER_ID "VisualAge" + /* __IBMCPP__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) + +#elif defined(__NVCOMPILER) +# define COMPILER_ID "NVHPC" +# define COMPILER_VERSION_MAJOR DEC(__NVCOMPILER_MAJOR__) +# define COMPILER_VERSION_MINOR DEC(__NVCOMPILER_MINOR__) +# if defined(__NVCOMPILER_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__NVCOMPILER_PATCHLEVEL__) +# endif + +#elif defined(__PGI) +# define COMPILER_ID "PGI" +# define COMPILER_VERSION_MAJOR DEC(__PGIC__) +# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) +# if defined(__PGIC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) +# endif + +#elif defined(_CRAYC) +# define COMPILER_ID "Cray" +# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) +# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) + +#elif defined(__TI_COMPILER_VERSION__) +# define COMPILER_ID "TI" + /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ +# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) +# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) +# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) + +#elif defined(__CLANG_FUJITSU) +# define COMPILER_ID "FujitsuClang" +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# define COMPILER_VERSION_INTERNAL_STR __clang_version__ + + +#elif defined(__FUJITSU) +# define COMPILER_ID "Fujitsu" +# if defined(__FCC_version__) +# define COMPILER_VERSION __FCC_version__ +# elif defined(__FCC_major__) +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# endif +# if defined(__fcc_version) +# define COMPILER_VERSION_INTERNAL DEC(__fcc_version) +# elif defined(__FCC_VERSION) +# define COMPILER_VERSION_INTERNAL DEC(__FCC_VERSION) +# endif + + +#elif defined(__ghs__) +# define COMPILER_ID "GHS" +/* __GHS_VERSION_NUMBER = VVVVRP */ +# ifdef __GHS_VERSION_NUMBER +# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) +# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) +# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) +# endif + +#elif defined(__TASKING__) +# define COMPILER_ID "Tasking" + # define COMPILER_VERSION_MAJOR DEC(__VERSION__/1000) + # define COMPILER_VERSION_MINOR DEC(__VERSION__ % 100) +# define COMPILER_VERSION_INTERNAL DEC(__VERSION__) + +#elif defined(__SCO_VERSION__) +# define COMPILER_ID "SCO" + +#elif defined(__ARMCC_VERSION) && !defined(__clang__) +# define COMPILER_ID "ARMCC" +#if __ARMCC_VERSION >= 1000000 + /* __ARMCC_VERSION = VRRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#else + /* __ARMCC_VERSION = VRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#endif + + +#elif defined(__clang__) && defined(__apple_build_version__) +# define COMPILER_ID "AppleClang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif +# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) + +#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) +# define COMPILER_ID "ARMClang" + # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) +# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) + +#elif defined(__clang__) +# define COMPILER_ID "Clang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif + +#elif defined(__LCC__) && (defined(__GNUC__) || defined(__GNUG__) || defined(__MCST__)) +# define COMPILER_ID "LCC" +# define COMPILER_VERSION_MAJOR DEC(1) +# if defined(__LCC__) +# define COMPILER_VERSION_MINOR DEC(__LCC__- 100) +# endif +# if defined(__LCC_MINOR__) +# define COMPILER_VERSION_PATCH DEC(__LCC_MINOR__) +# endif +# if defined(__GNUC__) && defined(__GNUC_MINOR__) +# define SIMULATE_ID "GNU" +# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) +# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) +# if defined(__GNUC_PATCHLEVEL__) +# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif +# endif + +#elif defined(__GNUC__) || defined(__GNUG__) +# define COMPILER_ID "GNU" +# if defined(__GNUC__) +# define COMPILER_VERSION_MAJOR DEC(__GNUC__) +# else +# define COMPILER_VERSION_MAJOR DEC(__GNUG__) +# endif +# if defined(__GNUC_MINOR__) +# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) +# endif +# if defined(__GNUC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif + +#elif defined(_MSC_VER) +# define COMPILER_ID "MSVC" + /* _MSC_VER = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) +# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) +# if defined(_MSC_FULL_VER) +# if _MSC_VER >= 1400 + /* _MSC_FULL_VER = VVRRPPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) +# else + /* _MSC_FULL_VER = VVRRPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) +# endif +# endif +# if defined(_MSC_BUILD) +# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) +# endif + +#elif defined(_ADI_COMPILER) +# define COMPILER_ID "ADSP" +#if defined(__VERSIONNUM__) + /* __VERSIONNUM__ = 0xVVRRPPTT */ +# define COMPILER_VERSION_MAJOR DEC(__VERSIONNUM__ >> 24 & 0xFF) +# define COMPILER_VERSION_MINOR DEC(__VERSIONNUM__ >> 16 & 0xFF) +# define COMPILER_VERSION_PATCH DEC(__VERSIONNUM__ >> 8 & 0xFF) +# define COMPILER_VERSION_TWEAK DEC(__VERSIONNUM__ & 0xFF) +#endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# define COMPILER_ID "IAR" +# if defined(__VER__) && defined(__ICCARM__) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) +# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) +# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__) || defined(__ICCSTM8__)) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) +# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) +# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# endif + + +/* These compilers are either not known or too old to define an + identification macro. Try to identify the platform and guess that + it is the native compiler. */ +#elif defined(__hpux) || defined(__hpua) +# define COMPILER_ID "HP" + +#else /* unknown compiler */ +# define COMPILER_ID "" +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; +#ifdef SIMULATE_ID +char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; +#endif + +#ifdef __QNXNTO__ +char const* qnxnto = "INFO" ":" "qnxnto[]"; +#endif + +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) +char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; +#endif + +#define STRINGIFY_HELPER(X) #X +#define STRINGIFY(X) STRINGIFY_HELPER(X) + +/* Identify known platforms by name. */ +#if defined(__linux) || defined(__linux__) || defined(linux) +# define PLATFORM_ID "Linux" + +#elif defined(__MSYS__) +# define PLATFORM_ID "MSYS" + +#elif defined(__CYGWIN__) +# define PLATFORM_ID "Cygwin" + +#elif defined(__MINGW32__) +# define PLATFORM_ID "MinGW" + +#elif defined(__APPLE__) +# define PLATFORM_ID "Darwin" + +#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) +# define PLATFORM_ID "Windows" + +#elif defined(__FreeBSD__) || defined(__FreeBSD) +# define PLATFORM_ID "FreeBSD" + +#elif defined(__NetBSD__) || defined(__NetBSD) +# define PLATFORM_ID "NetBSD" + +#elif defined(__OpenBSD__) || defined(__OPENBSD) +# define PLATFORM_ID "OpenBSD" + +#elif defined(__sun) || defined(sun) +# define PLATFORM_ID "SunOS" + +#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) +# define PLATFORM_ID "AIX" + +#elif defined(__hpux) || defined(__hpux__) +# define PLATFORM_ID "HP-UX" + +#elif defined(__HAIKU__) +# define PLATFORM_ID "Haiku" + +#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) +# define PLATFORM_ID "BeOS" + +#elif defined(__QNX__) || defined(__QNXNTO__) +# define PLATFORM_ID "QNX" + +#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) +# define PLATFORM_ID "Tru64" + +#elif defined(__riscos) || defined(__riscos__) +# define PLATFORM_ID "RISCos" + +#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) +# define PLATFORM_ID "SINIX" + +#elif defined(__UNIX_SV__) +# define PLATFORM_ID "UNIX_SV" + +#elif defined(__bsdos__) +# define PLATFORM_ID "BSDOS" + +#elif defined(_MPRAS) || defined(MPRAS) +# define PLATFORM_ID "MP-RAS" + +#elif defined(__osf) || defined(__osf__) +# define PLATFORM_ID "OSF1" + +#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) +# define PLATFORM_ID "SCO_SV" + +#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) +# define PLATFORM_ID "ULTRIX" + +#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) +# define PLATFORM_ID "Xenix" + +#elif defined(__WATCOMC__) +# if defined(__LINUX__) +# define PLATFORM_ID "Linux" + +# elif defined(__DOS__) +# define PLATFORM_ID "DOS" + +# elif defined(__OS2__) +# define PLATFORM_ID "OS2" + +# elif defined(__WINDOWS__) +# define PLATFORM_ID "Windows3x" + +# elif defined(__VXWORKS__) +# define PLATFORM_ID "VxWorks" + +# else /* unknown platform */ +# define PLATFORM_ID +# endif + +#elif defined(__INTEGRITY) +# if defined(INT_178B) +# define PLATFORM_ID "Integrity178" + +# else /* regular Integrity */ +# define PLATFORM_ID "Integrity" +# endif + +# elif defined(_ADI_COMPILER) +# define PLATFORM_ID "ADSP" + +#else /* unknown platform */ +# define PLATFORM_ID + +#endif + +/* For windows compilers MSVC and Intel we can determine + the architecture of the compiler being used. This is because + the compilers do not have flags that can change the architecture, + but rather depend on which compiler is being used +*/ +#if defined(_WIN32) && defined(_MSC_VER) +# if defined(_M_IA64) +# define ARCHITECTURE_ID "IA64" + +# elif defined(_M_ARM64EC) +# define ARCHITECTURE_ID "ARM64EC" + +# elif defined(_M_X64) || defined(_M_AMD64) +# define ARCHITECTURE_ID "x64" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# elif defined(_M_ARM64) +# define ARCHITECTURE_ID "ARM64" + +# elif defined(_M_ARM) +# if _M_ARM == 4 +# define ARCHITECTURE_ID "ARMV4I" +# elif _M_ARM == 5 +# define ARCHITECTURE_ID "ARMV5I" +# else +# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) +# endif + +# elif defined(_M_MIPS) +# define ARCHITECTURE_ID "MIPS" + +# elif defined(_M_SH) +# define ARCHITECTURE_ID "SHx" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__WATCOMC__) +# if defined(_M_I86) +# define ARCHITECTURE_ID "I86" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# if defined(__ICCARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__ICCRX__) +# define ARCHITECTURE_ID "RX" + +# elif defined(__ICCRH850__) +# define ARCHITECTURE_ID "RH850" + +# elif defined(__ICCRL78__) +# define ARCHITECTURE_ID "RL78" + +# elif defined(__ICCRISCV__) +# define ARCHITECTURE_ID "RISCV" + +# elif defined(__ICCAVR__) +# define ARCHITECTURE_ID "AVR" + +# elif defined(__ICC430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__ICCV850__) +# define ARCHITECTURE_ID "V850" + +# elif defined(__ICC8051__) +# define ARCHITECTURE_ID "8051" + +# elif defined(__ICCSTM8__) +# define ARCHITECTURE_ID "STM8" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__ghs__) +# if defined(__PPC64__) +# define ARCHITECTURE_ID "PPC64" + +# elif defined(__ppc__) +# define ARCHITECTURE_ID "PPC" + +# elif defined(__ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__x86_64__) +# define ARCHITECTURE_ID "x64" + +# elif defined(__i386__) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__TI_COMPILER_VERSION__) +# if defined(__TI_ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__MSP430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__TMS320C28XX__) +# define ARCHITECTURE_ID "TMS320C28x" + +# elif defined(__TMS320C6X__) || defined(_TMS320C6X) +# define ARCHITECTURE_ID "TMS320C6x" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +# elif defined(__ADSPSHARC__) +# define ARCHITECTURE_ID "SHARC" + +# elif defined(__ADSPBLACKFIN__) +# define ARCHITECTURE_ID "Blackfin" + +#elif defined(__TASKING__) + +# if defined(__CTC__) || defined(__CPTC__) +# define ARCHITECTURE_ID "TriCore" + +# elif defined(__CMCS__) +# define ARCHITECTURE_ID "MCS" + +# elif defined(__CARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__CARC__) +# define ARCHITECTURE_ID "ARC" + +# elif defined(__C51__) +# define ARCHITECTURE_ID "8051" + +# elif defined(__CPCP__) +# define ARCHITECTURE_ID "PCP" + +# else +# define ARCHITECTURE_ID "" +# endif + +#else +# define ARCHITECTURE_ID +#endif + +/* Convert integer to decimal digit literals. */ +#define DEC(n) \ + ('0' + (((n) / 10000000)%10)), \ + ('0' + (((n) / 1000000)%10)), \ + ('0' + (((n) / 100000)%10)), \ + ('0' + (((n) / 10000)%10)), \ + ('0' + (((n) / 1000)%10)), \ + ('0' + (((n) / 100)%10)), \ + ('0' + (((n) / 10)%10)), \ + ('0' + ((n) % 10)) + +/* Convert integer to hex digit literals. */ +#define HEX(n) \ + ('0' + ((n)>>28 & 0xF)), \ + ('0' + ((n)>>24 & 0xF)), \ + ('0' + ((n)>>20 & 0xF)), \ + ('0' + ((n)>>16 & 0xF)), \ + ('0' + ((n)>>12 & 0xF)), \ + ('0' + ((n)>>8 & 0xF)), \ + ('0' + ((n)>>4 & 0xF)), \ + ('0' + ((n) & 0xF)) + +/* Construct a string literal encoding the version number. */ +#ifdef COMPILER_VERSION +char const* info_version = "INFO" ":" "compiler_version[" COMPILER_VERSION "]"; + +/* Construct a string literal encoding the version number components. */ +#elif defined(COMPILER_VERSION_MAJOR) +char const info_version[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', + COMPILER_VERSION_MAJOR, +# ifdef COMPILER_VERSION_MINOR + '.', COMPILER_VERSION_MINOR, +# ifdef COMPILER_VERSION_PATCH + '.', COMPILER_VERSION_PATCH, +# ifdef COMPILER_VERSION_TWEAK + '.', COMPILER_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct a string literal encoding the internal version number. */ +#ifdef COMPILER_VERSION_INTERNAL +char const info_version_internal[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', + 'i','n','t','e','r','n','a','l','[', + COMPILER_VERSION_INTERNAL,']','\0'}; +#elif defined(COMPILER_VERSION_INTERNAL_STR) +char const* info_version_internal = "INFO" ":" "compiler_version_internal[" COMPILER_VERSION_INTERNAL_STR "]"; +#endif + +/* Construct a string literal encoding the version number components. */ +#ifdef SIMULATE_VERSION_MAJOR +char const info_simulate_version[] = { + 'I', 'N', 'F', 'O', ':', + 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', + SIMULATE_VERSION_MAJOR, +# ifdef SIMULATE_VERSION_MINOR + '.', SIMULATE_VERSION_MINOR, +# ifdef SIMULATE_VERSION_PATCH + '.', SIMULATE_VERSION_PATCH, +# ifdef SIMULATE_VERSION_TWEAK + '.', SIMULATE_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; +char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; + + + +#if defined(__INTEL_COMPILER) && defined(_MSVC_LANG) && _MSVC_LANG < 201403L +# if defined(__INTEL_CXX11_MODE__) +# if defined(__cpp_aggregate_nsdmi) +# define CXX_STD 201402L +# else +# define CXX_STD 201103L +# endif +# else +# define CXX_STD 199711L +# endif +#elif defined(_MSC_VER) && defined(_MSVC_LANG) +# define CXX_STD _MSVC_LANG +#else +# define CXX_STD __cplusplus +#endif + +const char* info_language_standard_default = "INFO" ":" "standard_default[" +#if CXX_STD > 202002L + "23" +#elif CXX_STD > 201703L + "20" +#elif CXX_STD >= 201703L + "17" +#elif CXX_STD >= 201402L + "14" +#elif CXX_STD >= 201103L + "11" +#else + "98" +#endif +"]"; + +const char* info_language_extensions_default = "INFO" ":" "extensions_default[" +#if (defined(__clang__) || defined(__GNUC__) || defined(__xlC__) || \ + defined(__TI_COMPILER_VERSION__)) && \ + !defined(__STRICT_ANSI__) + "ON" +#else + "OFF" +#endif +"]"; + +/*--------------------------------------------------------------------------*/ + +int main(int argc, char* argv[]) +{ + int require = 0; + require += info_compiler[argc]; + require += info_platform[argc]; + require += info_arch[argc]; +#ifdef COMPILER_VERSION_MAJOR + require += info_version[argc]; +#endif +#ifdef COMPILER_VERSION_INTERNAL + require += info_version_internal[argc]; +#endif +#ifdef SIMULATE_ID + require += info_simulate[argc]; +#endif +#ifdef SIMULATE_VERSION_MAJOR + require += info_simulate_version[argc]; +#endif +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) + require += info_cray[argc]; +#endif + require += info_language_standard_default[argc]; + require += info_language_extensions_default[argc]; + (void)argv; + return require; +} diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o new file mode 100644 index 0000000000000000000000000000000000000000..aacee10dfddc5e3114bb159eee743a03c1b12206 GIT binary patch literal 1712 zcmb_cJ#5oZ5PqShqzWV;F@P#TBo?M9PO7SaA|+}-fULGdhCoz3ti(wzIgaHx(6I;x z1_sK?QX~e%#7HI>vr!hr7?|3DoiY%1^Z6O|W@vfbVNlAN;TuDUd5eWoVTAL%&&wQohkn#@ z7xSq-j;d+D)t1v9ZFqXVP40J%U+PcIH{OeU>eqCQsxLdv1IwvNsTapLka_697F8IR1n^Z*cJ-l}YwvWy2!N#ELP!jS<=b%*cH!^r6J`FC4Zht{^ zzsAJjAR)R@A)ZAe`NM;S?e4sFu)LqhccYQ{*#1A{s8`rm?EJ5ueawaVcRtL>&$m`@ ztX-vFW7(!xDY&j}uGogt*bqU+wGF@C@|u;R;o-M&)bOgC753Y{;nWPTCTnKh=-7Vc z$}(qgUQDNLfkwmJ+Umw1e(Z_)ySp2^@ z#c`j+Ps4(Dam47{VX1)UfyFv=G-sR%Pq{mU!DV&cx`aV;sv}u}j^j6kad6amf6w`E zuq1DxRR1GDLcC-=%WFPoe1Y)`!ei?{C5*wsqwOppCjtl9ou4RJe%qk(9hUIXb hB0fW6ys-VIyU6WQZ~(Ik!U4=E2nSG85Dp-5 search starts here: + /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include + /Library/Developer/CommandLineTools/usr/include + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory) +End of search list. +Linking C executable cmTC_5913a +/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_5913a.dir/link.txt --verbose=1 +/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names -v -Wl,-v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -o cmTC_5913a +Apple clang version 13.1.6 (clang-1316.0.21.2.5) +Target: arm64-apple-darwin21.6.0 +Thread model: posix +InstalledDir: /Library/Developer/CommandLineTools/usr/bin + "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_5913a -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a +@(#)PROGRAM:ld PROJECT:ld64-764 +BUILD 11:22:55 Apr 28 2022 +configured to support archs: armv6 armv7 armv7s arm64 arm64e arm64_32 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em +Library search paths: + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib +Framework search paths: + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/ + + + +Parsed C implicit include dir info from above output: rv=done + found start of include info + found start of implicit include info + add: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + add: [/Library/Developer/CommandLineTools/usr/include] + end of search list found + collapse include dir [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] ==> [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + collapse include dir [/Library/Developer/CommandLineTools/usr/include] ==> [/Library/Developer/CommandLineTools/usr/include] + implicit include dirs: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include] + + +Parsed C implicit link information from above output: + link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] + ignore line: [Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-LcrFWX] + ignore line: [] + ignore line: [Run Build Command(s):/usr/bin/make -f Makefile cmTC_5913a/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_5913a.dir/build.make CMakeFiles/cmTC_5913a.dir/build] + ignore line: [Building C object CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o] + ignore line: [/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl -v -MD -MT CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -MF CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o.d -o CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCCompilerABI.c] + ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] + ignore line: [Target: arm64-apple-darwin21.6.0] + ignore line: [Thread model: posix] + ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] + ignore line: [clang: warning: -Wl -v: 'linker' input unused [-Wunused-command-line-argument]] + ignore line: [ "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCCompilerABI.c -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-LcrFWX -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -x c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCCompilerABI.c] + ignore line: [clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0] + ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include"] + ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks"] + ignore line: [#include "..." search starts here:] + ignore line: [#include <...> search starts here:] + ignore line: [ /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + ignore line: [ /Library/Developer/CommandLineTools/usr/include] + ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory)] + ignore line: [End of search list.] + ignore line: [Linking C executable cmTC_5913a] + ignore line: [/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_5913a.dir/link.txt --verbose=1] + ignore line: [/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl -search_paths_first -Wl -headerpad_max_install_names -v -Wl -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -o cmTC_5913a ] + ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] + ignore line: [Target: arm64-apple-darwin21.6.0] + ignore line: [Thread model: posix] + ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] + link line: [ "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_5913a -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + arg [/Library/Developer/CommandLineTools/usr/bin/ld] ==> ignore + arg [-demangle] ==> ignore + arg [-lto_library] ==> ignore, skip following value + arg [/Library/Developer/CommandLineTools/usr/lib/libLTO.dylib] ==> skip value of -lto_library + arg [-dynamic] ==> ignore + arg [-arch] ==> ignore + arg [arm64] ==> ignore + arg [-platform_version] ==> ignore + arg [macos] ==> ignore + arg [12.0.0] ==> ignore + arg [12.3] ==> ignore + arg [-syslibroot] ==> ignore + arg [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk] ==> ignore + arg [-o] ==> ignore + arg [cmTC_5913a] ==> ignore + arg [-search_paths_first] ==> ignore + arg [-headerpad_max_install_names] ==> ignore + arg [-v] ==> ignore + arg [CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o] ==> ignore + arg [-lSystem] ==> lib [System] + arg [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] ==> lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + Library search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + Framework search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] + remove lib [System] + remove lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + collapse library dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + collapse framework dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] + implicit libs: [] + implicit objs: [] + implicit dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + implicit fwks: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] + + +Detecting CXX compiler ABI info compiled with the following output: +Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C + +Run Build Command(s):/usr/bin/make -f Makefile cmTC_48750/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_48750.dir/build.make CMakeFiles/cmTC_48750.dir/build +Building CXX object CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o +/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl,-v -MD -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -MF CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp +Apple clang version 13.1.6 (clang-1316.0.21.2.5) +Target: arm64-apple-darwin21.6.0 +Thread model: posix +InstalledDir: /Library/Developer/CommandLineTools/usr/bin +clang: warning: -Wl,-v: 'linker' input unused [-Wunused-command-line-argument] + "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -D _DARWIN_USE_64_BIT_INODE=1 -D _LARGEFILE_SOURCE -D _FILE_OFFSET_BITS=64 -D BUILDING_NODE_EXTENSION -stdlib=libc++ -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdeprecated-macro -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fno-cxx-modules -fcxx-exceptions -fexceptions -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -x c++ /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp +clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0 +ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include" +ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks" +#include "..." search starts here: +#include <...> search starts here: + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 + /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include + /Library/Developer/CommandLineTools/usr/include + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory) +End of search list. +Linking CXX executable cmTC_48750 +/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_48750.dir/link.txt --verbose=1 +/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names -v -Wl,-v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_48750 +Apple clang version 13.1.6 (clang-1316.0.21.2.5) +Target: arm64-apple-darwin21.6.0 +Thread model: posix +InstalledDir: /Library/Developer/CommandLineTools/usr/bin + "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_48750 -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -lc++ -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a +@(#)PROGRAM:ld PROJECT:ld64-764 +BUILD 11:22:55 Apr 28 2022 +configured to support archs: armv6 armv7 armv7s arm64 arm64e arm64_32 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em +Library search paths: + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib +Framework search paths: + /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/ + + + +Parsed CXX implicit include dir info from above output: rv=done + found start of include info + found start of implicit include info + add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] + add: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + add: [/Library/Developer/CommandLineTools/usr/include] + end of search list found + collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] + collapse include dir [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] ==> [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + collapse include dir [/Library/Developer/CommandLineTools/usr/include] ==> [/Library/Developer/CommandLineTools/usr/include] + implicit include dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1;/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include] + + +Parsed CXX implicit link information from above output: + link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] + ignore line: [Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C] + ignore line: [] + ignore line: [Run Build Command(s):/usr/bin/make -f Makefile cmTC_48750/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_48750.dir/build.make CMakeFiles/cmTC_48750.dir/build] + ignore line: [Building CXX object CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o] + ignore line: [/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl -v -MD -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -MF CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp] + ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] + ignore line: [Target: arm64-apple-darwin21.6.0] + ignore line: [Thread model: posix] + ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] + ignore line: [clang: warning: -Wl -v: 'linker' input unused [-Wunused-command-line-argument]] + ignore line: [ "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -D _DARWIN_USE_64_BIT_INODE=1 -D _LARGEFILE_SOURCE -D _FILE_OFFSET_BITS=64 -D BUILDING_NODE_EXTENSION -stdlib=libc++ -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdeprecated-macro -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fno-cxx-modules -fcxx-exceptions -fexceptions -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -x c++ /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp] + ignore line: [clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0] + ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include"] + ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks"] + ignore line: [#include "..." search starts here:] + ignore line: [#include <...> search starts here:] + ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] + ignore line: [ /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] + ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] + ignore line: [ /Library/Developer/CommandLineTools/usr/include] + ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory)] + ignore line: [End of search list.] + ignore line: [Linking CXX executable cmTC_48750] + ignore line: [/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_48750.dir/link.txt --verbose=1] + ignore line: [/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl -search_paths_first -Wl -headerpad_max_install_names -v -Wl -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_48750 ] + ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] + ignore line: [Target: arm64-apple-darwin21.6.0] + ignore line: [Thread model: posix] + ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] + link line: [ "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_48750 -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -lc++ -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + arg [/Library/Developer/CommandLineTools/usr/bin/ld] ==> ignore + arg [-demangle] ==> ignore + arg [-lto_library] ==> ignore, skip following value + arg [/Library/Developer/CommandLineTools/usr/lib/libLTO.dylib] ==> skip value of -lto_library + arg [-dynamic] ==> ignore + arg [-arch] ==> ignore + arg [arm64] ==> ignore + arg [-platform_version] ==> ignore + arg [macos] ==> ignore + arg [12.0.0] ==> ignore + arg [12.3] ==> ignore + arg [-syslibroot] ==> ignore + arg [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk] ==> ignore + arg [-o] ==> ignore + arg [cmTC_48750] ==> ignore + arg [-search_paths_first] ==> ignore + arg [-headerpad_max_install_names] ==> ignore + arg [-v] ==> ignore + arg [CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o] ==> ignore + arg [-lc++] ==> lib [c++] + arg [-lSystem] ==> lib [System] + arg [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] ==> lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + Library search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + Framework search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] + remove lib [System] + remove lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] + collapse library dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + collapse framework dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] + implicit libs: [c++] + implicit objs: [] + implicit dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] + implicit fwks: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] + + diff --git a/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache b/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache new file mode 100644 index 00000000..3dccd731 --- /dev/null +++ b/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache @@ -0,0 +1 @@ +# This file is generated by cmake for dependency checking of the CMakeCache.txt file diff --git a/languages/c/templates/sdk/cmake/CopySymlink.cmake b/languages/c/templates/sdk/cmake/CopySymlink.cmake new file mode 100644 index 00000000..b25a5e22 --- /dev/null +++ b/languages/c/templates/sdk/cmake/CopySymlink.cmake @@ -0,0 +1,17 @@ +# 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 + +file(COPY "${LIBRARY}" DESTINATION "${DESTINATION}" FOLLOW_SYMLINK_CHAIN) diff --git a/languages/c/templates/sdk/cmake/HelperFunctions.cmake b/languages/c/templates/sdk/cmake/HelperFunctions.cmake new file mode 100644 index 00000000..bbd7ce65 --- /dev/null +++ b/languages/c/templates/sdk/cmake/HelperFunctions.cmake @@ -0,0 +1,139 @@ +# 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 + +macro(GetSubDirs subdirs currentdir) + file(GLOB subdirectories RELATIVE ${currentdir} ${currentdir}/*) + set(subdirs "") + foreach(subdir ${subdirectories}) + if (IS_DIRECTORY ${currentdir}/${subdir}) + list(APPEND subdirs ${subdir}) + endif() + endforeach() +endmacro() + +function(InstallHeaders) + set(optionsArgs EXCLUDE_ROOT_DIR) + set(oneValueArgs TARGET NAMESPACE SOURCE DESTINATION) + set(multiValueArgs HEADERS) + + cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) + if (Argument_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to InstallHeaders(): \"${Argument_UNPARSED_ARGUMENTS}\"") + endif() + if (Argument_HEADERS) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMENT "=================== Installing Headers ======================" + ) + foreach(directory ${Argument_HEADERS}) + if (Argument_EXCLUDE_ROOT_DIR) + set(destination ${Argument_DESTINATION}) + else() + set(destination ${Argument_DESTINATION}/${directory}) + endif() + + if (Argument_SOURCE) + set(source ${Argument_SOURCE}) + else() + set(source ${CMAKE_CURRENT_LIST_DIR}) + endif() + + GetSubDirs(subdirs ${source}/${directory}) + list(APPEND subdirs ${directory}) + + foreach(subdir ${subdirs}) + set(dest ${destination}/${subdir}) + file(GLOB headers "${source}/${directory}/${subdir}/*.h") + if (headers) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_NAMESPACE}/usr/include/${dest} + COMMAND ${CMAKE_COMMAND} -E copy ${source}/${directory}/${subdir}/*.h ${CMAKE_BINARY_DIR}/${Argument_NAMESPACE}/usr/include/${dest} + ) + endif() + endforeach(subdir) + endforeach(directory) + endif() +endfunction(InstallHeaders) + +function(InstallLibraries) + set(optionsArgs SHARED) + set(oneValueArgs TARGET DESTINATION) + set(multiValueArgs LIBRARIES) + + cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) + if (Argument_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to InstallLibraries(): \"${Argument_UNPARSED_ARGUMENTS}\"") + endif() + if (Argument_LIBRARIES) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMENT "=================== Installing Libraries ======================" + ) + foreach(LIBRARY ${Argument_LIBRARIES}) + if (Argument_SHARED) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + COMMAND ${CMAKE_COMMAND} -D "LIBRARY=${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR}" -D "DESTINATION=${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib" -P ${CMAKE_SOURCE_DIR}/cmake/CopySymlink.cmake + COMMAND ${CMAKE_COMMAND} -D "LIBRARY=${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so" -D "DESTINATION=${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib" -P ${CMAKE_SOURCE_DIR}/cmake/CopySymlink.cmake + ) + else() + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/lib${LIBRARY}.a ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + ) + + endif() + endforeach(LIBRARY) + endif() +endfunction(InstallLibraries) + +function(InstallCMakeConfigs) + set(optionsArgs) + set(oneValueArgs TARGET DESTINATION) + set(multiValueArgs) + + cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) + if (Argument_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to InstallCMakeConfigs(): \"${Argument_UNPARSED_ARGUMENTS}\"") + endif() + if (Argument_TARGET) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMENT "=================== Installing CMakeConfigs ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}Config*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Export/lib/cmake/${Argument_TARGET}/${Argument_TARGET}Targets*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} + ) + if (EXISTS ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}.pc) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/pkgconfig + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}.pc ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/pkgconfig + ) + endif() + endif() +endfunction(InstallCMakeConfigs) diff --git a/languages/c/templates/sdk/cmake/project.cmake.in b/languages/c/templates/sdk/cmake/project.cmake.in new file mode 100644 index 00000000..0855ca12 --- /dev/null +++ b/languages/c/templates/sdk/cmake/project.cmake.in @@ -0,0 +1,30 @@ +# 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 + +set(FIREBOLT_NAMESPACE "@FIREBOLT_NAMESPACE@" CACHE INTERNAL "" FORCE) +set("${FIREBOLT_NAMESPACE}_FOUND" TRUE CACHE INTERNAL "" FORCE) + +list(APPEND CMAKE_MODULE_PATH + "${CMAKE_SOURCE_DIR}/cmake" + "${SYSROOT_PATH}/usr/lib/cmake" + "${SYSROOT_PATH}/usr/lib/cmake/Firebolt" + "${SYSROOT_PATH}/tools/cmake") + +if (NOT DEFINED CMAKE_PREFIX_PATH) + set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) +endif() + + diff --git a/languages/c/templates/sdk/include/Error.h b/languages/c/templates/sdk/include/Error.h new file mode 100644 index 00000000..87cda9dd --- /dev/null +++ b/languages/c/templates/sdk/include/Error.h @@ -0,0 +1,41 @@ +/* + * 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 + */ + +#ifndef _FIREBOLT_ERROR_H +#define _FIREBOLT_ERROR_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum FireboltSDKError { + FireboltSDKErrorNone = 0, + FireboltSDKErrorGeneral = 1, + FireboltSDKErrorUnavailable = 2, + FireboltSDKErrorTimedout = 3, + FireboltSDKErrorNotSubscribed = 4, + FireboltSDKErrorUnknown = 5, + FireboltSDKErrorInUse = 6, + FireboltSDKErrorNotSupported = 7 +} FireboltSDKError_t; + +#ifdef __cplusplus +} +#endif + +#endif // _FIREBOLT_ERROR_H diff --git a/languages/c/templates/sdk/include/Types.h b/languages/c/templates/sdk/include/Types.h new file mode 100644 index 00000000..e7456cdd --- /dev/null +++ b/languages/c/templates/sdk/include/Types.h @@ -0,0 +1,43 @@ +/* + * 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 + */ + +#ifndef _FIREBOLT_TYPES_H +#define _FIREBOLT_TYPES_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + Test1, + Test2, + Test3, + Test4 +} TestEnum; + +typedef void* FireboltTypes_StringHandle; +const char* FireboltTypes_String(FireboltTypes_StringHandle handle); +void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle); + +#ifdef __cplusplus +} +#endif + +#endif // _FIREBOLT_TYPES_H diff --git a/languages/c/templates/sdk/scripts/install.js b/languages/c/templates/sdk/scripts/install.js new file mode 100644 index 00000000..5c332ceb --- /dev/null +++ b/languages/c/templates/sdk/scripts/install.js @@ -0,0 +1,32 @@ +import { createRequire } from 'module'; +const require = createRequire(import.meta.url); +const fs = require('fs'); +const path = require('path'); + +var dest = process.env.NODE_INSTALL_PATH; +var src = 'src/native/build/' + process.env.TARGET_NAME; + +installFiles(src, dest); +function installFiles(src, dest) { + if (!fs.existsSync(dest)) { + fs.mkdirSync(dest); + } + + var entries = fs.readdirSync(src); + entries.forEach((entry) => { + const srcPath = path.join(src, entry); + const destPath = path.join(dest, entry); + const stat = fs.lstatSync(srcPath); + + if (stat.isFile()) { + fs.copyFileSync(srcPath, destPath); + } else if (stat.isDirectory()) { + installFiles(srcPath, destPath); + } else if (stat.isSymbolicLink()) { + if (fs.existsSync(destPath)) { + fs.unlinkSync(destPath); + } + fs.symlinkSync(fs.readlinkSync(srcPath), destPath); + } + }); +} diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.cpp b/languages/c/templates/sdk/src/Accessor/Accessor.cpp new file mode 100644 index 00000000..b4cada4b --- /dev/null +++ b/languages/c/templates/sdk/src/Accessor/Accessor.cpp @@ -0,0 +1,134 @@ +/* + * 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 "Accessor.h" + +namespace FireboltSDK { + + Accessor* Accessor::_singleton = nullptr; + Accessor::Accessor() + : _threadCount(DefaultThreadCount) + , _queueSize(DefaultQueueSize) + , _workerPool() + , _transport(nullptr) + { + _singleton = this; + Config config; + LoadConfigs(config); + + Logger::SetLogLevel(WPEFramework::Core::EnumerateType(config.LogLevel.Value().c_str()).Value()); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Url = %s", config.Url.Value().c_str()); + CreateTransport(config.Url.Value(), config.WaitTime.Value()); + CreateEventHandler(); + + _workerPool = WPEFramework::Core::ProxyType::Create(_threadCount, WPEFramework::Core::Thread::DefaultStackSize(), _queueSize); + WPEFramework::Core::WorkerPool::Assign(&(*_workerPool)); + _workerPool->Run(); + } + + Accessor::~Accessor() + { + DestroyTransport(); + DestroyEventHandler(); + WPEFramework::Core::IWorkerPool::Assign(nullptr); + _workerPool->Stop(); + _singleton = nullptr; + } + + void Accessor::LoadConfigs(Config& config) + { + string prefixPath; + WPEFramework::Core::SystemInfo::GetEnvironment("OPENRPC_NATIVE_SDK_PREFIX", prefixPath); + string configFilePath = (prefixPath.empty() != true) ? + (prefixPath + '/' + Accessor::ConfigFile) : Accessor::ConfigFile; + WPEFramework::Core::File configFile(configFilePath); + + if (configFile.Open(true) == true) { + WPEFramework::Core::OptionalType error; + config.IElement::FromFile(configFile, error); + if (error.IsSet() == true) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in reading config"); + } + } + } + + uint32_t Accessor::CreateEventHandler() + { + Event::Instance().Configure(_transport); + return FireboltSDKErrorNone; + } + + uint32_t Accessor::DestroyEventHandler() + { + Event::Dispose(); + return FireboltSDKErrorNone; + } + + Event& Accessor::GetEventManager() + { + return Event::Instance(); + } + + uint32_t Accessor::CreateTransport(const string& url, const uint32_t waitTime) + { + if (_transport != nullptr) { + delete _transport; + } + + _transport = new Transport(static_cast(url), waitTime); + if (WaitForLinkReady(_transport, DefaultWaitTime) != FireboltSDKErrorNone) { + delete _transport; + _transport = nullptr; + } + + ASSERT(_transport != nullptr); + return ((_transport != nullptr) ? FireboltSDKErrorNone : FireboltSDKErrorUnavailable); + } + + uint32_t Accessor::DestroyTransport() + { + if (_transport != nullptr) { + delete _transport; + _transport = nullptr; + } + return FireboltSDKErrorNone; + } + + Transport* Accessor::GetTransport() + { + ASSERT(_transport != nullptr); + return _transport; + } + + uint32_t Accessor::WaitForLinkReady(Transport* transport, const uint32_t waitTime = DefaultWaitTime) { + uint32_t waiting = (waitTime == WPEFramework::Core::infinite ? WPEFramework::Core::infinite : waitTime); + static constexpr uint32_t SLEEPSLOT_TIME = 100; + + // Right, a wait till connection is closed is requested.. + while ((waiting > 0) && (transport->IsOpen() == false)) { + + uint32_t sleepSlot = (waiting > SLEEPSLOT_TIME ? SLEEPSLOT_TIME : waiting); + + // Right, lets sleep in slices of 100 ms + SleepMs(sleepSlot); + + waiting -= (waiting == WPEFramework::Core::infinite ? 0 : sleepSlot); + } + return (((waiting == 0) || (transport->IsOpen() == true)) ? FireboltSDKErrorNone : FireboltSDKErrorTimedout); + } +} diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.h b/languages/c/templates/sdk/src/Accessor/Accessor.h new file mode 100644 index 00000000..3e9b8784 --- /dev/null +++ b/languages/c/templates/sdk/src/Accessor/Accessor.h @@ -0,0 +1,79 @@ +/* + * 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 "Module.h" +#include "Config.h" +#include "WorkerPool.h" +#include "Transport/Transport.h" +#include "Event/Event.h" +#include "Logger/Logger.h" + +namespace FireboltSDK { + class Accessor { + private: + static constexpr uint8_t JSONVersion = 2; + static constexpr const TCHAR* ConfigFile = _T("/etc/Firebolt/config.json"); + static constexpr uint32_t DefaultWaitTime = 1000; + static constexpr uint8_t DefaultQueueSize = 8; + static constexpr uint8_t DefaultThreadCount = 3; + + public: + Accessor(const Accessor&) = delete; + Accessor& operator= (const Accessor&) = delete; + + Accessor(); + ~Accessor(); + + static Accessor& Instance() + { + static Accessor *instance = new Accessor(); + ASSERT(instance != nullptr); + return *instance; + } + + static void Dispose() + { + ASSERT(_singleton != nullptr); + + if (_singleton != nullptr) { + delete _singleton; + } + } + + uint32_t CreateEventHandler(); + uint32_t DestroyEventHandler(); + Event& GetEventManager(); + + uint32_t CreateTransport(const string& url, const uint32_t waitTime); + uint32_t DestroyTransport(); + Transport* GetTransport(); + uint32_t WaitForLinkReady(Transport* transport, const uint32_t waitTime); + + private: + void LoadConfigs(Config& config); + + private: + uint8_t _threadCount; + uint8_t _queueSize; + WPEFramework::Core::ProxyType _workerPool; + Transport* _transport; + static Accessor* _singleton; + }; +} diff --git a/languages/c/templates/sdk/src/Accessor/Config.h b/languages/c/templates/sdk/src/Accessor/Config.h new file mode 100644 index 00000000..f8389bf6 --- /dev/null +++ b/languages/c/templates/sdk/src/Accessor/Config.h @@ -0,0 +1,41 @@ +/* + * 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 + */ + +namespace FireboltSDK { + class EXTERNAL Config : public WPEFramework::Core::JSON::Container { + public: + Config(const Config&) = delete; + Config& operator=(const Config&) = delete; + + Config() + : WPEFramework::Core::JSON::Container() + , Url(_T("")) + , WaitTime(1000) + , LogLevel(_T("Info")) + { + Add(_T("url"), &Url); + Add(_T("waittime"), &WaitTime); + Add(_T("loglevel"), &LogLevel); + } + + public: + WPEFramework::Core::JSON::String Url; + WPEFramework::Core::JSON::DecUInt32 WaitTime; + WPEFramework::Core::JSON::String LogLevel; + }; +} diff --git a/languages/c/templates/sdk/src/Accessor/WorkerPool.h b/languages/c/templates/sdk/src/Accessor/WorkerPool.h new file mode 100644 index 00000000..521ccc65 --- /dev/null +++ b/languages/c/templates/sdk/src/Accessor/WorkerPool.h @@ -0,0 +1,72 @@ +/* + * 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 "Module.h" + +namespace FireboltSDK { + + class WorkerPoolImplementation : public WPEFramework::Core::WorkerPool { + public: + WorkerPoolImplementation() = delete; + WorkerPoolImplementation(const WorkerPoolImplementation&) = delete; + WorkerPoolImplementation& operator=(const WorkerPoolImplementation&) = delete; + + WorkerPoolImplementation(const uint8_t threads, const uint32_t stackSize, const uint32_t queueSize) + : WorkerPool(threads, stackSize, queueSize, &_dispatcher) + { + } + + ~WorkerPoolImplementation() + { + // Diable the queue so the minions can stop, even if they are processing and waiting for work.. + Stop(); + } + + public: + void Stop() + { + WPEFramework::Core::WorkerPool::Stop(); + } + + void Run() + { + WPEFramework::Core::WorkerPool::Run(); + } + + private: + class Dispatcher : public WPEFramework::Core::ThreadPool::IDispatcher { + public: + Dispatcher(const Dispatcher&) = delete; + Dispatcher& operator=(const Dispatcher&) = delete; + + Dispatcher() = default; + ~Dispatcher() override = default; + + private: + void Initialize() override { } + void Deinitialize() override { } + void Dispatch(WPEFramework::Core::IDispatch* job) override + { job->Dispatch(); } + }; + + Dispatcher _dispatcher; + }; + +} diff --git a/languages/c/templates/sdk/src/CMakeLists.txt b/languages/c/templates/sdk/src/CMakeLists.txt new file mode 100644 index 00000000..c411582a --- /dev/null +++ b/languages/c/templates/sdk/src/CMakeLists.txt @@ -0,0 +1,93 @@ +# 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 + +cmake_minimum_required(VERSION 3.3) + +project(FireboltSDK) +project_version(1.0.0) +set(TARGET ${PROJECT_NAME}) +message("Setup ${TARGET} v${PROJECT_VERSION}") + +add_library(${TARGET} SHARED + Types.cpp + Module.cpp + Logger/Logger.cpp + Transport/Transport.cpp + Accessor/Accessor.cpp + Event/Event.cpp) + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +find_package(${NAMESPACE}Core CONFIG REQUIRED) +find_package(${NAMESPACE}WebSocket CONFIG REQUIRED) + +target_link_libraries(${TARGET} + PUBLIC + ${NAMESPACE}Core::${NAMESPACE}Core + ${NAMESPACE}WebSocket::${NAMESPACE}WebSocket +) + +target_include_directories(${TARGET} + PRIVATE + $ + $ + $ +) + +set_target_properties(${TARGET} PROPERTIES + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED YES + FRAMEWORK FALSE + LINK_WHAT_YOU_USE TRUE + VERSION ${PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} +) + +install( + TARGETS ${TARGET} EXPORT ${TARGET}Targets + LIBRARY DESTINATION lib COMPONENT libs + PUBLIC_HEADER DESTINATION include/${TARGET} COMPONENT devel # headers for mac (note the different component -> different package) + INCLUDES DESTINATION include/${TARGET} # headers +) + +InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION ${FIREBOLT_NAMESPACE}SDK) +InstallHeaders(TARGET ${TARGET} EXCLUDE_ROOT_DIR HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} + SOURCE ${GENERATED_CODE_PATH}/include DESTINATION ${FIREBOLT_NAMESPACE}/generated) +InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} + SOURCE ${CMAKE_SOURCE_DIR}/include DESTINATION ${FIREBOLT_NAMESPACE}) + +InstallLibraries(TARGET ${TARGET} SHARED LIBRARIES ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallCMakeConfig(TARGETS ${TARGET}) +InstallPackageConfig(TARGETS ${TARGET} DESCRIPTION "Firebolt SDK Library") +InstallCMakeConfigs(TARGET ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) + +add_custom_command( + TARGET ${TARGET} + POST_BUILD + COMMENT "=================== Installing JsonConfig ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/etc/${FIREBOLT_NAMESPACE} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/config/${TARGET}.json ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/etc/${FIREBOLT_NAMESPACE}/config.json +) + +add_custom_command( + TARGET ${TARGET} + POST_BUILD + COMMENT "=================== Installing FireboltConfig & Helper CMakes ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/cmake/*.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} +) + +include(Config.cmake) diff --git a/languages/c/templates/sdk/src/Config.cmake b/languages/c/templates/sdk/src/Config.cmake new file mode 100644 index 00000000..a420ce32 --- /dev/null +++ b/languages/c/templates/sdk/src/Config.cmake @@ -0,0 +1,34 @@ +# 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 + +set(SERVER_PORT 9998 CACHE STRING "The port of the server") +set(SERVER_ADDRESS "127.0.0.1" CACHE STRING "The address of the server") + + #[[ ================================ Add additional config above this line ================================ ]] + + +find_package(ConfigGenerator REQUIRED) + +write_config( + SKIP_COMPARE + SKIP_CLASSNAME + SKIP_LOCATOR + DISABLE_LEGACY_GENERATOR + CUSTOM_PARAMS_WHITELIST "${CMAKE_CURRENT_LIST_DIR}/Params.config" + INSTALL_PATH "${CMAKE_INSTALL_PREFIX}/../etc/" + INSTALL_NAME "config.json" +) + diff --git a/languages/c/templates/sdk/src/Event/Event.cpp b/languages/c/templates/sdk/src/Event/Event.cpp new file mode 100644 index 00000000..69b448f6 --- /dev/null +++ b/languages/c/templates/sdk/src/Event/Event.cpp @@ -0,0 +1,148 @@ +/* + * 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 "Transport/Transport.h" +#include "Event.h" + +namespace FireboltSDK { + Event* Event::_singleton = nullptr; + Event::Event() + : _id(0) + , _eventMap() + , _adminLock() + , _transport(nullptr) + { + ASSERT(_singleton == nullptr); + _singleton = this; + } + + Event::~Event() /* override */ + { + _transport->SetEventHandler(nullptr); + _transport = nullptr; + + _singleton = nullptr; + } + + /* static */ Event& Event::Instance() + { + static Event *instance = new Event(); + ASSERT(instance != nullptr); + return *instance; + } + + /* static */ void Event::Dispose() + { + ASSERT(_singleton != nullptr); + + if (_singleton != nullptr) { + delete _singleton; + } + } + + void Event::Configure(Transport* transport) + { + _transport = transport; + _transport->SetEventHandler(this); + } + + uint32_t Event::Unsubscribe(const string& eventName, const uint32_t id) + { + uint32_t status = Revoke(eventName, id); + + if (status == FireboltSDKErrorNone) { + if (_transport != nullptr) { + + const string parameters("{\"listen\":false}"); + status = _transport->Unsubscribe(eventName, parameters); + } + } + return ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone: status); + } + + uint32_t Event::ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) /* override */ + { + uint32_t result = FireboltSDKErrorGeneral; + Response response; + _transport->FromMessage((WPEFramework::Core::JSON::IElement*)&response, *jsonResponse); + if (response.Listening.IsSet() == true) { + result = FireboltSDKErrorNone; + enabled = response.Listening.Value(); + } + return result; + } + + uint32_t Event::Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) /* override */ + { + string response = jsonResponse->Result.Value(); + _adminLock.Lock(); + EventMap::iterator eventIndex = _eventMap.find(eventName); + if (eventIndex != _eventMap.end()) { + IdMap::iterator idIndex = eventIndex->second.begin(); + while(idIndex != eventIndex->second.end()) { + State state; + if (idIndex->second.state != State::REVOKED) { + idIndex->second.state = State::EXECUTING; + } + state = idIndex->second.state; + _adminLock.Unlock(); + if (state == State::EXECUTING) { + idIndex->second.lambda(idIndex->second.userdata, (jsonResponse->Result.Value())); + } + _adminLock.Lock(); + if (idIndex->second.state == State::REVOKED) { + idIndex = eventIndex->second.erase(idIndex); + if (eventIndex->second.size() == 0) { + _eventMap.erase(eventIndex); + } + } else { + idIndex->second.state = State::IDLE; + idIndex++; + } + } + } + _adminLock.Unlock(); + + return FireboltSDKErrorNone;; + } + + uint32_t Event::Revoke(const string& eventName, const uint32_t id) + { + uint32_t status = FireboltSDKErrorNone; + _adminLock.Lock(); + EventMap::iterator eventIndex = _eventMap.find(eventName); + if (eventIndex != _eventMap.end()) { + IdMap::iterator idIndex = eventIndex->second.find(id); + if (idIndex->second.state != State::EXECUTING) { + if (idIndex != eventIndex->second.end()) { + eventIndex->second.erase(idIndex); + } + } else { + idIndex->second.state = State::REVOKED; + } + if (eventIndex->second.size() == 0) { + _eventMap.erase(eventIndex); + } else { + status = FireboltSDKErrorInUse; + } + } + _adminLock.Unlock(); + + return status; + } +} diff --git a/languages/c/templates/sdk/src/Event/Event.h b/languages/c/templates/sdk/src/Event/Event.h new file mode 100644 index 00000000..df9b1dc9 --- /dev/null +++ b/languages/c/templates/sdk/src/Event/Event.h @@ -0,0 +1,154 @@ +/* + * 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 "Module.h" + +namespace FireboltSDK { + + static constexpr uint32_t DefaultWaitTime = 1000; + + class Event : public IEventHandler { + public: + typedef std::function DispatchFunction; + private: + enum State : uint8_t { + IDLE, + EXECUTING, + REVOKED + }; + + struct CallbackData { + const DispatchFunction lambda; + const void* userdata; + State state; + }; + using IdMap = std::map; + using EventMap = std::map; + + + class Response : public WPEFramework::Core::JSON::Container { + public: + Response& operator=(const Response&) = delete; + Response() + : WPEFramework::Core::JSON::Container() + , Listening(false) + { + Add(_T("listening"), &Listening); + } + Response(const Response& copy) + : WPEFramework::Core::JSON::Container() + , Listening(copy.Listening) + { + Add(_T("listening"), &Listening); + } + ~Response() override = default; + + public: + WPEFramework::Core::JSON::Boolean Listening; + }; + + public: + Event(); + ~Event() override; + static Event& Instance(); + static void Dispose(); + void Configure(Transport* transport); + + public: + template + uint32_t Subscribe(const string& eventName, const CALLBACK& callback, const void* userdata, uint32_t& id) + { + uint32_t status = FireboltSDKErrorUnavailable; + if (_transport != nullptr) { + + status = Assign(eventName, callback, userdata, id); + if (status == FireboltSDKErrorNone) { + const string parameters("{\"listen\":true}"); + Response response; + status = _transport->Subscribe(eventName, parameters, response); + + if (status != FireboltSDKErrorNone) { + Revoke(eventName, id); + } else if ((response.Listening.IsSet() == true) && + (response.Listening.Value() == true)) { + status = FireboltSDKErrorNone; + } else { + status = FireboltSDKErrorNotSubscribed; + } + } + } + + return ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone: status); + } + + uint32_t Unsubscribe(const string& eventName, const uint32_t id); + + private: + template + uint32_t Assign(const string& eventName, const CALLBACK& callback, const void* userdata, uint32_t& id) + { + uint32_t status = FireboltSDKErrorNone; + id = Id(); + std::function actualCallback = callback; + DispatchFunction implementation = [actualCallback](const void* userdata, const string& parameters) -> uint32_t { + + WPEFramework::Core::ProxyType inbound = WPEFramework::Core::ProxyType::Create(); + inbound->FromString(parameters); + actualCallback(userdata, static_cast(&inbound)); + return (FireboltSDKErrorNone); + }; + CallbackData callbackData = {implementation, userdata, State::IDLE}; + + _adminLock.Lock(); + EventMap::iterator eventIndex = _eventMap.find(eventName); + if (eventIndex != _eventMap.end()) { + // Already registered, no need to register again; + status = FireboltSDKErrorInUse; + eventIndex->second.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(callbackData)); + } else { + + IdMap idMap; + idMap.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(callbackData)); + _eventMap.emplace(std::piecewise_construct, std::forward_as_tuple(eventName), std::forward_as_tuple(idMap)); + + } + + _adminLock.Unlock(); + return status; + } + uint32_t Revoke(const string& eventName, const uint32_t id); + + private: + uint32_t Id() const + { + return (++_id); + } + uint32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) override; + uint32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) override; + + private: + mutable std::atomic _id; + EventMap _eventMap; + WPEFramework::Core::CriticalSection _adminLock; + Transport* _transport; + + static Event* _singleton; + }; +} diff --git a/languages/c/templates/sdk/src/Firebolt.h b/languages/c/templates/sdk/src/Firebolt.h new file mode 100644 index 00000000..6a8f51a2 --- /dev/null +++ b/languages/c/templates/sdk/src/Firebolt.h @@ -0,0 +1,25 @@ +/* + * 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 "Transport/Transport.h" +#include "Properties/Properties.h" +#include "Accessor/Accessor.h" +#include "Logger/Logger.h" +#include "Types.h" diff --git a/languages/c/templates/sdk/src/FireboltSDK.conf.in b/languages/c/templates/sdk/src/FireboltSDK.conf.in new file mode 100644 index 00000000..6964a7bc --- /dev/null +++ b/languages/c/templates/sdk/src/FireboltSDK.conf.in @@ -0,0 +1,3 @@ +url = "@FIREBOLT_SERVER_URL@" +waittime = "@FIREBOLT_TRANSPORT_WAITTIME@" +loglevel = "@FIREBOLT_LOGLEVEL@" diff --git a/languages/c/templates/sdk/src/Logger/Logger.cpp b/languages/c/templates/sdk/src/Logger/Logger.cpp new file mode 100644 index 00000000..8acd8a14 --- /dev/null +++ b/languages/c/templates/sdk/src/Logger/Logger.cpp @@ -0,0 +1,84 @@ +/* + * 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 "Module.h" +#include "Error.h" +#include "Logger.h" + +namespace WPEFramework { + +ENUM_CONVERSION_BEGIN(FireboltSDK::Logger::LogLevel) + + { FireboltSDK::Logger::LogLevel::Error, _TXT("Error") }, + { FireboltSDK::Logger::LogLevel::Warning, _TXT("Warning") }, + { FireboltSDK::Logger::LogLevel::Info, _TXT("Info") }, + { FireboltSDK::Logger::LogLevel::Debug, _TXT("Debug") }, + +ENUM_CONVERSION_END(FireboltSDK::Logger::LogLevel) + +ENUM_CONVERSION_BEGIN(FireboltSDK::Logger::Category) + + { FireboltSDK::Logger::Category::OpenRPC, _TXT("FireboltSDK::OpenRPC") }, + { FireboltSDK::Logger::Category::Core, _TXT("FireboltSDK::Core") }, + { FireboltSDK::Logger::Category::Management, _TXT("FireboltSDK::Management") }, + { FireboltSDK::Logger::Category::Discovery, _TXT("FireboltSDK::Discovery") }, + +ENUM_CONVERSION_END(FireboltSDK::Logger::Category) + +} + +namespace FireboltSDK { + /* static */ Logger::LogLevel Logger::_logLevel = Logger::LogLevel::Error; + + uint32_t Logger::SetLogLevel(Logger::LogLevel logLevel) + { + ASSERT(logLevel < Logger::LogLevel::MaxLevel); + uint32_t status = FireboltSDKErrorNotSupported; + if (logLevel < Logger::LogLevel::MaxLevel) { + _logLevel = logLevel; + status = FireboltSDKErrorNone; + } + printf("logLevel = %d _logLevel = %d\n", logLevel, _logLevel); + return status; + } + + void Logger::Log(LogLevel logLevel, Category category, const std::string& module, const std::string file, const std::string function, const uint16_t line, const std::string& format, ...) + { + if (logLevel <= _logLevel) { + va_list arg; + char msg[Logger::MaxBufSize]; + va_start(arg, format); + int length = vsnprintf(msg, Logger::MaxBufSize, format.c_str(), arg); + va_end(arg); + + uint32_t position = (length >= Logger::MaxBufSize) ? (Logger::MaxBufSize - 1) : length; + msg[position] = '\0'; + + char formattedMsg[Logger::MaxBufSize]; + const string time = WPEFramework::Core::Time::Now().ToTimeOnly(true); + const string categoryName = WPEFramework::Core::EnumerateType(category).Data(); + if (categoryName.empty() != true) { + sprintf(formattedMsg, "--->\033[1;32m[%s]:[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), categoryName.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); + } else { + sprintf(formattedMsg, "--->\033[1;32m[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); + } + LOG_MESSAGE(formattedMsg); + } + } +} + diff --git a/languages/c/templates/sdk/src/Logger/Logger.h b/languages/c/templates/sdk/src/Logger/Logger.h new file mode 100644 index 00000000..cffeff54 --- /dev/null +++ b/languages/c/templates/sdk/src/Logger/Logger.h @@ -0,0 +1,85 @@ +/* + * 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 "Types.h" + +namespace FireboltSDK { + + class Logger { + private: + static constexpr uint16_t MaxBufSize = 512; + + public: + enum class LogLevel : uint8_t { + Error, + Warning, + Info, + Debug, + MaxLevel + }; + + enum class Category : uint8_t { + OpenRPC, + Core, + Management, + Discovery + }; + + public: + Logger() = default; + Logger(const Logger&) = delete; + Logger& operator=(const Logger&) = delete; + ~Logger() = default; + + public: + static uint32_t SetLogLevel(LogLevel logLevel); + static void Log(LogLevel logLevel, Category category, const std::string& module, const std::string file, const std::string function, const uint16_t line, const std::string& format, ...); + + public: + template + static const string Module() + { + return WPEFramework::Core::ClassNameOnly(typeid(CLASS).name()).Text(); + } + + private: + static LogLevel _logLevel; + }; +} + +#define FIREBOLT_LOG(level, category, module, ...) \ + FireboltSDK::Logger::Log(level, category, module, __FILE__, __func__, __LINE__, __VA_ARGS__) + +#define FIREBOLT_LOG_ERROR(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Error, category, module, __VA_ARGS__) +#define FIREBOLT_LOG_WARNING(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Warning, category, module, __VA_ARGS__) +#define FIREBOLT_LOG_INFO(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Info, category, module, __VA_ARGS__) +#define FIREBOLT_LOG_DEBUG(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Debug, category, module, __VA_ARGS__) + +#ifdef ENABLE_SYSLOG +#define LOG_MESSAGE(message) \ + syslog(sLOG_NOTIC, "%s", message); +#else +#define LOG_MESSAGE(message) \ + fprintf(stderr, "%s", message); fflush(stdout); +#endif diff --git a/languages/c/templates/schemas/src/Module.cpp b/languages/c/templates/sdk/src/Module.cpp similarity index 85% rename from languages/c/templates/schemas/src/Module.cpp rename to languages/c/templates/sdk/src/Module.cpp index 26a26050..d63badc4 100644 --- a/languages/c/templates/schemas/src/Module.cpp +++ b/languages/c/templates/sdk/src/Module.cpp @@ -16,14 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 */ -/* ${IMPORTS} */ +#include "Module.h" - -namespace FireboltSDK { - - namespace ${info.title} { - - /* ${METHODS} */ - - } -} +MODULE_NAME_DECLARATION(BUILD_REFERENCE) diff --git a/languages/c/templates/sdk/main.cpp b/languages/c/templates/sdk/src/Module.h similarity index 61% rename from languages/c/templates/sdk/main.cpp rename to languages/c/templates/sdk/src/Module.h index a9f2f5ca..5107d93e 100644 --- a/languages/c/templates/sdk/main.cpp +++ b/languages/c/templates/sdk/src/Module.h @@ -1,5 +1,5 @@ /* - * Copyright 2021 Comcast Cable Communications Management, LLC + * 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. @@ -16,15 +16,16 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { setMockResponses } from './Transport/MockTransport.mjs' +#pragma once -/* ${MOCK_IMPORTS} */ +#ifndef MODULE_NAME +#define MODULE_NAME OpenRPCNativeSDK +#endif -setMockResponses({ - /* ${MOCK_OBJECTS} */ -}) +#include +#include +#include +#include -/* ${EXPORTS} */ -export { default as Log } from './Log/index.mjs' -export { default as Events } from './Events/index.mjs' -export { default as Settings } from './Settings/index.mjs' +#undef EXTERNAL +#define EXTERNAL diff --git a/languages/c/templates/sdk/src/Params.config b/languages/c/templates/sdk/src/Params.config new file mode 100644 index 00000000..71a58750 --- /dev/null +++ b/languages/c/templates/sdk/src/Params.config @@ -0,0 +1,3 @@ +url +waittime +loglevel diff --git a/languages/c/templates/sdk/src/Properties/Properties.h b/languages/c/templates/sdk/src/Properties/Properties.h new file mode 100644 index 00000000..611811f8 --- /dev/null +++ b/languages/c/templates/sdk/src/Properties/Properties.h @@ -0,0 +1,90 @@ +/* + * 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 "Accessor/Accessor.h" +#include "Event/Event.h" + +namespace FireboltSDK { + + class Properties { + public: + Properties(const Properties&) = delete; + Properties& operator= (const Properties&) = delete; + + Properties() = default; + ~Properties() = default; + + public: + template + static uint32_t Get(const string& propertyName, WPEFramework::Core::ProxyType& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject parameters; + RESPONSETYPE responseType; + status = transport->Invoke(propertyName, parameters, responseType); + if (status == FireboltSDKErrorNone) { + ASSERT(response.IsValid() == false); + if (response.IsValid() == true) { + response.Release(); + } + response = WPEFramework::Core::ProxyType::Create(); + (*response) = responseType; + } + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static uint32_t Set(const string& propertyName, const PARAMETERS& parameters) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject responseType; + status = transport->Invoke(propertyName, parameters, responseType); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static uint32_t Subscribe(const string& propertyName, const CALLBACK& callback, const void* userdata, uint32_t& id) + { + return Event::Instance().Subscribe(EventName(propertyName), callback, userdata, id); + } + + static uint32_t Unsubscribe(const string& propertyName, const uint32_t id) + { + return Event::Instance().Unsubscribe(EventName(propertyName), id); + } + private: + static inline string EventName(const string& propertyName) { + size_t pos = propertyName.find_first_of('.'); + return string(propertyName.substr(0, pos + 1) + "on" + propertyName.substr(pos + 1) + "Changed"); + } + }; +} diff --git a/languages/c/templates/schemas/include/Module.h b/languages/c/templates/sdk/src/Transport/Transport.cpp similarity index 96% rename from languages/c/templates/schemas/include/Module.h rename to languages/c/templates/sdk/src/Transport/Transport.cpp index 4cee1781..280944c6 100644 --- a/languages/c/templates/schemas/include/Module.h +++ b/languages/c/templates/sdk/src/Transport/Transport.cpp @@ -16,8 +16,9 @@ * SPDX-License-Identifier: Apache-2.0 */ -namespace FireboltSDK { +#include "Transport.h" - /* ${DECLARATIONS} */ +namespace FireboltSDK { } + diff --git a/languages/c/templates/sdk/src/Transport/Transport.h b/languages/c/templates/sdk/src/Transport/Transport.h new file mode 100644 index 00000000..e0bff38c --- /dev/null +++ b/languages/c/templates/sdk/src/Transport/Transport.h @@ -0,0 +1,897 @@ +/* + * 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 "Module.h" +#include "Error.h" + +namespace FireboltSDK { + + using namespace WPEFramework::Core::TypeTraits; + + template + class CommunicationChannel { + public: + typedef std::function Callback; + class Entry { + private: + Entry(const Entry&) = delete; + Entry& operator=(const Entry& rhs) = delete; + struct Synchronous { + Synchronous() + : _signal(false, true) + , _response() + { + } + WPEFramework::Core::Event _signal; + std::list> _response; + }; + struct ASynchronous { + ASynchronous(const uint32_t waitTime, const Callback& completed) + : _waitTime(WPEFramework::Core::Time::Now().Add(waitTime).Ticks()) + , _completed(completed) + { + } + uint64_t _waitTime; + Callback _completed; + }; + + public: + Entry() + : _synchronous(true) + , _info() + { + } + Entry(const uint32_t waitTime, const Callback& completed) + : _synchronous(false) + , _info(waitTime, completed) + { + } + ~Entry() + { + if (_synchronous == true) { + _info.sync.~Synchronous(); + } + else { + _info.async.~ASynchronous(); + } + } + + public: + const WPEFramework::Core::ProxyType& Response() const + { + return (*(_info.sync._response.begin())); + } + bool Signal(const WPEFramework::Core::ProxyType& response) + { + if (_synchronous == true) { + _info.sync._response.push_back(response); + _info.sync._signal.SetEvent(); + } + else { + _info.async._completed(*response); + } + + return (_synchronous == false); + } + const uint64_t& Expiry() const + { + return (_info.async._waitTime); + } + void Abort(const uint32_t id) + { + if (_synchronous == true) { + _info.sync._signal.SetEvent(); + } + else { + MESSAGETYPE message; + ToMessage(id, message, WPEFramework::Core::ERROR_ASYNC_ABORTED); + _info.async._completed(message); + } + } + bool Expired(const uint32_t id, const uint64_t& currentTime, uint64_t& nextTime) + { + bool expired = false; + + if (_synchronous == false) { + if (_info.async._waitTime > currentTime) { + if (_info.async._waitTime < nextTime) { + nextTime = _info.async._waitTime; + } + } + else { + MESSAGETYPE message; + ToMessage(id, message, WPEFramework::Core::ERROR_TIMEDOUT); + _info.async._completed(message); + expired = true; + } + } + return (expired); + } + bool WaitForResponse(const uint32_t waitTime) + { + return (_info.sync._signal.Lock(waitTime) == WPEFramework::Core::ERROR_NONE); + } + + private: + void ToMessage(const uint32_t id, WPEFramework::Core::JSONRPC::Message& message, uint32_t error) + { + message.Id = id; + message.Error.Code = error; + switch (error) { + case WPEFramework::Core::ERROR_ASYNC_ABORTED: { + message.Error.Text = _T("Pending a-sync call has been aborted"); + break; + } + case WPEFramework::Core::ERROR_TIMEDOUT: { + message.Error.Text = _T("Pending a-sync call has timed out"); + break; + } + } + } + + bool _synchronous; + union Info { + public: + Info() + : sync() + { + } + Info(const uint32_t waitTime, const Callback& completed) + : async(waitTime, completed) + { + } + ~Info() + { + } + Synchronous sync; + ASynchronous async; + } _info; + }; + + + + private: + class FactoryImpl { + private: + FactoryImpl(const FactoryImpl&) = delete; + FactoryImpl& operator=(const FactoryImpl&) = delete; + + class WatchDog { + private: + WatchDog() = delete; + WatchDog& operator=(const WatchDog&) = delete; + + public: + WatchDog(CLIENT* client) + : _client(client) + { + } + WatchDog(const WatchDog& copy) + : _client(copy._client) + { + } + ~WatchDog() + { + } + + bool operator==(const WatchDog& rhs) const + { + return (rhs._client == _client); + } + bool operator!=(const WatchDog& rhs) const + { + return (!operator==(rhs)); + } + + public: + uint64_t Timed(const uint64_t scheduledTime) { + return (_client->Timed()); + } + + private: + CLIENT* _client; + }; + + friend WPEFramework::Core::SingletonType; + + FactoryImpl() + : _messageFactory(2) + , _watchDog(WPEFramework::Core::Thread::DefaultStackSize(), _T("TransportCleaner")) + { + } + + public: + static FactoryImpl& Instance() + { + return (WPEFramework::Core::SingletonType::Instance()); + } + + ~FactoryImpl() + { + } + + public: + WPEFramework::Core::ProxyType Element(const string&) + { + return (_messageFactory.Element()); + } + void Trigger(const uint64_t& time, CLIENT* client) + { + _watchDog.Trigger(time, client); + } + void Revoke(CLIENT* client) + { + _watchDog.Revoke(client); + } + private: + WPEFramework::Core::ProxyPoolType _messageFactory; + WPEFramework::Core::TimerType _watchDog; + }; + + class ChannelImpl : public WPEFramework::Core::StreamJSONType, FactoryImpl&, INTERFACE> { + private: + ChannelImpl(const ChannelImpl&) = delete; + ChannelImpl& operator=(const ChannelImpl&) = delete; + + typedef WPEFramework::Core::StreamJSONType, FactoryImpl&, INTERFACE> BaseClass; + + public: + ChannelImpl(CommunicationChannel* parent, const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask) + : BaseClass(5, FactoryImpl::Instance(), path, _T("JSON"), query, "", false, mask, false, remoteNode.AnyInterface(), remoteNode, 256, 256) + , _parent(*parent) + { + } + ~ChannelImpl() override = default; + + public: + void Received(WPEFramework::Core::ProxyType& response) override + { + WPEFramework::Core::ProxyType inbound(response); + + ASSERT(inbound.IsValid() == true); + if (inbound.IsValid() == true) { + _parent.Inbound(inbound); + } + } + void Send(WPEFramework::Core::ProxyType& msg) override + { +#ifdef __DEBUG__ + string message; + ToMessage(msg, message); + TRACE_L1("Message: %s send", message.c_str()); +#endif + } + void StateChange() override + { + _parent.StateChange(); + } + bool IsIdle() const override + { + return (true); + } + + private: + void ToMessage(const WPEFramework::Core::ProxyType& jsonObject, string& message) const + { + WPEFramework::Core::ProxyType inbound(jsonObject); + + ASSERT(inbound.IsValid() == true); + if (inbound.IsValid() == true) { + inbound->ToString(message); + } + } + void ToMessage(const WPEFramework::Core::ProxyType& jsonObject, string& message) const + { + WPEFramework::Core::ProxyType inbound(jsonObject); + + ASSERT(inbound.IsValid() == true); + if (inbound.IsValid() == true) { + std::vector values; + inbound->ToBuffer(values); + if (values.empty() != true) { + WPEFramework::Core::ToString(values.data(), static_cast(values.size()), false, message); + } + } + } + + private: + CommunicationChannel& _parent; + }; + + protected: + CommunicationChannel(const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask) + : _channel(this, remoteNode, path, query, mask) + , _sequence(0) + { + } + + public: + ~CommunicationChannel() = default; + static WPEFramework::Core::ProxyType Instance(const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask = true) + { + static WPEFramework::Core::ProxyMapType channelMap; + + string searchLine = remoteNode.HostAddress() + '@' + path; + + return (channelMap.template Instance(searchLine, remoteNode, path, query, mask)); + } + + public: + static void Trigger(const uint64_t& time, CLIENT* client) + { + FactoryImpl::Instance().Trigger(time, client); + } + static WPEFramework::Core::ProxyType Message() + { + return (FactoryImpl::Instance().Element(string())); + } + uint32_t Sequence() const + { + return (++_sequence); + } + void Register(CLIENT& client) + { + _adminLock.Lock(); + ASSERT(std::find(_observers.begin(), _observers.end(), &client) == _observers.end()); + _observers.push_back(&client); + if (_channel.IsOpen() == true) { + client.Opened(); + } + _adminLock.Unlock(); + } + void Unregister(CLIENT& client) + { + _adminLock.Lock(); + typename std::list::iterator index(std::find(_observers.begin(), _observers.end(), &client)); + if (index != _observers.end()) { + _observers.erase(index); + } + FactoryImpl::Instance().Revoke(&client); + _adminLock.Unlock(); + } + + void Submit(const WPEFramework::Core::ProxyType& message) + { + _channel.Submit(message); + } + bool IsSuspended() const + { + return (_channel.IsSuspended()); + } + uint32_t Initialize() + { + return (Open(0)); + } + void Deinitialize() + { + Close(); + } + bool IsOpen() + { + return (_channel.IsOpen() == true); + } + + protected: + void StateChange() + { + _adminLock.Lock(); + typename std::list::iterator index(_observers.begin()); + while (index != _observers.end()) { + if (_channel.IsOpen() == true) { + (*index)->Opened(); + } + else { + (*index)->Closed(); + } + index++; + } + _adminLock.Unlock(); + } + bool Open(const uint32_t waitTime) + { + bool result = true; + if (_channel.IsClosed() == true) { + result = (_channel.Open(waitTime) == WPEFramework::Core::ERROR_NONE); + } + return (result); + } + void Close() + { + _channel.Close(WPEFramework::Core::infinite); + } + + private: + uint32_t Inbound(const WPEFramework::Core::ProxyType& inbound) + { + uint32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + _adminLock.Lock(); + typename std::list::iterator index(_observers.begin()); + while ((result != WPEFramework::Core::ERROR_NONE) && (index != _observers.end())) { + result = (*index)->Submit(inbound); + index++; + } + _adminLock.Unlock(); + + return (result); + } + + private: + WPEFramework::Core::CriticalSection _adminLock; + ChannelImpl _channel; + mutable std::atomic _sequence; + std::list _observers; + }; + + class IEventHandler { + public: + virtual uint32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) = 0; + virtual uint32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) = 0; + virtual ~IEventHandler() = default; + }; + + template + class Transport { + private: + using Channel = CommunicationChannel; + using Entry = typename CommunicationChannel::Entry; + using PendingMap = std::unordered_map; + using EventMap = std::map; + typedef std::function& jsonResponse, bool& enabled)> EventResponseValidatioionFunction; + + class Job : public WPEFramework::Core::IDispatch { + protected: + Job(const WPEFramework::Core::ProxyType& inbound, class Transport* parent) + : _inbound(inbound) + , _parent(parent) + { + } + + public: + Job() = delete; + Job(const Job&) = delete; + Job& operator=(const Job&) = delete; + + ~Job() = default; + + public: + static WPEFramework::Core::ProxyType Create(const WPEFramework::Core::ProxyType& inbound, class Transport* parent); + + void Dispatch() override + { + _parent->Inbound(_inbound); + } + + private: + const WPEFramework::Core::ProxyType _inbound; + class Transport* _parent; + }; + + protected: + static constexpr uint32_t DefaultWaitTime = 10000; + + inline void Announce() { + _channel->Register(*this); + } + + private: + static constexpr const TCHAR* PathPrefix = _T("/"); + public: + Transport() = delete; + Transport(const Transport&) = delete; + Transport& operator=(Transport&) = delete; + Transport(const WPEFramework::Core::URL& url, const uint32_t waitTime) + : _adminLock() + , _connectId(WPEFramework::Core::NodeId(url.Host().Value().c_str(), url.Port().Value())) + , _channel(Channel::Instance(_connectId, ((url.Path().Value().rfind(PathPrefix, 0) == 0) ? url.Path().Value() : string(PathPrefix + url.Path().Value())), url.Query().Value(), true)) + , _eventHandler(nullptr) + , _pendingQueue() + , _scheduledTime(0) + , _waitTime(waitTime) + { + _channel->Register(*this); + } + + virtual ~Transport() + { + _channel->Unregister(*this); + + for (auto& element : _pendingQueue) { + element.second.Abort(element.first); + } + } + + public: + inline bool IsOpen() + { + _channel->IsOpen(); + } + + void Revoke(const string& eventName) + { + _adminLock.Lock(); + _eventMap.erase(eventName); + _adminLock.Unlock(); + } + + void SetEventHandler(IEventHandler* eventHandler) + { + _eventHandler = eventHandler; + } + + template + uint32_t Invoke(const string& method, const PARAMETERS& parameters, RESPONSE& response) + { + Entry slot; + uint32_t id = _channel->Sequence(); + uint32_t result = Send(method, parameters, id); + if (result == WPEFramework::Core::ERROR_NONE) { + result = WaitForResponse(id, response, _waitTime); + } + + return (FireboltErrorValue(result)); + } + + template + uint32_t Subscribe(const string& eventName, const string& parameters, RESPONSE& response) + { + Entry slot; + uint32_t id = _channel->Sequence(); + uint32_t result = Send(eventName, parameters, id); + if (result == WPEFramework::Core::ERROR_NONE) { + _adminLock.Lock(); + _eventMap.emplace(std::piecewise_construct, + std::forward_as_tuple(eventName), + std::forward_as_tuple(~0)); + _adminLock.Unlock(); + + result = WaitForEventResponse(id, eventName, response, _waitTime); + } + + return (FireboltErrorValue(result)); + } + + uint32_t Unsubscribe(const string& eventName, const string& parameters) + { + Revoke(eventName); + Entry slot; + uint32_t id = _channel->Sequence(); + uint32_t result = Send(eventName, parameters, id); + + return (FireboltErrorValue(result)); + } + + private: + friend Channel; + inline bool IsEvent(const uint32_t id, string& eventName) + { + _adminLock.Lock(); + for (auto& event : _eventMap) { + if (event.second == id) { + eventName = event.first; + break; + } + } + _adminLock.Unlock(); + return (eventName.empty() != true); + } + uint64_t Timed() + { + uint64_t result = ~0; + uint64_t currentTime = WPEFramework::Core::Time::Now().Ticks(); + + // Lets see if some callback are expire. If so trigger and remove... + _adminLock.Lock(); + + typename PendingMap::iterator index = _pendingQueue.begin(); + + while (index != _pendingQueue.end()) { + + if (index->second.Expired(index->first, currentTime, result) == true) { + index = _pendingQueue.erase(index); + } + else { + index++; + } + } + _scheduledTime = (result != static_cast(~0) ? result : 0); + + _adminLock.Unlock(); + + return (_scheduledTime); + } + + virtual void Opened() + { + // Nice to know :-) + } + + void Closed() + { + // Abort any in progress RPC command: + _adminLock.Lock(); + + // See if we issued anything, if so abort it.. + while (_pendingQueue.size() != 0) { + + _pendingQueue.begin()->second.Abort(_pendingQueue.begin()->first); + _pendingQueue.erase(_pendingQueue.begin()); + } + + _adminLock.Unlock(); + } + + uint32_t Submit(const WPEFramework::Core::ProxyType& inbound) + { + uint32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(inbound, this)); + WPEFramework::Core::IWorkerPool::Instance().Submit(job); + return result; + } + + uint32_t Inbound(const WPEFramework::Core::ProxyType& inbound) + { + uint32_t result = WPEFramework::Core::ERROR_INVALID_SIGNATURE; + + ASSERT(inbound.IsValid() == true); + + if ((inbound->Id.IsSet() == true) && (inbound->Result.IsSet() || inbound->Error.IsSet())) { + // Looks like this is a response.. + ASSERT(inbound->Parameters.IsSet() == false); + ASSERT(inbound->Designator.IsSet() == false); + + _adminLock.Lock(); + + // See if we issued this.. + typename PendingMap::iterator index = _pendingQueue.find(inbound->Id.Value()); + + if (index != _pendingQueue.end()) { + + if (index->second.Signal(inbound) == true) { + _pendingQueue.erase(index); + } + + result = WPEFramework::Core::ERROR_NONE; + } else { + + string eventName; + if (IsEvent(inbound->Id.Value(), eventName)) { + _eventHandler->Dispatch(eventName, inbound); + } + + } + _adminLock.Unlock(); + } + + return (result); + } + + + template + uint32_t Send(const string& method, const PARAMETERS& parameters, const uint32_t& id) + { + uint32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + + if ((_channel.IsValid() == true) && (_channel->IsSuspended() == true)) { + result = WPEFramework::Core::ERROR_ASYNC_FAILED; + } + else if (_channel.IsValid() == true) { + + result = WPEFramework::Core::ERROR_ASYNC_FAILED; + + WPEFramework::Core::ProxyType message(Channel::Message()); + message->Id = id; + message->Designator = method; + ToMessage(parameters, message); + + _adminLock.Lock(); + + typename std::pair< typename PendingMap::iterator, bool> newElement = + _pendingQueue.emplace(std::piecewise_construct, + std::forward_as_tuple(id), + std::forward_as_tuple()); + ASSERT(newElement.second == true); + + if (newElement.second == true) { + + _adminLock.Unlock(); + + _channel->Submit(WPEFramework::Core::ProxyType(message)); + + message.Release(); + result = WPEFramework::Core::ERROR_NONE; + } + } + return result; + } + + template + uint32_t WaitForResponse(const uint32_t& id, RESPONSE& response, const uint32_t waitTime) + { + uint32_t result = WPEFramework::Core::ERROR_TIMEDOUT; + _adminLock.Lock(); + typename PendingMap::iterator index = _pendingQueue.find(id); + Entry& slot(index->second); + _adminLock.Unlock(); + + if (slot.WaitForResponse(waitTime) == true) { + WPEFramework::Core::ProxyType jsonResponse = slot.Response(); + + // See if we have a jsonResponse, maybe it was just the connection + // that closed? + if (jsonResponse.IsValid() == true) { + if (jsonResponse->Error.IsSet() == true) { + result = jsonResponse->Error.Code.Value(); + } + else { + result = WPEFramework::Core::ERROR_NONE; + if ((jsonResponse->Result.IsSet() == true) + && (jsonResponse->Result.Value().empty() == false)) { + FromMessage((INTERFACE*)&response, *jsonResponse); + } + } + } + } else { + result = WPEFramework::Core::ERROR_TIMEDOUT; + } + _adminLock.Lock(); + _pendingQueue.erase(id); + _adminLock.Unlock(); + return result; + } + + static constexpr uint32_t WAITSLOT_TIME = 100; + template + uint32_t WaitForEventResponse(const uint32_t& id, const string& eventName, RESPONSE& response, const uint32_t waitTime) + { + uint32_t result = WPEFramework::Core::ERROR_TIMEDOUT; + _adminLock.Lock(); + typename PendingMap::iterator index = _pendingQueue.find(id); + Entry& slot(index->second); + _adminLock.Unlock(); + + uint8_t waiting = waitTime; + do { + uint32_t waitSlot = (waiting > WAITSLOT_TIME ? WAITSLOT_TIME : waiting); + if (slot.WaitForResponse(waitSlot) == true) { + WPEFramework::Core::ProxyType jsonResponse = slot.Response(); + + // See if we have a jsonResponse, maybe it was just the connection + // that closed? + if (jsonResponse.IsValid() == true) { + if (jsonResponse->Error.IsSet() == true) { + result = jsonResponse->Error.Code.Value(); + } else { + if ((jsonResponse->Result.IsSet() == true) + && (jsonResponse->Result.Value().empty() == false)) { + result = WPEFramework::Core::ERROR_NONE; + bool enabled; + result = _eventHandler->ValidateResponse(jsonResponse, enabled); + if (result == WPEFramework::Core::ERROR_NONE) { + FromMessage((INTERFACE*)&response, *jsonResponse); + if (enabled) { + _adminLock.Lock(); + typename EventMap::iterator index = _eventMap.find(eventName); + if (index != _eventMap.end()) { + index->second = id; + } + _adminLock.Unlock(); + } + } + } + } + } + } else { + result = WPEFramework::Core::ERROR_TIMEDOUT; + } + waiting -= (waiting == WPEFramework::Core::infinite ? 0 : waitSlot); + } while ((result != WPEFramework::Core::ERROR_NONE) && (waiting > 0 )); + _adminLock.Lock(); + _pendingQueue.erase(id); + _adminLock.Unlock(); + + return result; + } + + public: + void FromMessage(WPEFramework::Core::JSON::IElement* response, const WPEFramework::Core::JSONRPC::Message& message) const + { + response->FromString(message.Result.Value()); + } + + void FromMessage(WPEFramework::Core::JSON::IMessagePack* response, const WPEFramework::Core::JSONRPC::Message& message) const + { + string value = message.Result.Value(); + std::vector result(value.begin(), value.end()); + response->FromBuffer(result); + } + + + private: + + void ToMessage(const string& parameters, WPEFramework::Core::ProxyType& message) const + { + if (parameters.empty() != true) { + message->Parameters = parameters; + } + } + + template + void ToMessage(PARAMETERS& parameters, WPEFramework::Core::ProxyType& message) const + { + ToMessage((INTERFACE*)(¶meters), message); + return; + } + + void ToMessage(WPEFramework::Core::JSON::IMessagePack* parameters, WPEFramework::Core::ProxyType& message) const + { + std::vector values; + parameters->ToBuffer(values); + if (values.empty() != true) { + string strValues(values.begin(), values.end()); + message->Parameters = strValues; + } + return; + } + + void ToMessage(WPEFramework::Core::JSON::IElement* parameters, WPEFramework::Core::ProxyType& message) const + { + string values; + parameters->ToString(values); + if (values.empty() != true) { + message->Parameters = values; + } + return; + } + + uint32_t FireboltErrorValue(const uint32_t error) + { + + uint32_t fireboltError = FireboltSDKErrorUnknown; + switch (error) { + case WPEFramework::Core::ERROR_NONE: + fireboltError = FireboltSDKErrorNone; + break; + case WPEFramework::Core::ERROR_GENERAL: + fireboltError = FireboltSDKErrorGeneral; + break; + case WPEFramework::Core::ERROR_UNAVAILABLE: + fireboltError = FireboltSDKErrorUnavailable; + break; + case WPEFramework::Core::ERROR_TIMEDOUT: + fireboltError = FireboltSDKErrorTimedout; + break; + default: + break; + } + + return fireboltError; + } + + private: + WPEFramework::Core::CriticalSection _adminLock; + WPEFramework::Core::NodeId _connectId; + WPEFramework::Core::ProxyType _channel; + IEventHandler* _eventHandler; + PendingMap _pendingQueue; + EventMap _eventMap; + uint64_t _scheduledTime; + uint32_t _waitTime; + }; +} diff --git a/languages/c/templates/sdk/src/Types.cpp b/languages/c/templates/sdk/src/Types.cpp new file mode 100644 index 00000000..e573c0c9 --- /dev/null +++ b/languages/c/templates/sdk/src/Types.cpp @@ -0,0 +1,41 @@ +/* + * 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 "Module.h" +#include "Types.h" +#include "TypesPriv.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// String Type Handler Interfaces +const char* FireboltTypes_String(FireboltTypes_StringHandle handle) +{ + FireboltSDK::String* str = static_cast(handle); + return (str->Value().c_str()); +} +void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle) +{ + FireboltSDK::String* str = static_cast(handle); + delete str; +} + +#ifdef __cplusplus +} +#endif diff --git a/languages/c/templates/sdk/src/TypesPriv.h b/languages/c/templates/sdk/src/TypesPriv.h new file mode 100644 index 00000000..eda9547f --- /dev/null +++ b/languages/c/templates/sdk/src/TypesPriv.h @@ -0,0 +1,55 @@ +/* + * 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 + +namespace FireboltSDK { +class String { + public: + String() + : _value() + { + } + String(const std::string& value) + : _value(value) + { + } + String(const String& copy) + : _value(copy._value) + { + + } + inline ~String() = default; + String& operator=(const String& RHS) + { + _value = RHS._value; + return (*this); + } + + public: + const std::string& Value() const + { + return _value; + } + + private: + std::string _value; + }; +} diff --git a/languages/c/templates/sdk/src/cmake/CopySymlink.cmake b/languages/c/templates/sdk/src/cmake/CopySymlink.cmake new file mode 100644 index 00000000..8ac3c1f8 --- /dev/null +++ b/languages/c/templates/sdk/src/cmake/CopySymlink.cmake @@ -0,0 +1 @@ +file(COPY "${LIBRARY}" DESTINATION "${DESTINATION}" FOLLOW_SYMLINK_CHAIN) diff --git a/languages/c/templates/sdk/test/CMakeLists.txt b/languages/c/templates/sdk/test/CMakeLists.txt new file mode 100644 index 00000000..a56ca20a --- /dev/null +++ b/languages/c/templates/sdk/test/CMakeLists.txt @@ -0,0 +1,86 @@ +# 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 + +cmake_minimum_required(VERSION 3.3) + +project(FireboltSDKTests) +project_version(1.0.0) + +set(TESTLIB ${PROJECT_NAME}) + +message("Setup ${TESTLIB} v${PROJECT_VERSION}") + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +find_package(${NAMESPACE}Core CONFIG REQUIRED) + +add_library(${TESTLIB} STATIC OpenRPCTests.cpp) + +target_link_libraries(${TESTLIB} + PUBLIC + ${NAMESPACE}Core::${NAMESPACE}Core + ${FIREBOLT_NAMESPACE}SDK +) + +target_include_directories(${TESTLIB} + PRIVATE + $ + $ +) + +set_target_properties(${TESTLIB} PROPERTIES + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED YES + LINK_WHAT_YOU_USE TRUE + FRAMEWORK FALSE +) + +install( + TARGETS ${TESTLIB} EXPORT ${TESTLIB}Targets + LIBRARY DESTINATION lib COMPONENT libs + PUBLIC_HEADER DESTINATION include/${FIREBOLT_NAMESPACE}Test COMPONENT devel # headers for mac (note the different component -> different package) + INCLUDES DESTINATION include/${FIREBOLT_NAMESPACE}Test # headers +) + +InstallCMakeConfig(TARGETS ${TESTLIB}) +InstallCMakeConfigs(TARGET ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallHeaders(TARGET ${TESTLIB} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION FireboltTest) +InstallLibraries(TARGET ${TESTLIB} LIBRARIES ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) + +set(TESTAPP "FireboltSDKTestApp") + +message("Setup ${TESTAPP}") + +add_executable(${TESTAPP} Main.c) + +target_link_libraries(${TESTAPP} + PRIVATE + ${TESTLIB} +) + +target_include_directories(${TESTAPP} + PRIVATE + $ + $ +) + +add_custom_command( + TARGET ${TESTAPP} + POST_BUILD + COMMENT "=================== Installing TestApp ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/bin + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${TESTAPP} ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/bin +) + diff --git a/languages/c/templates/sdk/test/Main.c b/languages/c/templates/sdk/test/Main.c new file mode 100644 index 00000000..7c4c94a5 --- /dev/null +++ b/languages/c/templates/sdk/test/Main.c @@ -0,0 +1,44 @@ +/* + * 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 "OpenRPCCTests.h" + +int __cnt = 0; +int __pass = 0; + +int TotalTests = 0; +int TotalTestsPassed = 0; + +int main() +{ + test_firebolt_create_instance(); + test_firebolt_main(); + + // Calling C function sequences + printf("%s:%s:%d Calling C function tests\n", __FILE__, __func__, __LINE__); + EXECUTE("test_properties_get_device_id", test_properties_get_device_id); + EXECUTE("test_properties_set", test_properties_set); + EXECUTE("test_eventregister_by_providing_callback", test_eventregister_by_providing_callback); + EXECUTE("test_eventregister", test_eventregister); + EXECUTE("test_string_set_get_value", test_string_set_get_value); + + test_firebolt_dispose_instance(); + + printf("TOTAL: %i tests; %i PASSED, %i FAILED\n", TotalTests, TotalTestsPassed, (TotalTests - TotalTestsPassed)); +} + diff --git a/languages/c/templates/sdk/test/Module.cpp b/languages/c/templates/sdk/test/Module.cpp new file mode 100644 index 00000000..d63badc4 --- /dev/null +++ b/languages/c/templates/sdk/test/Module.cpp @@ -0,0 +1,21 @@ +/* + * 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 "Module.h" + +MODULE_NAME_DECLARATION(BUILD_REFERENCE) diff --git a/languages/c/templates/modules/src/Module_Common.cpp b/languages/c/templates/sdk/test/Module.h similarity index 79% rename from languages/c/templates/modules/src/Module_Common.cpp rename to languages/c/templates/sdk/test/Module.h index bce775ff..d5340b68 100644 --- a/languages/c/templates/modules/src/Module_Common.cpp +++ b/languages/c/templates/sdk/test/Module.h @@ -16,16 +16,14 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "FireboltSDK.h" -#include "Common/${info.title}.h" -#include "JsonData_${info.title}.h" -} -#ifdef __cplusplus -extern "C" { +#pragma once + +#ifndef MODULE_NAME +#define MODULE_NAME OpenRPCTestApp #endif - /* ${SCHEMAS}} */ +#include +#include -#ifdef __cplusplus -} -#endif \ No newline at end of file +#undef EXTERNAL +#define EXTERNAL diff --git a/languages/c/templates/sdk/test/OpenRPCCTests.h b/languages/c/templates/sdk/test/OpenRPCCTests.h new file mode 100644 index 00000000..7f2fb59e --- /dev/null +++ b/languages/c/templates/sdk/test/OpenRPCCTests.h @@ -0,0 +1,42 @@ +/* + * 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 + */ + +#ifndef _OPENRPC_C_TESTS_H +#define _OPENRPC_C_TESTS_H + +#include "TestUtils.h" + +#ifdef __cplusplus +extern "C" { +#endif + +uint32_t test_firebolt_create_instance(); +uint32_t test_firebolt_dispose_instance(); + +uint32_t test_firebolt_main(); +uint32_t test_properties_get_device_id(); +uint32_t test_properties_set(); +uint32_t test_eventregister(); +uint32_t test_eventregister_by_providing_callback(); +uint32_t test_string_set_get_value(); + +#ifdef __cplusplus +} +#endif + +#endif // _OPENRPC_C_TESTS_H diff --git a/languages/c/templates/sdk/test/OpenRPCTests.cpp b/languages/c/templates/sdk/test/OpenRPCTests.cpp new file mode 100644 index 00000000..cf9ea5a0 --- /dev/null +++ b/languages/c/templates/sdk/test/OpenRPCTests.cpp @@ -0,0 +1,385 @@ +/* + * 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 "Module.h" +#include "OpenRPCTests.h" +#include "OpenRPCCTests.h" + +namespace WPEFramework { + +ENUM_CONVERSION_BEGIN(::JsonValue::type) + + { JsonValue::type::EMPTY, _TXT("empty") }, + { JsonValue::type::BOOLEAN, _TXT("boolean") }, + { JsonValue::type::NUMBER, _TXT("number") }, + { JsonValue::type::STRING, _TXT("string") }, + +ENUM_CONVERSION_END(::JsonValue::type) + +ENUM_CONVERSION_BEGIN(TestEnum) + { TestEnum::Test1, _TXT("Test1ValueCheck") }, + { TestEnum::Test2, _TXT("Test2ValueCheck") }, + { TestEnum::Test3, _TXT("Test3ValueCheck") }, + { TestEnum::Test4, _TXT("Test4ValueCheck") }, +ENUM_CONVERSION_END(TestEnum) +} +namespace FireboltSDK { + Tests::Tests() + { + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEventWithMultipleCallback"), + std::forward_as_tuple(&SubscribeEventWithMultipleCallback)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEvent"), + std::forward_as_tuple(&SubscribeEvent)); + + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Set UnKnown Method"), + std::forward_as_tuple(&SetUnKnownMethod)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Set LifeCycle Close"), + std::forward_as_tuple(&SetLifeCycleClose)); + + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Get UnKnown Method"), + std::forward_as_tuple(&GetUnKnownMethod)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Get Device Version"), + std::forward_as_tuple(&GetDeviceVersion)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Get Device Id"), + std::forward_as_tuple(&GetDeviceId)); + } + + /* static */ void Tests::PrintJsonObject(const JsonObject::Iterator& iterator) + { + JsonObject::Iterator index = iterator; + while (index.Next() == true) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "Element [%s]: <%s> = \"%s\"\n", + index.Label(), + WPEFramework::Core::EnumerateType(index.Current().Content()).Data(), + index.Current().Value().c_str()); + } + } + + /* static */ uint32_t Tests::GetDeviceId() + { + const string method = _T("device.id"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "DeviceId : %s", response->Value().c_str()); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d\n", method.c_str(), status); + } + + return status; + } + + /*static */ uint32_t Tests::GetDeviceVersion() + { + const string method = _T("device.version"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "DeviceVersion"); + PrintJsonObject(response->Variants()); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d", method.c_str(), status); + } + + return status; + } + + /* static */ uint32_t Tests::GetUnKnownMethod() + { + const string method = _T("get.unknownMethod"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_NE(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d\n", method.c_str(), status); + } + + return status; + } + + /* static */ uint32_t Tests::SetLifeCycleClose() + { + const string method = _T("lifecycle.close"); + JsonObject parameters; + parameters["reason"] = "remoteButton"; + uint32_t status = FireboltSDK::Properties::Set(method, parameters); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d\n", method.c_str(), status); + } + + return status; + } + + /* static */ uint32_t Tests::SetUnKnownMethod() + { + const string method = _T("set.unknownMethod"); + JsonObject parameters; + uint32_t status = FireboltSDK::Properties::Set(method, parameters); + + EXPECT_NE(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", method.c_str(), status); + } + + return status; + } + + static void deviceNameChangeCallback(const void* userData, void* response) + { + WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Received a new event: %s", jsonResponse->Value().c_str()); + jsonResponse.Release(); + FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + eventControl->NotifyEvent(); + } + + /* static */ uint32_t Tests::SubscribeEvent() + { + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + + uint32_t id = 0; + + eventControl->ResetEvent(); + uint32_t status = Properties::Subscribe(eventName, deviceNameChangeCallback, userdata, id); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), + "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered successfully", __func__); + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + EXPECT_EQ(Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + delete eventControl; + + return status; + } + + template + /* static */ uint32_t Tests::SubscribeEventForC(const string& eventName, CALLBACK& callbackFunc, const void* userdata, uint32_t& id) + { + return Properties::Subscribe(eventName, callbackFunc, userdata, id);; + } + + static void deviceNameChangeMultipleCallback(const void* userData, void* response) + { + WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "Received a new event from deviceNameChangeMultipleCallback: %s", jsonResponse->Value().c_str()); + jsonResponse.Release(); + FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + eventControl->NotifyEvent(); + } + + /* static */ uint32_t Tests::SubscribeEventWithMultipleCallback() + { + FireboltSDK::Tests::EventControl* eventControl1 = new FireboltSDK::Tests::EventControl(); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl1); + uint32_t id1 = 0, id2 = 0; + + eventControl1->ResetEvent(); + uint32_t status = Properties::Subscribe(eventName, deviceNameChangeCallback, userdata, id1); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), + "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered successfully", __func__); + } + + if (status == FireboltSDKErrorNone) { + FireboltSDK::Tests::EventControl* eventControl2 = new FireboltSDK::Tests::EventControl(); + userdata = static_cast(eventControl2); + + status = Properties::Subscribe(eventName, deviceNameChangeMultipleCallback, userdata, id2); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered second callback also successfully", __func__); + eventControl1->WaitForEvent(WPEFramework::Core::infinite); + eventControl2->WaitForEvent(WPEFramework::Core::infinite); + } + EXPECT_EQ(Properties::Unsubscribe(eventName, id1), FireboltSDKErrorNone); + delete eventControl2; + } + EXPECT_EQ(Properties::Unsubscribe(eventName, id2), FireboltSDKErrorNone); + + delete eventControl1; + return status; + } + +} + +#ifdef __cplusplus +extern "C" { +#endif + +uint32_t test_firebolt_create_instance() +{ + FireboltSDK::Accessor::Instance(); +} + +uint32_t test_firebolt_dispose_instance() +{ + FireboltSDK::Accessor::Dispose(); +} + +uint32_t test_firebolt_main() +{ + return FireboltSDK::Tests::Main(); +} + +uint32_t test_properties_get_device_id() +{ + const string method = _T("device.id"); + WPEFramework::Core::ProxyType response; + uint32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "DeviceId : %s", response->Value().c_str()); + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "Get %s status = %d", method.c_str(), status); + } + + return status; +} + +uint32_t test_properties_set() +{ + const string method = _T("lifecycle.close"); + JsonObject parameters; + parameters["reason"] = "remoteButton"; + uint32_t status = FireboltSDK::Properties::Set(method, parameters); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "Set %s status = %d", method.c_str(), status); + } + + return status; +} + +static void deviceNameChangeCallbackForC(const void* userData, void* response) +{ + WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "Received a new event--->: %s", jsonResponse->Value().c_str()); + jsonResponse.Release(); + + FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + eventControl->NotifyEvent(); +} + +uint32_t test_eventregister() +{ + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + JsonObject parameters; + + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + uint32_t id = 0; + + eventControl->ResetEvent(); + uint32_t status = FireboltSDK::Properties::Subscribe(eventName, deviceNameChangeCallbackForC, userdata, id); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Set %s status = %d", __func__, eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes registered successfully", __func__); + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + delete eventControl; + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + + return status; +} + +uint32_t test_eventregister_by_providing_callback() +{ + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + uint32_t id = 0; + + eventControl->ResetEvent(); + uint32_t status = FireboltSDK::Tests::SubscribeEventForC(eventName, deviceNameChangeCallbackForC, userdata, id); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Set %s status = %d", __func__, eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes registered successfully", __func__); + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + delete eventControl; + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); +} + +#include "TypesPriv.h" +uint32_t test_string_set_get_value() +{ + uint32_t status = FireboltSDKErrorNone; + FireboltSDK::String* str = new FireboltSDK::String("testString"); + void* handle = static_cast(str); + + const char* value = FireboltTypes_String(handle); + EXPECT_EQ(strncmp(value, str->Value().c_str(), str->Value().length()), 0); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + " ---> type name = %s %s", str->Value().c_str(), value); + + WPEFramework::Core::JSON::EnumType<::TestEnum> testEnum = Test4; + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + " EnumTest = %d %s", testEnum.Value(), testEnum.Data()); + FireboltTypes_StringHandle_Release(handle); + return status; +} + +#ifdef __cplusplus +} +#endif diff --git a/languages/c/templates/sdk/test/OpenRPCTests.h b/languages/c/templates/sdk/test/OpenRPCTests.h new file mode 100644 index 00000000..00abd364 --- /dev/null +++ b/languages/c/templates/sdk/test/OpenRPCTests.h @@ -0,0 +1,99 @@ +/* + * 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 "TestUtils.h" +#include "Firebolt.h" + +namespace FireboltSDK { + typedef uint32_t (*Func)(); + + class Tests { + public: + class EventControl { + public: + EventControl() + : _event(false, true) + { + } + ~EventControl() = default; + + public: + void NotifyEvent() + { + _event.SetEvent(); + } + uint32_t WaitForEvent(uint32_t waitTime) + { + return _event.Lock(waitTime); + } + void ResetEvent() + { + _event.ResetEvent(); + } + private: + WPEFramework::Core::Event _event; + }; + + private: + typedef std::unordered_map TestFunctionMap; + + public: + Tests(); + virtual ~Tests() = default; + + inline TestFunctionMap& TestList() + { + return _functionMap; + } + + template + static uint32_t Main() + { + TESTS fireboltTest; + for (auto i = fireboltTest.TestList().begin(); i != fireboltTest.TestList().end(); i++) { + EXECUTE(i->first.c_str(), i->second); + } + + printf("TOTAL: %i tests; %i PASSED, %i FAILED\n", TotalTests, TotalTestsPassed, (TotalTests - TotalTestsPassed)); + + return 0; + } + + static uint32_t GetDeviceId(); + static uint32_t GetDeviceVersion(); + static uint32_t GetUnKnownMethod(); + + static uint32_t SetLifeCycleClose(); + static uint32_t SetUnKnownMethod(); + + static uint32_t SubscribeEvent(); + static uint32_t SubscribeEventWithMultipleCallback(); + + template + static uint32_t SubscribeEventForC(const string& eventName, CALLBACK& callbackFunc, const void* userdata, uint32_t& id); + + protected: + static void PrintJsonObject(const JsonObject::Iterator& iterator); + + protected: + std::list menu; + TestFunctionMap _functionMap; + }; +} diff --git a/languages/c/templates/sdk/test/TestUtils.h b/languages/c/templates/sdk/test/TestUtils.h new file mode 100644 index 00000000..8c3cb732 --- /dev/null +++ b/languages/c/templates/sdk/test/TestUtils.h @@ -0,0 +1,38 @@ +#ifndef _TEST_UTILS_H +#define _TEST_UTILS_H + +#include +#include +#include + +#define MAX(x, y) (((x) > (y)) ? (x) : (y)) +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) + +#define _RESULT(expr, exprorig, result) if (expr) { printf(" SUCCESS: %s\n", #exprorig); __pass++; } else printf(" FAILED: %s, actual: %u\n", #exprorig, result) +#define _EVAL(result, expected, op) do { __cnt++; uint32_t resval = ((uint32_t)(result)); uint32_t expval = ((uint32_t)(expected)); _RESULT(resval op expval, result op expected, resval); } while(0) +#define _HEAD(name) printf("\n======== %s\n", name); __cnt = 0; __pass = 0 +#define _FOOT(name) printf("\n======== %s - %i PASSED, %i FAILED\n", name, __pass, (__cnt - __pass)); TotalTests += __cnt; TotalTestsPassed += __pass; + +#define EXECUTE(name, test) do { _HEAD(name); test(); _FOOT(name); printf("\n"); } while(0) +#define EXPECT_EQ(result, expected) _EVAL(result, expected, ==) +#define EXPECT_NE(result, expected) _EVAL(result, expected, !=) +#define EXPECT_LT(result, expected) _EVAL(result, expected, <) +#define EXPECT_LE(result, expected) _EVAL(result, expected, <=) +#define EXPECT_GT(result, expected) _EVAL(result, expected, >) +#define EXPECT_GE(result, expected) _EVAL(result, expected, >=) + +#ifdef __cplusplus +extern "C" { +#endif + +extern int __cnt; +extern int __pass; + +extern int TotalTests ; +extern int TotalTestsPassed; + +#ifdef __cplusplus +} +#endif + +#endif // _TEST_UTILS_H diff --git a/languages/c/templates/sections/accessors.c b/languages/c/templates/sections/accessors.c new file mode 100644 index 00000000..0586b2a5 --- /dev/null +++ b/languages/c/templates/sections/accessors.c @@ -0,0 +1,3 @@ +// Accessors + +${schema.list} diff --git a/languages/c/templates/sections/declarations.js b/languages/c/templates/sections/declarations.c similarity index 100% rename from languages/c/templates/sections/declarations.js rename to languages/c/templates/sections/declarations.c diff --git a/languages/c/templates/sections/events.js b/languages/c/templates/sections/events.c similarity index 100% rename from languages/c/templates/sections/events.js rename to languages/c/templates/sections/events.c diff --git a/languages/c/templates/sections/methods.js b/languages/c/templates/sections/methods.c similarity index 100% rename from languages/c/templates/sections/methods.js rename to languages/c/templates/sections/methods.c diff --git a/languages/c/templates/sections/provider-interfaces.js b/languages/c/templates/sections/provider-interfaces.c similarity index 100% rename from languages/c/templates/sections/provider-interfaces.js rename to languages/c/templates/sections/provider-interfaces.c diff --git a/languages/c/templates/sections/schemas.c b/languages/c/templates/sections/schemas.c new file mode 100644 index 00000000..a1847009 --- /dev/null +++ b/languages/c/templates/sections/schemas.c @@ -0,0 +1,3 @@ +// Types & Enums + +${schema.list} diff --git a/languages/c/templates/sections/schemas.js b/languages/c/templates/sections/types.c similarity index 100% rename from languages/c/templates/sections/schemas.js rename to languages/c/templates/sections/types.c diff --git a/languages/c/templates/types/enum.c b/languages/c/templates/types/enum.c new file mode 100644 index 00000000..2a8e94d7 --- /dev/null +++ b/languages/c/templates/types/enum.c @@ -0,0 +1,3 @@ +typedef enum { + ${info.TITLE}_${NAME}_${key}, +} ${info.title}_${name}; diff --git a/languages/c/templates/types/enum.mjs b/languages/c/templates/types/enum.mjs deleted file mode 100644 index 907fb37d..00000000 --- a/languages/c/templates/types/enum.mjs +++ /dev/null @@ -1,3 +0,0 @@ -${name}: { - ${key}: '${value}', -}, diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 65156709..5c51b23e 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -60,7 +60,8 @@ let config = { } const state = { - destination: undefined + destination: undefined, + section: undefined } const setTyper = (t) => { @@ -106,7 +107,7 @@ const getLinkForSchema = (schema, json) => { schema = schema.schema } - const type = types.getSchemaType(schema, json, { destination: state.destination }) + const type = types.getSchemaType(schema, json, { 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]) { @@ -337,8 +338,12 @@ const generateMacros = (obj, templates, languages, options = {}) => { 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 schemasArray = generateSchemas(obj, templates, { baseUrl: '' }).filter(s => (options.copySchemasIntoModules || !s.uri)) + const schemasArray = generateSchemas(obj, templates, { baseUrl: '', section: 'schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) + const accessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).join('\n')) : '' + const typesArray = schemasArray.filter(x => !x.enum) + const types = typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).join('\n')) : '' + const accessors = accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).join('\n')) : '' const module = getTemplate('/codeblocks/module', templates) const macros = { @@ -350,10 +355,12 @@ const generateMacros = (obj, templates, languages, options = {}) => { eventsEnum, methods, methodList, + accessors, declarations, defaults, examples, schemas, + types, providerInterfaces, version: getSemanticVersion(obj), title: obj.info.title, @@ -385,12 +392,14 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{module.list\}/g, macros.module) fContents = fContents.replace(/[ \t]*\/\* \$\{METHODS\} \*\/[ \t]*\n/, macros.methods) + fContents = fContents.replace(/[ \t]*\/\* \$\{ACCESSORS\} \*\/[ \t]*\n/, macros.accessors) fContents = fContents.replace(/[ \t]*\/\* \$\{DECLARATIONS\} \*\/[ \t]*\n/, macros.declarations) 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) fContents = fContents.replace(/[ \t]*\/\* \$\{SCHEMAS\} \*\/[ \t]*\n/, macros.schemas) + fContents = fContents.replace(/[ \t]*\/\* \$\{TYPES\} \*\/[ \t]*\n/, macros.types) fContents = fContents.replace(/[ \t]*\/\* \$\{PROVIDERS\} \*\/[ \t]*\n/, macros.providerInterfaces) fContents = fContents.replace(/[ \t]*\/\* \$\{ENUMS\} \*\/[ \t]*\n/, macros.enums) fContents = fContents.replace(/[ \t]*\/\* \$\{IMPORTS\} \*\/[ \t]*\n/, macros.imports) @@ -402,6 +411,7 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{minor\}/g, macros.version.minor) fContents = fContents.replace(/\$\{patch\}/g, macros.version.patch) fContents = fContents.replace(/\$\{info\.title\}/g, macros.title) + fContents = fContents.replace(/\$\{info\.TITLE\}/g, macros.title.toUpperCase()) fContents = fContents.replace(/\$\{info\.description\}/g, macros.description) fContents = fContents.replace(/\$\{info\.version\}/g, macros.version.readable) @@ -492,11 +502,12 @@ const generateEnums = (json, templates) => { if (template[i].indexOf('${key}') >= 0) { template[i] = schema.enum.map(value => { const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() - return template[i].replace(/\$\{key\}/g, safeName).replace(/\$\{value\}/g, value) + return template[i].replace(/\$\{key\}/g, safeName) + .replace(/\$\{value\}/g, value) }).join('\n') } } - return template.join('\n').replace(/\$\{name\}/g, schema.title) + return template.join('\n').replace(/\$\{name\}/g, schema.title).replace(/\$\{NAME\}/g, schema.title.toUpperCase()) })), map(enumFinder), getSchemas @@ -581,7 +592,7 @@ function generateSchemas(json, templates, options) { else { content = content.replace(/\$\{if\.description\}(.*?)\{end\.if\.description\}/gms, '$1') } - const schemaShape = types.getSchemaShape(schema, json, { name, destination: state.destination }) + const schemaShape = types.getSchemaShape(schema, json, { name, destination: state.destination, section: options.section }) content = content .replace(/\$\{schema.title\}/, (schema.title || name)) @@ -600,13 +611,17 @@ function generateSchemas(json, templates, options) { content = content.replace(/.*\$\{schema.seeAlso\}/, '') } + const isEnum = x => x.type === 'string' && Array.isArray(x.enum) && x.title + const result = uri ? { uri: uri, name: schema.title || name, - body: content + body: content, + enum: isEnum(schema) } : { name: schema.title || name, - body: content + body: content, + enum: isEnum(schema) } results.push(result) @@ -643,7 +658,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, { destination: state.destination }) + '](' + getLinkForSchema(schema, json, true) + ')') // need full module here, not just the schema + .map(schema => '[' + types.getSchemaType(schema, json, { destination: state.destination, section: state.section }) + '](' + getLinkForSchema(schema, json, true) + ')') // need full module here, not just the schema .filter(link => link) .join('\n') @@ -681,6 +696,12 @@ const generateImports = (json, templates) => { imports += getTemplate('/imports/x-method', templates) } + + + if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0) { + imports += Object.keys(json['x-schemas']).map(shared => getTemplate('/imports/default', templates).replace(/\$\{info.title\}/g, shared)).join('\n') + } + return imports } @@ -921,13 +942,13 @@ function insertMethodMacros(template, methodObj, json, templates, 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 - const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination }) - const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination }) - const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination }) : '' + const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) + const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) + const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' let seeAlso = '' - if (isPolymorphicPullMethod(methodObj)) { + if (isPolymorphicPullMethod(methodObj) && pullsForType) { seeAlso = `See also: [${pullsForType}](#${pullsForType.toLowerCase()}-1)` // this assumes the schema will be after the method... } else if (methodObj.tags.find(t => t.name === 'polymorphic-pull')) { @@ -938,7 +959,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { if (isTemporalSetMethod(methodObj)) { itemName = result.schema.items.title || 'item' itemName = itemName.charAt(0).toLowerCase() + itemName.substring(1) - itemType = types.getSchemaType(result.schema.items, json, { destination: state.destination }) + itemType = types.getSchemaType(result.schema.items, json, { destination: state.destination, section: state.section }) } template = insertExampleMacros(template, examples[methodObj.name] || [], methodObj, json, templates) @@ -958,8 +979,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/gms, method.params.length ? '$1' : '') .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event.params.length ? '$1' : '') // Typed signature stuff - .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination })) - .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination })) + .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) + .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(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) @@ -968,7 +989,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{event\.name\}/g, method.name.toLowerCase()[2] + method.name.substr(3)) .replace(/\$\{event\.params\}/g, eventParams) .replace(/\$\{event\.params\.table\.rows\}/g, eventParamsRows) - .replace(/\$\{event\.signature\.params\}/g, types.getMethodSignatureParams(event, json, { destination: state.destination })) + .replace(/\$\{event\.signature\.params\}/g, types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section })) .replace(/\$\{info\.title\}/g, info.title) .replace(/\$\{info\.TITLE\}/g, info.title.toUpperCase()) .replace(/\$\{method\.property\.immutable\}/g, hasTag(methodObj, 'property:immutable')) @@ -1114,7 +1135,7 @@ function insertExampleMacros(template, examples, method, json, templates) { } function generateResult(result, json, templates) { - const type = types.getSchemaType(result, json, { destination: state.destination }) + const type = types.getSchemaType(result, json, { destination: state.destination, section: state.section }) if (result.type === 'object' && result.properties) { let content = getTemplate('/types/object', templates).split('\n') @@ -1135,7 +1156,7 @@ function generateResult(result, json, templates) { // if we get a real link use it if (link !== '#') { - return `[${types.getSchemaType(result, json, { destination: state.destination })}](${link})` + return `[${types.getSchemaType(result, json, { destination: state.destination, section: state.section })}](${link})` } // otherwise this was a schema with no title, and we'll just copy it here else { @@ -1151,7 +1172,7 @@ function generateResult(result, json, templates) { function insertSchemaMacros(template, title, schema, module) { return template.replace(/\$\{property\}/g, title) - .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { destination: state.destination, code: false })) + .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { destination: state.destination, section: state.section, code: false })) .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module)) .replace(/\$\{description\}/g, schema.description || '') .replace(/\$\{name\}/g, title || '') @@ -1162,9 +1183,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, { destination: state.destination, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl + let type = types.getSchemaType(param.schema, module, { destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl let typeLink = getLinkForSchema(param, module) - let jsonType = types.getJsonType(param.schema, module, { destination: state.destination, code: false, link: false, title: true, asPath: false, expandEnums: false }) + let jsonType = types.getJsonType(param.schema, module, { destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) if (constraints && type) { constraints = '
' + constraints @@ -1213,7 +1234,7 @@ function generateProviderInterfaces(json, templates) { } function insertProviderInterfaceMacros(template, capability, moduleJson = {}, templates) { - const iface = getProviderInterface(capability, moduleJson, { destination: state.destination })//.map(method => { method.name = method.name.charAt(9).toLowerCase() + method.name.substr(10); return method } ) + const iface = getProviderInterface(capability, moduleJson, { destination: state.destination, section: state.section })//.map(method => { method.name = method.name.charAt(9).toLowerCase() + method.name.substr(10); return method } ) const capitalize = str => str[0].toUpperCase() + str.substr(1) const uglyName = capability.split(":").slice(-2).map(capitalize).reverse().join('') + "Provider" @@ -1227,7 +1248,7 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te interfaceShape = interfaceShape.replace(/\$\{name\}/g, name) .replace(/\$\{capability\}/g, capability) - .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => `\t${types.getMethodSignature(method, moduleJson, { destination: state.destination, isInterface: true })}`).join('\n') + '\n') + .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => `\t${types.getMethodSignature(method, moduleJson, { destination: state.destination, section: state.section, isInterface: true })}`).join('\n') + '\n') if (iface.length === 0) { template = template.replace(/\$\{provider\.methods\}/gms, '') @@ -1246,7 +1267,7 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te name: 'provider' }) const parametersSchema = method.params[0].schema - const parametersShape = types.getSchemaShape(parametersSchema, moduleJson, { destination: state.destination }) + const parametersShape = types.getSchemaShape(parametersSchema, moduleJson, { destination: state.destination, section: state.section }) let methodBlock = insertMethodMacros(getTemplateForMethod(method, templates), method, moduleJson, templates) methodBlock = methodBlock.replace(/\${parameters\.shape\}/g, parametersShape) const hasProviderParameters = parametersSchema && parametersSchema.properties && Object.keys(parametersSchema.properties).length > 0 @@ -1338,7 +1359,7 @@ function insertProviderParameterMacros(data = '', parameters, module = {}, optio Object.entries(parameters.properties).forEach(([name, param]) => { let constraints = getSchemaConstraints(param, module) - let type = types.getSchemaType(param, module, { destination: state.destination, code: true, link: true, title: true, asPath: options.asPath, baseUrl: options.baseUrl }) + let type = types.getSchemaType(param, module, { destination: state.destination, section: state.section, code: true, link: true, title: true, asPath: options.asPath, baseUrl: options.baseUrl }) if (constraints && type) { constraints = '
' + constraints From 3700c99a7a21c91a9e682064f926af1844c10aee Mon Sep 17 00:00:00 2001 From: sramani-metro <71630728+sramani-metro@users.noreply.github.com> Date: Tue, 23 May 2023 12:33:26 +0530 Subject: [PATCH 071/137] fix: Sort the macrofied schemas based on schema refs (#90) * fix: Sort the macrofied schemas based on schema refs * fix: Sort the schemas before macrofying * fix: Handle the schemas part --- languages/c/templates/modules/src/Module.cpp | 15 ++++++++-- src/macrofier/engine.mjs | 29 ++++++++++++-------- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 0783b416..b5522fd6 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -22,16 +22,25 @@ /* ${IMPORTS} */ +namespace FireboltSDK { + namespace ${info.title} { + + /* ${TYPES} */ + + } +} + #ifdef __cplusplus extern "C" { #endif -/* ${TYPES} */ +/* ${ACCESSORS} */ +/* ${METHODS} */ + #ifdef __cplusplus } #endif -/* ${ACCESSORS} */ -/* ${METHODS} */ + diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 5c51b23e..f236954a 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -31,7 +31,7 @@ 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 isEmpty from 'crocks/core/isEmpty.js' -import { getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies } from '../shared/json-schema.mjs' +import { getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies, isDefinitionReferencedBySchema } from '../shared/json-schema.mjs' // util for visually debugging crocks ADTs const _inspector = obj => { @@ -566,6 +566,8 @@ function generateDefaults(json = {}, templates) { return reducer(json) } +const isEnum = x => x.type && x.type === 'string' && Array.isArray(x.enum) && x.title + function generateSchemas(json, templates, options) { let results = [] @@ -611,8 +613,6 @@ function generateSchemas(json, templates, options) { content = content.replace(/.*\$\{schema.seeAlso\}/, '') } - const isEnum = x => x.type === 'string' && Array.isArray(x.enum) && x.title - const result = uri ? { uri: uri, name: schema.title || name, @@ -627,21 +627,28 @@ function generateSchemas(json, templates, options) { results.push(result) } + const list = [] + // schemas may be 1 or 2 levels deeps Object.entries(schemas).forEach( ([name, schema]) => { if (isSchema(schema)) { - generate(name, schema) + list.push([name, schema]) } - else if (typeof schema === 'object') { - const uri = schema.uri - Object.entries(schema).forEach( ([name, schema]) => { - if (name !== 'uri') { - generate(name, schema, uri) - } - }) + }) + + list.sort((a, b) => { + const aInB = isDefinitionReferencedBySchema('#/components/schemas/' + a[0], b[1]) + const bInA = isDefinitionReferencedBySchema('#/components/schemas/' + b[0], a[1]) + if(isEnum(a[1]) || (aInB && !bInA)) { + return -1 + } else if(isEnum(b[1]) || (!aInB && bInA)) { + return 1 } + return 0; }) + list.forEach(item => generate(...item)) + return results } From 56c6278b0b0ec6706c70ef1e719ba392ed8944a5 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 1 Jun 2023 20:08:21 +0530 Subject: [PATCH 072/137] Enum fixes (#93) Enum fixes : 1. missing description added 2. alignment fixes 3. implementation added for enum inside properties 4. Enum to String value Conversion logic added for C --- languages/c/src/types/JSONHelpers.mjs | 31 +------ languages/c/templates/declarations/default.c | 9 +- .../declarations/polymorphic-reducer.c | 11 ++- .../templates/modules/include/Common/Module.h | 10 +- .../c/templates/modules/include/Module.h | 15 ++- languages/c/templates/modules/src/Module.cpp | 6 +- languages/c/templates/schemas/default.c | 7 +- .../templates/schemas/include/Common/Module.h | 10 +- .../c/templates/schemas/src/JsonData_Module.h | 6 +- .../c/templates/schemas/src/Module_Common.cpp | 3 +- languages/c/templates/sections/enum.cpp | 5 + languages/c/templates/sections/schemas.c | 2 - languages/c/templates/sections/types.c | 2 - languages/c/templates/types/enum.cpp | 4 + .../c/templates/types/{enum.c => enum.h} | 1 + src/macrofier/engine.mjs | 92 ++++++++++++++----- 16 files changed, 125 insertions(+), 89 deletions(-) create mode 100644 languages/c/templates/sections/enum.cpp create mode 100644 languages/c/templates/types/enum.cpp rename languages/c/templates/types/{enum.c => enum.h} (71%) diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index 25d1ad3b..97a9385a 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -27,35 +27,6 @@ function getJsonContainerDefinition (name, props) { return c } -/* - -ENUM_CONVERSION_BEGIN(Advertising_SkipRestriction) - { ADVERTISING_SKIPRESTRICTION_NONE, _T("none") }, - { ADVERTISING_SKIPRESTRICTION_ADS_UNWATCHED, _T("adsUnwatched") }, - { ADVERTISING_SKIPRESTRICTION_ADS_ALL, _T("adsAll") }, - { ADVERTISING_SKIPRESTRICTION_ALL, _T("all") }, -ENUM_CONVERSION_END(Advertising_SkipRestriction) - - -*/ - -// TODO - this should be a global function in the main /src/ directory... not part of a language pack -const keyName = val => val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() - -function getJsonEnumConversion(schema, module, { name }) { - name = capitalize(schema.title || name) - let e = `ENUM_CONVERSION_BEGIN(${module.info.title}_${name})\n` - - schema.enum.forEach(value => { - e += `{ ${module.info.title.toUpperCase()}_${name.toUpperCase()}_${keyName(value)}, _T("${value}") },` - }) - - e += `ENUM_CONVERSION_END(${module.info.title}_${name})` - - return e -} - export { - getJsonContainerDefinition, - getJsonEnumConversion + getJsonContainerDefinition } diff --git a/languages/c/templates/declarations/default.c b/languages/c/templates/declarations/default.c index 72fbf14f..be0b1e14 100644 --- a/languages/c/templates/declarations/default.c +++ b/languages/c/templates/declarations/default.c @@ -1,4 +1,5 @@ - /** - * ${method.summary} - ${method.params} */ - ${method.signature}; +/* + * ${method.summary} + * ${method.params} + */ +${method.signature}; diff --git a/languages/c/templates/declarations/polymorphic-reducer.c b/languages/c/templates/declarations/polymorphic-reducer.c index 979832b2..cf974e1a 100644 --- a/languages/c/templates/declarations/polymorphic-reducer.c +++ b/languages/c/templates/declarations/polymorphic-reducer.c @@ -1,6 +1,7 @@ - /** - * ${method.summary} - ${method.params} */ - ${method.signature} +/* + * ${method.summary} + * ${method.params} + */ +${method.signature} -// TODO: generate reducer signature \ No newline at end of file +// TODO: generate reducer signature diff --git a/languages/c/templates/modules/include/Common/Module.h b/languages/c/templates/modules/include/Common/Module.h index 2834b997..809418a2 100644 --- a/languages/c/templates/modules/include/Common/Module.h +++ b/languages/c/templates/modules/include/Common/Module.h @@ -25,16 +25,16 @@ extern "C" { #endif - // Enums +// Enums - /* ${ENUMS}} */ +/* ${ENUMS} */ - // Schemas +// Schemas - /* ${SCHEMAS} */ +/* ${SCHEMAS} */ #ifdef __cplusplus } #endif -#endif // Header Include Guard \ No newline at end of file +#endif // Header Include Guard diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h index e24c869f..ee034605 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/Module.h @@ -26,13 +26,20 @@ extern "C" { #endif - /* ${SCHEMAS} */ +// Enums - /* ${ACCESSORS} */ - /* ${DECLARATIONS} */ +/* ${ENUMS} */ + +// Types + +/* ${TYPES} */ + +/* ${ACCESSORS} */ + +/* ${DECLARATIONS} */ #ifdef __cplusplus } #endif -#endif // Header Include Guard \ No newline at end of file +#endif // Header Include Guard diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index b5522fd6..346d07cd 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -24,12 +24,13 @@ namespace FireboltSDK { namespace ${info.title} { + // Types - /* ${TYPES} */ - + /* ${TYPES} */ } } +/* ${ENUMS} */ #ifdef __cplusplus extern "C" { @@ -38,7 +39,6 @@ extern "C" { /* ${ACCESSORS} */ /* ${METHODS} */ - #ifdef __cplusplus } #endif diff --git a/languages/c/templates/schemas/default.c b/languages/c/templates/schemas/default.c index bc9ab873..a2058da5 100644 --- a/languages/c/templates/schemas/default.c +++ b/languages/c/templates/schemas/default.c @@ -1,5 +1,4 @@ - /** - * ${schema.description} - */ - +/* + * ${schema.description} + */ ${schema.shape} diff --git a/languages/c/templates/schemas/include/Common/Module.h b/languages/c/templates/schemas/include/Common/Module.h index 50ef1fd9..0326c220 100644 --- a/languages/c/templates/schemas/include/Common/Module.h +++ b/languages/c/templates/schemas/include/Common/Module.h @@ -25,16 +25,14 @@ extern "C" { #endif - // Enums +// Enums - /* ${ENUMS} */ +/* ${ENUMS} */ - // Types - - /* ${TYPES} */ +/* ${TYPES} */ #ifdef __cplusplus } #endif -#endif // Header Include Guard \ No newline at end of file +#endif // Header Include Guard diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/JsonData_Module.h index 4cee1781..9ba90428 100644 --- a/languages/c/templates/schemas/src/JsonData_Module.h +++ b/languages/c/templates/schemas/src/JsonData_Module.h @@ -17,7 +17,9 @@ */ namespace FireboltSDK { + namespace ${info.title} { + // Types - /* ${DECLARATIONS} */ - + /* ${SCHEMAS}*/ + } } diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/Module_Common.cpp index 632f38d6..9dc2ee0a 100644 --- a/languages/c/templates/schemas/src/Module_Common.cpp +++ b/languages/c/templates/schemas/src/Module_Common.cpp @@ -21,11 +21,12 @@ #include "Common/${info.title}.h" #include "JsonData_${info.title}.h" +/* ${ENUMS} */ + #ifdef __cplusplus extern "C" { #endif - /* ${TYPES} */ /* ${ACCESSORS} */ /* ${METHODS} */ diff --git a/languages/c/templates/sections/enum.cpp b/languages/c/templates/sections/enum.cpp new file mode 100644 index 00000000..e5165c61 --- /dev/null +++ b/languages/c/templates/sections/enum.cpp @@ -0,0 +1,5 @@ +namespace WPEFramework { + +${schema.list} + +} diff --git a/languages/c/templates/sections/schemas.c b/languages/c/templates/sections/schemas.c index a1847009..9295133c 100644 --- a/languages/c/templates/sections/schemas.c +++ b/languages/c/templates/sections/schemas.c @@ -1,3 +1 @@ -// Types & Enums - ${schema.list} diff --git a/languages/c/templates/sections/types.c b/languages/c/templates/sections/types.c index a2d20dbb..9295133c 100644 --- a/languages/c/templates/sections/types.c +++ b/languages/c/templates/sections/types.c @@ -1,3 +1 @@ -// Types - ${schema.list} diff --git a/languages/c/templates/types/enum.cpp b/languages/c/templates/types/enum.cpp new file mode 100644 index 00000000..ddda2ae9 --- /dev/null +++ b/languages/c/templates/types/enum.cpp @@ -0,0 +1,4 @@ + /* ${title} ${description} */ + ENUM_CONVERSION_BEGIN(${info.title}_${name}) + { ${info.TITLE}_${NAME}_${key}, _T("${value}") }, + ENUM_CONVERSION_END(${info.title}_${name}) diff --git a/languages/c/templates/types/enum.c b/languages/c/templates/types/enum.h similarity index 71% rename from languages/c/templates/types/enum.c rename to languages/c/templates/types/enum.h index 2a8e94d7..6926fa77 100644 --- a/languages/c/templates/types/enum.c +++ b/languages/c/templates/types/enum.h @@ -1,3 +1,4 @@ +/* ${title} ${description} */ typedef enum { ${info.TITLE}_${NAME}_${key}, } ${info.title}_${name}; diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index f236954a..f7873abb 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -64,6 +64,8 @@ const state = { section: undefined } +const capitalize = str => str[0].toUpperCase() + str.substr(1) + const setTyper = (t) => { types = t } @@ -73,7 +75,7 @@ const setConfig = (c) => { } const getTemplate = (name, templates) => { - return templates[Object.keys(templates).find(k => k.startsWith(name + '.'))] || '' + return templates[Object.keys(templates).find(k => k === name)] || templates[Object.keys(templates).find(k => k.startsWith(name + '.'))] || '' } const getTemplateTypeForMethod = (method, type, templates) => { @@ -322,7 +324,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { const imports = generateImports(obj, templates) const initialization = generateInitialization(obj, templates) - const enums = generateEnums(obj, templates) + const enums = generateEnums(obj, templates, { destination : (options.destination ? options.destination : '') }) const eventsEnum = generateEvents(obj, templates) const examples = generateExamples(obj, templates, languages) @@ -486,29 +488,80 @@ function insertTableofContents(content) { return content } +const isEnumType = x => x.type !== 'undefined' && x.type === 'string' && Array.isArray(x.enum) + +const getProperties = x => { + return Array.isArray(x.properties) ? x.properties[0] : x.properties +} + +const isEnumProperties = schema => compose( + getProperties, + filter(enm => enm), + map(filter(enm => enm)), + map(props => props.map(([k, v]) => ((v.type === 'object') ? isEnumProperties(v) : ((v.type === 'array') ? isEnumType(v.items[0] ? v.items[0] : v.items): isEnumType(v))))), + map(Object.entries), + filter(schema => isObject(schema)) +)(schema) + +const getEnumProperties = schema => compose( + getProperties, + filter(enm => enm), + map(filter(isEnumType)), + map(props => props.map(([k, v]) => { + let enm = v + if (isEnumType(v) == true) { + enm = Object.assign({}, v) + enm.title = k + } else if (v.type === 'object') { + enm = getEnumProperties(v) + } else if (v.type === 'array') { + enm = Object.assign({}, (v.items[0] ? v.items[0] : v.items)) + enm.title = k + } + return enm + })), + map(Object.entries), + filter(schema => isObject(schema)) +)(schema) + +const convertEnumTemplate = (sch, templateName, templates) => { + const template = getTemplate(templateName, templates).split('\n') + let schema = isEnumType(sch) ? sch : getEnumProperties(sch) + for (var i = 0; i < template.length; i++) { + if (template[i].indexOf('${key}') >= 0) { + template[i] = schema.enum.map(value => { + const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + return template[i].replace(/\$\{key\}/g, safeName) + .replace(/\$\{value\}/g, value) + }).join('\n') + if (!templateName.includes(".cpp")) { + template[i] = template[i].replace(/,*$/, ''); + } + } + } + return template.join('\n') + .replace(/\$\{title\}/g, capitalize(schema.title)) + .replace(/\$\{description\}/g, schema.description ? ('- ' + schema.description) : '') + .replace(/\$\{name\}/g, schema.title) + .replace(/\$\{NAME\}/g, schema.title.toUpperCase()) +} + const enumFinder = compose( - filter(x => x.type === 'string' && Array.isArray(x.enum) && x.title), + filter(x => ((isEnumType(x) && x.title) || isEnumProperties(x))), map(([_, val]) => val), filter(([_key, val]) => isObject(val)) ) -const generateEnums = (json, templates) => { +const generateEnums = (json, templates, options = { destination: '' }) => { + const suffix = options.destination.split('.').pop() return compose( option(''), + map(val => { + let template = getTemplate(`/sections/enum.${suffix}`, templates) + return template ? template.replace(/\$\{schema.list\}/g, val.trimEnd()) : val + }), map(reduce((acc, val) => acc.concat(val).concat('\n'), '')), - map(map((schema) => { - const template = getTemplate('/types/enum', templates).split('\n') - for (var i = 0; i < template.length; i++) { - if (template[i].indexOf('${key}') >= 0) { - template[i] = schema.enum.map(value => { - const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() - return template[i].replace(/\$\{key\}/g, safeName) - .replace(/\$\{value\}/g, value) - }).join('\n') - } - } - return template.join('\n').replace(/\$\{name\}/g, schema.title).replace(/\$\{NAME\}/g, schema.title.toUpperCase()) - })), + map(map((schema) => convertEnumTemplate(schema, suffix ? `/types/enum.${suffix}` : '/types/enum', templates))), map(enumFinder), getSchemas )(json) @@ -703,8 +756,6 @@ const generateImports = (json, templates) => { imports += getTemplate('/imports/x-method', templates) } - - if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0) { imports += Object.keys(json['x-schemas']).map(shared => getTemplate('/imports/default', templates).replace(/\$\{info.title\}/g, shared)).join('\n') } @@ -1243,7 +1294,6 @@ function generateProviderInterfaces(json, templates) { function insertProviderInterfaceMacros(template, capability, moduleJson = {}, templates) { const iface = getProviderInterface(capability, moduleJson, { destination: state.destination, section: state.section })//.map(method => { method.name = method.name.charAt(9).toLowerCase() + method.name.substr(10); return method } ) - const capitalize = str => str[0].toUpperCase() + str.substr(1) const uglyName = capability.split(":").slice(-2).map(capitalize).reverse().join('') + "Provider" let name = iface.length === 1 ? iface[0].name.charAt(0).toUpperCase() + iface[0].name.substr(1) + "Provider" : uglyName @@ -1397,4 +1447,4 @@ export default { insertAggregateMacros, setTyper, setConfig -} \ No newline at end of file +} From 57550c17ed71a9ebfd0fa4a2b37c5366d68d64dd Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 5 Jun 2023 21:54:53 +0530 Subject: [PATCH 073/137] Types and Accessor related fixes (#94) Types and Accessor related fixes: 1. Accessor creation 2. JsonContainer creation 3. Types order placed based on depenedencies 4. filtered redundant new lines 5. UnamedSchema issue fixes 6. Types and Accessors: generation added for objects inside methods result/params 7. AnyOf support added --- languages/c/Types.mjs | 915 ++++++++++++------ languages/c/src/types/ImplHelpers.mjs | 392 ++++---- languages/c/src/types/JSONHelpers.mjs | 67 +- languages/c/src/types/NativeHelpers.mjs | 141 +-- languages/c/templates/methods/property.c | 16 +- .../c/templates/modules/include/Module.h | 4 - languages/c/templates/modules/src/Module.cpp | 1 - languages/c/templates/schemas/default.c | 3 - .../c/templates/schemas/src/JsonData_Module.h | 2 +- languages/c/templates/sections/accessors.c | 1 - languages/c/templates/sections/methods.c | 3 +- .../c/templates/sections/methods_accessors.c | 1 + .../c/templates/sections/methods_types.c | 1 + src/macrofier/engine.mjs | 79 +- src/macrofier/index.mjs | 4 +- 15 files changed, 993 insertions(+), 637 deletions(-) create mode 100644 languages/c/templates/sections/methods_accessors.c create mode 100644 languages/c/templates/sections/methods_types.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index e44b4a78..0bb6cc59 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -18,365 +18,660 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' -import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors } from './src/types/NativeHelpers.mjs' -import { getObjectHandleManagementImpl, getPropertyAccessorsImpl } from './src/types/ImplHelpers.mjs' -import { getJsonContainerDefinition } from './src/types/JSONHelpers.mjs' +import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema } from './src/types/NativeHelpers.mjs' +import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getPropertyAccessorsImpl } from './src/types/ImplHelpers.mjs' +import { getJsonContainerDefinition, getJsonDataStructName } from './src/types/JSONHelpers.mjs' -function getMethodSignature(method, module, { destination, isInterface = false }) { - const extraParam = '${method.result.type}* ${method.result.name}' - - const prefix = method.tags.find(t => t.name.split(":")[0] === "property") ? "Get" : "" +const getSdkNameSpace = () => 'FireboltSDK' +const getJsonNativeTypeForOpaqueString = () => getSdkNameSpace() + '::JSON::String' +const getEnumName = (name, prefix) => ((prefix.length > 0) ? (prefix + '_' + name) : name) - return 'uint32_t ${info.title}_' + prefix + '${method.Name}(' + extraParam + ')' +const getRefModule = (title) => { + let module = { + info: { + title: `${title}` + } + } + return module } -function getMethodSignatureParams(method, module, { destination }) { - return method.params.map(param => param.name + (!param.required ? '?' : '') + ': ' + getSchemaType(param.schema, module, { title: true, destination })).join(', ') +const hasProperties = (prop) => { + let hasProperty = false + if (prop.properties) { + hasProperty = true + } else if (prop.additionalProperties && ( prop.additionalProperties.type && (((prop.additionalProperties.type === 'object') && prop.additionalProperties.properties) || (prop.additionalProperties.type !== 'object')))) { + hasProperty = true + } + return hasProperty } -const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - -function getSchemaType(schema, module, { name, destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - let type = '' - let theTitle = schema.title || name || ('UnamedSchema' + (Math.floor(Math.random() * 100))) +function validJsonObjectProperties(json = {}) { - if (schema['x-method']) { - console.log(`WARNING UNHANDLED: x-method in ${theTitle}`) - //throw "x-methods not supported yet" - } - - if (schema['$ref']) { - if (schema['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType - let definition = getPath(schema['$ref'], module) - let tName = definition.title || schema['$ref'].split('/').pop() - return getSchemaType(definition, module, { name: tName, destination, link, title, code, asPath, event, expandEnums, baseUrl }) + let valid = true + if (json.type === 'object' || (json.additonalProperties && typeof json.additonalProperties.type === 'object')) { + if (json.properties || json.additonalProperties) { + Object.entries(json.properties || json.additonalProperties).every(([pname, prop]) => { + if (!prop['$ref'] && (pname !== 'additionalProperties') && + ((!prop.type && !prop.const && (prop.schema && !prop.schema.type)) || (Array.isArray(prop.type) && (prop.type.find(t => t === 'null'))))) { + valid = false } + return valid + }) } - else if (schema.const) { - type = getNativeType(schema) - return type - } - else if (schema.type === 'string' && schema.enum) { - //Enum - let typeName = getTypeName(getModuleName(module), theTitle) - return typeName - } - else if (Array.isArray(schema.type)) { - let type = schema.type.find(t => t !== 'null') - console.log(`WARNING UNHANDLED: type is an array containing ${schema.type}`) - } - else if (schema.type === 'array' && schema.items) { - let res - if (Array.isArray(schema.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(schema.items)) { - throw 'Heterogenous Arrays not supported yet' - } - res = getSchemaType(schema.items[0], module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) - } - else { - // grab the type for the non-array schema - res = getSchemaType(schema.items, module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) - } + } + return valid +} - if (!schema.title && !name) { - console.log(`WARNING: generated name for ${module.info.title} schema w/ no title: ${theTitle}`) - console.dir(schema) +function union(schemas, module, commonSchemas) { + + const result = {}; + for (const schema of schemas) { + for (const [key, value] of Object.entries(schema)) { + if (!result.hasOwnProperty(key)) { + // If the key does not already exist in the result schema, add it + if (value && value.anyOf) { + result[key] = union(value.anyOf, module, commonSchemas) + } else if (key === 'title' || key === 'description' || key === 'required') { + //console.warn(`Ignoring "${key}"`) + } else { + result[key] = value; } - - let n = getTypeName(getModuleName(module), theTitle) - return n + 'ArrayHandle' - } - else if (schema.allOf) { - let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x)]) - if (theTitle) { - union['title'] = theTitle + } else if (key === 'type') { + // If the key is 'type', merge the types of the two schemas + if(result[key] === value) { + //console.warn(`Ignoring "${key}" that is already present and same`) + } else { + console.warn(`ERROR "${key}" is not same -${JSON.stringify(result, null, 4)} ${key} ${result[key]} - ${value}`); + throw "ERROR: type is not same" } - delete union['$ref'] - return getSchemaType(union, module, { destination, link, title, code, asPath, event, expandEnums, baseUrl }) - } - else if (schema.oneOf || schema.anyOf) { - return type - //TODO - } - else if (schema.type === 'object') { - if (!schema.title && !name) { - console.log(`WARNING: generated name for ${module.info.title} schema w/ no title: ${theTitle}`) - console.dir(schema) + } else { + //If the Key is a const then merge them into an enum + if(value && value.const) { + if(result[key].enum) { + result[key].enum = Array.from(new Set([...result[key].enum, value.const])) + } + else { + result[key].enum = Array.from(new Set([result[key].const, value.const])) + delete result[key].const + } } - return getTypeName(getModuleName(module), theTitle) + 'Handle' - //TODO - } - else if (schema.type) { - type = getNativeType(schema) - return type + // If the key exists in both schemas and is not 'type', merge the values + else if (Array.isArray(result[key])) { + // If the value is an array, concatenate the arrays and remove duplicates + result[key] = Array.from(new Set([...result[key], ...value])) + } else if (result[key] && result[key].enum && value && value.enum) { + //If the value is an enum, merge the enums together and remove duplicates + result[key].enum = Array.from(new Set([...result[key].enum, ...value.enum])) + } else if (typeof result[key] === 'object' && typeof value === 'object') { + // If the value is an object, recursively merge the objects + result[key] = union([result[key], value], module, commonSchemas); + } else if (result[key] !== value) { + // If the value is a primitive and is not the same in both schemas, ignore it + //console.warn(`Ignoring conflicting value for key "${key}"`) + } + } } - - // TODO: deal with dependencies - return type + } + return result; } -//function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, summary, descriptions = true, destination, enums = true } = {}) -// function getSchemaType() -function getSchemaShape(schema, module, { name = '', level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { - const isHeader = destination.endsWith(".h") - const isCPP = (destination.endsWith(".cpp") && section !== 'accessors') +function getMergedSchema(module, json, name, schemas) { + let refsResolved = [...json.anyOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)] + let allOfsResolved = refsResolved.map(sch => sch.allOf ? deepmerge.all([...sch.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)]) : sch) - schema = JSON.parse(JSON.stringify(schema)) + let mergedSchema = union(allOfsResolved, module, schemas) + if (json.title) { + mergedSchema['title'] = json.title + } + else { + mergedSchema['title'] = name + } - let shape = '' + delete mergedSchema['$ref'] + return mergedSchema +} - name = schema.title || name +const deepMergeAll = (module, name, schema, schemas, options) => { + let nonRefsProperty = [...schema.allOf.map(x => x['$ref'] ? '' : x)].filter(elm => elm) + let refsProperty = [...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) : '')].filter(elm => elm) + let mergedProperty = [] + let mergedParamSchema = { + type: "object", + properties: {} + } + + nonRefsProperty.forEach(p => { + if (p.properties) { + Object.entries(p.properties).every(([pname, prop]) => { + let present = false + refsProperty.forEach(refP => { + if (refP.properties) { + Object.entries(refP.properties).every(([refname, refprop]) => { + if (refname == pname) { + present = true + } + return !present + }) + } + }) + let prefixedName = (present == false) ? (name + capitalize(pname)) : pname + mergedParamSchema.properties[prefixedName] = prop + return true + }) + mergedProperty.push(mergedParamSchema) + } + }) + refsProperty.forEach(ref => mergedProperty.push(ref)) + let union = deepmerge.all(mergedProperty) + + return union +} - if (!name) { - console.log(`WARNING: schema without a name in ${module.info.title}`) - return shape - } +function getMethodSignature(method, module, { destination, isInterface = false }) { + const extraParam = '${method.result.type}* ${method.result.name}' - if (schema['$ref']) { - if (schema['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType + const prefix = method.tags.find(t => t.name.split(":")[0] === "property") ? "Get" : "" - const schema = getPath(schema['$ref'], module) - const tname = name || schema['$ref'].split('/').pop() - return getSchemaShape(schema, module, { name: tname, descriptions: descriptions, level: level }) - } - } - //If the schema is a const, - else if (schema.hasOwnProperty('const') && !isCPP) { - if (level > 0) { + return 'uint32_t ${info.title}_' + prefix + '${method.Name}(' + extraParam + ')' +} - let t = description(name, schema.description) - typeName = getTypeName(getModuleName(module), name) - t += (isHeader ? getPropertyAccessors(typeName, capitalize(name), typeof schema.const, { level: level, readonly: true, optional: false }) : getPropertyAccessorsImpl(typeName, capitalize(name), getJsonType(schema, module, { level, name }), typeof schema.const, { level: level, readonly: true, optional: false })) - shape += '\n' + t - } - } - else if (schema.type === 'object') { - if (!name) { - console.log(`WARNING: unnamed schema in ${module.info.title}.`) - console.dir(schema) - shape = '' - } - else if (schema.properties) { - let tName = getTypeName(getModuleName(module), name) - let c_shape = description(name, schema.description) - let cpp_shape = '' - c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(schema, module, { name }))) - Object.entries(schema.properties).forEach(([pname, prop]) => { - c_shape += '\n' + description(pname, prop.description) - let res - if (prop.type === 'array') { - if (Array.isArray(prop.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(prop.items)) { - throw 'Heterogenous Arrays not supported yet' - } - res = getSchemaType(prop.items[0], module, { name: pname, level: level, descriptions: descriptions, title: true }) - } - else { - // grab the type for the non-array schema - res = getSchemaType(prop.items, module, { name: pname, level: level, descriptions: descriptions, title: true }) - } - if (res && res.length > 0) { - let n = tName + '_' + capitalize(pname || prop.title) - let def = getArrayAccessors(n + 'Array', res) - c_shape += '\n' + def - } - else { - console.log(`a. WARNING: Type undetermined for ${name}:${pname}`) - } - } else { - res = getSchemaType(prop, module, { name: pname, descriptions: descriptions, level: level + 1, title: true }) - if (res && res.length > 0) { - c_shape += '\n' + (isHeader ? getPropertyAccessors(tName, capitalize(pname), res, { level: level, readonly: false, optional: isOptional(pname, schema) }) : getPropertyAccessorsImpl(tName, capitalize(pname), getJsonType(prop, module, { level, name }), res, { level: level, readonly: false, optional: isOptional(pname, schema) })) - } - else { - console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) - } - } - }) - cpp_shape += getJsonContainerDefinition(tName, Object.entries(schema.properties).map(([name, prop]) => ({ name, type: getJsonType(prop, module) }))) +function getMethodSignatureParams(method, module, { destination }) { - if (isCPP) { - shape += '\n' + cpp_shape - } - else { - shape += '\n' + c_shape - } - } - else if (schema.propertyNames && schema.propertyNames.enum) { - //propertyNames in object not handled yet - } - else if (schema.additionalProperties && (typeof schema.additionalProperties === 'object') && !isCPP) { - //This is a map of string to type in schema - //Get the Type - let type = getSchemaType(schema.additionalProperties, module, { name: name }) - if (type && type.length > 0) { - let tName = getTypeName(getModuleName(module), name) - // type.deps.forEach(dep => structure.deps.add(dep)) - let t = description(name, schema.description) - t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(schema, module, { name }))) - t += getMapAccessors(getTypeName(getModuleName(module), name), type, { descriptions: descriptions, level: level }) - shape += '\n' + t - } - else { - console.log(`c. WARNING: Type undetermined for ${name}`) - } - } - else if (schema.patternProperties) { - console.log(`WARNING: patternProperties not supported yet...`) - // throw "patternProperties are not supported by Firebolt" - } - } - else if (schema.anyOf) { + return method.params.map(param => param.name + (!param.required ? '?' : '') + ': ' + getSchemaType(param.schema, module, { name: param.name, title: true, destination })).join(', ') +} - } - else if (schema.oneOf) { +const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop - } - else if (schema.allOf) { - let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module) || x : x)]) - if (name) { - union['title'] = name - } - delete union['$ref'] - return getSchemaShape(union, module, { name, level, title, summary, descriptions, destination, section, enums }) +function getSchemaType(schema, module, { name, prefix = '', destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + let info = getSchemaTypeInfo(module, schema, name, module['x-schemas'], prefix, { title: title }) + return info.type +} - } - else if (schema.type === 'array') { - let res = getSchemaType(schema, module, { name, level: 0, descriptions: descriptions }) - // res.deps.forEach(dep => structure.deps.add(dep)) +function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = {level: 0, descriptions: true, title: false}) { + + if (json.schema) { + json = json.schema + } + + let structure = {} + structure["type"] = '' + structure["json"] = [] + structure["name"] = {} + structure["namespace"] = {} + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(json['$ref'], module, schemas) + let tName = definition.title || json['$ref'].split('/').pop() + let schema = module + if (json['$ref'].includes('x-schemas')) { + schema = (getRefModule(json['$ref'].split('/')[2])) + } + + const res = getSchemaTypeInfo(schema, definition, tName, schemas, '', options) + structure.type = res.type + structure.json = res.json + structure.name = res.name + structure.namespace = res.namespace + return structure + } + } + else if (json.const) { + structure.type = getNativeType(json) + structure.json = json + return structure + } + else if (json['x-method']) { + console.log(`WARNING UNHANDLED: x-method in ${name}`) + return structure + //throw "x-methods not supported yet" + } + else if (json.type === 'string' && json.enum) { + //Enum + structure.name = name || json.title + let typeName = getTypeName(getModuleName(module), name || json.title, prefix, false, false) + let res = description(capitalize(name || json.title), json.description) + '\n' + generateEnum(json, typeName) + structure.json = json + structure.type = typeName + structure.namespace = getModuleName(module) + return structure + } + else if (Array.isArray(json.type)) { + let type = json.type.find(t => t !== 'null') + console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) + } + else if (json.type === 'array' && json.items && (validJsonObjectProperties(json) === true)) { + let res = '' + if (Array.isArray(json.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(json.items)) { + throw 'Heterogenous Arrays not supported yet' + } + res = getSchemaTypeInfo(module, json.items[0], json.items[0].name || name, schemas, prefix) } else { - let res = getSchemaType(schema, module, { name, level: level, descriptions: descriptions }) - // res.deps.forEach(dep => structure.deps.add(dep)) + // grab the type for the non-array schema + res = getSchemaTypeInfo(module, json.items, json.items.name || name, schemas, prefix) + } + + let arrayName = capitalize(res.name) + capitalize(res.json.type) + let n = getTypeName(getModuleName(module), arrayName, prefix) + structure.name = res.name || name && (capitalize(name)) + structure.type = n + 'ArrayHandle' + structure.json = json + structure.namespace = getModuleName(module) + return structure + } + else if (json.allOf) { + let title = json.title ? json.title : name + let union = deepMergeAll(module, title, json, schemas, options) + union['title'] = title + + delete union['$ref'] + return getSchemaTypeInfo(module, union, '', schemas, '', options) + } + else if (json.oneOf) { + structure.type = 'char*' + structure.json.type = 'string' + return structure + } + else if (json.anyOf) { + let mergedSchema = getMergedSchema(module, json, name, schemas) + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + return getSchemaTypeInfo(module, mergedSchema, '', schemas, prefixName, options) + } + else if (json.type === 'object') { + structure.json = json + if (hasProperties(json)) { + structure.type = getTypeName(getModuleName(module), json.title || name, prefix) + 'Handle' + structure.name = (json.name ? json.name : (json.title ? json.title : name)) + structure.namespace = (json.namespace ? json.namespace : getModuleName(module)) } - // console.dir(structure.deps) - return shape -} - -// function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - -const getJsonDataStructName = (modName, name) => `${capitalize(modName)}::${capitalize(name)}` - -const getJsonNativeType = json => { - let type - let jsonType = json.const ? typeof json.const : json.type - - if (jsonType === 'string') { - type = 'WPEFramework::Core::JSON::String' - } - else if (jsonType === 'number' || json.type === 'integer') { //Lets keep it simple for now - type = 'WPEFramework::Core::JSON::Number' + else { + structure.type = 'char*' } - else if (jsonType === 'boolean') { - type = 'WPEFramework::Core::JSON::Boolean' + if (name) { + structure.name = capitalize(name) } - else { - throw 'Unknown JSON Native Type !!!' + + return structure + } + else if (json.type) { + structure.type = getNativeType(json) + structure.json = json + if (name || json.title) { + structure.name = capitalize(name || json.title) } - return type -} + structure.namespace = getModuleName(module) -function getJsonType(schema = {}, module = {}, { name = '', descriptions = false, level = 0 } = {}) { + return structure + } + return structure +} - let type = '' +function getSchemaShape(json, module, { name = '', prefix = '', level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { - if (schema['$ref']) { - if (schema['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType - let definition = getPath(schema['$ref'], module) - let tName = definition.title || schema['$ref'].split('/').pop() - return getJsonType(definition, module, { name: tName, descriptions: descriptions, level: level }) - } - } - else if (schema.const) { - return getJsonNativeType(schema) - } - else if (schema['x-method']) { - console.log(`WARNING: x-methods are not supported yet...`) - return type - //throw "x-methods not supported yet" - } - else if (schema.type === 'string' && schema.enum) { - //Enum - let t = getSchemaType(schema, module, { name }) - return 'WPEFramework::Core::JSON::EnumType<::' + t + '>' - } - else if (Array.isArray(schema.type)) { - let type = schema.type.find(t => t !== 'null') - console.log(`WARNING UNHANDLED: type is an array containing ${schema.type}`) + let shape = getSchemaShapeInfo(json, module, module['x-schemas'], { name, prefix, merged: false, level, title, summary, descriptions, destination, section, enums }) + return shape +} +function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '', merged = false, level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { + const isHeader = (destination.includes("JsonData_") !== true) && destination.endsWith(".h") + const isCPP = ((destination.endsWith(".cpp") || destination.includes("JsonData_")) && (section.includes('accessors') !== true)) + json = JSON.parse(JSON.stringify(json)) + + name = json.title || name + let shape = '' + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + const schema = getPath(json['$ref'], module, schemas) + const tname = schema.title || json['$ref'].split('/').pop() + if (json['$ref'].includes('x-schemas')) { + schema = (getRefModule(json['$ref'].split('/')[2])) + } + + shape = getSchemaShapeInfo(schema, module, schemas, { name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) + } + } + //If the schema is a const, + else if (json.hasOwnProperty('const') && !isCPP) { + if (level > 0) { + + let t = description(capitalize(name), json.description) + typeName = getTypeName(getModuleName(module), name, prefix) + t += (isHeader ? getPropertyAccessors(typeName, capitalize(name), typeof schema.const, { level: level, readonly: true, optional: false }) : getPropertyAccessorsImpl(typeName, getJsonType(schema, module, { level, name }), typeof schema.const, { level: level, readonly: true, optional: false })) + shape += '\n' + t } - else if (schema.type === 'array' && schema.items) { - let res - if (Array.isArray(schema.items)) { + } + else if (json.type === 'object') { + if (!name) { + console.log(`WARNING: unnamed schema in ${module.info.title}.`) + console.dir(json) + shape = '' + } + else if (json.properties && (validJsonObjectProperties(json) === true)) { + let c_shape = description(capitalize(name), json.description) + let cpp_shape = '' + let tName = getTypeName(getModuleName(module), name, prefix) + c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(json, module, { name }))) + let props = [] + let containerName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? (prefix + '_' + capitalize(name)) : capitalize(name) + Object.entries(json.properties).forEach(([pname, prop]) => { + let items + var desc = '\n' + description(capitalize(pname), prop.description) + if (prop.type === 'array') { + if (Array.isArray(prop.items)) { //TODO - const IsHomogenous = arr => new Set(arr.map(item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(schema.items)) { - throw 'Heterogenous Arrays not supported yet' + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(prop.items)) { + throw 'Heterogenous Arrays not supported yet' } - res = getJsonType(schema.items[0], module, { name: '' }) - } - else { + items = prop.items[0] + } + else { // grab the type for the non-array schema - res = getJsonType(schema.items, module, { name: '' }) + items = prop.items + } + let info = getSchemaTypeInfo(module, items, items.name || pname, schemas, prefix, {level : level, descriptions: descriptions, title: true}) + if (info.type && info.type.length > 0) { + let objName = tName + '_' + capitalize(prop.title || pname) + let moduleName = info.namespace + info.json.namespace = info.namespace + let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) + let prefixName = ((prefix.length > 0) && items['$ref']) ? '' : prefix + let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, schemas, prefix) + + let t = description(capitalize(info.name), json.description) + '\n' + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) + c_shape += '\n' + t + props.push({name: `${pname}`, type: `WPEFramework::Core::JSON::ArrayType<${subModuleProperty.type}>`}) + } + else { + console.log(`a. WARNING: Type undetermined for ${name}:${pname}`) + } + } else { + if (((merged === false) || ((merged === true) && (pname.includes(name)))) && (prop.type === 'object' || prop.anyOf || prop.allOf)) { + shape += getSchemaShapeInfo(prop, module, schemas, { name : pname, prefix, merged: false, level: 1, title, summary, descriptions, destination, section, enums }) + } + let info = getSchemaTypeInfo(module, prop, pname, module['x-schemas'], prefix, {descriptions: descriptions, level: level + 1, title: true}) + if (info.type && info.type.length > 0) { + let subPropertyName = ((pname.length !== 0) ? capitalize(pname) : info.name) + let moduleProperty = getJsonTypeInfo(module, json, name, schemas, prefix) + let subProperty = getJsonTypeInfo(module, prop, pname, schemas, prefix) + c_shape += '\n' + description(capitalize(pname), info.json.description) + c_shape += '\n' + (isHeader ? getPropertyAccessors(tName, capitalize(pname), info.type, { level: 0, readonly: false, optional: isOptional(pname, json) }) : getPropertyAccessorsImpl(tName, moduleProperty.type, subProperty.type, subPropertyName, info.type, info.json, {readonly:false, optional:isOptional(pname, json)})) + let property = getJsonType(prop, module, { name : pname, prefix }) + props.push({name: `${pname}`, type: `${property}`}) + } + else { + console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) + } } - - return `WPEFramework::Core::JSON::ArrayType<${res}>` + }) + + cpp_shape += getJsonContainerDefinition(json, containerName, props) + + if (isCPP) { + shape += '\n' + cpp_shape + } + else { + shape += '\n' + c_shape + } + } + else if (json.propertyNames && json.propertyNames.enum) { + //propertyNames in object not handled yet + } + else if (json.additionalProperties && (typeof json.additionalProperties === 'object') && (validJsonObjectProperties(json) === true) && !isCPP) { + let info = getSchemaTypeInfo(module, json.additionalProperties, name, module['x-schemas'], prefix) + if (!info.type || (info.type.length === 0)) { + info.type = 'char*' + info.json = json.additionalProperties + info.json.type = 'string' + } + + let tName = getTypeName(getModuleName(module), name, prefix) + let t = description(capitalize(name), json.description) + '\n' + let containerType = 'WPEFramework::Core::JSON::VariantContainer' + + let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, module['x-schemas']) + if (isCPP && ((info.json.type === 'object' && info.json.properties) || info.json.type === 'array')) { + // Handle Container generation here + } + + t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, containerType)) + t += (isHeader ? getMapAccessors(tName, info.type, { descriptions: descriptions, level: level }) : getMapAccessorsImpl(tName, containerType, subModuleProperty.type, info.type, info.json, { readonly: true, optional: false })) + shape += '\n' + t + } + else if (json.patternProperties) { + console.log(`WARNING: patternProperties are not supported by Firebolt(inside getModuleName(module):${name})`) + } + } + else if (json.anyOf) { + if (level > 0) { + let mergedSchema = getMergedSchema(module, json, name, schemas) + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + shape += getSchemaShapeInfo(mergedSchema, module, schemas, { name, prefix: prefixName, merged, level, title, summary, descriptions, destination, section, enums }) + } + } + else if (json.oneOf) { + //Just ignore schema shape, since this has to be treated as string + } + else if (json.allOf) { + let title = (json.title ? json.title : name) + let union = deepMergeAll(module, title, json, schemas) + union.title = title + + delete union['$ref'] + + return getSchemaShapeInfo(union, module, schemas, { name, prefix, merged: true, level, title, summary, descriptions, destination, section, enums }) + } + else if (json.type === 'array' && !isCPP) { + let j + if (Array.isArray(json.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(json.items)) { + throw 'Heterogenous Arrays not supported yet' + } + j = json.items[0] } - else if (schema.allOf) { - let union = deepmerge.all([...schema.allOf.map(x => x['$ref'] ? getPath(x['$ref'], module, schemas) || x : x)]) - if (schema.title) { - union['title'] = schema.title - } - else { - union['title'] = name - } - delete union['$ref'] - return getJsonType(union, module, { name: '', level, descriptions }) - } - else if (schema.oneOf || schema.anyOf) { - return type - //TODO - } - else if (schema.type === 'object') { - if (!schema.title && !name) { - console.log(`WARNING: schema with no name`) - console.dir(schema) - return 'Unknown' - } - return getJsonDataStructName(getModuleName(module), schema.title || name) - //TODO - } - else if (schema.type) { - return getJsonNativeType(schema) - } - return type + else { + j = json.items + } + + let info = getSchemaTypeInfo(module, j, j.name || name, schemas, prefix, {level : level, descriptions: descriptions, title: true}) + + if (info.type && info.type.length > 0) { + let type = getArrayElementSchema(json, module, schemas, info.name) + let arrayName = capitalize(info.name) + capitalize(type.type) + let objName = getTypeName(info.namespace, arrayName, prefix) + let tName = objName + 'Array' + let moduleName = info.namespace + info.json.namespace = info.namespace + let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) + let t = '' + if (level === 0) { + t += description(capitalize(info.name), json.description) + '\n' + t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, moduleProperty.type)) + } + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + 'Handle'), getJsonNativeType(type), '', info.type, info.json)) + shape += '\n' + t + } + } + else { + shape += '\n' + getSchemaType(module, json, name, schemas, prefix, {level: level, descriptions: descriptions}) + } + + return shape } -function getTypeScriptType(jsonType) { - if (jsonType === 'integer') { - return 'number' +const getJsonNativeType = json => { + let type + let jsonType = json.const ? typeof json.const : json.type + + if (jsonType === 'string') { + type = getSdkNameSpace() + '::JSON::String' + } + else if (jsonType === 'number') { + type = 'WPEFramework::Core::JSON::Float' + } + else if (json.type === 'integer') { + type = 'WPEFramework::Core::JSON::DecSInt32' + } + else if (jsonType === 'boolean') { + type = 'WPEFramework::Core::JSON::Boolean' + } + else { + throw 'Unknown JSON Native Type !!!' + } + return type +} + +function getJsonType(schema = {}, module = {}, { name = '', prefix = '', descriptions = false, level = 0 } = {}) { + let info = getJsonTypeInfo(module, schema, name, module['x-schemas'], prefix, { descriptions: descriptions, level: level }) + return info.type +} + +function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '', {descriptions = false, level = 0} = {}) { + + if (json.schema) { + json = json.schema + } + + let structure = {} + structure["deps"] = new Set() //To avoid duplication of local ref definitions + structure["type"] = [] + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(json['$ref'], module, schemas) + let tName = definition.title || json['$ref'].split('/').pop() + + let schema = module + if (json['$ref'].includes('x-schemas')) { + schema = (getRefModule(json['$ref'].split('/')[2])) + } + + const res = getJsonTypeInfo(schema, definition, tName, schemas, '', {descriptions, level}) + structure.deps = res.deps + structure.type = res.type + return structure + } + } + else if (json.const) { + structure.type = getJsonNativeType(json) + return structure + } + else if (json['x-method']) { + return structure + //throw "x-methods not supported yet" + } + else if (json.additionalProperties && (typeof json.additionalProperties === 'object')) { + //This is a map of string to type in schema + //Get the Type + let type = getJsonTypeInfo(module, json.additionalProperties, name, schemas, prefix) + if (type.type && type.type.length > 0) { + structure.type = 'WPEFramework::Core::JSON::VariantContainer'; + return structure + } + else { + console.log(`WARNING: Type undetermined for ${name}`) + } + } + else if (json.type === 'string' && json.enum) { + //Enum + let t = 'WPEFramework::Core::JSON::EnumType<' + (json.namespace ? json.namespace : getModuleName(module)) + '_' + (getEnumName(name, prefix)) + '>' + structure.type.push(t) + return structure + } + else if (Array.isArray(json.type)) { + let type = json.type.find(t => t !== 'null') + console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) + } + else if (json.type === 'array' && json.items) { + let res + let items + if (Array.isArray(json.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(json.items)) { + throw 'Heterogenous Arrays not supported yet' + } + items = json.items[0] } else { - return jsonType + items = json.items + // grab the type for the non-array schema + } + res = getJsonTypeInfo(module, items, items.name || name, schemas, prefix) + structure.deps = res.deps + structure.type.push(`WPEFramework::Core::JSON::ArrayType<${res.type}>`) + + return structure + } + else if (json.allOf) { + let title = json.title ? json.title : name + let union = deepMergeAll(module, title, json, schemas) + union['title'] = title + + delete union['$ref'] + return getJsonTypeInfo(module, union, '', schemas, '', {descriptions, level}) + } + else if (json.oneOf) { + structure.type = getJsonNativeTypeForOpaqueString() + return structure + } + else if (json.patternProperties) { + structure.type = getJsonNativeTypeForOpaqueString() + return structure + } + else if (json.anyOf) { + let mergedSchema = getMergedSchema(module, json, name, schemas) + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + structure = getJsonTypeInfo(module, mergedSchema, name, schemas, prefixName, {descriptions, level}) + } + else if (json.type === 'object') { + if (hasProperties(json) !== true) { + structure.type = getJsonNativeTypeForOpaqueString() } + else { + let schema = getSchemaTypeInfo(module, json, name, module['x-schemas'], prefix) + if (schema.namespace && schema.namespace.length > 0) { + structure.type.push(getJsonDataStructName(schema.namespace, json.title || name, prefix)) + } + } + return structure + } + else if (json.type) { + structure.type = getJsonNativeType(json) + return structure + } + return structure +} + +function getTypeScriptType(jsonType) { + if (jsonType === 'integer') { + return 'number' + } + else { + return jsonType + } } const enumReducer = (acc, val, i, arr) => { - const keyName = val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() - acc = acc + ` ${keyName} = '${val}'` - if (i < arr.length - 1) { - acc = acc.concat(',\n') - } - return acc + const keyName = val.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() + acc = acc + ` ${keyName} = '${val}'` + if (i < arr.length - 1) { + acc = acc.concat(',\n') + } + return acc } export default { @@ -385,4 +680,4 @@ export default { getSchemaShape, getSchemaType, getJsonType -} \ No newline at end of file +} diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index f3b39cbf..47852c9e 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -1,28 +1,35 @@ const Indent = '\t' +const getSdkNameSpace = () => 'FireboltSDK' +const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' +const getFireboltStringType = () => 'FireboltTypes_StringHandle' + const getObjectHandleManagementImpl = (varName, jsonDataName) => { - let result = ` -${varName}Handle ${varName}Handle_Create(void) { + let result = `${varName}Handle ${varName}Handle_Create(void) +{ WPEFramework::Core::ProxyType<${jsonDataName}>* type = new WPEFramework::Core::ProxyType<${jsonDataName}>(); *type = WPEFramework::Core::ProxyType<${jsonDataName}>::Create(); return (static_cast<${varName}Handle>(type)); } -void ${varName}Handle_Addref(${varName}Handle handle) { +void ${varName}Handle_Addref(${varName}Handle handle) +{ ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); ASSERT(var->IsValid()); var->AddRef(); } -void ${varName}Handle_Release(${varName}Handle handle) { +void ${varName}Handle_Release(${varName}Handle handle) +{ ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); var->Release(); - if(var->IsValid() != true) { + if (var->IsValid() != true) { delete var; } } -bool ${varName}Handle_IsValid(${varName}Handle handle) { +bool ${varName}Handle_IsValid(${varName}Handle handle) +{ ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); ASSERT(var->IsValid()); @@ -32,263 +39,258 @@ bool ${varName}Handle_IsValid(${varName}Handle handle) { return result } -const getPropertyAccessorsImpl = (objName, propertyName, jsonDataName, propertyType, json = {}, options = {readonly:false, optional:false}) => { - - let result - if (json.type === 'object') { - result += `${objName}_${propertyName}Handle ${objName}_Get_${propertyName}(${objName}Handle handle) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); - - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyName}>(); - *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); - *(*object) = (*var)->${propertyName}; - return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' - } else if (json.type === 'array') { - result += `${objName}_${propertyName}ArrayHandle ${objName}_Get_${propertyName}(${objName}Handle handle) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); - - WPEFramework::Core::ProxyType>* object = new WPEFramework::Core::ProxyType>(); - *object = WPEFramework::Core::ProxyType>::Create(); - *(*object) = (*var)->${propertyName}.Element(); - return (static_cast<${objName}_${propertyType}ArrayHandle>(object));` + '\n' - } else if (json.enum) { - result += `${objName}_${propertyName} ${objName}_Get_${propertyName}(${objName}Handle handle) { +const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, subPropertyName, accessorPropertyType, json = {}, options = {readonly:false, optional:false}) => { + let result = '' + result += `${accessorPropertyType} ${objName}_Get_${subPropertyName}(${objName}Handle handle) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - - return static_cast<${propertyType}>((*var)->${propertyName}.Value());` + '\n' - } else { - result += `${propertyType} ${objName}_Get_${propertyName}(${objName}Handle handle) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid());` + '\n' - if (json.type === 'string') { - result += ` - return static_cast<${propertyType}>((*var)->${propertyName}.Value().c_str());` + '\n' - } else { - result += ` - return static_cast<${propertyType}>((*var)->${propertyName}.Value());` + '\n' +` + '\n' + if ((json.type === 'object') && (accessorPropertyType !== 'char*')) { + result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); + *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); + *(*element) = (*var)->${subPropertyName}; + return (static_cast<${accessorPropertyType}>(element));` + '\n' + } + else { + if ((typeof json.const === 'string') || (json.type === 'string' && !json.enum) || (accessorPropertyType === 'char*')) { + result += ` return (const_cast<${accessorPropertyType}>((*var)->${subPropertyName}.Value().c_str()));` + '\n' + } + else { + result += ` return (static_cast<${accessorPropertyType}>((*var)->${subPropertyName}.Value()));` + '\n' } } - result += ` -}` + '\n' - if (!options.readonly) { - if (json.type === 'object') { - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName}Handle ${propertyName.toLowerCase()}) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); + result += `}` + '\n' - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* object = static_cast*>(${propertyName.toLowerCase()}); - (*var)->${propertyName} = *(*object);` + '\n' - } - if (json.type === 'array') { - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName}ArrayHandle ${propertyName.toLowerCase()}) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); - WPEFramework::Core::ProxyType>* object = static_cast>*>(${propertyName.toLowerCase()}).Element(); - (*var)->${propertyName} = *(*object);` + '\n' - } if (json.enum) { - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${objName}_${propertyName} ${propertyName.toLowerCase()}) { + if (!options.readonly) { + let type = (accessorPropertyType === getFireboltStringType()) ? 'char*' : accessorPropertyType + result += `void ${objName}_Set_${subPropertyName}(${objName}Handle handle, ${type} value)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); +` + '\n' - (*var)->${propertyName} = static_cast<${propertyType}>(${propertyName.toLowerCase()});` + '\n' + if (json.type === 'object' && (accessorPropertyType !== 'char*')) { + result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* object = static_cast*>(value); + (*var)->${subPropertyName} = *(*object);` + '\n' } else { - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${propertyType} ${propertyName.toLowerCase()}) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); - - (*var)->${propertyName} = static_cast<${propertyType}>(${propertyName.toLowerCase()});` + '\n' + result += ` (*var)->${subPropertyName} = value;` + '\n' } -result += `}` + '\n' + result += `}` + '\n' } if (options.optional === true) { - result += `${Indent.repeat(options.level)}bool ${objName}_has_${propertyName}(${objName}Handle handle) { + result += `bool ${objName}_Has_${subPropertyName}(${objName}Handle handle)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - return ((*var)->${propertyName}.IsSet()); + + return ((*var)->${subPropertyName}.IsSet()); }` + '\n' - result += `${Indent.repeat(options.level)}void ${objName}_clear_${propertyName}(${objName}Handle handle) { + result += `void ${objName}_Clear_${subPropertyName}(${objName}Handle handle)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - ((*var)->${propertyName}.Clear()); + ((*var)->${subPropertyName}.Clear()); }` + '\n' } + return result } +const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPropertyType, subPropertyName, accessorPropertyType, json = {}) => { + + let propertyName + if (subPropertyName) { + propertyName = '(*var)->' + `${subPropertyName}` + objName = objName + '_' + subPropertyName + } + else { + propertyName = '(*(*var))' + } -const getArrayAccessors = (objName, propertyName, propertyType, json = {}, options = {readonly:false, optional:false}) => { - let result = ` -uint32_t ${objName}_${propertyName}Array_Size(${objName}::${propertyName}ArrayHandle handle) { + let result = `uint32_t ${objName}Array_Size(${objHandleType} handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - return ((*var)->Length()); + return (${propertyName}.Length()); }` + '\n' - if (json.type === 'object') { -result += `${objName}_${propertyType}Handle ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { + result += `${accessorPropertyType} ${objName}Array_Get(${objHandleType} handle, uint32_t index) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); - ASSERT(var->IsValid()); - WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyType}>(); - *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); - *(*object) = (*var)->Get(index); - return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' - } else if (json.enum) { - result += `${objName}_${propertyType} ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); - ASSERT(var->IsValid()); - - return (static_cast<${propertyType}>((*var)->Get(index)));` + '\n' - } else { - result += `${propertyType} ${objName}_${propertyName}Array_Get(${objName}_${propertyName}ArrayHandle handle, uint32_t index) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid());` + '\n' - if (json.type === 'string') { - result += `return (static_cast<${propertyType}>((*var)->Get(index).Value().c_str()));` + '\n' - } else { - result += `return (static_cast<${propertyType}>((*var)->Get(index)));` + '\n' - } + if ((json.type === 'object') || (json.type === 'array')) { + result += `WPEFramework::Core::ProxyType<${subPropertyType}>* object = new WPEFramework::Core::ProxyType<${subPropertyType}>(); + *object = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); + *(*object) = ${propertyName}.Get(index); + return (static_cast<${accessorPropertyType}>(object));` + '\n' + } + else { + if ((typeof json.const === 'string') || (json.type === 'string' && !json.enum)) { + result += ` return (const_cast<${accessorPropertyType}>(${propertyName}.Get(index).Value().c_str()));` + '\n' + } + else { + result += ` return (static_cast<${accessorPropertyType}>(${propertyName}.Get(index)));` + '\n' + } } result += `}` + '\n' - if (json.type === 'object') { - result += `void ${objName}_${propertyName}Array_Add(${objName}_${propertyName}ArrayHandle handle, ${objName}_${propertyType}Handle value) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); - ASSERT(var->IsValid()); - WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = static_cast*>(value); - - (*var)->Add(*(*object));` + '\n' - } else { - result += `void ${objName}_${propertyName}Array_Add(${objName}_${propertyName}ArrayHandle handle, ${propertyType} value) { + let type = (accessorPropertyType === getFireboltStringType()) ? 'char*' : accessorPropertyType + result += `void ${objName}Array_Add(${objHandleType} handle, ${type} value) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid());` + '\n' - if (json.type === 'string') { - result += `WPEFramework::Core::JSON::String element(value);` + '\n' - } else if (json.type === 'number') { - result += `WPEFramework::Core::JSON::Number element(value);` + '\n' - } else if (json.enum) { - result += `WPEFramework::Core::JSON::EnumType<${propertyType}> element(value);` + '\n' - } - result += `(*var)->Add(element);` + '\n' + + if ((json.type === 'object') || (json.type === 'array')) { + result += ` ${subPropertyType}& element = *(*(static_cast*>(value)));` + '\n' } - result += `}` + '\n' + else { + result += ` ${subPropertyType} element(value);` + '\n' + } + result += ` + ${propertyName}.Add(element); +}` + '\n' - result += `void ${objName}_${propertyName}Array_Clear(${objName}_${propertyName}ArrayHandle handle) { + result += `void ${objName}Array_Clear(${objHandleType} handle) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType>* var = static_cast>*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - (*var)->Clear(); + + ${propertyName}.Clear(); }` + '\n' return result } -const getMapAccessors = (objName, propertyName, propertyType, json = {}, options = {readonly:false, optional:false}) => { - let result = `uint32_t ${objName}_${propertyName}_KeysCount(${objName}_${propertyName}Handle handle) { +const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPropertyType, json = {}, options = {readonly:false, optional:false}) => { + let result = `uint32_t ${objName}_KeysCount(${objName}Handle handle) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - return (*var)->Size()); - - }` + '\n' - result += `void ${objName}_${propertyName}_AddKey(${objName}_${propertyName}Handle handle, char* key, ${propertyType} value) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); - ASSERT(var->IsValid());` + '\n' - - if (json.type === 'object') { - result += ` - (*var)->Add(key, value);` + '\n' - } else if (json.type === 'boolean') { - result += ` - WPEFramework::Core::JSON::Boolean element(value);` - } else if (json.type === 'string') { - result += ` - WPEFramework::Core::JSON::String element(value);` - } else if (json.type === 'number') { - result += ` - WPEFramework::Core::JSON::Number element(value);` - } else if (json.type === 'array') { - result += ` - WPEFramework::Core::JSON::ArrayType element(value);` - } else if (json.enum) { - result += ` - WPEFramework::Core::JSON::EnumType element(value); - (*var)->Add(key, element);` + '\n' + ${containerType}::Iterator elements = (*var)->Variants(); + uint32_t count = 0; + while (elements.Next()) { + count++; } - result += ` - }` + '\n' - result += `void ${objName}_${propertyName}_RemoveKey(${objName}_${propertyName}Handle handle, char* key) { + return (count); +}` + '\n' + result += `void ${objName}_AddKey(${objName}Handle handle, char* key, ${accessorPropertyType} value) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - - (*var)->Remove(key); - }` + '\n' +` + '\n' + let elementContainer = subPropertyType + if (containerType.includes('VariantContainer')) { + elementContainer = 'WPEFramework::Core::JSON::Variant' + } + if ((json.type === 'object') || (json.type === 'array' && json.items)) { + if (containerType.includes('VariantContainer')) { + result += ` ${subPropertyType}& container = *(*(static_cast*>(value)));` + '\n' + result += ` string containerStr;` + '\n' + result += ` element.ToString(containerStr);` + '\n' + result += ` WPEFramework::Core::JSON::VariantContainer containerVariant(containerStr);` + '\n' + result += ` WPEFramework::Core::JSON::Variant element = containerVariant;` + '\n' + } + else { + result += ` ${subPropertyType}& element = *(*(static_cast*>(value)));` + '\n' + } + } else { + result += ` ${elementContainer} element(value);` + '\n' + } + result += ` (*var)->Set(const_cast(key), element); +}` + '\n' - if (json.type === 'object') { - result += `${objName}_${propertyType}Handle ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { + result += `void ${objName}_RemoveKey(${objName}Handle handle, char* key) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); ASSERT(var->IsValid()); - WPEFramework::Core::ProxyType<${objName}::${propertyType}>* object = new WPEFramework::Core::ProxyType<${objName}::${propertyType}>(); - *object = WPEFramework::Core::ProxyType<${objName}::${propertyName}>::Create(); - *(*object) = (*var)->Find(key); - return (static_cast<${objName}_${propertyType}Handle>(object));` + '\n' - } else if (json.type === 'array') { - result += `${objName}_${propertyType}ArrayHandle ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { - ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); - ASSERT(var->IsValid()); - WPEFramework::Core::ProxyType>* object = new WPEFramework::Core::ProxyType>(); - *object = WPEFramework::Core::ProxyType>::Create(); - *(*object) = (*var)->Find(key); - return (static_cast<${objName}_${propertyType}ArrayHandle>(object));` + '\n' + (*var)->Remove(key); +}` + '\n' - } else { - result += `${propertyType} ${objName}_${propertyName}_FindKey(${objName}_${propertyName}Handle handle, char* key) { + result += `${accessorPropertyType} ${objName}_FindKey(${objName}Handle handle, char* key) +{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${objName}::${propertyName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); ASSERT(var->IsValid());` + '\n' - - if (json.type === 'string') { + if ((json.type === 'object') || (json.type === 'array') || + ((json.type === 'string' || (typeof json.const === 'string')) && !json.enum)) { + result += ` ${accessorPropertyType} status = nullptr;` + '\n' + } + else if (json.type === 'boolean') { + result += ` ${accessorPropertyType} status = false;` + '\n' + } + else { + result += ` ${accessorPropertyType} status = 0;` + '\n' + } + + result += ` + if ((*var)->HasLabel(key) == true) {` + if (json.type === 'object') { + result += ` + string objectStr; + (*var)->Get(key).Object().ToString(objectStr); + ${subPropertyType} objectMap; + objectMap.FromString(objectStr); + + WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); + *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); + *(*element) = objectMap; + + status = (static_cast<${accessorPropertyType}>(element));` + '\n' + } + else if (json.type === 'array' && json.items) { + result += ` + WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); + *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); + *(*element) = (*var)->Get(key).Array(); + status = (static_cast<${accessorPropertyType}>(element));` + '\n' + } + else { + if (json.type === 'string' || (typeof json.const === 'string')) { + if (json.enum) { + result += ` + status = (const_cast<${accessorPropertyType}>((*var)->Get(key).));` + '\n' + } + else { + result += ` + status = (const_cast<${accessorPropertyType}>((*var)->Get(key).String().c_str()));` + '\n' + } + } + else if (json.type === 'boolean') { + result += ` + status = (static_cast<${accessorPropertyType}>((*var)->Get(key).Boolean()));` + '\n' + } + else if (json.type === 'number') { result += ` - return (static_cast<${propertyType}>((*var)->(Find(key).Value().c_str())));` + '\n' - } else { + status = (static_cast<${accessorPropertyType}>((*var)->Get(key).Float()));` + '\n' + } + else if (json.type === 'integer') { result += ` - return (static_cast<${propertyType}>((*var)->(Find(key).Value())));` + '\n' + status = (static_cast<${accessorPropertyType}>((*var)->Get(key).Number()));` + '\n' } } - result += ` -}` + '\n' + result += ` } + return status; +}` return result } export { + getArrayAccessorsImpl, + getMapAccessorsImpl, getObjectHandleManagementImpl, getPropertyAccessorsImpl } diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index 97a9385a..3437c98c 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -1,31 +1,54 @@ const capitalize = str => str[0].toUpperCase() + str.substr(1) +const getSdkNameSpace = () => 'FireboltSDK' +const getJsonDataPrefix = () => 'JsonData_' +const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' -function getJsonContainerDefinition (name, props) { - name = capitalize(name) - let c = ` class ${name}: public Core::JSON::Container { - public: - ${name}(const ${name}&) = delete; - ${name}& operator=(const ${name}&) = delete; - ~${name}() override = default; - - public: - ${name}() - : Core::JSON::Container() - {` +const getJsonDataStructName = (modName, name, prefix = '') => { + let result =((prefix.length > 0) && (!name.startsWith(prefix))) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}_${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` + + return ((result.includes(wpeJsonNameSpace()) === true) ? result : `${getSdkNameSpace()}::${result}`) +} + +function getJsonContainerDefinition (schema, name, props) { + let c = schema.description ? (' /*\n * ${info.title} - ' + `${schema.description}\n */\n`) : '' + name = getJsonDataPrefix() + capitalize(name) + c += ` class ${name}: public WPEFramework::Core::JSON::Container { + public: + ~${name}() override = default; - props.forEach(prop => { - c += `\n Add(_T("${prop.name}"), &${capitalize(prop.name)});` - }) + public: + ${name}() + : WPEFramework::Core::JSON::Container() + {` - c += `\n }\n\n public:` + props.forEach(prop => { + c += `\n Add(_T("${prop.name}"), &${capitalize(prop.name)});` + }) + c += `\n }\n` + c += `\n ${name}(const ${name}& copy) + {` + props.forEach(prop => { + c += `\n Add(_T("${prop.name}"), &${capitalize(prop.name)});` + c += `\n ${capitalize(prop.name)} = copy.${capitalize(prop.name)};` + }) + c += ` + }\n + ${name}& operator=(const ${name}& rhs) + {` + props.forEach(prop => { + c += `\n ${capitalize(prop.name)} = rhs.${capitalize(prop.name)};` + }) + c += `\n return (*this); + }\n + public:` - props.forEach(prop => { - c += `\n ${prop.type} ${capitalize(prop.name)};` - }) + props.forEach(prop => { + c += `\n ${prop.type} ${capitalize(prop.name)};` + }) - c += '\n };' - return c - } + c += '\n };' + return c +} export { getJsonContainerDefinition diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 79242d1f..eac20c16 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -29,6 +29,7 @@ const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = pre const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' +const getFireboltStringType = () => 'FireboltTypes_StringHandle' const getHeaderText = () => { return `/* @@ -83,35 +84,53 @@ const SdkTypesPrefix = 'Firebolt' const Indent = ' ' -const getNativeType = json => { - let type - - if (json.const) { - if (typeof json.const === 'string') { - type = 'char*' - } - else if (typeof json.const === 'number') { - type = 'uint32_t' - if (json.const < 0) - type = 'int32_t' - } else if (typeof json.const === 'boolean'){ - type = 'bool' - } +const getArrayElementSchema = (json, module, schemas = {}, name) => { + let result = '' + if (json.type === 'array' && json.items) { + if (Array.isArray(json.items)) { + result = json.items[0] } - else if (json.type === 'string') { - type = 'char*' + else { + // grab the type for the non-array schema + result = json.items } - else if (json.type === 'number' || json.type === 'integer') { //Lets keep it simple for now - type = 'uint32_t' - if ((json.minimum && json.minimum < 0) - || (json.exclusiveMinimum && json.exclusiveMinimum < 0)) { - type = 'int32_t' - } + if (result['$ref']) { + result = getPath(result['$ref'], module, schemas) } - else if (json.type === 'boolean') { - type = 'bool' + } + else if (json.type == 'object') { + if (json.properties) { + Object.entries(json.properties).every(([pname, prop]) => { + if (prop.type === 'array') { + result = getArrayElementSchema(prop, module, schemas) + if (name === capitalize(pname)) { + return false + } + } + return true + }) } - return type + } + + return result +} + +const getNativeType = json => { + let type = '' + let jsonType = json.const ? typeof json.const : json.type + if (jsonType === 'string') { + type = 'char*' + } + else if (jsonType === 'number') { + type = 'float' + } + else if (jsonType === 'integer') { + type = 'int32_t' + } + else if (jsonType === 'boolean') { + type = 'bool' + } + return type } const getObjectHandleManagement = varName => { @@ -126,46 +145,51 @@ bool ${varName}Handle_IsValid(${varName}Handle handle); } const getPropertyAccessors = (objName, propertyName, propertyType, options = {level:0, readonly:false, optional:false}) => { - let result = `${Indent.repeat(options.level)}${propertyType} ${objName}_Get_${propertyName}(${objName}Handle handle);` + '\n' if (!options.readonly) { - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${propertyType} ${propertyName.toLowerCase()});` + '\n' + let type = (propertyType === getFireboltStringType()) ? 'char*' : propertyType + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${type} ${propertyName.toLowerCase()});` + '\n' } if (options.optional === true) { - result += `${Indent.repeat(options.level)}bool ${objName}_has_${propertyName}(${objName}Handle handle);` + '\n' - result += `${Indent.repeat(options.level)}void ${objName}_clear_${propertyName}(${objName}Handle handle);` + '\n' + result += `${Indent.repeat(options.level)}bool ${objName}_Has_${propertyName}(${objName}Handle handle);` + '\n' + result += `${Indent.repeat(options.level)}void ${objName}_Clear_${propertyName}(${objName}Handle handle);` + '\n' } return result } -const getMapAccessors = (typeName, nativeType, level=0) => { +const getMapAccessors = (typeName, accessorPropertyType, level = 0) => { let res res = `${Indent.repeat(level)}uint32_t ${typeName}_KeysCount(${typeName}Handle handle);` + '\n' - res += `${Indent.repeat(level)}void ${typeName}_AddKey(${typeName}Handle handle, char* key, ${nativeType} value);` + '\n' + res += `${Indent.repeat(level)}void ${typeName}_AddKey(${typeName}Handle handle, char* key, ${accessorPropertyType} value);` + '\n' res += `${Indent.repeat(level)}void ${typeName}_RemoveKey(${typeName}Handle handle, char* key);` + '\n' - res += `${Indent.repeat(level)}${nativeType} ${typeName}_FindKey(${typeName}Handle handle, char* key);` + '\n' + res += `${Indent.repeat(level)}${accessorPropertyType} ${typeName}_FindKey(${typeName}Handle handle, char* key);` + '\n' return res } -const getTypeName = (moduleName, varName, upperCase = false) => { - let mName = upperCase ? moduleName.toUpperCase() : capitalize(moduleName) - let vName = upperCase ? varName.toUpperCase() : capitalize(varName) +const getTypeName = (moduleName, varName, prefix = '', upperCase = false, capitalCase = true) => { - return `${mName}_${vName}` + let mName = upperCase ? moduleName.toUpperCase() : capitalize(moduleName) + let vName = upperCase ? varName.toUpperCase() : capitalCase ? capitalize(varName) : varName + if (prefix.length > 0) { + prefix = (!varName.startsWith(prefix)) ? (upperCase ? prefix.toUpperCase() : capitalize(prefix)) : '' + } + prefix = (prefix.length > 0) ?(upperCase ? prefix.toUpperCase() : capitalize(prefix)) : prefix + let name = (prefix.length > 0) ? `${mName}_${prefix}_${vName}` : `${mName}_${vName}` + return name } -const getArrayAccessors = (arrayName, valueType) => { +const getArrayAccessors = (arrayName, propertyType, valueType) => { - let res = `uint32_t ${arrayName}_Size(${arrayName}Handle handle);` + '\n' - res += `${valueType} ${arrayName}_Get(${arrayName}Handle handle, uint32_t index);` + '\n' - res += `void ${arrayName}_Add(${arrayName}Handle handle, ${valueType} value);` + '\n' - res += `void ${arrayName}_Clear(${arrayName}Handle handle);` + '\n' + let res = `uint32_t ${arrayName}Array_Size(${propertyType}Handle handle);` + '\n' + res += `${valueType} ${arrayName}Array_Get(${propertyType}Handle handle, uint32_t index);` + '\n' + res += `void ${arrayName}Array_Add(${propertyType}Handle handle, ${valueType} value);` + '\n' + res += `void ${arrayName}Array_Clear(${propertyType}Handle handle);` + '\n' return res } @@ -201,25 +225,25 @@ const getIncludeDefinitions = (json = {}, jsonData = false) => { .concat([`#include "Firebolt/Types.h"`]) } - function getPropertyGetterSignature(method, module, paramType) { - let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` - return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` - } +function getPropertyGetterSignature(method, module, paramType) { + let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` + return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` +} - function getPropertySetterSignature(method, module, paramType) { - let m = `${capitalize(getModuleName(module))}_Set${capitalize(method.name)}` - return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType} ${method.result.name || method.name} )` - } +function getPropertySetterSignature(method, module, paramType) { + let m = `${capitalize(getModuleName(module))}_Set${capitalize(method.name)}` + return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType} ${method.result.name || method.name} )` +} - function getPropertyEventCallbackSignature(method, module, paramType) { - return `typedef void (*On${capitalize(method.name)}Changed)(${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType})` - } +function getPropertyEventCallbackSignature(method, module, paramType) { + return `typedef void (*On${capitalize(method.name)}Changed)(${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType})` +} - function getPropertyEventSignature(method, module) { - return `${description(method.name, 'Listen to updates')}\n` + `uint32_t ${capitalize(getModuleName(module))}_Listen${capitalize(method.name)}Update(On${capitalize(method.name)}Changed notification, uint16_t* listenerId)` - } +function getPropertyEventSignature(method, module) { + return `${description(method.name, 'Listen to updates')}\n` + `uint32_t ${capitalize(getModuleName(module))}_Listen${capitalize(method.name)}Update(On${capitalize(method.name)}Changed notification, uint16_t* listenerId)` +} - export { +export { getHeaderText, getIncludeGuardOpen, getStyleGuardOpen, @@ -240,5 +264,6 @@ const getIncludeDefinitions = (json = {}, jsonData = false) => { getObjectHandleManagement, getPropertyAccessors, isOptional, - generateEnum - } + generateEnum, + getArrayElementSchema +} diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 8f301bea..1c70ba29 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,12 +1,12 @@ /* ${method.name} - ${method.description} */ uint32_t ${info.title}_Get${method.Name}(${method.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { - const string method = _T("${info.title}.${method.name}"); - FireboltSDK::${info.title}::${method.result.type} jsonResult; + const string method = _T("${info.title}.${method.name}"); + FireboltSDK::${info.title}::${method.result.type} jsonResult; - uint32_t status = FireboltSDK::Properties::Get(method, jsonResult); - if (status == FireboltSDKErrorNone) { - WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); - *${method.result.name} = static_cast<${info.title}_${method.result.type}Handle>(resultPtr); - } - return status; + uint32_t status = FireboltSDK::Properties::Get(method, jsonResult); + if (status == FireboltSDKErrorNone) { + WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); + *${method.result.name} = static_cast<${info.title}_${method.result.type}Handle>(resultPtr); + } + return status; } diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/Module.h index ee034605..a202f643 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/Module.h @@ -30,10 +30,6 @@ extern "C" { /* ${ENUMS} */ -// Types - -/* ${TYPES} */ - /* ${ACCESSORS} */ /* ${DECLARATIONS} */ diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 346d07cd..c412abf2 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -25,7 +25,6 @@ namespace FireboltSDK { namespace ${info.title} { // Types - /* ${TYPES} */ } } diff --git a/languages/c/templates/schemas/default.c b/languages/c/templates/schemas/default.c index a2058da5..9a52cff7 100644 --- a/languages/c/templates/schemas/default.c +++ b/languages/c/templates/schemas/default.c @@ -1,4 +1 @@ -/* - * ${schema.description} - */ ${schema.shape} diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/JsonData_Module.h index 9ba90428..7fa2b6f4 100644 --- a/languages/c/templates/schemas/src/JsonData_Module.h +++ b/languages/c/templates/schemas/src/JsonData_Module.h @@ -20,6 +20,6 @@ namespace FireboltSDK { namespace ${info.title} { // Types - /* ${SCHEMAS}*/ + /* ${SCHEMAS} */ } } diff --git a/languages/c/templates/sections/accessors.c b/languages/c/templates/sections/accessors.c index 0586b2a5..1c790810 100644 --- a/languages/c/templates/sections/accessors.c +++ b/languages/c/templates/sections/accessors.c @@ -1,3 +1,2 @@ // Accessors - ${schema.list} diff --git a/languages/c/templates/sections/methods.c b/languages/c/templates/sections/methods.c index 3f382a63..3ab606c0 100644 --- a/languages/c/templates/sections/methods.c +++ b/languages/c/templates/sections/methods.c @@ -1,3 +1,4 @@ - // Methods +// Methods + ${method.list} diff --git a/languages/c/templates/sections/methods_accessors.c b/languages/c/templates/sections/methods_accessors.c new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/c/templates/sections/methods_accessors.c @@ -0,0 +1 @@ +${schema.list} diff --git a/languages/c/templates/sections/methods_types.c b/languages/c/templates/sections/methods_types.c new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/c/templates/sections/methods_types.c @@ -0,0 +1 @@ +${schema.list} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index f7873abb..37cf09d5 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -65,6 +65,7 @@ const state = { } const capitalize = str => str[0].toUpperCase() + str.substr(1) +const hasMethodsSchema = (json, options) => json.methods && json.methods.length const setTyper = (t) => { types = t @@ -101,15 +102,11 @@ const getTemplateForExampleResult = (method, templates) => { return template || JSON.stringify(method.examples[0].result.value, null, '\t') } -const getLinkForSchema = (schema, json) => { +const getLinkForSchema = (schema, json, { name = '' } = {}) => { const dirs = config.createModuleDirectories const copySchemasIntoModules = config.copySchemasIntoModules - if (schema.schema) { - schema = schema.schema - } - - const type = types.getSchemaType(schema, json, { destination: state.destination, section: state.section }) + const type = types.getSchemaType(schema, json, { name: name, 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]) { @@ -336,16 +333,22 @@ const generateMacros = (obj, templates, languages, options = {}) => { const declarations = declarationsArray.length ? getTemplate('/sections/declarations', templates).replace(/\$\{declaration\.list\}/g, declarationsArray.map(m => m.declaration).join('\n')) : '' 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 methodTypesArray = generateSchemas(obj, templates, { baseUrl: '', section: 'methods_schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) + const methodTypes = methodTypesArray.length ? getTemplate('/sections/methods_types', templates).replace(/\$\{schema.list\}/g, methodTypesArray.map(s => s.body).filter(body => body).join('\n')) : '' + const methodAccessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'methods_accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) + const methodAccessors = methodAccessorsArray.length ? getTemplate('/sections/methods_accessors', templates).replace(/\$\{schema.list\}/g, methodAccessorsArray.map(s => s.body).filter(body => body).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 schemasArray = generateSchemas(obj, templates, { baseUrl: '', section: 'schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) const accessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) - const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).join('\n')) : '' + const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).filter(body => body).join('\n')) : '' const typesArray = schemasArray.filter(x => !x.enum) - const types = typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).join('\n')) : '' - const accessors = accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).join('\n')) : '' + const types = (typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodTypes + + const accessors = (accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodAccessors const module = getTemplate('/codeblocks/module', templates) const macros = { @@ -624,9 +627,9 @@ const isEnum = x => x.type && x.type === 'string' && Array.isArray(x.enum) && x. function generateSchemas(json, templates, options) { let results = [] - const schemas = json.definitions || (json.components && json.components.schemas) || {} + const schemas = (options.section.includes('methods') ? (hasMethodsSchema(json) ? json.methods : '') : (json.definitions || (json.components && json.components.schemas) || {})) - const generate = (name, schema, uri) => { + const generate = (name, schema, uri, { prefix = '' } = {}) => { // these are internal schemas used by the firebolt-openrpc tooling, and not meant to be used in code/doc generation if (['ListenResponse', 'ProviderRequest', 'ProviderResponse', 'FederatedResponse', 'FederatedRequest'].includes(name)) { return @@ -647,7 +650,7 @@ function generateSchemas(json, templates, options) { else { content = content.replace(/\$\{if\.description\}(.*?)\{end\.if\.description\}/gms, '$1') } - const schemaShape = types.getSchemaShape(schema, json, { name, destination: state.destination, section: options.section }) + const schemaShape = types.getSchemaShape(schema, json, { name, prefix, destination: state.destination, section: options.section }) content = content .replace(/\$\{schema.title\}/, (schema.title || name)) @@ -665,6 +668,9 @@ function generateSchemas(json, templates, options) { else { content = content.replace(/.*\$\{schema.seeAlso\}/, '') } + content = content.trim().length ? content.trimEnd() : content.trim() + + const isEnum = x => x.type === 'string' && Array.isArray(x.enum) && x.title const result = uri ? { uri: uri, @@ -687,6 +693,18 @@ function generateSchemas(json, templates, options) { if (isSchema(schema)) { list.push([name, schema]) } + else if (schema.tags) { + if (!isDeprecatedMethod(schema)) { + schema.params.forEach(param => { + if (param.schema && (param.schema.type === 'object')) { + list.push([param.name, param.schema, '', { prefix : schema.name}]) + } + }) + if (schema.result.schema && (schema.result.schema.type === 'object')) { + list.push([schema.result.name, schema.result.schema, '', { prefix : schema.name}]) + } + } + } }) list.sort((a, b) => { @@ -718,7 +736,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, { destination: state.destination, section: state.section }) + '](' + getLinkForSchema(schema, json, true) + ')') // need full module here, not just the schema + .map(schema => '[' + types.getSchemaType(schema, json, { name: schema.title, 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') @@ -1061,10 +1079,10 @@ 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, json)) //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result.schema, json, {title: true, asPath: false, destination: state.destination })) //, baseUrl: options.baseUrl - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates)) + .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, title: true, asPath: false, destination: state.destination })) //, baseUrl: options.baseUrl + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name : result.name })) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) .replace(/\$\{method\.alternative.link\}/g, '#'+(method.alternative || "").toLowerCase()) @@ -1192,8 +1210,9 @@ function insertExampleMacros(template, examples, method, json, templates) { return template.replace(/\$\{method\.examples\}/g, content) } -function generateResult(result, json, templates) { - const type = types.getSchemaType(result, json, { destination: state.destination, section: state.section }) +function generateResult(result, json, templates, { name = '' } = {}) { + + const type = types.getSchemaType(result, json, { name: name, destination: state.destination, section: state.section }) if (result.type === 'object' && result.properties) { let content = getTemplate('/types/object', templates).split('\n') @@ -1204,13 +1223,13 @@ function generateResult(result, json, templates) { } } - return insertSchemaMacros(content.join('\n'), result.title, result, json) + return insertSchemaMacros(content.join('\n'), name, result, json) } else if (type === 'string' && Array.isArray(result.enum)) { - return insertSchemaMacros(getTemplate('/types/enum', templates), result, json) + return insertSchemaMacros(getTemplate('/types/enum', templates), name, result, json) } else if (result.$ref) { - const link = getLinkForSchema(result, json) + const link = getLinkForSchema(result, json, { name: name}) // if we get a real link use it if (link !== '#') { @@ -1220,18 +1239,18 @@ function generateResult(result, json, templates) { else { const schema = localizeDependencies(result, json) return getTemplate('/types/default', templates) - .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { name: result.$ref.split("/").pop()})) + .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { name: result.$ref.split("/").pop() })) } } else { - return insertSchemaMacros(getTemplate('/types/default', templates), result.title, result, json) + return insertSchemaMacros(getTemplate('/types/default', templates), name, result, json) } } function insertSchemaMacros(template, title, schema, module) { return template.replace(/\$\{property\}/g, title) - .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { destination: state.destination, section: state.section, code: false })) - .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module)) + .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { name: title, destination: state.destination, section: state.section, code: false })) + .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module, { name: title })) .replace(/\$\{description\}/g, schema.description || '') .replace(/\$\{name\}/g, title || '') } @@ -1241,9 +1260,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, { destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl - let typeLink = getLinkForSchema(param, module) - let jsonType = types.getJsonType(param.schema, module, { destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) + let type = types.getSchemaType(param.schema, module, { name: param.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl + let typeLink = getLinkForSchema(param.schema, module, { name: param.name }) + let jsonType = types.getJsonType(param.schema, module, { name: param.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) if (constraints && type) { constraints = '
' + constraints @@ -1256,7 +1275,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, module)) //getType(param)) + .replace(/\$\{method.param.link\}/g, getLinkForSchema(param.schema, module, { name: param.name} )) //getType(param)) .replace(/\$\{method.param.constraints\}/g, constraints) //getType(param)) } diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 89c194e2..f8acada8 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -199,8 +199,6 @@ const macrofy = async ( delete outputFiles[file] } }) - - console.log() } // Grab all schema groups w/ a URI string. These came from some external json-schema that was bundled into the OpenRPC @@ -271,4 +269,4 @@ const macrofy = async ( }) } -export default macrofy \ No newline at end of file +export default macrofy From 3ab8bad0f575fa8ada217420f5409fa093c8cf2a Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 8 Jun 2023 09:23:36 +0530 Subject: [PATCH 074/137] Static code implementation updates (#96) Static code implementation updates Co-authored-by: Jeremy LaCivita --- languages/c/templates/modules/src/Module.cpp | 2 - languages/c/templates/sdk/CMakeLists.txt | 24 +- .../c/templates/sdk/build/CMakeCache.txt | 407 -------- .../CMakeFiles/3.25.3/CMakeCCompiler.cmake | 72 -- .../CMakeFiles/3.25.3/CMakeCXXCompiler.cmake | 83 -- .../3.25.3/CMakeDetermineCompilerABI_C.bin | Bin 16999 -> 0 bytes .../3.25.3/CMakeDetermineCompilerABI_CXX.bin | Bin 16983 -> 0 bytes .../build/CMakeFiles/3.25.3/CMakeSystem.cmake | 15 - .../3.25.3/CompilerIdC/CMakeCCompilerId.c | 868 ------------------ .../3.25.3/CompilerIdC/CMakeCCompilerId.o | Bin 1712 -> 0 bytes .../CompilerIdCXX/CMakeCXXCompilerId.cpp | 857 ----------------- .../3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o | Bin 1712 -> 0 bytes .../sdk/build/CMakeFiles/CMakeError.log | 0 .../sdk/build/CMakeFiles/CMakeOutput.log | 266 ------ .../sdk/build/CMakeFiles/cmake.check_cache | 1 - .../c/templates/sdk/cmake/CopySymlink.cmake | 17 - .../templates/sdk/cmake/HelperFunctions.cmake | 19 +- .../c/templates/sdk/cmake/project.cmake.in | 5 + languages/c/templates/sdk/include/Firebolt.h | 65 ++ languages/c/templates/sdk/include/Types.h | 8 +- languages/c/templates/sdk/scripts/build.sh | 11 + .../c/templates/sdk/src/Accessor/Accessor.cpp | 41 +- .../c/templates/sdk/src/Accessor/Accessor.h | 77 +- .../c/templates/sdk/src/Accessor/WorkerPool.h | 30 + languages/c/templates/sdk/src/CMakeLists.txt | 29 +- languages/c/templates/sdk/src/Config.cmake | 34 - languages/c/templates/sdk/src/Event/Event.cpp | 39 +- languages/c/templates/sdk/src/Event/Event.h | 75 +- .../src/{Accessor/Config.h => Firebolt.cpp} | 43 +- .../sdk/src/{Firebolt.h => FireboltSDK.h} | 1 + .../c/templates/sdk/src/Logger/Logger.cpp | 1 - languages/c/templates/sdk/src/Module.h | 2 - languages/c/templates/sdk/src/Params.config | 3 - .../templates/sdk/src/Properties/Properties.h | 72 +- .../c/templates/sdk/src/Transport/Transport.h | 4 +- languages/c/templates/sdk/src/Types.cpp | 7 +- languages/c/templates/sdk/src/TypesPriv.h | 29 +- .../templates/sdk/src/cmake/CopySymlink.cmake | 1 - 38 files changed, 393 insertions(+), 2815 deletions(-) delete mode 100644 languages/c/templates/sdk/build/CMakeCache.txt delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake delete mode 100755 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin delete mode 100755 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_CXX.bin delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeSystem.cmake delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.c delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.cpp delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/CMakeError.log delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/CMakeOutput.log delete mode 100644 languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache delete mode 100644 languages/c/templates/sdk/cmake/CopySymlink.cmake create mode 100644 languages/c/templates/sdk/include/Firebolt.h create mode 100755 languages/c/templates/sdk/scripts/build.sh delete mode 100644 languages/c/templates/sdk/src/Config.cmake rename languages/c/templates/sdk/src/{Accessor/Config.h => Firebolt.cpp} (50%) rename languages/c/templates/sdk/src/{Firebolt.h => FireboltSDK.h} (97%) delete mode 100644 languages/c/templates/sdk/src/Params.config delete mode 100644 languages/c/templates/sdk/src/cmake/CopySymlink.cmake diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index c412abf2..47a356d6 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -41,5 +41,3 @@ extern "C" { #ifdef __cplusplus } #endif - - diff --git a/languages/c/templates/sdk/CMakeLists.txt b/languages/c/templates/sdk/CMakeLists.txt index a29658f7..5efcad1a 100644 --- a/languages/c/templates/sdk/CMakeLists.txt +++ b/languages/c/templates/sdk/CMakeLists.txt @@ -20,19 +20,31 @@ project(Firebolt) set(FIREBOLT_TRANSPORT_WAITTIME 1000 CACHE STRING "Maximum time to wait for Transport layer to get response") set(FIREBOLT_LOGLEVEL "Info" CACHE STRING "Log level to be enabled") - +option(FIREBOLT_ENABLE_STATIC_LIB "Create Firebolt library as Static library" OFF) option(ENABLE_TESTS "Build openrpc native test" OFF) +if (NOT SYSROOT_PATH) + # Set sysroot to support PC builds, sysroot_path not configured case + set(SYSROOT_PATH "${CMAKE_SOURCE_DIR}/../../firebolt") +endif() + +if (FIREBOLT_ENABLE_STATIC_LIB) + set(FIREBOLT_LIBRARY_TYPE STATIC) +else () + set(FIREBOLT_LIBRARY_TYPE SHARED) +endif () + +if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${SYSROOT_PATH}/usr" CACHE INTERNAL "" FORCE) + set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) +endif() + list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake" "${SYSROOT_PATH}/usr/lib/cmake" "${SYSROOT_PATH}/tools/cmake") include(HelperFunctions) -if (NOT DEFINED CMAKE_PREFIX_PATH) - set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) -endif() - set(FIREBOLT_NAMESPACE ${PROJECT_NAME} CACHE STRING "Namespace of the project") find_package(WPEFramework CONFIG REQUIRED) @@ -45,5 +57,5 @@ endif() # make sure others can make use cmake settings of Firebolt OpenRPC configure_file( "${CMAKE_SOURCE_DIR}/cmake/project.cmake.in" - "${CMAKE_CURRENT_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake" + "${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake" @ONLY) diff --git a/languages/c/templates/sdk/build/CMakeCache.txt b/languages/c/templates/sdk/build/CMakeCache.txt deleted file mode 100644 index f10d476d..00000000 --- a/languages/c/templates/sdk/build/CMakeCache.txt +++ /dev/null @@ -1,407 +0,0 @@ -# This is the CMakeCache file. -# For build in directory: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build -# It was generated by CMake: /opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -# You can edit this file to change values found and used by cmake. -# If you do not want to change any of the values, simply exit the editor. -# If you do want to change a value, simply edit, save, and exit the editor. -# The syntax for the file is as follows: -# KEY:TYPE=VALUE -# KEY is the name of a variable in the cache. -# TYPE is a hint to GUIs for the type of VALUE, DO NOT EDIT TYPE!. -# VALUE is the current value for the KEY. - -######################## -# EXTERNAL cache entries -######################## - -//Path to a program. -CMAKE_ADDR2LINE:FILEPATH=CMAKE_ADDR2LINE-NOTFOUND - -//Path to a program. -CMAKE_AR:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ar - -//Choose the type of build, options are: None Debug Release RelWithDebInfo -// MinSizeRel ... -CMAKE_BUILD_TYPE:STRING=Release - -//Enable/Disable color output during build. -CMAKE_COLOR_MAKEFILE:BOOL=ON - -//CXX compiler -CMAKE_CXX_COMPILER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/c++ - -//Flags used by the CXX compiler during all build types. -CMAKE_CXX_FLAGS:STRING=-D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION - -//Flags used by the CXX compiler during DEBUG builds. -CMAKE_CXX_FLAGS_DEBUG:STRING=-g - -//Flags used by the CXX compiler during MINSIZEREL builds. -CMAKE_CXX_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG - -//Flags used by the CXX compiler during RELEASE builds. -CMAKE_CXX_FLAGS_RELEASE:STRING=-O3 -DNDEBUG - -//Flags used by the CXX compiler during RELWITHDEBINFO builds. -CMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG - -//C compiler -CMAKE_C_COMPILER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/cc - -//Flags used by the C compiler during all build types. -CMAKE_C_FLAGS:STRING= - -//Flags used by the C compiler during DEBUG builds. -CMAKE_C_FLAGS_DEBUG:STRING=-g - -//Flags used by the C compiler during MINSIZEREL builds. -CMAKE_C_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG - -//Flags used by the C compiler during RELEASE builds. -CMAKE_C_FLAGS_RELEASE:STRING=-O3 -DNDEBUG - -//Flags used by the C compiler during RELWITHDEBINFO builds. -CMAKE_C_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG - -//Path to a program. -CMAKE_DLLTOOL:FILEPATH=CMAKE_DLLTOOL-NOTFOUND - -//Flags used by the linker during all build types. -CMAKE_EXE_LINKER_FLAGS:STRING= - -//Flags used by the linker during DEBUG builds. -CMAKE_EXE_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during MINSIZEREL builds. -CMAKE_EXE_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during RELEASE builds. -CMAKE_EXE_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during RELWITHDEBINFO builds. -CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//Enable/Disable output of compile commands during generation. -CMAKE_EXPORT_COMPILE_COMMANDS:BOOL= - -//Value Computed by CMake. -CMAKE_FIND_PACKAGE_REDIRECTS_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/pkgRedirects - -//Path to a program. -CMAKE_INSTALL_NAME_TOOL:FILEPATH=/usr/bin/install_name_tool - -//Install path prefix, prepended onto install directories. -CMAKE_INSTALL_PREFIX:PATH=/usr - -//No help, variable specified on the command line. -CMAKE_JS_INC:UNINITIALIZED=/Users/JLaciv000/.cmake-js/node-arm64/v19.6.1/include/node - -//No help, variable specified on the command line. -CMAKE_JS_SRC:UNINITIALIZED= - -//No help, variable specified on the command line. -CMAKE_JS_VERSION:UNINITIALIZED=undefined - -//No help, variable specified on the command line. -CMAKE_LIBRARY_OUTPUT_DIRECTORY:UNINITIALIZED=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/Release - -//Path to a program. -CMAKE_LINKER:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ld - -//Path to a program. -CMAKE_MAKE_PROGRAM:FILEPATH=/usr/bin/make - -//Flags used by the linker during the creation of modules during -// all build types. -CMAKE_MODULE_LINKER_FLAGS:STRING= - -//Flags used by the linker during the creation of modules during -// DEBUG builds. -CMAKE_MODULE_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during the creation of modules during -// MINSIZEREL builds. -CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during the creation of modules during -// RELEASE builds. -CMAKE_MODULE_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during the creation of modules during -// RELWITHDEBINFO builds. -CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//No help, variable specified on the command line. -CMAKE_MSVC_RUNTIME_LIBRARY:UNINITIALIZED=MultiThreaded$<$:Debug> - -//Path to a program. -CMAKE_NM:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/nm - -//Path to a program. -CMAKE_OBJCOPY:FILEPATH=CMAKE_OBJCOPY-NOTFOUND - -//Path to a program. -CMAKE_OBJDUMP:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/objdump - -//Build architectures for OSX -CMAKE_OSX_ARCHITECTURES:STRING=arm64 - -//Minimum OS X version to target for deployment (at runtime); newer -// APIs weak linked. Set to empty string for default value. -CMAKE_OSX_DEPLOYMENT_TARGET:STRING= - -//The product will be built against the headers and libraries located -// inside the indicated SDK. -CMAKE_OSX_SYSROOT:PATH=/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk - -//Value Computed by CMake -CMAKE_PROJECT_DESCRIPTION:STATIC= - -//Value Computed by CMake -CMAKE_PROJECT_HOMEPAGE_URL:STATIC= - -//Value Computed by CMake -CMAKE_PROJECT_NAME:STATIC=Firebolt - -//Path to a program. -CMAKE_RANLIB:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/ranlib - -//Path to a program. -CMAKE_READELF:FILEPATH=CMAKE_READELF-NOTFOUND - -//Flags used by the linker during the creation of shared libraries -// during all build types. -CMAKE_SHARED_LINKER_FLAGS:STRING=-undefined dynamic_lookup - -//Flags used by the linker during the creation of shared libraries -// during DEBUG builds. -CMAKE_SHARED_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during the creation of shared libraries -// during MINSIZEREL builds. -CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during the creation of shared libraries -// during RELEASE builds. -CMAKE_SHARED_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during the creation of shared libraries -// during RELWITHDEBINFO builds. -CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//If set, runtime paths are not added when installing shared libraries, -// but are added when building. -CMAKE_SKIP_INSTALL_RPATH:BOOL=NO - -//If set, runtime paths are not added when using shared libraries. -CMAKE_SKIP_RPATH:BOOL=NO - -//Flags used by the linker during the creation of static libraries -// during all build types. -CMAKE_STATIC_LINKER_FLAGS:STRING= - -//Flags used by the linker during the creation of static libraries -// during DEBUG builds. -CMAKE_STATIC_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during the creation of static libraries -// during MINSIZEREL builds. -CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during the creation of static libraries -// during RELEASE builds. -CMAKE_STATIC_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during the creation of static libraries -// during RELWITHDEBINFO builds. -CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//Path to a program. -CMAKE_STRIP:FILEPATH=/Library/Developer/CommandLineTools/usr/bin/strip - -//If this value is on, makefiles will be generated without the -// .SILENT directive, and all commands will be echoed to the console -// during the make. This is useful for debugging only. With Visual -// Studio IDE projects all commands are done without /nologo. -CMAKE_VERBOSE_MAKEFILE:BOOL=FALSE - -//Build openrpc native test -ENABLE_TESTS:BOOL=OFF - -//Log level to be enabled -FIREBOLT_LOGLEVEL:STRING=Info - -//Namespace of the project -FIREBOLT_NAMESPACE:STRING=Firebolt - -//Maximum time to wait for Transport layer to get response -FIREBOLT_TRANSPORT_WAITTIME:STRING=1000 - -//Value Computed by CMake -Firebolt_BINARY_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build - -//Value Computed by CMake -Firebolt_IS_TOP_LEVEL:STATIC=ON - -//Value Computed by CMake -Firebolt_SOURCE_DIR:STATIC=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native - -//No help, variable specified on the command line. -GENERATED_CODE_PATH:UNINITIALIZED=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/build/sdk/native-c - -//No help, variable specified on the command line. -NODE_ARCH:UNINITIALIZED=arm64 - -//No help, variable specified on the command line. -NODE_RUNTIME:UNINITIALIZED=node - -//No help, variable specified on the command line. -NODE_RUNTIMEVERSION:UNINITIALIZED=19.6.1 - -//The directory containing a CMake configuration file for WPEFramework. -WPEFramework_DIR:PATH=WPEFramework_DIR-NOTFOUND - - -######################## -# INTERNAL cache entries -######################## - -//ADVANCED property for variable: CMAKE_ADDR2LINE -CMAKE_ADDR2LINE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_AR -CMAKE_AR-ADVANCED:INTERNAL=1 -//This is the directory where this CMakeCache.txt was created -CMAKE_CACHEFILE_DIR:INTERNAL=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build -//Major version of cmake used to create the current loaded cache -CMAKE_CACHE_MAJOR_VERSION:INTERNAL=3 -//Minor version of cmake used to create the current loaded cache -CMAKE_CACHE_MINOR_VERSION:INTERNAL=25 -//Patch version of cmake used to create the current loaded cache -CMAKE_CACHE_PATCH_VERSION:INTERNAL=3 -//ADVANCED property for variable: CMAKE_COLOR_MAKEFILE -CMAKE_COLOR_MAKEFILE-ADVANCED:INTERNAL=1 -//Path to CMake executable. -CMAKE_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -//Path to cpack program executable. -CMAKE_CPACK_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/cpack -//Path to ctest program executable. -CMAKE_CTEST_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/ctest -//ADVANCED property for variable: CMAKE_CXX_COMPILER -CMAKE_CXX_COMPILER-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_CXX_FLAGS -CMAKE_CXX_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_CXX_FLAGS_DEBUG -CMAKE_CXX_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_CXX_FLAGS_MINSIZEREL -CMAKE_CXX_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELEASE -CMAKE_CXX_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELWITHDEBINFO -CMAKE_CXX_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_COMPILER -CMAKE_C_COMPILER-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS -CMAKE_C_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_DEBUG -CMAKE_C_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_MINSIZEREL -CMAKE_C_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_RELEASE -CMAKE_C_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_RELWITHDEBINFO -CMAKE_C_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_DLLTOOL -CMAKE_DLLTOOL-ADVANCED:INTERNAL=1 -//Path to cache edit program executable. -CMAKE_EDIT_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/bin/ccmake -//Executable file format -CMAKE_EXECUTABLE_FORMAT:INTERNAL=MACHO -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS -CMAKE_EXE_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_DEBUG -CMAKE_EXE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_MINSIZEREL -CMAKE_EXE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELEASE -CMAKE_EXE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXPORT_COMPILE_COMMANDS -CMAKE_EXPORT_COMPILE_COMMANDS-ADVANCED:INTERNAL=1 -//Name of external makefile project generator. -CMAKE_EXTRA_GENERATOR:INTERNAL= -//Name of generator. -CMAKE_GENERATOR:INTERNAL=Unix Makefiles -//Generator instance identifier. -CMAKE_GENERATOR_INSTANCE:INTERNAL= -//Name of generator platform. -CMAKE_GENERATOR_PLATFORM:INTERNAL= -//Name of generator toolset. -CMAKE_GENERATOR_TOOLSET:INTERNAL= -//Source directory with the top level CMakeLists.txt file for this -// project -CMAKE_HOME_DIRECTORY:INTERNAL=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native -//ADVANCED property for variable: CMAKE_INSTALL_NAME_TOOL -CMAKE_INSTALL_NAME_TOOL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_LINKER -CMAKE_LINKER-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MAKE_PROGRAM -CMAKE_MAKE_PROGRAM-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS -CMAKE_MODULE_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_DEBUG -CMAKE_MODULE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL -CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELEASE -CMAKE_MODULE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_NM -CMAKE_NM-ADVANCED:INTERNAL=1 -//number of local generators -CMAKE_NUMBER_OF_MAKEFILES:INTERNAL=1 -//ADVANCED property for variable: CMAKE_OBJCOPY -CMAKE_OBJCOPY-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_OBJDUMP -CMAKE_OBJDUMP-ADVANCED:INTERNAL=1 -//Platform information initialized -CMAKE_PLATFORM_INFO_INITIALIZED:INTERNAL=1 -CMAKE_PREFIX_PATH:INTERNAL=/usr/lib/cmake -//ADVANCED property for variable: CMAKE_RANLIB -CMAKE_RANLIB-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_READELF -CMAKE_READELF-ADVANCED:INTERNAL=1 -//Path to CMake installation. -CMAKE_ROOT:INTERNAL=/opt/homebrew/Cellar/cmake/3.25.3/share/cmake -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS -CMAKE_SHARED_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_DEBUG -CMAKE_SHARED_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL -CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELEASE -CMAKE_SHARED_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SKIP_INSTALL_RPATH -CMAKE_SKIP_INSTALL_RPATH-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SKIP_RPATH -CMAKE_SKIP_RPATH-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS -CMAKE_STATIC_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_DEBUG -CMAKE_STATIC_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL -CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELEASE -CMAKE_STATIC_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STRIP -CMAKE_STRIP-ADVANCED:INTERNAL=1 -//uname command -CMAKE_UNAME:INTERNAL=/usr/bin/uname -//ADVANCED property for variable: CMAKE_VERBOSE_MAKEFILE -CMAKE_VERBOSE_MAKEFILE-ADVANCED:INTERNAL=1 - diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake deleted file mode 100644 index dc7a67f2..00000000 --- a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCCompiler.cmake +++ /dev/null @@ -1,72 +0,0 @@ -set(CMAKE_C_COMPILER "/Library/Developer/CommandLineTools/usr/bin/cc") -set(CMAKE_C_COMPILER_ARG1 "") -set(CMAKE_C_COMPILER_ID "AppleClang") -set(CMAKE_C_COMPILER_VERSION "13.1.6.13160021") -set(CMAKE_C_COMPILER_VERSION_INTERNAL "") -set(CMAKE_C_COMPILER_WRAPPER "") -set(CMAKE_C_STANDARD_COMPUTED_DEFAULT "17") -set(CMAKE_C_EXTENSIONS_COMPUTED_DEFAULT "ON") -set(CMAKE_C_COMPILE_FEATURES "c_std_90;c_function_prototypes;c_std_99;c_restrict;c_variadic_macros;c_std_11;c_static_assert;c_std_17;c_std_23") -set(CMAKE_C90_COMPILE_FEATURES "c_std_90;c_function_prototypes") -set(CMAKE_C99_COMPILE_FEATURES "c_std_99;c_restrict;c_variadic_macros") -set(CMAKE_C11_COMPILE_FEATURES "c_std_11;c_static_assert") -set(CMAKE_C17_COMPILE_FEATURES "c_std_17") -set(CMAKE_C23_COMPILE_FEATURES "c_std_23") - -set(CMAKE_C_PLATFORM_ID "Darwin") -set(CMAKE_C_SIMULATE_ID "") -set(CMAKE_C_COMPILER_FRONTEND_VARIANT "") -set(CMAKE_C_SIMULATE_VERSION "") - - - - -set(CMAKE_AR "/Library/Developer/CommandLineTools/usr/bin/ar") -set(CMAKE_C_COMPILER_AR "") -set(CMAKE_RANLIB "/Library/Developer/CommandLineTools/usr/bin/ranlib") -set(CMAKE_C_COMPILER_RANLIB "") -set(CMAKE_LINKER "/Library/Developer/CommandLineTools/usr/bin/ld") -set(CMAKE_MT "") -set(CMAKE_COMPILER_IS_GNUCC ) -set(CMAKE_C_COMPILER_LOADED 1) -set(CMAKE_C_COMPILER_WORKS TRUE) -set(CMAKE_C_ABI_COMPILED TRUE) - -set(CMAKE_C_COMPILER_ENV_VAR "CC") - -set(CMAKE_C_COMPILER_ID_RUN 1) -set(CMAKE_C_SOURCE_FILE_EXTENSIONS c;m) -set(CMAKE_C_IGNORE_EXTENSIONS h;H;o;O;obj;OBJ;def;DEF;rc;RC) -set(CMAKE_C_LINKER_PREFERENCE 10) - -# Save compiler ABI information. -set(CMAKE_C_SIZEOF_DATA_PTR "8") -set(CMAKE_C_COMPILER_ABI "") -set(CMAKE_C_BYTE_ORDER "LITTLE_ENDIAN") -set(CMAKE_C_LIBRARY_ARCHITECTURE "") - -if(CMAKE_C_SIZEOF_DATA_PTR) - set(CMAKE_SIZEOF_VOID_P "${CMAKE_C_SIZEOF_DATA_PTR}") -endif() - -if(CMAKE_C_COMPILER_ABI) - set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_C_COMPILER_ABI}") -endif() - -if(CMAKE_C_LIBRARY_ARCHITECTURE) - set(CMAKE_LIBRARY_ARCHITECTURE "") -endif() - -set(CMAKE_C_CL_SHOWINCLUDES_PREFIX "") -if(CMAKE_C_CL_SHOWINCLUDES_PREFIX) - set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_C_CL_SHOWINCLUDES_PREFIX}") -endif() - - - - - -set(CMAKE_C_IMPLICIT_INCLUDE_DIRECTORIES "/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include") -set(CMAKE_C_IMPLICIT_LINK_LIBRARIES "") -set(CMAKE_C_IMPLICIT_LINK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib") -set(CMAKE_C_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks") diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake deleted file mode 100644 index 67dc227a..00000000 --- a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeCXXCompiler.cmake +++ /dev/null @@ -1,83 +0,0 @@ -set(CMAKE_CXX_COMPILER "/Library/Developer/CommandLineTools/usr/bin/c++") -set(CMAKE_CXX_COMPILER_ARG1 "") -set(CMAKE_CXX_COMPILER_ID "AppleClang") -set(CMAKE_CXX_COMPILER_VERSION "13.1.6.13160021") -set(CMAKE_CXX_COMPILER_VERSION_INTERNAL "") -set(CMAKE_CXX_COMPILER_WRAPPER "") -set(CMAKE_CXX_STANDARD_COMPUTED_DEFAULT "98") -set(CMAKE_CXX_EXTENSIONS_COMPUTED_DEFAULT "ON") -set(CMAKE_CXX_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters;cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates;cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates;cxx_std_17;cxx_std_20;cxx_std_23") -set(CMAKE_CXX98_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters") -set(CMAKE_CXX11_COMPILE_FEATURES "cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates") -set(CMAKE_CXX14_COMPILE_FEATURES "cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates") -set(CMAKE_CXX17_COMPILE_FEATURES "cxx_std_17") -set(CMAKE_CXX20_COMPILE_FEATURES "cxx_std_20") -set(CMAKE_CXX23_COMPILE_FEATURES "cxx_std_23") - -set(CMAKE_CXX_PLATFORM_ID "Darwin") -set(CMAKE_CXX_SIMULATE_ID "") -set(CMAKE_CXX_COMPILER_FRONTEND_VARIANT "") -set(CMAKE_CXX_SIMULATE_VERSION "") - - - - -set(CMAKE_AR "/Library/Developer/CommandLineTools/usr/bin/ar") -set(CMAKE_CXX_COMPILER_AR "") -set(CMAKE_RANLIB "/Library/Developer/CommandLineTools/usr/bin/ranlib") -set(CMAKE_CXX_COMPILER_RANLIB "") -set(CMAKE_LINKER "/Library/Developer/CommandLineTools/usr/bin/ld") -set(CMAKE_MT "") -set(CMAKE_COMPILER_IS_GNUCXX ) -set(CMAKE_CXX_COMPILER_LOADED 1) -set(CMAKE_CXX_COMPILER_WORKS TRUE) -set(CMAKE_CXX_ABI_COMPILED TRUE) - -set(CMAKE_CXX_COMPILER_ENV_VAR "CXX") - -set(CMAKE_CXX_COMPILER_ID_RUN 1) -set(CMAKE_CXX_SOURCE_FILE_EXTENSIONS C;M;c++;cc;cpp;cxx;m;mm;mpp;CPP;ixx;cppm) -set(CMAKE_CXX_IGNORE_EXTENSIONS inl;h;hpp;HPP;H;o;O;obj;OBJ;def;DEF;rc;RC) - -foreach (lang C OBJC OBJCXX) - if (CMAKE_${lang}_COMPILER_ID_RUN) - foreach(extension IN LISTS CMAKE_${lang}_SOURCE_FILE_EXTENSIONS) - list(REMOVE_ITEM CMAKE_CXX_SOURCE_FILE_EXTENSIONS ${extension}) - endforeach() - endif() -endforeach() - -set(CMAKE_CXX_LINKER_PREFERENCE 30) -set(CMAKE_CXX_LINKER_PREFERENCE_PROPAGATES 1) - -# Save compiler ABI information. -set(CMAKE_CXX_SIZEOF_DATA_PTR "8") -set(CMAKE_CXX_COMPILER_ABI "") -set(CMAKE_CXX_BYTE_ORDER "LITTLE_ENDIAN") -set(CMAKE_CXX_LIBRARY_ARCHITECTURE "") - -if(CMAKE_CXX_SIZEOF_DATA_PTR) - set(CMAKE_SIZEOF_VOID_P "${CMAKE_CXX_SIZEOF_DATA_PTR}") -endif() - -if(CMAKE_CXX_COMPILER_ABI) - set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_CXX_COMPILER_ABI}") -endif() - -if(CMAKE_CXX_LIBRARY_ARCHITECTURE) - set(CMAKE_LIBRARY_ARCHITECTURE "") -endif() - -set(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX "") -if(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX) - set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_CXX_CL_SHOWINCLUDES_PREFIX}") -endif() - - - - - -set(CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1;/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include") -set(CMAKE_CXX_IMPLICIT_LINK_LIBRARIES "c++") -set(CMAKE_CXX_IMPLICIT_LINK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib") -set(CMAKE_CXX_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks") diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CMakeDetermineCompilerABI_C.bin deleted file mode 100755 index 9b3e67d1d3825990645b4978d3a1e9da0ed43128..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 16999 zcmeI3Uuau(6vt1J4mw-bDPw=A+wvq%M%!73vA8vv&DOh>G+QHv1^Joe-nN%DNljAM zl(`jkY7xOI!Vn*PvJ@tW2r~~t@nOEH-NO_gw8E4Y8SKRe>sb7r-@Ug@j7;$P960yf zbI$K~a?a=G^?bX2`(8Vdk05^Nc4#O-beV#9BiaKUgenz}oQR%{o*Cw7qv*?xp(c;( zgm6%)L^PRbOzZpM#u&N&7KB;Rk`|@P)^yo*VE$R}&QWI=?+E)m*M_vv?8ZA@l*$(J zCGT`|J+t4b=e6wl^)>3>m72<*xAUg5^P>e_zj59#+QD&^VNZ&#>~h z;4}Y6w&79`ivJvSPnC+@6LzNCtW22jSvsNI$NH7x4Rex!tKWiOSUF)2!VyE|=*7+mzTkW;b zYDc)*>f743TAy1(u3}IBYc74XDYt?e_^tV+fVyeKjt}>h>=~;ts?5o9G1U`#o+xGv zAJ6oaE6OSsEHhO!j;Rx|s4)CVfjdF!HA3a*weJh$P*jJqFy()F*nK40$e zIUC+Q`%d-|^!D+w?~S}OJLiMg>~HQ(Z{;_1rF6GWd=t0I*kj7dn|3-+O}PoXT%NGJ zG=8gI)_-bW0>NE~aT_c<5JRWF0Qp;Z>6}N&LX(_?VE;T45Bl{=yc4VM6Pqn++5DY9SA;OK&E`)@a62ozG~Gg3vqrwOy?1(}Yo+U07k`F$ z7?Bt+1c@g+5Q2z4kcE(VVk9IUWCXE^ga;BL=A8RyyHz3a>YU`pZ)-|0EOudnCf zw+}yx7_%`DJ7_Uz)WO(6Ccuud$)NS1oHx4HdYU~O8t^n*w9DB?ITq$|K_KUTPr#q; z*6xehXUwoi!7(b7qzUIKr6Xk+u>6|u<4V05GX!nyYgqDF*YF-ToJSJzHZwXmpS()X zXO?W*)*RM7=k4*GYFy@Oyd|OK&+hl8kq?=opq*8pemwjg;qR4v>pgXnS%_#n8myWa zYm<=-nOfgv5o2BBFc9Kgu+$i~3+yVe@!BNN?O-GCURXO|Ed*@@MZq^f#aN8_7a0qe z1W@?TvC8(gWMxbZSIX&_3^qy`DAwVeb!t!?td8y9F?eTu;g@JNoC%I$f4{hdd)E zeq*{VrL>Y5g-CY zfCvx)B0vO)01+SpM1Tko0U|&IhyW2F0z`la5CI}U1c(3;AOb{y2oM1xKm>>Y5g-CY zfCvx)B0vO)01+SpM1Tko0U|&IhyW2F0z}}yA~1A-^$pEnnf@}Cd0EK54mnw7psXtc zGrC9fdsg%mr~|HdPBD{jD=2(t^$mb8t#xUfhTRpuF{#5dIGs{>A}K4$pjYzyy&mrI z)k$t2_;F--s_}Bx6=#}p<{9R_HC14~90hHhmBy**aoTM#1bqZrfGy5MqoP>Hk@fj% z{XFYy<1hnm=dDq$bSRN_C^V{spi(xoHKfMbY%IjVKJGRynH#KiEcnbhdYD7k>`u#^ zJ^D`=Hl}gfa8g>YYl3F$Jz|{#Oz`K{z_l7UZ}u)+f`j>_B0ZR-(lxt1=jV$0r_me)L)enUEBe|6e9e#*%eORpTb7ZmQE>poLc zH~P}0y%($?}6|C|5qI)^f8eSKp>24 & 0x00FF) -# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) -# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) - -#elif defined(__BORLANDC__) -# define COMPILER_ID "Borland" - /* __BORLANDC__ = 0xVRR */ -# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) -# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) - -#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 -# define COMPILER_ID "Watcom" - /* __WATCOMC__ = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__WATCOMC__) -# define COMPILER_ID "OpenWatcom" - /* __WATCOMC__ = VVRP + 1100 */ -# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__SUNPRO_C) -# define COMPILER_ID "SunPro" -# if __SUNPRO_C >= 0x5100 - /* __SUNPRO_C = 0xVRRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>12) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xFF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) -# else - /* __SUNPRO_CC = 0xVRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>8) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) -# endif - -#elif defined(__HP_cc) -# define COMPILER_ID "HP" - /* __HP_cc = VVRRPP */ -# define COMPILER_VERSION_MAJOR DEC(__HP_cc/10000) -# define COMPILER_VERSION_MINOR DEC(__HP_cc/100 % 100) -# define COMPILER_VERSION_PATCH DEC(__HP_cc % 100) - -#elif defined(__DECC) -# define COMPILER_ID "Compaq" - /* __DECC_VER = VVRRTPPPP */ -# define COMPILER_VERSION_MAJOR DEC(__DECC_VER/10000000) -# define COMPILER_VERSION_MINOR DEC(__DECC_VER/100000 % 100) -# define COMPILER_VERSION_PATCH DEC(__DECC_VER % 10000) - -#elif defined(__IBMC__) && defined(__COMPILER_VER__) -# define COMPILER_ID "zOS" - /* __IBMC__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) - -#elif defined(__open_xl__) && defined(__clang__) -# define COMPILER_ID "IBMClang" -# define COMPILER_VERSION_MAJOR DEC(__open_xl_version__) -# define COMPILER_VERSION_MINOR DEC(__open_xl_release__) -# define COMPILER_VERSION_PATCH DEC(__open_xl_modification__) -# define COMPILER_VERSION_TWEAK DEC(__open_xl_ptf_fix_level__) - - -#elif defined(__ibmxl__) && defined(__clang__) -# define COMPILER_ID "XLClang" -# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) -# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) -# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) -# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) - - -#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ >= 800 -# define COMPILER_ID "XL" - /* __IBMC__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) - -#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ < 800 -# define COMPILER_ID "VisualAge" - /* __IBMC__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) - -#elif defined(__NVCOMPILER) -# define COMPILER_ID "NVHPC" -# define COMPILER_VERSION_MAJOR DEC(__NVCOMPILER_MAJOR__) -# define COMPILER_VERSION_MINOR DEC(__NVCOMPILER_MINOR__) -# if defined(__NVCOMPILER_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__NVCOMPILER_PATCHLEVEL__) -# endif - -#elif defined(__PGI) -# define COMPILER_ID "PGI" -# define COMPILER_VERSION_MAJOR DEC(__PGIC__) -# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) -# if defined(__PGIC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) -# endif - -#elif defined(_CRAYC) -# define COMPILER_ID "Cray" -# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) -# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) - -#elif defined(__TI_COMPILER_VERSION__) -# define COMPILER_ID "TI" - /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ -# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) -# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) -# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) - -#elif defined(__CLANG_FUJITSU) -# define COMPILER_ID "FujitsuClang" -# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) -# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) -# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) -# define COMPILER_VERSION_INTERNAL_STR __clang_version__ - - -#elif defined(__FUJITSU) -# define COMPILER_ID "Fujitsu" -# if defined(__FCC_version__) -# define COMPILER_VERSION __FCC_version__ -# elif defined(__FCC_major__) -# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) -# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) -# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) -# endif -# if defined(__fcc_version) -# define COMPILER_VERSION_INTERNAL DEC(__fcc_version) -# elif defined(__FCC_VERSION) -# define COMPILER_VERSION_INTERNAL DEC(__FCC_VERSION) -# endif - - -#elif defined(__ghs__) -# define COMPILER_ID "GHS" -/* __GHS_VERSION_NUMBER = VVVVRP */ -# ifdef __GHS_VERSION_NUMBER -# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) -# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) -# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) -# endif - -#elif defined(__TASKING__) -# define COMPILER_ID "Tasking" - # define COMPILER_VERSION_MAJOR DEC(__VERSION__/1000) - # define COMPILER_VERSION_MINOR DEC(__VERSION__ % 100) -# define COMPILER_VERSION_INTERNAL DEC(__VERSION__) - -#elif defined(__TINYC__) -# define COMPILER_ID "TinyCC" - -#elif defined(__BCC__) -# define COMPILER_ID "Bruce" - -#elif defined(__SCO_VERSION__) -# define COMPILER_ID "SCO" - -#elif defined(__ARMCC_VERSION) && !defined(__clang__) -# define COMPILER_ID "ARMCC" -#if __ARMCC_VERSION >= 1000000 - /* __ARMCC_VERSION = VRRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#else - /* __ARMCC_VERSION = VRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#endif - - -#elif defined(__clang__) && defined(__apple_build_version__) -# define COMPILER_ID "AppleClang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif -# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) - -#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) -# define COMPILER_ID "ARMClang" - # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) -# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) - -#elif defined(__clang__) -# define COMPILER_ID "Clang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif - -#elif defined(__LCC__) && (defined(__GNUC__) || defined(__GNUG__) || defined(__MCST__)) -# define COMPILER_ID "LCC" -# define COMPILER_VERSION_MAJOR DEC(1) -# if defined(__LCC__) -# define COMPILER_VERSION_MINOR DEC(__LCC__- 100) -# endif -# if defined(__LCC_MINOR__) -# define COMPILER_VERSION_PATCH DEC(__LCC_MINOR__) -# endif -# if defined(__GNUC__) && defined(__GNUC_MINOR__) -# define SIMULATE_ID "GNU" -# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) -# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) -# if defined(__GNUC_PATCHLEVEL__) -# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif -# endif - -#elif defined(__GNUC__) -# define COMPILER_ID "GNU" -# define COMPILER_VERSION_MAJOR DEC(__GNUC__) -# if defined(__GNUC_MINOR__) -# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) -# endif -# if defined(__GNUC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif - -#elif defined(_MSC_VER) -# define COMPILER_ID "MSVC" - /* _MSC_VER = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) -# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) -# if defined(_MSC_FULL_VER) -# if _MSC_VER >= 1400 - /* _MSC_FULL_VER = VVRRPPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) -# else - /* _MSC_FULL_VER = VVRRPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) -# endif -# endif -# if defined(_MSC_BUILD) -# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) -# endif - -#elif defined(_ADI_COMPILER) -# define COMPILER_ID "ADSP" -#if defined(__VERSIONNUM__) - /* __VERSIONNUM__ = 0xVVRRPPTT */ -# define COMPILER_VERSION_MAJOR DEC(__VERSIONNUM__ >> 24 & 0xFF) -# define COMPILER_VERSION_MINOR DEC(__VERSIONNUM__ >> 16 & 0xFF) -# define COMPILER_VERSION_PATCH DEC(__VERSIONNUM__ >> 8 & 0xFF) -# define COMPILER_VERSION_TWEAK DEC(__VERSIONNUM__ & 0xFF) -#endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# define COMPILER_ID "IAR" -# if defined(__VER__) && defined(__ICCARM__) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) -# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) -# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__) || defined(__ICCSTM8__)) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) -# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) -# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# endif - -#elif defined(__SDCC_VERSION_MAJOR) || defined(SDCC) -# define COMPILER_ID "SDCC" -# if defined(__SDCC_VERSION_MAJOR) -# define COMPILER_VERSION_MAJOR DEC(__SDCC_VERSION_MAJOR) -# define COMPILER_VERSION_MINOR DEC(__SDCC_VERSION_MINOR) -# define COMPILER_VERSION_PATCH DEC(__SDCC_VERSION_PATCH) -# else - /* SDCC = VRP */ -# define COMPILER_VERSION_MAJOR DEC(SDCC/100) -# define COMPILER_VERSION_MINOR DEC(SDCC/10 % 10) -# define COMPILER_VERSION_PATCH DEC(SDCC % 10) -# endif - - -/* These compilers are either not known or too old to define an - identification macro. Try to identify the platform and guess that - it is the native compiler. */ -#elif defined(__hpux) || defined(__hpua) -# define COMPILER_ID "HP" - -#else /* unknown compiler */ -# define COMPILER_ID "" -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; -#ifdef SIMULATE_ID -char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; -#endif - -#ifdef __QNXNTO__ -char const* qnxnto = "INFO" ":" "qnxnto[]"; -#endif - -#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) -char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; -#endif - -#define STRINGIFY_HELPER(X) #X -#define STRINGIFY(X) STRINGIFY_HELPER(X) - -/* Identify known platforms by name. */ -#if defined(__linux) || defined(__linux__) || defined(linux) -# define PLATFORM_ID "Linux" - -#elif defined(__MSYS__) -# define PLATFORM_ID "MSYS" - -#elif defined(__CYGWIN__) -# define PLATFORM_ID "Cygwin" - -#elif defined(__MINGW32__) -# define PLATFORM_ID "MinGW" - -#elif defined(__APPLE__) -# define PLATFORM_ID "Darwin" - -#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) -# define PLATFORM_ID "Windows" - -#elif defined(__FreeBSD__) || defined(__FreeBSD) -# define PLATFORM_ID "FreeBSD" - -#elif defined(__NetBSD__) || defined(__NetBSD) -# define PLATFORM_ID "NetBSD" - -#elif defined(__OpenBSD__) || defined(__OPENBSD) -# define PLATFORM_ID "OpenBSD" - -#elif defined(__sun) || defined(sun) -# define PLATFORM_ID "SunOS" - -#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) -# define PLATFORM_ID "AIX" - -#elif defined(__hpux) || defined(__hpux__) -# define PLATFORM_ID "HP-UX" - -#elif defined(__HAIKU__) -# define PLATFORM_ID "Haiku" - -#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) -# define PLATFORM_ID "BeOS" - -#elif defined(__QNX__) || defined(__QNXNTO__) -# define PLATFORM_ID "QNX" - -#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) -# define PLATFORM_ID "Tru64" - -#elif defined(__riscos) || defined(__riscos__) -# define PLATFORM_ID "RISCos" - -#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) -# define PLATFORM_ID "SINIX" - -#elif defined(__UNIX_SV__) -# define PLATFORM_ID "UNIX_SV" - -#elif defined(__bsdos__) -# define PLATFORM_ID "BSDOS" - -#elif defined(_MPRAS) || defined(MPRAS) -# define PLATFORM_ID "MP-RAS" - -#elif defined(__osf) || defined(__osf__) -# define PLATFORM_ID "OSF1" - -#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) -# define PLATFORM_ID "SCO_SV" - -#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) -# define PLATFORM_ID "ULTRIX" - -#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) -# define PLATFORM_ID "Xenix" - -#elif defined(__WATCOMC__) -# if defined(__LINUX__) -# define PLATFORM_ID "Linux" - -# elif defined(__DOS__) -# define PLATFORM_ID "DOS" - -# elif defined(__OS2__) -# define PLATFORM_ID "OS2" - -# elif defined(__WINDOWS__) -# define PLATFORM_ID "Windows3x" - -# elif defined(__VXWORKS__) -# define PLATFORM_ID "VxWorks" - -# else /* unknown platform */ -# define PLATFORM_ID -# endif - -#elif defined(__INTEGRITY) -# if defined(INT_178B) -# define PLATFORM_ID "Integrity178" - -# else /* regular Integrity */ -# define PLATFORM_ID "Integrity" -# endif - -# elif defined(_ADI_COMPILER) -# define PLATFORM_ID "ADSP" - -#else /* unknown platform */ -# define PLATFORM_ID - -#endif - -/* For windows compilers MSVC and Intel we can determine - the architecture of the compiler being used. This is because - the compilers do not have flags that can change the architecture, - but rather depend on which compiler is being used -*/ -#if defined(_WIN32) && defined(_MSC_VER) -# if defined(_M_IA64) -# define ARCHITECTURE_ID "IA64" - -# elif defined(_M_ARM64EC) -# define ARCHITECTURE_ID "ARM64EC" - -# elif defined(_M_X64) || defined(_M_AMD64) -# define ARCHITECTURE_ID "x64" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# elif defined(_M_ARM64) -# define ARCHITECTURE_ID "ARM64" - -# elif defined(_M_ARM) -# if _M_ARM == 4 -# define ARCHITECTURE_ID "ARMV4I" -# elif _M_ARM == 5 -# define ARCHITECTURE_ID "ARMV5I" -# else -# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) -# endif - -# elif defined(_M_MIPS) -# define ARCHITECTURE_ID "MIPS" - -# elif defined(_M_SH) -# define ARCHITECTURE_ID "SHx" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__WATCOMC__) -# if defined(_M_I86) -# define ARCHITECTURE_ID "I86" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# if defined(__ICCARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__ICCRX__) -# define ARCHITECTURE_ID "RX" - -# elif defined(__ICCRH850__) -# define ARCHITECTURE_ID "RH850" - -# elif defined(__ICCRL78__) -# define ARCHITECTURE_ID "RL78" - -# elif defined(__ICCRISCV__) -# define ARCHITECTURE_ID "RISCV" - -# elif defined(__ICCAVR__) -# define ARCHITECTURE_ID "AVR" - -# elif defined(__ICC430__) -# define ARCHITECTURE_ID "MSP430" - -# elif defined(__ICCV850__) -# define ARCHITECTURE_ID "V850" - -# elif defined(__ICC8051__) -# define ARCHITECTURE_ID "8051" - -# elif defined(__ICCSTM8__) -# define ARCHITECTURE_ID "STM8" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__ghs__) -# if defined(__PPC64__) -# define ARCHITECTURE_ID "PPC64" - -# elif defined(__ppc__) -# define ARCHITECTURE_ID "PPC" - -# elif defined(__ARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__x86_64__) -# define ARCHITECTURE_ID "x64" - -# elif defined(__i386__) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__TI_COMPILER_VERSION__) -# if defined(__TI_ARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__MSP430__) -# define ARCHITECTURE_ID "MSP430" - -# elif defined(__TMS320C28XX__) -# define ARCHITECTURE_ID "TMS320C28x" - -# elif defined(__TMS320C6X__) || defined(_TMS320C6X) -# define ARCHITECTURE_ID "TMS320C6x" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -# elif defined(__ADSPSHARC__) -# define ARCHITECTURE_ID "SHARC" - -# elif defined(__ADSPBLACKFIN__) -# define ARCHITECTURE_ID "Blackfin" - -#elif defined(__TASKING__) - -# if defined(__CTC__) || defined(__CPTC__) -# define ARCHITECTURE_ID "TriCore" - -# elif defined(__CMCS__) -# define ARCHITECTURE_ID "MCS" - -# elif defined(__CARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__CARC__) -# define ARCHITECTURE_ID "ARC" - -# elif defined(__C51__) -# define ARCHITECTURE_ID "8051" - -# elif defined(__CPCP__) -# define ARCHITECTURE_ID "PCP" - -# else -# define ARCHITECTURE_ID "" -# endif - -#else -# define ARCHITECTURE_ID -#endif - -/* Convert integer to decimal digit literals. */ -#define DEC(n) \ - ('0' + (((n) / 10000000)%10)), \ - ('0' + (((n) / 1000000)%10)), \ - ('0' + (((n) / 100000)%10)), \ - ('0' + (((n) / 10000)%10)), \ - ('0' + (((n) / 1000)%10)), \ - ('0' + (((n) / 100)%10)), \ - ('0' + (((n) / 10)%10)), \ - ('0' + ((n) % 10)) - -/* Convert integer to hex digit literals. */ -#define HEX(n) \ - ('0' + ((n)>>28 & 0xF)), \ - ('0' + ((n)>>24 & 0xF)), \ - ('0' + ((n)>>20 & 0xF)), \ - ('0' + ((n)>>16 & 0xF)), \ - ('0' + ((n)>>12 & 0xF)), \ - ('0' + ((n)>>8 & 0xF)), \ - ('0' + ((n)>>4 & 0xF)), \ - ('0' + ((n) & 0xF)) - -/* Construct a string literal encoding the version number. */ -#ifdef COMPILER_VERSION -char const* info_version = "INFO" ":" "compiler_version[" COMPILER_VERSION "]"; - -/* Construct a string literal encoding the version number components. */ -#elif defined(COMPILER_VERSION_MAJOR) -char const info_version[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', - COMPILER_VERSION_MAJOR, -# ifdef COMPILER_VERSION_MINOR - '.', COMPILER_VERSION_MINOR, -# ifdef COMPILER_VERSION_PATCH - '.', COMPILER_VERSION_PATCH, -# ifdef COMPILER_VERSION_TWEAK - '.', COMPILER_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct a string literal encoding the internal version number. */ -#ifdef COMPILER_VERSION_INTERNAL -char const info_version_internal[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', - 'i','n','t','e','r','n','a','l','[', - COMPILER_VERSION_INTERNAL,']','\0'}; -#elif defined(COMPILER_VERSION_INTERNAL_STR) -char const* info_version_internal = "INFO" ":" "compiler_version_internal[" COMPILER_VERSION_INTERNAL_STR "]"; -#endif - -/* Construct a string literal encoding the version number components. */ -#ifdef SIMULATE_VERSION_MAJOR -char const info_simulate_version[] = { - 'I', 'N', 'F', 'O', ':', - 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', - SIMULATE_VERSION_MAJOR, -# ifdef SIMULATE_VERSION_MINOR - '.', SIMULATE_VERSION_MINOR, -# ifdef SIMULATE_VERSION_PATCH - '.', SIMULATE_VERSION_PATCH, -# ifdef SIMULATE_VERSION_TWEAK - '.', SIMULATE_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; -char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; - - - -#if !defined(__STDC__) && !defined(__clang__) -# if defined(_MSC_VER) || defined(__ibmxl__) || defined(__IBMC__) -# define C_VERSION "90" -# else -# define C_VERSION -# endif -#elif __STDC_VERSION__ > 201710L -# define C_VERSION "23" -#elif __STDC_VERSION__ >= 201710L -# define C_VERSION "17" -#elif __STDC_VERSION__ >= 201000L -# define C_VERSION "11" -#elif __STDC_VERSION__ >= 199901L -# define C_VERSION "99" -#else -# define C_VERSION "90" -#endif -const char* info_language_standard_default = - "INFO" ":" "standard_default[" C_VERSION "]"; - -const char* info_language_extensions_default = "INFO" ":" "extensions_default[" -#if (defined(__clang__) || defined(__GNUC__) || defined(__xlC__) || \ - defined(__TI_COMPILER_VERSION__)) && \ - !defined(__STRICT_ANSI__) - "ON" -#else - "OFF" -#endif -"]"; - -/*--------------------------------------------------------------------------*/ - -#ifdef ID_VOID_MAIN -void main() {} -#else -# if defined(__CLASSIC_C__) -int main(argc, argv) int argc; char *argv[]; -# else -int main(int argc, char* argv[]) -# endif -{ - int require = 0; - require += info_compiler[argc]; - require += info_platform[argc]; - require += info_arch[argc]; -#ifdef COMPILER_VERSION_MAJOR - require += info_version[argc]; -#endif -#ifdef COMPILER_VERSION_INTERNAL - require += info_version_internal[argc]; -#endif -#ifdef SIMULATE_ID - require += info_simulate[argc]; -#endif -#ifdef SIMULATE_VERSION_MAJOR - require += info_simulate_version[argc]; -#endif -#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) - require += info_cray[argc]; -#endif - require += info_language_standard_default[argc]; - require += info_language_extensions_default[argc]; - (void)argv; - return require; -} -#endif diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdC/CMakeCCompilerId.o deleted file mode 100644 index 537fbf261a76f93972038901b25169a2bbc47274..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1712 zcmb_cJ!n%=6uz;wrbZJ52c@6^7pIWdlqyOfp;1&q+aW_FlnbM8Iw+;_kGKK=Uf`-Bi7 z0i(w>M)3$9aSYfwjIS!I=z&L%dbCZ%s}_<rdz)YvA0HYv+3-?QBs2c#UYr|Wo}&rIo+0dl*8pp+HUHwP5`=CXzCkY{+GmpJqe z^{C`F`qO(H&ZhmA8*Xd3;mQ8ix!yHi)SKvUv=;ePuiiAvzHGbqZMPz2J~uk&HP?%C zFpj>cWEaS(u`SOdcNQbasV}Tn(j%)}% za%=g<%2hfV+p)Y-w%K&7CC7AYYeHq3j_Fq$UcHnvJscZHO|QIOV!!2^ZpHK}vSL-u zw&RzK%bdY|vD}so84YqP%WHr6vB&z8_biVJmXgYhR3dPahISScM#@-BCg+Wb7peOc zS66bZgO^}XPkuYV^b_Do@J9iro4^>j6JVM&1pVam0j3v#QSfAdY0@6FmOm3y4i@8<*X7~Z$a`P`qk_SaKIb%|g!jTF5YI&NLI#U*ukag2`Ii@wwl*BF^ czusKnN(nfiDNW&k&T9$>)X)?TD9J>24 & 0x00FF) -# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) -# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) - -#elif defined(__BORLANDC__) -# define COMPILER_ID "Borland" - /* __BORLANDC__ = 0xVRR */ -# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) -# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) - -#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 -# define COMPILER_ID "Watcom" - /* __WATCOMC__ = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__WATCOMC__) -# define COMPILER_ID "OpenWatcom" - /* __WATCOMC__ = VVRP + 1100 */ -# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__SUNPRO_CC) -# define COMPILER_ID "SunPro" -# if __SUNPRO_CC >= 0x5100 - /* __SUNPRO_CC = 0xVRRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>12) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xFF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) -# else - /* __SUNPRO_CC = 0xVRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>8) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) -# endif - -#elif defined(__HP_aCC) -# define COMPILER_ID "HP" - /* __HP_aCC = VVRRPP */ -# define COMPILER_VERSION_MAJOR DEC(__HP_aCC/10000) -# define COMPILER_VERSION_MINOR DEC(__HP_aCC/100 % 100) -# define COMPILER_VERSION_PATCH DEC(__HP_aCC % 100) - -#elif defined(__DECCXX) -# define COMPILER_ID "Compaq" - /* __DECCXX_VER = VVRRTPPPP */ -# define COMPILER_VERSION_MAJOR DEC(__DECCXX_VER/10000000) -# define COMPILER_VERSION_MINOR DEC(__DECCXX_VER/100000 % 100) -# define COMPILER_VERSION_PATCH DEC(__DECCXX_VER % 10000) - -#elif defined(__IBMCPP__) && defined(__COMPILER_VER__) -# define COMPILER_ID "zOS" - /* __IBMCPP__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) - -#elif defined(__open_xl__) && defined(__clang__) -# define COMPILER_ID "IBMClang" -# define COMPILER_VERSION_MAJOR DEC(__open_xl_version__) -# define COMPILER_VERSION_MINOR DEC(__open_xl_release__) -# define COMPILER_VERSION_PATCH DEC(__open_xl_modification__) -# define COMPILER_VERSION_TWEAK DEC(__open_xl_ptf_fix_level__) - - -#elif defined(__ibmxl__) && defined(__clang__) -# define COMPILER_ID "XLClang" -# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) -# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) -# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) -# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) - - -#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ >= 800 -# define COMPILER_ID "XL" - /* __IBMCPP__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) - -#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ < 800 -# define COMPILER_ID "VisualAge" - /* __IBMCPP__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) - -#elif defined(__NVCOMPILER) -# define COMPILER_ID "NVHPC" -# define COMPILER_VERSION_MAJOR DEC(__NVCOMPILER_MAJOR__) -# define COMPILER_VERSION_MINOR DEC(__NVCOMPILER_MINOR__) -# if defined(__NVCOMPILER_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__NVCOMPILER_PATCHLEVEL__) -# endif - -#elif defined(__PGI) -# define COMPILER_ID "PGI" -# define COMPILER_VERSION_MAJOR DEC(__PGIC__) -# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) -# if defined(__PGIC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) -# endif - -#elif defined(_CRAYC) -# define COMPILER_ID "Cray" -# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) -# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) - -#elif defined(__TI_COMPILER_VERSION__) -# define COMPILER_ID "TI" - /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ -# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) -# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) -# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) - -#elif defined(__CLANG_FUJITSU) -# define COMPILER_ID "FujitsuClang" -# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) -# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) -# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) -# define COMPILER_VERSION_INTERNAL_STR __clang_version__ - - -#elif defined(__FUJITSU) -# define COMPILER_ID "Fujitsu" -# if defined(__FCC_version__) -# define COMPILER_VERSION __FCC_version__ -# elif defined(__FCC_major__) -# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) -# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) -# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) -# endif -# if defined(__fcc_version) -# define COMPILER_VERSION_INTERNAL DEC(__fcc_version) -# elif defined(__FCC_VERSION) -# define COMPILER_VERSION_INTERNAL DEC(__FCC_VERSION) -# endif - - -#elif defined(__ghs__) -# define COMPILER_ID "GHS" -/* __GHS_VERSION_NUMBER = VVVVRP */ -# ifdef __GHS_VERSION_NUMBER -# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) -# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) -# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) -# endif - -#elif defined(__TASKING__) -# define COMPILER_ID "Tasking" - # define COMPILER_VERSION_MAJOR DEC(__VERSION__/1000) - # define COMPILER_VERSION_MINOR DEC(__VERSION__ % 100) -# define COMPILER_VERSION_INTERNAL DEC(__VERSION__) - -#elif defined(__SCO_VERSION__) -# define COMPILER_ID "SCO" - -#elif defined(__ARMCC_VERSION) && !defined(__clang__) -# define COMPILER_ID "ARMCC" -#if __ARMCC_VERSION >= 1000000 - /* __ARMCC_VERSION = VRRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#else - /* __ARMCC_VERSION = VRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#endif - - -#elif defined(__clang__) && defined(__apple_build_version__) -# define COMPILER_ID "AppleClang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif -# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) - -#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) -# define COMPILER_ID "ARMClang" - # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) -# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) - -#elif defined(__clang__) -# define COMPILER_ID "Clang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif - -#elif defined(__LCC__) && (defined(__GNUC__) || defined(__GNUG__) || defined(__MCST__)) -# define COMPILER_ID "LCC" -# define COMPILER_VERSION_MAJOR DEC(1) -# if defined(__LCC__) -# define COMPILER_VERSION_MINOR DEC(__LCC__- 100) -# endif -# if defined(__LCC_MINOR__) -# define COMPILER_VERSION_PATCH DEC(__LCC_MINOR__) -# endif -# if defined(__GNUC__) && defined(__GNUC_MINOR__) -# define SIMULATE_ID "GNU" -# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) -# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) -# if defined(__GNUC_PATCHLEVEL__) -# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif -# endif - -#elif defined(__GNUC__) || defined(__GNUG__) -# define COMPILER_ID "GNU" -# if defined(__GNUC__) -# define COMPILER_VERSION_MAJOR DEC(__GNUC__) -# else -# define COMPILER_VERSION_MAJOR DEC(__GNUG__) -# endif -# if defined(__GNUC_MINOR__) -# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) -# endif -# if defined(__GNUC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif - -#elif defined(_MSC_VER) -# define COMPILER_ID "MSVC" - /* _MSC_VER = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) -# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) -# if defined(_MSC_FULL_VER) -# if _MSC_VER >= 1400 - /* _MSC_FULL_VER = VVRRPPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) -# else - /* _MSC_FULL_VER = VVRRPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) -# endif -# endif -# if defined(_MSC_BUILD) -# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) -# endif - -#elif defined(_ADI_COMPILER) -# define COMPILER_ID "ADSP" -#if defined(__VERSIONNUM__) - /* __VERSIONNUM__ = 0xVVRRPPTT */ -# define COMPILER_VERSION_MAJOR DEC(__VERSIONNUM__ >> 24 & 0xFF) -# define COMPILER_VERSION_MINOR DEC(__VERSIONNUM__ >> 16 & 0xFF) -# define COMPILER_VERSION_PATCH DEC(__VERSIONNUM__ >> 8 & 0xFF) -# define COMPILER_VERSION_TWEAK DEC(__VERSIONNUM__ & 0xFF) -#endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# define COMPILER_ID "IAR" -# if defined(__VER__) && defined(__ICCARM__) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) -# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) -# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__) || defined(__ICCSTM8__)) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) -# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) -# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# endif - - -/* These compilers are either not known or too old to define an - identification macro. Try to identify the platform and guess that - it is the native compiler. */ -#elif defined(__hpux) || defined(__hpua) -# define COMPILER_ID "HP" - -#else /* unknown compiler */ -# define COMPILER_ID "" -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; -#ifdef SIMULATE_ID -char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; -#endif - -#ifdef __QNXNTO__ -char const* qnxnto = "INFO" ":" "qnxnto[]"; -#endif - -#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) -char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; -#endif - -#define STRINGIFY_HELPER(X) #X -#define STRINGIFY(X) STRINGIFY_HELPER(X) - -/* Identify known platforms by name. */ -#if defined(__linux) || defined(__linux__) || defined(linux) -# define PLATFORM_ID "Linux" - -#elif defined(__MSYS__) -# define PLATFORM_ID "MSYS" - -#elif defined(__CYGWIN__) -# define PLATFORM_ID "Cygwin" - -#elif defined(__MINGW32__) -# define PLATFORM_ID "MinGW" - -#elif defined(__APPLE__) -# define PLATFORM_ID "Darwin" - -#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) -# define PLATFORM_ID "Windows" - -#elif defined(__FreeBSD__) || defined(__FreeBSD) -# define PLATFORM_ID "FreeBSD" - -#elif defined(__NetBSD__) || defined(__NetBSD) -# define PLATFORM_ID "NetBSD" - -#elif defined(__OpenBSD__) || defined(__OPENBSD) -# define PLATFORM_ID "OpenBSD" - -#elif defined(__sun) || defined(sun) -# define PLATFORM_ID "SunOS" - -#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) -# define PLATFORM_ID "AIX" - -#elif defined(__hpux) || defined(__hpux__) -# define PLATFORM_ID "HP-UX" - -#elif defined(__HAIKU__) -# define PLATFORM_ID "Haiku" - -#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) -# define PLATFORM_ID "BeOS" - -#elif defined(__QNX__) || defined(__QNXNTO__) -# define PLATFORM_ID "QNX" - -#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) -# define PLATFORM_ID "Tru64" - -#elif defined(__riscos) || defined(__riscos__) -# define PLATFORM_ID "RISCos" - -#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) -# define PLATFORM_ID "SINIX" - -#elif defined(__UNIX_SV__) -# define PLATFORM_ID "UNIX_SV" - -#elif defined(__bsdos__) -# define PLATFORM_ID "BSDOS" - -#elif defined(_MPRAS) || defined(MPRAS) -# define PLATFORM_ID "MP-RAS" - -#elif defined(__osf) || defined(__osf__) -# define PLATFORM_ID "OSF1" - -#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) -# define PLATFORM_ID "SCO_SV" - -#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) -# define PLATFORM_ID "ULTRIX" - -#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) -# define PLATFORM_ID "Xenix" - -#elif defined(__WATCOMC__) -# if defined(__LINUX__) -# define PLATFORM_ID "Linux" - -# elif defined(__DOS__) -# define PLATFORM_ID "DOS" - -# elif defined(__OS2__) -# define PLATFORM_ID "OS2" - -# elif defined(__WINDOWS__) -# define PLATFORM_ID "Windows3x" - -# elif defined(__VXWORKS__) -# define PLATFORM_ID "VxWorks" - -# else /* unknown platform */ -# define PLATFORM_ID -# endif - -#elif defined(__INTEGRITY) -# if defined(INT_178B) -# define PLATFORM_ID "Integrity178" - -# else /* regular Integrity */ -# define PLATFORM_ID "Integrity" -# endif - -# elif defined(_ADI_COMPILER) -# define PLATFORM_ID "ADSP" - -#else /* unknown platform */ -# define PLATFORM_ID - -#endif - -/* For windows compilers MSVC and Intel we can determine - the architecture of the compiler being used. This is because - the compilers do not have flags that can change the architecture, - but rather depend on which compiler is being used -*/ -#if defined(_WIN32) && defined(_MSC_VER) -# if defined(_M_IA64) -# define ARCHITECTURE_ID "IA64" - -# elif defined(_M_ARM64EC) -# define ARCHITECTURE_ID "ARM64EC" - -# elif defined(_M_X64) || defined(_M_AMD64) -# define ARCHITECTURE_ID "x64" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# elif defined(_M_ARM64) -# define ARCHITECTURE_ID "ARM64" - -# elif defined(_M_ARM) -# if _M_ARM == 4 -# define ARCHITECTURE_ID "ARMV4I" -# elif _M_ARM == 5 -# define ARCHITECTURE_ID "ARMV5I" -# else -# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) -# endif - -# elif defined(_M_MIPS) -# define ARCHITECTURE_ID "MIPS" - -# elif defined(_M_SH) -# define ARCHITECTURE_ID "SHx" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__WATCOMC__) -# if defined(_M_I86) -# define ARCHITECTURE_ID "I86" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# if defined(__ICCARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__ICCRX__) -# define ARCHITECTURE_ID "RX" - -# elif defined(__ICCRH850__) -# define ARCHITECTURE_ID "RH850" - -# elif defined(__ICCRL78__) -# define ARCHITECTURE_ID "RL78" - -# elif defined(__ICCRISCV__) -# define ARCHITECTURE_ID "RISCV" - -# elif defined(__ICCAVR__) -# define ARCHITECTURE_ID "AVR" - -# elif defined(__ICC430__) -# define ARCHITECTURE_ID "MSP430" - -# elif defined(__ICCV850__) -# define ARCHITECTURE_ID "V850" - -# elif defined(__ICC8051__) -# define ARCHITECTURE_ID "8051" - -# elif defined(__ICCSTM8__) -# define ARCHITECTURE_ID "STM8" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__ghs__) -# if defined(__PPC64__) -# define ARCHITECTURE_ID "PPC64" - -# elif defined(__ppc__) -# define ARCHITECTURE_ID "PPC" - -# elif defined(__ARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__x86_64__) -# define ARCHITECTURE_ID "x64" - -# elif defined(__i386__) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__TI_COMPILER_VERSION__) -# if defined(__TI_ARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__MSP430__) -# define ARCHITECTURE_ID "MSP430" - -# elif defined(__TMS320C28XX__) -# define ARCHITECTURE_ID "TMS320C28x" - -# elif defined(__TMS320C6X__) || defined(_TMS320C6X) -# define ARCHITECTURE_ID "TMS320C6x" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -# elif defined(__ADSPSHARC__) -# define ARCHITECTURE_ID "SHARC" - -# elif defined(__ADSPBLACKFIN__) -# define ARCHITECTURE_ID "Blackfin" - -#elif defined(__TASKING__) - -# if defined(__CTC__) || defined(__CPTC__) -# define ARCHITECTURE_ID "TriCore" - -# elif defined(__CMCS__) -# define ARCHITECTURE_ID "MCS" - -# elif defined(__CARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__CARC__) -# define ARCHITECTURE_ID "ARC" - -# elif defined(__C51__) -# define ARCHITECTURE_ID "8051" - -# elif defined(__CPCP__) -# define ARCHITECTURE_ID "PCP" - -# else -# define ARCHITECTURE_ID "" -# endif - -#else -# define ARCHITECTURE_ID -#endif - -/* Convert integer to decimal digit literals. */ -#define DEC(n) \ - ('0' + (((n) / 10000000)%10)), \ - ('0' + (((n) / 1000000)%10)), \ - ('0' + (((n) / 100000)%10)), \ - ('0' + (((n) / 10000)%10)), \ - ('0' + (((n) / 1000)%10)), \ - ('0' + (((n) / 100)%10)), \ - ('0' + (((n) / 10)%10)), \ - ('0' + ((n) % 10)) - -/* Convert integer to hex digit literals. */ -#define HEX(n) \ - ('0' + ((n)>>28 & 0xF)), \ - ('0' + ((n)>>24 & 0xF)), \ - ('0' + ((n)>>20 & 0xF)), \ - ('0' + ((n)>>16 & 0xF)), \ - ('0' + ((n)>>12 & 0xF)), \ - ('0' + ((n)>>8 & 0xF)), \ - ('0' + ((n)>>4 & 0xF)), \ - ('0' + ((n) & 0xF)) - -/* Construct a string literal encoding the version number. */ -#ifdef COMPILER_VERSION -char const* info_version = "INFO" ":" "compiler_version[" COMPILER_VERSION "]"; - -/* Construct a string literal encoding the version number components. */ -#elif defined(COMPILER_VERSION_MAJOR) -char const info_version[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', - COMPILER_VERSION_MAJOR, -# ifdef COMPILER_VERSION_MINOR - '.', COMPILER_VERSION_MINOR, -# ifdef COMPILER_VERSION_PATCH - '.', COMPILER_VERSION_PATCH, -# ifdef COMPILER_VERSION_TWEAK - '.', COMPILER_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct a string literal encoding the internal version number. */ -#ifdef COMPILER_VERSION_INTERNAL -char const info_version_internal[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', - 'i','n','t','e','r','n','a','l','[', - COMPILER_VERSION_INTERNAL,']','\0'}; -#elif defined(COMPILER_VERSION_INTERNAL_STR) -char const* info_version_internal = "INFO" ":" "compiler_version_internal[" COMPILER_VERSION_INTERNAL_STR "]"; -#endif - -/* Construct a string literal encoding the version number components. */ -#ifdef SIMULATE_VERSION_MAJOR -char const info_simulate_version[] = { - 'I', 'N', 'F', 'O', ':', - 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', - SIMULATE_VERSION_MAJOR, -# ifdef SIMULATE_VERSION_MINOR - '.', SIMULATE_VERSION_MINOR, -# ifdef SIMULATE_VERSION_PATCH - '.', SIMULATE_VERSION_PATCH, -# ifdef SIMULATE_VERSION_TWEAK - '.', SIMULATE_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; -char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; - - - -#if defined(__INTEL_COMPILER) && defined(_MSVC_LANG) && _MSVC_LANG < 201403L -# if defined(__INTEL_CXX11_MODE__) -# if defined(__cpp_aggregate_nsdmi) -# define CXX_STD 201402L -# else -# define CXX_STD 201103L -# endif -# else -# define CXX_STD 199711L -# endif -#elif defined(_MSC_VER) && defined(_MSVC_LANG) -# define CXX_STD _MSVC_LANG -#else -# define CXX_STD __cplusplus -#endif - -const char* info_language_standard_default = "INFO" ":" "standard_default[" -#if CXX_STD > 202002L - "23" -#elif CXX_STD > 201703L - "20" -#elif CXX_STD >= 201703L - "17" -#elif CXX_STD >= 201402L - "14" -#elif CXX_STD >= 201103L - "11" -#else - "98" -#endif -"]"; - -const char* info_language_extensions_default = "INFO" ":" "extensions_default[" -#if (defined(__clang__) || defined(__GNUC__) || defined(__xlC__) || \ - defined(__TI_COMPILER_VERSION__)) && \ - !defined(__STRICT_ANSI__) - "ON" -#else - "OFF" -#endif -"]"; - -/*--------------------------------------------------------------------------*/ - -int main(int argc, char* argv[]) -{ - int require = 0; - require += info_compiler[argc]; - require += info_platform[argc]; - require += info_arch[argc]; -#ifdef COMPILER_VERSION_MAJOR - require += info_version[argc]; -#endif -#ifdef COMPILER_VERSION_INTERNAL - require += info_version_internal[argc]; -#endif -#ifdef SIMULATE_ID - require += info_simulate[argc]; -#endif -#ifdef SIMULATE_VERSION_MAJOR - require += info_simulate_version[argc]; -#endif -#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) - require += info_cray[argc]; -#endif - require += info_language_standard_default[argc]; - require += info_language_extensions_default[argc]; - (void)argv; - return require; -} diff --git a/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o b/languages/c/templates/sdk/build/CMakeFiles/3.25.3/CompilerIdCXX/CMakeCXXCompilerId.o deleted file mode 100644 index aacee10dfddc5e3114bb159eee743a03c1b12206..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1712 zcmb_cJ#5oZ5PqShqzWV;F@P#TBo?M9PO7SaA|+}-fULGdhCoz3ti(wzIgaHx(6I;x z1_sK?QX~e%#7HI>vr!hr7?|3DoiY%1^Z6O|W@vfbVNlAN;TuDUd5eWoVTAL%&&wQohkn#@ z7xSq-j;d+D)t1v9ZFqXVP40J%U+PcIH{OeU>eqCQsxLdv1IwvNsTapLka_697F8IR1n^Z*cJ-l}YwvWy2!N#ELP!jS<=b%*cH!^r6J`FC4Zht{^ zzsAJjAR)R@A)ZAe`NM;S?e4sFu)LqhccYQ{*#1A{s8`rm?EJ5ueawaVcRtL>&$m`@ ztX-vFW7(!xDY&j}uGogt*bqU+wGF@C@|u;R;o-M&)bOgC753Y{;nWPTCTnKh=-7Vc z$}(qgUQDNLfkwmJ+Umw1e(Z_)ySp2^@ z#c`j+Ps4(Dam47{VX1)UfyFv=G-sR%Pq{mU!DV&cx`aV;sv}u}j^j6kad6amf6w`E zuq1DxRR1GDLcC-=%WFPoe1Y)`!ei?{C5*wsqwOppCjtl9ou4RJe%qk(9hUIXb hB0fW6ys-VIyU6WQZ~(Ik!U4=E2nSG85Dp-5 search starts here: - /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include - /Library/Developer/CommandLineTools/usr/include - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory) -End of search list. -Linking C executable cmTC_5913a -/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_5913a.dir/link.txt --verbose=1 -/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names -v -Wl,-v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -o cmTC_5913a -Apple clang version 13.1.6 (clang-1316.0.21.2.5) -Target: arm64-apple-darwin21.6.0 -Thread model: posix -InstalledDir: /Library/Developer/CommandLineTools/usr/bin - "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_5913a -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a -@(#)PROGRAM:ld PROJECT:ld64-764 -BUILD 11:22:55 Apr 28 2022 -configured to support archs: armv6 armv7 armv7s arm64 arm64e arm64_32 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em -Library search paths: - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib -Framework search paths: - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/ - - - -Parsed C implicit include dir info from above output: rv=done - found start of include info - found start of implicit include info - add: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - add: [/Library/Developer/CommandLineTools/usr/include] - end of search list found - collapse include dir [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] ==> [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - collapse include dir [/Library/Developer/CommandLineTools/usr/include] ==> [/Library/Developer/CommandLineTools/usr/include] - implicit include dirs: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include] - - -Parsed C implicit link information from above output: - link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] - ignore line: [Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-LcrFWX] - ignore line: [] - ignore line: [Run Build Command(s):/usr/bin/make -f Makefile cmTC_5913a/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_5913a.dir/build.make CMakeFiles/cmTC_5913a.dir/build] - ignore line: [Building C object CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o] - ignore line: [/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl -v -MD -MT CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -MF CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o.d -o CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCCompilerABI.c] - ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] - ignore line: [Target: arm64-apple-darwin21.6.0] - ignore line: [Thread model: posix] - ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] - ignore line: [clang: warning: -Wl -v: 'linker' input unused [-Wunused-command-line-argument]] - ignore line: [ "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCCompilerABI.c -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-LcrFWX -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -x c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCCompilerABI.c] - ignore line: [clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0] - ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include"] - ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks"] - ignore line: [#include "..." search starts here:] - ignore line: [#include <...> search starts here:] - ignore line: [ /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - ignore line: [ /Library/Developer/CommandLineTools/usr/include] - ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory)] - ignore line: [End of search list.] - ignore line: [Linking C executable cmTC_5913a] - ignore line: [/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_5913a.dir/link.txt --verbose=1] - ignore line: [/Library/Developer/CommandLineTools/usr/bin/cc -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl -search_paths_first -Wl -headerpad_max_install_names -v -Wl -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -o cmTC_5913a ] - ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] - ignore line: [Target: arm64-apple-darwin21.6.0] - ignore line: [Thread model: posix] - ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] - link line: [ "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_5913a -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - arg [/Library/Developer/CommandLineTools/usr/bin/ld] ==> ignore - arg [-demangle] ==> ignore - arg [-lto_library] ==> ignore, skip following value - arg [/Library/Developer/CommandLineTools/usr/lib/libLTO.dylib] ==> skip value of -lto_library - arg [-dynamic] ==> ignore - arg [-arch] ==> ignore - arg [arm64] ==> ignore - arg [-platform_version] ==> ignore - arg [macos] ==> ignore - arg [12.0.0] ==> ignore - arg [12.3] ==> ignore - arg [-syslibroot] ==> ignore - arg [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk] ==> ignore - arg [-o] ==> ignore - arg [cmTC_5913a] ==> ignore - arg [-search_paths_first] ==> ignore - arg [-headerpad_max_install_names] ==> ignore - arg [-v] ==> ignore - arg [CMakeFiles/cmTC_5913a.dir/CMakeCCompilerABI.c.o] ==> ignore - arg [-lSystem] ==> lib [System] - arg [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] ==> lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - Library search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - Framework search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] - remove lib [System] - remove lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - collapse library dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - collapse framework dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] - implicit libs: [] - implicit objs: [] - implicit dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - implicit fwks: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] - - -Detecting CXX compiler ABI info compiled with the following output: -Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C - -Run Build Command(s):/usr/bin/make -f Makefile cmTC_48750/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_48750.dir/build.make CMakeFiles/cmTC_48750.dir/build -Building CXX object CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl,-v -MD -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -MF CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp -Apple clang version 13.1.6 (clang-1316.0.21.2.5) -Target: arm64-apple-darwin21.6.0 -Thread model: posix -InstalledDir: /Library/Developer/CommandLineTools/usr/bin -clang: warning: -Wl,-v: 'linker' input unused [-Wunused-command-line-argument] - "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -D _DARWIN_USE_64_BIT_INODE=1 -D _LARGEFILE_SOURCE -D _FILE_OFFSET_BITS=64 -D BUILDING_NODE_EXTENSION -stdlib=libc++ -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdeprecated-macro -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fno-cxx-modules -fcxx-exceptions -fexceptions -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -x c++ /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp -clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0 -ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include" -ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks" -#include "..." search starts here: -#include <...> search starts here: - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 - /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include - /Library/Developer/CommandLineTools/usr/include - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory) -End of search list. -Linking CXX executable cmTC_48750 -/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_48750.dir/link.txt --verbose=1 -/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names -v -Wl,-v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_48750 -Apple clang version 13.1.6 (clang-1316.0.21.2.5) -Target: arm64-apple-darwin21.6.0 -Thread model: posix -InstalledDir: /Library/Developer/CommandLineTools/usr/bin - "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_48750 -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -lc++ -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a -@(#)PROGRAM:ld PROJECT:ld64-764 -BUILD 11:22:55 Apr 28 2022 -configured to support archs: armv6 armv7 armv7s arm64 arm64e arm64_32 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em -Library search paths: - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib -Framework search paths: - /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/ - - - -Parsed CXX implicit include dir info from above output: rv=done - found start of include info - found start of implicit include info - add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] - add: [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - add: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - add: [/Library/Developer/CommandLineTools/usr/include] - end of search list found - collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] - collapse include dir [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] ==> [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - collapse include dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - collapse include dir [/Library/Developer/CommandLineTools/usr/include] ==> [/Library/Developer/CommandLineTools/usr/include] - implicit include dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1;/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include;/Library/Developer/CommandLineTools/usr/include] - - -Parsed CXX implicit link information from above output: - link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] - ignore line: [Change Dir: /Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C] - ignore line: [] - ignore line: [Run Build Command(s):/usr/bin/make -f Makefile cmTC_48750/fast && /Library/Developer/CommandLineTools/usr/bin/make -f CMakeFiles/cmTC_48750.dir/build.make CMakeFiles/cmTC_48750.dir/build] - ignore line: [Building CXX object CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o] - ignore line: [/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -v -Wl -v -MD -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -MF CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -c /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp] - ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] - ignore line: [Target: arm64-apple-darwin21.6.0] - ignore line: [Thread model: posix] - ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] - ignore line: [clang: warning: -Wl -v: 'linker' input unused [-Wunused-command-line-argument]] - ignore line: [ "/Library/Developer/CommandLineTools/usr/bin/clang" -cc1 -triple arm64-apple-macosx12.0.0 -Wundef-prefix=TARGET_OS_ -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -emit-obj -mrelax-all --mrelax-relocations -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model pic -pic-level 2 -mframe-pointer=non-leaf -fno-strict-return -fno-rounding-math -munwind-tables -target-sdk-version=12.3 -fvisibility-inlines-hidden-static-local-var -target-cpu apple-m1 -target-feature +v8.5a -target-feature +fp-armv8 -target-feature +neon -target-feature +crc -target-feature +crypto -target-feature +dotprod -target-feature +fp16fml -target-feature +ras -target-feature +lse -target-feature +rdm -target-feature +rcpc -target-feature +zcm -target-feature +zcz -target-feature +fullfp16 -target-feature +sm4 -target-feature +sha3 -target-feature +sha2 -target-feature +aes -target-abi darwinpcs -fallow-half-arguments-and-returns -debugger-tuning=lldb -target-linker-version 763 -v -resource-dir /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6 -dependency-file CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o.d -skip-unused-modulemap-deps -MT CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -sys-header-deps -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -D _DARWIN_USE_64_BIT_INODE=1 -D _LARGEFILE_SOURCE -D _FILE_OFFSET_BITS=64 -D BUILDING_NODE_EXTENSION -stdlib=libc++ -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1 -internal-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include -internal-isystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include -internal-externc-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include -internal-externc-isystem /Library/Developer/CommandLineTools/usr/include -Wno-reorder-init-list -Wno-implicit-int-float-conversion -Wno-c99-designator -Wno-final-dtor-non-final-class -Wno-extra-semi-stmt -Wno-misleading-indentation -Wno-quoted-include-in-framework-header -Wno-implicit-fallthrough -Wno-enum-enum-conversion -Wno-enum-float-conversion -Wno-elaborated-enum-base -Wno-reserved-identifier -Wno-gnu-folding-constant -Wno-objc-load-method -fdeprecated-macro -fdebug-compilation-dir=/Users/JLaciv000/Downloads/firebolt-openrpc-development-native-sdk/src/native/build/CMakeFiles/CMakeScratch/TryCompile-bgRv1C -ferror-limit 19 -stack-protector 1 -fstack-check -mdarwin-stkchk-strong-link -fblocks -fencode-extended-block-signature -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fno-cxx-modules -fcxx-exceptions -fexceptions -fmax-type-align=16 -fcommon -clang-vendor-feature=+messageToSelfInClassMethodIdReturnType -clang-vendor-feature=+disableInferNewAvailabilityFromInit -clang-vendor-feature=+disableNonDependentMemberExprInCurrentInstantiation -fno-odr-hash-protocols -clang-vendor-feature=+enableAggressiveVLAFolding -clang-vendor-feature=+revert09abecef7bbf -clang-vendor-feature=+thisNoAlignAttr -clang-vendor-feature=+thisNoNullAttr -mllvm -disable-aligned-alloc-awareness=1 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -x c++ /opt/homebrew/Cellar/cmake/3.25.3/share/cmake/Modules/CMakeCXXCompilerABI.cpp] - ignore line: [clang -cc1 version 13.1.6 (clang-1316.0.21.2.5) default target arm64-apple-darwin21.6.0] - ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/local/include"] - ignore line: [ignoring nonexistent directory "/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/Library/Frameworks"] - ignore line: [#include "..." search starts here:] - ignore line: [#include <...> search starts here:] - ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include/c++/v1] - ignore line: [ /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include] - ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/include] - ignore line: [ /Library/Developer/CommandLineTools/usr/include] - ignore line: [ /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks (framework directory)] - ignore line: [End of search list.] - ignore line: [Linking CXX executable cmTC_48750] - ignore line: [/opt/homebrew/Cellar/cmake/3.25.3/bin/cmake -E cmake_link_script CMakeFiles/cmTC_48750.dir/link.txt --verbose=1] - ignore line: [/Library/Developer/CommandLineTools/usr/bin/c++ -D_DARWIN_USE_64_BIT_INODE=1 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DBUILDING_NODE_EXTENSION -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl -search_paths_first -Wl -headerpad_max_install_names -v -Wl -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_48750 ] - ignore line: [Apple clang version 13.1.6 (clang-1316.0.21.2.5)] - ignore line: [Target: arm64-apple-darwin21.6.0] - ignore line: [Thread model: posix] - ignore line: [InstalledDir: /Library/Developer/CommandLineTools/usr/bin] - link line: [ "/Library/Developer/CommandLineTools/usr/bin/ld" -demangle -lto_library /Library/Developer/CommandLineTools/usr/lib/libLTO.dylib -dynamic -arch arm64 -platform_version macos 12.0.0 12.3 -syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -o cmTC_48750 -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o -lc++ -lSystem /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - arg [/Library/Developer/CommandLineTools/usr/bin/ld] ==> ignore - arg [-demangle] ==> ignore - arg [-lto_library] ==> ignore, skip following value - arg [/Library/Developer/CommandLineTools/usr/lib/libLTO.dylib] ==> skip value of -lto_library - arg [-dynamic] ==> ignore - arg [-arch] ==> ignore - arg [arm64] ==> ignore - arg [-platform_version] ==> ignore - arg [macos] ==> ignore - arg [12.0.0] ==> ignore - arg [12.3] ==> ignore - arg [-syslibroot] ==> ignore - arg [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk] ==> ignore - arg [-o] ==> ignore - arg [cmTC_48750] ==> ignore - arg [-search_paths_first] ==> ignore - arg [-headerpad_max_install_names] ==> ignore - arg [-v] ==> ignore - arg [CMakeFiles/cmTC_48750.dir/CMakeCXXCompilerABI.cpp.o] ==> ignore - arg [-lc++] ==> lib [c++] - arg [-lSystem] ==> lib [System] - arg [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] ==> lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - Library search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - Framework search paths: [;/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] - remove lib [System] - remove lib [/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/lib/darwin/libclang_rt.osx.a] - collapse library dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - collapse framework dir [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/] ==> [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] - implicit libs: [c++] - implicit objs: [] - implicit dirs: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/usr/lib] - implicit fwks: [/Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk/System/Library/Frameworks] - - diff --git a/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache b/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache deleted file mode 100644 index 3dccd731..00000000 --- a/languages/c/templates/sdk/build/CMakeFiles/cmake.check_cache +++ /dev/null @@ -1 +0,0 @@ -# This file is generated by cmake for dependency checking of the CMakeCache.txt file diff --git a/languages/c/templates/sdk/cmake/CopySymlink.cmake b/languages/c/templates/sdk/cmake/CopySymlink.cmake deleted file mode 100644 index b25a5e22..00000000 --- a/languages/c/templates/sdk/cmake/CopySymlink.cmake +++ /dev/null @@ -1,17 +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 - -file(COPY "${LIBRARY}" DESTINATION "${DESTINATION}" FOLLOW_SYMLINK_CHAIN) diff --git a/languages/c/templates/sdk/cmake/HelperFunctions.cmake b/languages/c/templates/sdk/cmake/HelperFunctions.cmake index bbd7ce65..b3647c16 100644 --- a/languages/c/templates/sdk/cmake/HelperFunctions.cmake +++ b/languages/c/templates/sdk/cmake/HelperFunctions.cmake @@ -72,8 +72,8 @@ function(InstallHeaders) endfunction(InstallHeaders) function(InstallLibraries) - set(optionsArgs SHARED) - set(oneValueArgs TARGET DESTINATION) + set(optionsArgs SHARED STATIC) + set(oneValueArgs TARGET DESTINATION LIBDIR) set(multiValueArgs LIBRARIES) cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) @@ -92,11 +92,11 @@ function(InstallLibraries) TARGET ${Argument_TARGET} POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib - COMMAND ${CMAKE_COMMAND} -D "LIBRARY=${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR}" -D "DESTINATION=${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib" -P ${CMAKE_SOURCE_DIR}/cmake/CopySymlink.cmake - COMMAND ${CMAKE_COMMAND} -D "LIBRARY=${CMAKE_BINARY_DIR}/Release/lib${LIBRARY}.so" -D "DESTINATION=${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib" -P ${CMAKE_SOURCE_DIR}/cmake/CopySymlink.cmake + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_LIBDIR}/lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib + COMMAND ${CMAKE_COMMAND} -E create_symlink lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR} + COMMAND ${CMAKE_COMMAND} -E create_symlink lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/lib${LIBRARY}.so ) - else() + elseif (Argument_STATIC) add_custom_command( TARGET ${Argument_TARGET} POST_BUILD @@ -119,13 +119,18 @@ function(InstallCMakeConfigs) message(FATAL_ERROR "Unknown keywords given to InstallCMakeConfigs(): \"${Argument_UNPARSED_ARGUMENTS}\"") endif() if (Argument_TARGET) + if (${CMAKE_VERSION} VERSION_LESS "3.25.0") + set(EXPORT_CONFIG_PATH "lib/cmake/${Argument_TARGET}") + else () + set(EXPORT_CONFIG_PATH "*") + endif () add_custom_command( TARGET ${Argument_TARGET} POST_BUILD COMMENT "=================== Installing CMakeConfigs ======================" COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}Config*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Export/lib/cmake/${Argument_TARGET}/${Argument_TARGET}Targets*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Export/${EXPORT_CONFIG_PATH}/${Argument_TARGET}Targets*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} ) if (EXISTS ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}.pc) add_custom_command( diff --git a/languages/c/templates/sdk/cmake/project.cmake.in b/languages/c/templates/sdk/cmake/project.cmake.in index 0855ca12..eca32f8c 100644 --- a/languages/c/templates/sdk/cmake/project.cmake.in +++ b/languages/c/templates/sdk/cmake/project.cmake.in @@ -27,4 +27,9 @@ if (NOT DEFINED CMAKE_PREFIX_PATH) set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) endif() +if (FIREBOLT_ENABLE_STATIC_LIB) + set(FIREBOLT_LIBRARY_TYPE STATIC) +else () + set(FIREBOLT_LIBRARY_TYPE SHARED) +endif () diff --git a/languages/c/templates/sdk/include/Firebolt.h b/languages/c/templates/sdk/include/Firebolt.h new file mode 100644 index 00000000..2223bad3 --- /dev/null +++ b/languages/c/templates/sdk/include/Firebolt.h @@ -0,0 +1,65 @@ +/* + * 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 + */ + +#ifndef _FIREBOLT_H +#define _FIREBOLT_H + +#include "Error.h" +#include "Types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Intitialize the Firebolt SDK + * + * @param configLine JSON String with configuration options + * + * CONFIG Format: + * { + * "waitTime": 1000, + * "logLevel": "Info", + * "workerPool":{ + * "queueSize": 8, + * "threadCount": 3 + * }, + * "wsUrl": "ws://127.0.0.1:9998" + * } + * + * + * @return FireboltSDKErrorNone if success, appropriate error otherwise. + * + */ +uint32_t FireboltSDK_Initialize(char* configLine); + + +/** + * @brief Deintitialize the Firebolt SDK + * + * @return FireboltSDKErrorNone if success, appropriate error otherwise. + * + */ +uint32_t FireboltSDK_Deinitialize(void); + +#ifdef __cplusplus +} +#endif + + +#endif // _FIREBOLT_H diff --git a/languages/c/templates/sdk/include/Types.h b/languages/c/templates/sdk/include/Types.h index e7456cdd..4fd16256 100644 --- a/languages/c/templates/sdk/include/Types.h +++ b/languages/c/templates/sdk/include/Types.h @@ -20,18 +20,12 @@ #define _FIREBOLT_TYPES_H #include +#include #ifdef __cplusplus extern "C" { #endif -typedef enum { - Test1, - Test2, - Test3, - Test4 -} TestEnum; - typedef void* FireboltTypes_StringHandle; const char* FireboltTypes_String(FireboltTypes_StringHandle handle); void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle); diff --git a/languages/c/templates/sdk/scripts/build.sh b/languages/c/templates/sdk/scripts/build.sh new file mode 100755 index 00000000..e9b01f20 --- /dev/null +++ b/languages/c/templates/sdk/scripts/build.sh @@ -0,0 +1,11 @@ +#!/bin/bash +SDK_PATH="." +if [ "$1" != "" ] +then + SDK_PATH=$1 + echo "inside ${1}" +fi +echo ${SDK_PATH} +rm -rf ${SDK_PATH}/build +cmake -B${SDK_PATH}/build -S${SDK_PATH} -DSYSROOT_PATH=${SYSROOT_PATH} +cmake --build ${SDK_PATH}/build diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.cpp b/languages/c/templates/sdk/src/Accessor/Accessor.cpp index b4cada4b..e4a5df32 100644 --- a/languages/c/templates/sdk/src/Accessor/Accessor.cpp +++ b/languages/c/templates/sdk/src/Accessor/Accessor.cpp @@ -21,22 +21,22 @@ namespace FireboltSDK { Accessor* Accessor::_singleton = nullptr; - Accessor::Accessor() - : _threadCount(DefaultThreadCount) - , _queueSize(DefaultQueueSize) - , _workerPool() + + Accessor::Accessor(const string& configLine) + : _workerPool() , _transport(nullptr) + , _config() { _singleton = this; - Config config; - LoadConfigs(config); + _config.FromString(configLine); + + Logger::SetLogLevel(WPEFramework::Core::EnumerateType(_config.LogLevel.Value().c_str()).Value()); - Logger::SetLogLevel(WPEFramework::Core::EnumerateType(config.LogLevel.Value().c_str()).Value()); - FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Url = %s", config.Url.Value().c_str()); - CreateTransport(config.Url.Value(), config.WaitTime.Value()); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Url = %s", _config.WsUrl.Value().c_str()); + CreateTransport(_config.WsUrl.Value().c_str(), _config.WaitTime.Value()); CreateEventHandler(); - _workerPool = WPEFramework::Core::ProxyType::Create(_threadCount, WPEFramework::Core::Thread::DefaultStackSize(), _queueSize); + _workerPool = WPEFramework::Core::ProxyType::Create(_config.WorkerPool.ThreadCount.Value(), _config.WorkerPool.StackSize.Value(), _config.WorkerPool.QueueSize.Value()); WPEFramework::Core::WorkerPool::Assign(&(*_workerPool)); _workerPool->Run(); } @@ -50,23 +50,6 @@ namespace FireboltSDK { _singleton = nullptr; } - void Accessor::LoadConfigs(Config& config) - { - string prefixPath; - WPEFramework::Core::SystemInfo::GetEnvironment("OPENRPC_NATIVE_SDK_PREFIX", prefixPath); - string configFilePath = (prefixPath.empty() != true) ? - (prefixPath + '/' + Accessor::ConfigFile) : Accessor::ConfigFile; - WPEFramework::Core::File configFile(configFilePath); - - if (configFile.Open(true) == true) { - WPEFramework::Core::OptionalType error; - config.IElement::FromFile(configFile, error); - if (error.IsSet() == true) { - FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in reading config"); - } - } - } - uint32_t Accessor::CreateEventHandler() { Event::Instance().Configure(_transport); @@ -84,14 +67,14 @@ namespace FireboltSDK { return Event::Instance(); } - uint32_t Accessor::CreateTransport(const string& url, const uint32_t waitTime) + uint32_t Accessor::CreateTransport(const string& url, const uint32_t waitTime = DefaultWaitTime) { if (_transport != nullptr) { delete _transport; } _transport = new Transport(static_cast(url), waitTime); - if (WaitForLinkReady(_transport, DefaultWaitTime) != FireboltSDKErrorNone) { + if (WaitForLinkReady(_transport, waitTime) != FireboltSDKErrorNone) { delete _transport; _transport = nullptr; } diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.h b/languages/c/templates/sdk/src/Accessor/Accessor.h index 3e9b8784..f12dc51c 100644 --- a/languages/c/templates/sdk/src/Accessor/Accessor.h +++ b/languages/c/templates/sdk/src/Accessor/Accessor.h @@ -19,7 +19,6 @@ #pragma once #include "Module.h" -#include "Config.h" #include "WorkerPool.h" #include "Transport/Transport.h" #include "Event/Event.h" @@ -29,21 +28,69 @@ namespace FireboltSDK { class Accessor { private: static constexpr uint8_t JSONVersion = 2; - static constexpr const TCHAR* ConfigFile = _T("/etc/Firebolt/config.json"); - static constexpr uint32_t DefaultWaitTime = 1000; - static constexpr uint8_t DefaultQueueSize = 8; - static constexpr uint8_t DefaultThreadCount = 3; + + private: + //Singleton + Accessor(const string& configLine); public: + class EXTERNAL Config : public WPEFramework::Core::JSON::Container { + public: + Config(const Config&) = delete; + Config& operator=(const Config&) = delete; + + class WorkerPoolConfig : public WPEFramework::Core::JSON::Container { + public: + WorkerPoolConfig& operator=(const WorkerPoolConfig&); + + WorkerPoolConfig() + : WPEFramework::Core::JSON::Container() + , QueueSize(8) + , ThreadCount(3) + , StackSize(WPEFramework::Core::Thread::DefaultStackSize()) + { + Add("queueSize", &QueueSize); + Add("threadCount", &ThreadCount); + Add("stackSize", &StackSize); + } + + virtual ~WorkerPoolConfig() = default; + + public: + WPEFramework::Core::JSON::DecUInt32 QueueSize; + WPEFramework::Core::JSON::DecUInt32 ThreadCount; + WPEFramework::Core::JSON::DecUInt32 StackSize; + }; + + + Config() + : WPEFramework::Core::JSON::Container() + , WaitTime(1000) + , LogLevel(_T("Info")) + , WorkerPool() + , WsUrl(_T("ws://127.0.0.1:9998")) + { + Add(_T("waitTime"), &WaitTime); + Add(_T("logLevel"), &LogLevel); + Add(_T("workerPool"), &WorkerPool); + Add(_T("wsUrl"), &WsUrl); + } + + public: + WPEFramework::Core::JSON::DecUInt32 WaitTime; + WPEFramework::Core::JSON::String LogLevel; + WorkerPoolConfig WorkerPool; + WPEFramework::Core::JSON::String WsUrl; + }; + Accessor(const Accessor&) = delete; Accessor& operator= (const Accessor&) = delete; - - Accessor(); + Accessor() = delete; ~Accessor(); - static Accessor& Instance() + static Accessor& Instance(const string& configLine = "") { - static Accessor *instance = new Accessor(); + static Accessor *instance = new Accessor(configLine); ASSERT(instance != nullptr); return *instance; } @@ -56,24 +103,20 @@ namespace FireboltSDK { delete _singleton; } } + Event& GetEventManager(); + Transport* GetTransport(); + private: uint32_t CreateEventHandler(); uint32_t DestroyEventHandler(); - Event& GetEventManager(); - uint32_t CreateTransport(const string& url, const uint32_t waitTime); uint32_t DestroyTransport(); - Transport* GetTransport(); uint32_t WaitForLinkReady(Transport* transport, const uint32_t waitTime); private: - void LoadConfigs(Config& config); - - private: - uint8_t _threadCount; - uint8_t _queueSize; WPEFramework::Core::ProxyType _workerPool; Transport* _transport; static Accessor* _singleton; + Config _config; }; } diff --git a/languages/c/templates/sdk/src/Accessor/WorkerPool.h b/languages/c/templates/sdk/src/Accessor/WorkerPool.h index 521ccc65..69005a5e 100644 --- a/languages/c/templates/sdk/src/Accessor/WorkerPool.h +++ b/languages/c/templates/sdk/src/Accessor/WorkerPool.h @@ -69,4 +69,34 @@ namespace FireboltSDK { Dispatcher _dispatcher; }; + class Worker : public WPEFramework::Core::IDispatch { + public: + typedef std::function Dispatcher; + + protected: + Worker(const Dispatcher& dispatcher, const void* userData) + : _dispatcher(dispatcher) + , _userData(userData) + { + } + + public: + Worker() = delete; + Worker(const Worker&) = delete; + Worker& operator=(const Worker&) = delete; + + ~Worker() = default; + + public: + static WPEFramework::Core::ProxyType Create(const Dispatcher& dispatcher, const void* userData); + + void Dispatch() override + { + _dispatcher(_userData); + } + + private: + Dispatcher _dispatcher; + const void* _userData; + }; } diff --git a/languages/c/templates/sdk/src/CMakeLists.txt b/languages/c/templates/sdk/src/CMakeLists.txt index c411582a..2f00bdf1 100644 --- a/languages/c/templates/sdk/src/CMakeLists.txt +++ b/languages/c/templates/sdk/src/CMakeLists.txt @@ -20,29 +20,30 @@ project(FireboltSDK) project_version(1.0.0) set(TARGET ${PROJECT_NAME}) message("Setup ${TARGET} v${PROJECT_VERSION}") +file(GLOB GENERATED_SOURCES "${GENERATED_CODE_PATH}/src/*.cpp") -add_library(${TARGET} SHARED - Types.cpp - Module.cpp +file(GLOB SOURCES *.cpp) +add_library(${TARGET} ${FIREBOLT_LIBRARY_TYPE} + ${SOURCES} Logger/Logger.cpp Transport/Transport.cpp Accessor/Accessor.cpp - Event/Event.cpp) + Event/Event.cpp +) set(CMAKE_POSITION_INDEPENDENT_CODE ON) -find_package(${NAMESPACE}Core CONFIG REQUIRED) find_package(${NAMESPACE}WebSocket CONFIG REQUIRED) target_link_libraries(${TARGET} PUBLIC - ${NAMESPACE}Core::${NAMESPACE}Core ${NAMESPACE}WebSocket::${NAMESPACE}WebSocket ) target_include_directories(${TARGET} PRIVATE $ - $ + $ + $ $ ) @@ -66,21 +67,13 @@ InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTIN InstallHeaders(TARGET ${TARGET} EXCLUDE_ROOT_DIR HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} SOURCE ${GENERATED_CODE_PATH}/include DESTINATION ${FIREBOLT_NAMESPACE}/generated) InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} - SOURCE ${CMAKE_SOURCE_DIR}/include DESTINATION ${FIREBOLT_NAMESPACE}) + SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../include DESTINATION ${FIREBOLT_NAMESPACE}) -InstallLibraries(TARGET ${TARGET} SHARED LIBRARIES ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallLibraries(TARGET ${TARGET} ${FIREBOLT_LIBRARY_TYPE} LIBDIR ${LIBDIR} LIBRARIES ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) InstallCMakeConfig(TARGETS ${TARGET}) InstallPackageConfig(TARGETS ${TARGET} DESCRIPTION "Firebolt SDK Library") InstallCMakeConfigs(TARGET ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) -add_custom_command( - TARGET ${TARGET} - POST_BUILD - COMMENT "=================== Installing JsonConfig ======================" - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/etc/${FIREBOLT_NAMESPACE} - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/config/${TARGET}.json ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/etc/${FIREBOLT_NAMESPACE}/config.json -) - add_custom_command( TARGET ${TARGET} POST_BUILD @@ -89,5 +82,3 @@ add_custom_command( COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/cmake/*.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} ) - -include(Config.cmake) diff --git a/languages/c/templates/sdk/src/Config.cmake b/languages/c/templates/sdk/src/Config.cmake deleted file mode 100644 index a420ce32..00000000 --- a/languages/c/templates/sdk/src/Config.cmake +++ /dev/null @@ -1,34 +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 - -set(SERVER_PORT 9998 CACHE STRING "The port of the server") -set(SERVER_ADDRESS "127.0.0.1" CACHE STRING "The address of the server") - - #[[ ================================ Add additional config above this line ================================ ]] - - -find_package(ConfigGenerator REQUIRED) - -write_config( - SKIP_COMPARE - SKIP_CLASSNAME - SKIP_LOCATOR - DISABLE_LEGACY_GENERATOR - CUSTOM_PARAMS_WHITELIST "${CMAKE_CURRENT_LIST_DIR}/Params.config" - INSTALL_PATH "${CMAKE_INSTALL_PREFIX}/../etc/" - INSTALL_NAME "config.json" -) - diff --git a/languages/c/templates/sdk/src/Event/Event.cpp b/languages/c/templates/sdk/src/Event/Event.cpp index 69b448f6..5e98a36f 100644 --- a/languages/c/templates/sdk/src/Event/Event.cpp +++ b/languages/c/templates/sdk/src/Event/Event.cpp @@ -22,8 +22,7 @@ namespace FireboltSDK { Event* Event::_singleton = nullptr; Event::Event() - : _id(0) - , _eventMap() + : _eventMap() , _adminLock() , _transport(nullptr) { @@ -61,9 +60,9 @@ namespace FireboltSDK { _transport->SetEventHandler(this); } - uint32_t Event::Unsubscribe(const string& eventName, const uint32_t id) + uint32_t Event::Unsubscribe(const string& eventName, void* usercb) { - uint32_t status = Revoke(eventName, id); + uint32_t status = Revoke(eventName, usercb); if (status == FireboltSDKErrorNone) { if (_transport != nullptr) { @@ -93,26 +92,26 @@ namespace FireboltSDK { _adminLock.Lock(); EventMap::iterator eventIndex = _eventMap.find(eventName); if (eventIndex != _eventMap.end()) { - IdMap::iterator idIndex = eventIndex->second.begin(); - while(idIndex != eventIndex->second.end()) { + CallbackMap::iterator callbackIndex = eventIndex->second.begin(); + while(callbackIndex != eventIndex->second.end()) { State state; - if (idIndex->second.state != State::REVOKED) { - idIndex->second.state = State::EXECUTING; + if (callbackIndex->second.state != State::REVOKED) { + callbackIndex->second.state = State::EXECUTING; } - state = idIndex->second.state; + state = callbackIndex->second.state; _adminLock.Unlock(); if (state == State::EXECUTING) { - idIndex->second.lambda(idIndex->second.userdata, (jsonResponse->Result.Value())); + callbackIndex->second.lambda(callbackIndex->first, callbackIndex->second.userdata, (jsonResponse->Result.Value())); } _adminLock.Lock(); - if (idIndex->second.state == State::REVOKED) { - idIndex = eventIndex->second.erase(idIndex); + if (callbackIndex->second.state == State::REVOKED) { + callbackIndex = eventIndex->second.erase(callbackIndex); if (eventIndex->second.size() == 0) { _eventMap.erase(eventIndex); } } else { - idIndex->second.state = State::IDLE; - idIndex++; + callbackIndex->second.state = State::IDLE; + callbackIndex++; } } } @@ -121,19 +120,19 @@ namespace FireboltSDK { return FireboltSDKErrorNone;; } - uint32_t Event::Revoke(const string& eventName, const uint32_t id) + uint32_t Event::Revoke(const string& eventName, void* usercb) { uint32_t status = FireboltSDKErrorNone; _adminLock.Lock(); EventMap::iterator eventIndex = _eventMap.find(eventName); if (eventIndex != _eventMap.end()) { - IdMap::iterator idIndex = eventIndex->second.find(id); - if (idIndex->second.state != State::EXECUTING) { - if (idIndex != eventIndex->second.end()) { - eventIndex->second.erase(idIndex); + CallbackMap::iterator callbackIndex = eventIndex->second.find(usercb); + if (callbackIndex->second.state != State::EXECUTING) { + if (callbackIndex != eventIndex->second.end()) { + eventIndex->second.erase(callbackIndex); } } else { - idIndex->second.state = State::REVOKED; + callbackIndex->second.state = State::REVOKED; } if (eventIndex->second.size() == 0) { _eventMap.erase(eventIndex); diff --git a/languages/c/templates/sdk/src/Event/Event.h b/languages/c/templates/sdk/src/Event/Event.h index df9b1dc9..efa8457a 100644 --- a/languages/c/templates/sdk/src/Event/Event.h +++ b/languages/c/templates/sdk/src/Event/Event.h @@ -26,7 +26,7 @@ namespace FireboltSDK { class Event : public IEventHandler { public: - typedef std::function DispatchFunction; + typedef std::function DispatchFunction; private: enum State : uint8_t { IDLE, @@ -39,9 +39,8 @@ namespace FireboltSDK { const void* userdata; State state; }; - using IdMap = std::map; - using EventMap = std::map; - + using CallbackMap = std::map; + using EventMap = std::map; class Response : public WPEFramework::Core::JSON::Container { public: @@ -64,28 +63,41 @@ namespace FireboltSDK { WPEFramework::Core::JSON::Boolean Listening; }; - public: + private: Event(); + public: ~Event() override; static Event& Instance(); static void Dispose(); void Configure(Transport* transport); public: - template - uint32_t Subscribe(const string& eventName, const CALLBACK& callback, const void* userdata, uint32_t& id) + template + uint32_t Subscribe(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) + { + JsonObject jsonParameters; + return Subscribe(eventName, jsonParameters, callback, usercb, userdata); + } + + template + uint32_t Subscribe(const string& eventName, JsonObject& jsonParameters, const CALLBACK& callback, void* usercb, const void* userdata) { uint32_t status = FireboltSDKErrorUnavailable; if (_transport != nullptr) { - status = Assign(eventName, callback, userdata, id); + status = Assign(eventName, callback, usercb, userdata); if (status == FireboltSDKErrorNone) { - const string parameters("{\"listen\":true}"); Response response; - status = _transport->Subscribe(eventName, parameters, response); + + WPEFramework::Core::JSON::Variant Listen = true; + jsonParameters.Set(_T("listen"), Listen); + string parameters; + jsonParameters.ToString(parameters); + + status = _transport->Subscribe(eventName, parameters, response); if (status != FireboltSDKErrorNone) { - Revoke(eventName, id); + Revoke(eventName, usercb); } else if ((response.Listening.IsSet() == true) && (response.Listening.Value() == true)) { status = FireboltSDKErrorNone; @@ -95,23 +107,23 @@ namespace FireboltSDK { } } - return ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone: status); + return status; } - uint32_t Unsubscribe(const string& eventName, const uint32_t id); + uint32_t Unsubscribe(const string& eventName, void* usercb); private: template - uint32_t Assign(const string& eventName, const CALLBACK& callback, const void* userdata, uint32_t& id) + uint32_t Assign(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) { uint32_t status = FireboltSDKErrorNone; - id = Id(); - std::function actualCallback = callback; - DispatchFunction implementation = [actualCallback](const void* userdata, const string& parameters) -> uint32_t { + std::function actualCallback = callback; + DispatchFunction implementation = [actualCallback](void* usercb, const void* userdata, const string& parameters) -> uint32_t { - WPEFramework::Core::ProxyType inbound = WPEFramework::Core::ProxyType::Create(); - inbound->FromString(parameters); - actualCallback(userdata, static_cast(&inbound)); + WPEFramework::Core::ProxyType* inbound = new WPEFramework::Core::ProxyType(); + *inbound = WPEFramework::Core::ProxyType::Create(); + (*inbound)->FromString(parameters); + actualCallback(usercb, userdata, static_cast(inbound)); return (FireboltSDKErrorNone); }; CallbackData callbackData = {implementation, userdata, State::IDLE}; @@ -119,32 +131,31 @@ namespace FireboltSDK { _adminLock.Lock(); EventMap::iterator eventIndex = _eventMap.find(eventName); if (eventIndex != _eventMap.end()) { - // Already registered, no need to register again; - status = FireboltSDKErrorInUse; - eventIndex->second.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(callbackData)); + CallbackMap::iterator callbackIndex = eventIndex->second.find(usercb); + if (callbackIndex == eventIndex->second.end()) { + eventIndex->second.emplace(std::piecewise_construct, std::forward_as_tuple(usercb), std::forward_as_tuple(callbackData)); + } else { + // Already registered, no need to register again; + status = FireboltSDKErrorInUse; + } } else { - IdMap idMap; - idMap.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(callbackData)); - _eventMap.emplace(std::piecewise_construct, std::forward_as_tuple(eventName), std::forward_as_tuple(idMap)); + CallbackMap callbackMap; + callbackMap.emplace(std::piecewise_construct, std::forward_as_tuple(usercb), std::forward_as_tuple(callbackData)); + _eventMap.emplace(std::piecewise_construct, std::forward_as_tuple(eventName), std::forward_as_tuple(callbackMap)); } _adminLock.Unlock(); return status; } - uint32_t Revoke(const string& eventName, const uint32_t id); + uint32_t Revoke(const string& eventName, void* usercb); private: - uint32_t Id() const - { - return (++_id); - } uint32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) override; uint32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) override; private: - mutable std::atomic _id; EventMap _eventMap; WPEFramework::Core::CriticalSection _adminLock; Transport* _transport; diff --git a/languages/c/templates/sdk/src/Accessor/Config.h b/languages/c/templates/sdk/src/Firebolt.cpp similarity index 50% rename from languages/c/templates/sdk/src/Accessor/Config.h rename to languages/c/templates/sdk/src/Firebolt.cpp index f8389bf6..ffc1369a 100644 --- a/languages/c/templates/sdk/src/Accessor/Config.h +++ b/languages/c/templates/sdk/src/Firebolt.cpp @@ -16,26 +16,25 @@ * SPDX-License-Identifier: Apache-2.0 */ -namespace FireboltSDK { - class EXTERNAL Config : public WPEFramework::Core::JSON::Container { - public: - Config(const Config&) = delete; - Config& operator=(const Config&) = delete; - - Config() - : WPEFramework::Core::JSON::Container() - , Url(_T("")) - , WaitTime(1000) - , LogLevel(_T("Info")) - { - Add(_T("url"), &Url); - Add(_T("waittime"), &WaitTime); - Add(_T("loglevel"), &LogLevel); - } - - public: - WPEFramework::Core::JSON::String Url; - WPEFramework::Core::JSON::DecUInt32 WaitTime; - WPEFramework::Core::JSON::String LogLevel; - }; +#include "FireboltSDK.h" + + +#ifdef __cplusplus +extern "C" { +#endif + + + +uint32_t FireboltSDK_Initialize(char* configLine) { + FireboltSDK::Accessor::Instance(configLine); + return FireboltSDKErrorNone; +} + +uint32_t FireboltSDK_Deinitialize(void) { + FireboltSDK::Accessor::Dispose(); + return FireboltSDKErrorNone; +} + +#ifdef __cplusplus } +#endif diff --git a/languages/c/templates/sdk/src/Firebolt.h b/languages/c/templates/sdk/src/FireboltSDK.h similarity index 97% rename from languages/c/templates/sdk/src/Firebolt.h rename to languages/c/templates/sdk/src/FireboltSDK.h index 6a8f51a2..19946126 100644 --- a/languages/c/templates/sdk/src/Firebolt.h +++ b/languages/c/templates/sdk/src/FireboltSDK.h @@ -22,4 +22,5 @@ #include "Properties/Properties.h" #include "Accessor/Accessor.h" #include "Logger/Logger.h" +#include "TypesPriv.h" #include "Types.h" diff --git a/languages/c/templates/sdk/src/Logger/Logger.cpp b/languages/c/templates/sdk/src/Logger/Logger.cpp index 8acd8a14..0e49dfce 100644 --- a/languages/c/templates/sdk/src/Logger/Logger.cpp +++ b/languages/c/templates/sdk/src/Logger/Logger.cpp @@ -53,7 +53,6 @@ namespace FireboltSDK { _logLevel = logLevel; status = FireboltSDKErrorNone; } - printf("logLevel = %d _logLevel = %d\n", logLevel, _logLevel); return status; } diff --git a/languages/c/templates/sdk/src/Module.h b/languages/c/templates/sdk/src/Module.h index 5107d93e..00ea64bb 100644 --- a/languages/c/templates/sdk/src/Module.h +++ b/languages/c/templates/sdk/src/Module.h @@ -23,8 +23,6 @@ #endif #include -#include -#include #include #undef EXTERNAL diff --git a/languages/c/templates/sdk/src/Params.config b/languages/c/templates/sdk/src/Params.config deleted file mode 100644 index 71a58750..00000000 --- a/languages/c/templates/sdk/src/Params.config +++ /dev/null @@ -1,3 +0,0 @@ -url -waittime -loglevel diff --git a/languages/c/templates/sdk/src/Properties/Properties.h b/languages/c/templates/sdk/src/Properties/Properties.h index 611811f8..d75c3ba5 100644 --- a/languages/c/templates/sdk/src/Properties/Properties.h +++ b/languages/c/templates/sdk/src/Properties/Properties.h @@ -52,7 +52,60 @@ namespace FireboltSDK { } else { FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); } - + + return status; + } + + template + static uint32_t Get(const string& propertyName, const PARAMETERS& parameters, WPEFramework::Core::ProxyType& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + RESPONSETYPE responseType; + status = transport->Invoke(propertyName, parameters, responseType); + if (status == FireboltSDKErrorNone) { + ASSERT(response.IsValid() == false); + if (response.IsValid() == true) { + response.Release(); + } + response = WPEFramework::Core::ProxyType::Create(); + (*response) = responseType; + } + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + + template + static uint32_t Get(const string& propertyName, RESPONSETYPE& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject parameters; + status = transport->Invoke(propertyName, parameters, response); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static uint32_t Get(const string& propertyName, const PARAMETERS& parameters, RESPONSETYPE& response) + { + uint32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + status = transport->Invoke(propertyName, parameters, response); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + return status; } @@ -71,20 +124,25 @@ namespace FireboltSDK { return status; } - template - static uint32_t Subscribe(const string& propertyName, const CALLBACK& callback, const void* userdata, uint32_t& id) + template + static uint32_t Subscribe(const string& propertyName, JsonObject& paramsters, const CALLBACK& callback, void* usercb, const void* userdata) { - return Event::Instance().Subscribe(EventName(propertyName), callback, userdata, id); + return Event::Instance().Subscribe(EventName(propertyName), paramsters, callback, usercb, userdata); } - static uint32_t Unsubscribe(const string& propertyName, const uint32_t id) + static uint32_t Unsubscribe(const string& propertyName, void* usercb) { - return Event::Instance().Unsubscribe(EventName(propertyName), id); + return Event::Instance().Unsubscribe(EventName(propertyName), usercb); } private: static inline string EventName(const string& propertyName) { size_t pos = propertyName.find_first_of('.'); - return string(propertyName.substr(0, pos + 1) + "on" + propertyName.substr(pos + 1) + "Changed"); + string eventName = propertyName; + if (pos != std::string::npos) { + eventName[pos + 1] = std::toupper(eventName[pos + 1]); + eventName = string(eventName.substr(0, pos + 1) + "on" + eventName.substr(pos + 1) + "Changed"); + } + return eventName; } }; } diff --git a/languages/c/templates/sdk/src/Transport/Transport.h b/languages/c/templates/sdk/src/Transport/Transport.h index e0bff38c..2aff350d 100644 --- a/languages/c/templates/sdk/src/Transport/Transport.h +++ b/languages/c/templates/sdk/src/Transport/Transport.h @@ -254,7 +254,7 @@ namespace FireboltSDK { public: ChannelImpl(CommunicationChannel* parent, const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask) - : BaseClass(5, FactoryImpl::Instance(), path, _T("JSON"), query, "", false, mask, false, remoteNode.AnyInterface(), remoteNode, 256, 256) + : BaseClass(5, FactoryImpl::Instance(), path, _T("JSON"), query, "", false, mask, false, remoteNode.AnyInterface(), remoteNode, 1024 * 2, 1024 * 2) //TODO Relook this size issue , _parent(*parent) { } @@ -520,7 +520,7 @@ namespace FireboltSDK { public: inline bool IsOpen() { - _channel->IsOpen(); + return _channel->IsOpen(); } void Revoke(const string& eventName) diff --git a/languages/c/templates/sdk/src/Types.cpp b/languages/c/templates/sdk/src/Types.cpp index e573c0c9..f19cfe63 100644 --- a/languages/c/templates/sdk/src/Types.cpp +++ b/languages/c/templates/sdk/src/Types.cpp @@ -27,13 +27,12 @@ extern "C" { // String Type Handler Interfaces const char* FireboltTypes_String(FireboltTypes_StringHandle handle) { - FireboltSDK::String* str = static_cast(handle); - return (str->Value().c_str()); + return ((static_cast(handle))->Value().c_str()); } + void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle) { - FireboltSDK::String* str = static_cast(handle); - delete str; + delete static_cast(handle); } #ifdef __cplusplus diff --git a/languages/c/templates/sdk/src/TypesPriv.h b/languages/c/templates/sdk/src/TypesPriv.h index eda9547f..6e365ec7 100644 --- a/languages/c/templates/sdk/src/TypesPriv.h +++ b/languages/c/templates/sdk/src/TypesPriv.h @@ -21,35 +21,36 @@ #include namespace FireboltSDK { -class String { +namespace JSON { +class String : public WPEFramework::Core::JSON::String { + using Base = WPEFramework::Core::JSON::String; public: String() - : _value() + : Base() + , _value() { } - String(const std::string& value) - : _value(value) + String(const char value[]) + : Base(value) + , _value(value) { } - String(const String& copy) - : _value(copy._value) + String& operator=(const char RHS[]) { - - } - inline ~String() = default; - String& operator=(const String& RHS) - { - _value = RHS._value; + Base::operator = (RHS); + _value = RHS; return (*this); } public: - const std::string& Value() const + const string& Value() const { + _value = Base::Value(); return _value; } private: - std::string _value; + mutable std::string _value; }; } +} diff --git a/languages/c/templates/sdk/src/cmake/CopySymlink.cmake b/languages/c/templates/sdk/src/cmake/CopySymlink.cmake deleted file mode 100644 index 8ac3c1f8..00000000 --- a/languages/c/templates/sdk/src/cmake/CopySymlink.cmake +++ /dev/null @@ -1 +0,0 @@ -file(COPY "${LIBRARY}" DESTINATION "${DESTINATION}" FOLLOW_SYMLINK_CHAIN) From 0e742f2f6e90fac9674bcfd5b32c360118d9f159 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 15 Jun 2023 09:09:06 +0530 Subject: [PATCH 075/137] Add support to generate file inclusion for common schema also (#97) Add support to generate file inclusion for common schema also --- languages/c/Types.mjs | 336 +++++++++--------- languages/c/src/types/JSONHelpers.mjs | 3 +- languages/c/src/types/NativeHelpers.mjs | 15 - languages/c/templates/imports/default.cpp | 1 + .../imports/{default.c => default.h} | 0 .../c/templates/imports/default.jsondata | 1 + .../templates/modules/include/Common/Module.h | 40 --- .../c/templates/modules/src/JsonData_Module.h | 29 -- languages/c/templates/modules/src/Module.cpp | 6 +- .../templates/schemas/include/Common/Module.h | 1 + .../c/templates/schemas/src/JsonData_Module.h | 5 + .../c/templates/schemas/src/Module_Common.cpp | 5 +- src/macrofier/engine.mjs | 50 ++- src/shared/typescript.mjs | 2 +- 14 files changed, 226 insertions(+), 268 deletions(-) create mode 100644 languages/c/templates/imports/default.cpp rename languages/c/templates/imports/{default.c => default.h} (100%) create mode 100644 languages/c/templates/imports/default.jsondata delete mode 100644 languages/c/templates/modules/include/Common/Module.h delete mode 100644 languages/c/templates/modules/src/JsonData_Module.h diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 0bb6cc59..bbd74eec 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -318,193 +318,201 @@ function getSchemaShape(json, module, { name = '', prefix = '', level = 0, title return shape } function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '', merged = false, level = 0, title, summary, descriptions = true, destination = '', section = '', enums = true } = {}) { - const isHeader = (destination.includes("JsonData_") !== true) && destination.endsWith(".h") - const isCPP = ((destination.endsWith(".cpp") || destination.includes("JsonData_")) && (section.includes('accessors') !== true)) - json = JSON.parse(JSON.stringify(json)) - - name = json.title || name let shape = '' - if (json['$ref']) { - if (json['$ref'][0] === '#') { - //Ref points to local schema - //Get Path to ref in this module and getSchemaType - const schema = getPath(json['$ref'], module, schemas) - const tname = schema.title || json['$ref'].split('/').pop() - if (json['$ref'].includes('x-schemas')) { - schema = (getRefModule(json['$ref'].split('/')[2])) - } - - shape = getSchemaShapeInfo(schema, module, schemas, { name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) - } - } - //If the schema is a const, - else if (json.hasOwnProperty('const') && !isCPP) { - if (level > 0) { + if (destination && section) { + const isHeader = (destination.includes("JsonData_") !== true) && destination.endsWith(".h") + const isCPP = ((destination.endsWith(".cpp") || destination.includes("JsonData_")) && (section.includes('accessors') !== true)) + json = JSON.parse(JSON.stringify(json)) + + name = json.title || name + + if (json['$ref']) { + if (json['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + const schema = getPath(json['$ref'], module, schemas) + const tname = schema.title || json['$ref'].split('/').pop() + if (json['$ref'].includes('x-schemas')) { + schema = (getRefModule(json['$ref'].split('/')[2])) + } - let t = description(capitalize(name), json.description) - typeName = getTypeName(getModuleName(module), name, prefix) - t += (isHeader ? getPropertyAccessors(typeName, capitalize(name), typeof schema.const, { level: level, readonly: true, optional: false }) : getPropertyAccessorsImpl(typeName, getJsonType(schema, module, { level, name }), typeof schema.const, { level: level, readonly: true, optional: false })) - shape += '\n' + t + shape = getSchemaShapeInfo(schema, module, schemas, { name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) + } } - } - else if (json.type === 'object') { - if (!name) { - console.log(`WARNING: unnamed schema in ${module.info.title}.`) - console.dir(json) - shape = '' + //If the schema is a const, + else if (json.hasOwnProperty('const') && !isCPP) { + if (level > 0) { + + let t = description(capitalize(name), json.description) + typeName = getTypeName(getModuleName(module), name, prefix) + t += (isHeader ? getPropertyAccessors(typeName, capitalize(name), typeof schema.const, { level: level, readonly: true, optional: false }) : getPropertyAccessorsImpl(typeName, getJsonType(schema, module, { level, name }), typeof schema.const, { level: level, readonly: true, optional: false })) + shape += '\n' + t + } } - else if (json.properties && (validJsonObjectProperties(json) === true)) { - let c_shape = description(capitalize(name), json.description) - let cpp_shape = '' - let tName = getTypeName(getModuleName(module), name, prefix) - c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(json, module, { name }))) - let props = [] - let containerName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? (prefix + '_' + capitalize(name)) : capitalize(name) - Object.entries(json.properties).forEach(([pname, prop]) => { - let items - var desc = '\n' + description(capitalize(pname), prop.description) - if (prop.type === 'array') { - if (Array.isArray(prop.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(prop.items)) { - throw 'Heterogenous Arrays not supported yet' + else if (json.type === 'object') { + if (!name) { + console.log(`WARNING: unnamed schema in ${module.info.title}.`) + console.dir(json) + shape = '' + } + else if (json.properties && (validJsonObjectProperties(json) === true)) { + let c_shape = description(capitalize(name), json.description) + let cpp_shape = '' + let tName = getTypeName(getModuleName(module), name, prefix) + c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(json, module, { name }))) + let props = [] + let containerName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? (prefix + '_' + capitalize(name)) : capitalize(name) + Object.entries(json.properties).forEach(([pname, prop]) => { + let items + var desc = '\n' + description(capitalize(pname), prop.description) + if (prop.type === 'array') { + if (Array.isArray(prop.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(prop.items)) { + throw 'Heterogenous Arrays not supported yet' + } + items = prop.items[0] + } + else { + // grab the type for the non-array schema + items = prop.items + } + + let info = getSchemaTypeInfo(module, items, items.name || pname, schemas, prefix, {level : level, descriptions: descriptions, title: true}) + if (info.type && info.type.length > 0) { + let objName = tName + '_' + capitalize(prop.title || pname) + let moduleName = info.namespace + info.json.namespace = info.namespace + let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) + let prefixName = ((prefix.length > 0) && items['$ref']) ? '' : prefix + let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, schemas, prefix) + + let t = description(capitalize(info.name), json.description) + '\n' + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) + c_shape += '\n' + t + props.push({name: `${pname}`, type: `WPEFramework::Core::JSON::ArrayType<${subModuleProperty.type}>`}) + } + else { + console.log(`a. WARNING: Type undetermined for ${name}:${pname}`) + } + } else { + if (((merged === false) || ((merged === true) && (pname.includes(name)))) && (prop.type === 'object' || prop.anyOf || prop.allOf)) { + shape += getSchemaShapeInfo(prop, module, schemas, { name : pname, prefix, merged: false, level: 1, title, summary, descriptions, destination, section, enums }) + } + let info = getSchemaTypeInfo(module, prop, pname, module['x-schemas'], prefix, {descriptions: descriptions, level: level + 1, title: true}) + if (info.type && info.type.length > 0) { + let subPropertyName = ((pname.length !== 0) ? capitalize(pname) : info.name) + let moduleProperty = getJsonTypeInfo(module, json, name, schemas, prefix) + let subProperty = getJsonTypeInfo(module, prop, pname, schemas, prefix) + c_shape += '\n' + description(capitalize(pname), info.json.description) + c_shape += '\n' + (isHeader ? getPropertyAccessors(tName, capitalize(pname), info.type, { level: 0, readonly: false, optional: isOptional(pname, json) }) : getPropertyAccessorsImpl(tName, moduleProperty.type, subProperty.type, subPropertyName, info.type, info.json, {readonly:false, optional:isOptional(pname, json)})) + let property = getJsonType(prop, module, { name : pname, prefix }) + props.push({name: `${pname}`, type: `${property}`}) + } + else { + console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) } - items = prop.items[0] - } - else { - // grab the type for the non-array schema - items = prop.items - } - let info = getSchemaTypeInfo(module, items, items.name || pname, schemas, prefix, {level : level, descriptions: descriptions, title: true}) - if (info.type && info.type.length > 0) { - let objName = tName + '_' + capitalize(prop.title || pname) - let moduleName = info.namespace - info.json.namespace = info.namespace - let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) - let prefixName = ((prefix.length > 0) && items['$ref']) ? '' : prefix - let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, schemas, prefix) - - let t = description(capitalize(info.name), json.description) + '\n' - t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) - c_shape += '\n' + t - props.push({name: `${pname}`, type: `WPEFramework::Core::JSON::ArrayType<${subModuleProperty.type}>`}) - } - else { - console.log(`a. WARNING: Type undetermined for ${name}:${pname}`) - } - } else { - if (((merged === false) || ((merged === true) && (pname.includes(name)))) && (prop.type === 'object' || prop.anyOf || prop.allOf)) { - shape += getSchemaShapeInfo(prop, module, schemas, { name : pname, prefix, merged: false, level: 1, title, summary, descriptions, destination, section, enums }) - } - let info = getSchemaTypeInfo(module, prop, pname, module['x-schemas'], prefix, {descriptions: descriptions, level: level + 1, title: true}) - if (info.type && info.type.length > 0) { - let subPropertyName = ((pname.length !== 0) ? capitalize(pname) : info.name) - let moduleProperty = getJsonTypeInfo(module, json, name, schemas, prefix) - let subProperty = getJsonTypeInfo(module, prop, pname, schemas, prefix) - c_shape += '\n' + description(capitalize(pname), info.json.description) - c_shape += '\n' + (isHeader ? getPropertyAccessors(tName, capitalize(pname), info.type, { level: 0, readonly: false, optional: isOptional(pname, json) }) : getPropertyAccessorsImpl(tName, moduleProperty.type, subProperty.type, subPropertyName, info.type, info.json, {readonly:false, optional:isOptional(pname, json)})) - let property = getJsonType(prop, module, { name : pname, prefix }) - props.push({name: `${pname}`, type: `${property}`}) - } - else { - console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) } - } - }) + }) - cpp_shape += getJsonContainerDefinition(json, containerName, props) + cpp_shape += getJsonContainerDefinition(json, containerName, props) - if (isCPP) { - shape += '\n' + cpp_shape - } - else { - shape += '\n' + c_shape + if (isCPP) { + shape += '\n' + cpp_shape + } + else { + shape += '\n' + c_shape + } } - } - else if (json.propertyNames && json.propertyNames.enum) { - //propertyNames in object not handled yet - } - else if (json.additionalProperties && (typeof json.additionalProperties === 'object') && (validJsonObjectProperties(json) === true) && !isCPP) { - let info = getSchemaTypeInfo(module, json.additionalProperties, name, module['x-schemas'], prefix) - if (!info.type || (info.type.length === 0)) { - info.type = 'char*' - info.json = json.additionalProperties - info.json.type = 'string' + else if (json.propertyNames && json.propertyNames.enum) { + //propertyNames in object not handled yet } + else if (json.additionalProperties && (typeof json.additionalProperties === 'object') && (validJsonObjectProperties(json) === true) && !isCPP) { + let info = getSchemaTypeInfo(module, json.additionalProperties, name, module['x-schemas'], prefix) + if (!info.type || (info.type.length === 0)) { + info.type = 'char*' + info.json = json.additionalProperties + info.json.type = 'string' + } - let tName = getTypeName(getModuleName(module), name, prefix) - let t = description(capitalize(name), json.description) + '\n' - let containerType = 'WPEFramework::Core::JSON::VariantContainer' + let tName = getTypeName(getModuleName(module), name, prefix) + let t = description(capitalize(name), json.description) + '\n' + let containerType = 'WPEFramework::Core::JSON::VariantContainer' - let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, module['x-schemas']) - if (isCPP && ((info.json.type === 'object' && info.json.properties) || info.json.type === 'array')) { - // Handle Container generation here - } + let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, module['x-schemas']) + if (isCPP && ((info.json.type === 'object' && info.json.properties) || info.json.type === 'array')) { + // Handle Container generation here + } - t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, containerType)) - t += (isHeader ? getMapAccessors(tName, info.type, { descriptions: descriptions, level: level }) : getMapAccessorsImpl(tName, containerType, subModuleProperty.type, info.type, info.json, { readonly: true, optional: false })) - shape += '\n' + t + t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, containerType)) + t += (isHeader ? getMapAccessors(tName, info.type, { descriptions: descriptions, level: level }) : getMapAccessorsImpl(tName, containerType, subModuleProperty.type, info.type, info.json, { readonly: true, optional: false })) + shape += '\n' + t + } + else if (json.patternProperties) { + console.log(`WARNING: patternProperties are not supported by Firebolt(inside getModuleName(module):${name})`) + } } - else if (json.patternProperties) { - console.log(`WARNING: patternProperties are not supported by Firebolt(inside getModuleName(module):${name})`) + else if (json.anyOf) { + if (level > 0) { + let mergedSchema = getMergedSchema(module, json, name, schemas) + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + shape += getSchemaShapeInfo(mergedSchema, module, schemas, { name, prefix: prefixName, merged, level, title, summary, descriptions, destination, section, enums }) + } } - } - else if (json.anyOf) { - if (level > 0) { - let mergedSchema = getMergedSchema(module, json, name, schemas) - let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) - shape += getSchemaShapeInfo(mergedSchema, module, schemas, { name, prefix: prefixName, merged, level, title, summary, descriptions, destination, section, enums }) + else if (json.oneOf) { + //Just ignore schema shape, since this has to be treated as string } - } - else if (json.oneOf) { - //Just ignore schema shape, since this has to be treated as string - } - else if (json.allOf) { - let title = (json.title ? json.title : name) - let union = deepMergeAll(module, title, json, schemas) - union.title = title + else if (json.allOf) { + let title = (json.title ? json.title : name) + let union = deepMergeAll(module, title, json, schemas) + union.title = title - delete union['$ref'] + delete union['$ref'] - return getSchemaShapeInfo(union, module, schemas, { name, prefix, merged: true, level, title, summary, descriptions, destination, section, enums }) - } - else if (json.type === 'array' && !isCPP) { - let j - if (Array.isArray(json.items)) { - //TODO - const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 - if (!IsHomogenous(json.items)) { - throw 'Heterogenous Arrays not supported yet' + return getSchemaShapeInfo(union, module, schemas, { name, prefix, merged: true, level, title, summary, descriptions, destination, section, enums }) + } + else if (json.type === 'array') { + let j + if (Array.isArray(json.items)) { + //TODO + const IsHomogenous = arr => new Set(arr.map( item => item.type ? item.type : typeof item)).size === 1 + if (!IsHomogenous(json.items)) { + throw 'Heterogenous Arrays not supported yet' + } + j = json.items[0] + } + else { + j = json.items + } + shape += getSchemaShapeInfo(j, module, schemas, { name: j.title || name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) + + if (!isCPP) { + let info = getSchemaTypeInfo(module, j, j.title || name, schemas, prefix, {level : level, descriptions: descriptions, title: true}) + + if (info.type && info.type.length > 0) { + let type = getArrayElementSchema(json, module, schemas, info.name) + let arrayName = capitalize(name) + capitalize(type.type) + let objName = getTypeName(info.namespace, arrayName, prefix) + let tName = objName + 'Array' + let moduleName = info.namespace + info.json.namespace = info.namespace + let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) + let subModuleProperty = getJsonTypeInfo(module, j, j.title, schemas, prefix) + let t = '' + if (level === 0) { + t += description(capitalize(info.name), json.description) + '\n' + t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, moduleProperty.type)) + } + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, '', info.type, info.json)) + shape += '\n' + t + } } - j = json.items[0] } else { - j = json.items + shape += '\n' + getSchemaType(module, json, name, schemas, prefix, {level: level, descriptions: descriptions}) } - - let info = getSchemaTypeInfo(module, j, j.name || name, schemas, prefix, {level : level, descriptions: descriptions, title: true}) - - if (info.type && info.type.length > 0) { - let type = getArrayElementSchema(json, module, schemas, info.name) - let arrayName = capitalize(info.name) + capitalize(type.type) - let objName = getTypeName(info.namespace, arrayName, prefix) - let tName = objName + 'Array' - let moduleName = info.namespace - info.json.namespace = info.namespace - let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) - let t = '' - if (level === 0) { - t += description(capitalize(info.name), json.description) + '\n' - t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, moduleProperty.type)) - } - t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + 'Handle'), getJsonNativeType(type), '', info.type, info.json)) - shape += '\n' + t - } - } - else { - shape += '\n' + getSchemaType(module, json, name, schemas, prefix, {level: level, descriptions: descriptions}) } return shape diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index 3437c98c..b2a260b5 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -51,5 +51,6 @@ function getJsonContainerDefinition (schema, name, props) { } export { - getJsonContainerDefinition + getJsonContainerDefinition, + getJsonDataStructName } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index eac20c16..489b3f52 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -211,20 +211,6 @@ const generateEnum = (schema, prefix)=> { } } -const getIncludeDefinitions = (json = {}, jsonData = false) => { - return getExternalSchemaPaths(json) - .map(ref => { - const mod = ref.split('#')[0].split('/').pop() - let i = `#include "Common/${capitalize(mod)}.h"` - if(jsonData === true) { - i += '\n' + `#include "JsonData_${capitalize(mod)}.h"` - } - return i - }) - .filter((item, index, arr) => arr.indexOf(item) === index) - .concat([`#include "Firebolt/Types.h"`]) -} - function getPropertyGetterSignature(method, module, paramType) { let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` @@ -251,7 +237,6 @@ export { getIncludeGuardClose, getNativeType, getModuleName, - getIncludeDefinitions, getPropertyGetterSignature, getPropertySetterSignature, getPropertyEventCallbackSignature, diff --git a/languages/c/templates/imports/default.cpp b/languages/c/templates/imports/default.cpp new file mode 100644 index 00000000..69e241f9 --- /dev/null +++ b/languages/c/templates/imports/default.cpp @@ -0,0 +1 @@ +#include "JsonData_${info.title}.h" diff --git a/languages/c/templates/imports/default.c b/languages/c/templates/imports/default.h similarity index 100% rename from languages/c/templates/imports/default.c rename to languages/c/templates/imports/default.h diff --git a/languages/c/templates/imports/default.jsondata b/languages/c/templates/imports/default.jsondata new file mode 100644 index 00000000..69e241f9 --- /dev/null +++ b/languages/c/templates/imports/default.jsondata @@ -0,0 +1 @@ +#include "JsonData_${info.title}.h" diff --git a/languages/c/templates/modules/include/Common/Module.h b/languages/c/templates/modules/include/Common/Module.h deleted file mode 100644 index 809418a2..00000000 --- a/languages/c/templates/modules/include/Common/Module.h +++ /dev/null @@ -1,40 +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 - */ - -#ifndef _COMMON_${info.TITLE}_H -#define _COMMON_${info.TITLE}_H - -#include "Firebolt.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// Enums - -/* ${ENUMS} */ - -// Schemas - -/* ${SCHEMAS} */ - -#ifdef __cplusplus -} -#endif - -#endif // Header Include Guard diff --git a/languages/c/templates/modules/src/JsonData_Module.h b/languages/c/templates/modules/src/JsonData_Module.h deleted file mode 100644 index 2c7ca8c8..00000000 --- a/languages/c/templates/modules/src/JsonData_Module.h +++ /dev/null @@ -1,29 +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 - */ - -#pragma once - -#include "Firebolt.h" - -namespace FireboltSDK { - namespace ${info.title} { - - /* ${SCHEMAS}} */ - - } -} diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index 47a356d6..d34c1da5 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -16,11 +16,9 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "Firebolt.h" -#include "${info.title}.h" -#include "JsonData_${info.title}.h" - +#include "FireboltSDK.h" /* ${IMPORTS} */ +#include "${info.title}.h" namespace FireboltSDK { namespace ${info.title} { diff --git a/languages/c/templates/schemas/include/Common/Module.h b/languages/c/templates/schemas/include/Common/Module.h index 0326c220..ff037fba 100644 --- a/languages/c/templates/schemas/include/Common/Module.h +++ b/languages/c/templates/schemas/include/Common/Module.h @@ -20,6 +20,7 @@ #define _COMMON_${info.TITLE}_H #include "Firebolt.h" +/* ${IMPORTS} */ #ifdef __cplusplus extern "C" { diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/JsonData_Module.h index 7fa2b6f4..d0ecbbac 100644 --- a/languages/c/templates/schemas/src/JsonData_Module.h +++ b/languages/c/templates/schemas/src/JsonData_Module.h @@ -16,6 +16,11 @@ * SPDX-License-Identifier: Apache-2.0 */ +#pragma once + +/* ${IMPORTS} */ +#include "Common/${info.title}.h" + namespace FireboltSDK { namespace ${info.title} { // Types diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/Module_Common.cpp index 9dc2ee0a..e2389d50 100644 --- a/languages/c/templates/schemas/src/Module_Common.cpp +++ b/languages/c/templates/schemas/src/Module_Common.cpp @@ -16,9 +16,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "Firebolt.h" -#include "${info.title}.h" -#include "Common/${info.title}.h" +#include "FireboltSDK.h" +/* ${IMPORTS} */ #include "JsonData_${info.title}.h" /* ${ENUMS} */ diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 37cf09d5..03d6cf70 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -46,6 +46,7 @@ const _inspector = obj => { // getMethodSignatureParams(method, module, options = { destination: 'file.txt' }) // getSchemaType(schema, module, options = { destination: 'file.txt', title: true }) // getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) +// getJsonType(schema, module, options = { name: 'Foo', prefix: '', descriptions: false, level: 0 }) let types = { getMethodSignature: ()=>null, @@ -133,6 +134,24 @@ const getLinkForSchema = (schema, json, { name = '' } = {}) => { return '#' } +const getComponentExternalSchema = (json) => { + let refSchemas = [] + if (json.components && json.components.schemas) { + Object.entries(json.components.schemas).forEach(([name, schema]) => { + let refs = getLinkedSchemaPaths(schema).map(path => getPathOr(null, path, schema)) + refs.map(ref => { + let title = '' + if (ref.includes('x-schemas')) { + if (ref.split('/')[2] !== json.info.title) { + title = ref.split('/')[2] + } + } + title && !refSchemas.includes(title) ? refSchemas.push(title) : null + }) + }) + } + return (refSchemas) +} // Maybe methods array of objects const getMethods = compose( @@ -319,7 +338,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { // grab the options so we don't have to pass them from method to method Object.assign(state, options) - const imports = generateImports(obj, templates) + const imports = generateImports(obj, templates, { destination : (options.destination ? options.destination : '') }) const initialization = generateInitialization(obj, templates) const enums = generateEnums(obj, templates, { destination : (options.destination ? options.destination : '') }) const eventsEnum = generateEvents(obj, templates) @@ -345,7 +364,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { const schemasArray = generateSchemas(obj, templates, { baseUrl: '', section: 'schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) const accessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).filter(body => body).join('\n')) : '' - const typesArray = schemasArray.filter(x => !x.enum) + const typesArray = schemasArray.length ? schemasArray.filter(x => !x.enum) : [] const types = (typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodTypes const accessors = (accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodAccessors @@ -634,7 +653,6 @@ function generateSchemas(json, templates, options) { if (['ListenResponse', 'ProviderRequest', 'ProviderResponse', 'FederatedResponse', 'FederatedRequest'].includes(name)) { return } - let content = getTemplate('/schemas/default', templates) if (!schema.examples || schema.examples.length === 0) { @@ -697,11 +715,11 @@ function generateSchemas(json, templates, options) { if (!isDeprecatedMethod(schema)) { schema.params.forEach(param => { if (param.schema && (param.schema.type === 'object')) { - list.push([param.name, param.schema, '', { prefix : schema.name}]) + list.push([param.name, param.schema, '', { prefix : schema.name }]) } }) if (schema.result.schema && (schema.result.schema.type === 'object')) { - list.push([schema.result.name, schema.result.schema, '', { prefix : schema.name}]) + list.push([schema.result.name, schema.result.schema, '', { prefix : schema.name }]) } } } @@ -743,8 +761,8 @@ function getRelatedSchemaLinks(schema = {}, json = {}, templates = {}, options = return links } -const generateImports = (json, templates) => { - let imports = getTemplate('/imports/default', templates) +const generateImports = (json, templates, options = { destination: '' }) => { + let imports = '' if (rpcMethodsOrEmptyArray(json).length) { imports += getTemplate('/imports/rpc', templates) @@ -773,11 +791,22 @@ const generateImports = (json, templates) => { 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() + + let template = prefix ? getTemplate(`/imports/default.${prefix}`, templates) : '' + if (!template) { + template = getTemplate(suffix ? `/imports/default.${suffix}` : '/imports/default', templates) + } - if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0) { - imports += Object.keys(json['x-schemas']).map(shared => getTemplate('/imports/default', templates).replace(/\$\{info.title\}/g, shared)).join('\n') + if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0 && !json.info['x-uri-titles']) { + imports += Object.keys(json['x-schemas']).map(shared => template.replace(/\$\{info.title\}/g, shared)).join('') } + let componentExternalSchema = getComponentExternalSchema(json) + if (componentExternalSchema.length && json.info['x-uri-titles']) { + imports += componentExternalSchema.map(shared => template.replace(/\$\{info.title\}/g, shared)).join('') + } return imports } @@ -1021,9 +1050,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' - + let seeAlso = '' - if (isPolymorphicPullMethod(methodObj) && pullsForType) { seeAlso = `See also: [${pullsForType}](#${pullsForType.toLowerCase()}-1)` // this assumes the schema will be after the method... } diff --git a/src/shared/typescript.mjs b/src/shared/typescript.mjs index e53747cd..79c3e022 100644 --- a/src/shared/typescript.mjs +++ b/src/shared/typescript.mjs @@ -327,7 +327,7 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { return '' } - + function getTypeScriptType(jsonType) { if (jsonType === 'integer') { return 'number' From 99c003312f817dfa2fca42608eb41d6cc0a94a25 Mon Sep 17 00:00:00 2001 From: sramani-metro <71630728+sramani-metro@users.noreply.github.com> Date: Tue, 20 Jun 2023 20:19:13 +0530 Subject: [PATCH 076/137] C-Language: Templates based property methods (#100) * feat: Add method templates for properties * feat: Property setters using templates * fix: Macro name correction --- languages/c/Types.mjs | 98 ++++++++++++++++--- languages/c/src/types/ImplHelpers.mjs | 63 +++++++++++- languages/c/src/types/NativeHelpers.mjs | 70 ++++++++++--- languages/c/templates/codeblocks/setter.c | 9 ++ languages/c/templates/declarations/default.c | 5 - languages/c/templates/declarations/property.c | 5 + languages/c/templates/defaults/default.c | 1 - languages/c/templates/defaults/property.c | 1 - .../c/templates/methods/{clear.js => clear.c} | 0 languages/c/templates/methods/property.c | 19 +++- languages/c/templates/methods/provide.c | 3 - languages/c/templates/methods/setter.c | 0 src/macrofier/engine.mjs | 12 ++- src/shared/typescript.mjs | 6 +- 14 files changed, 243 insertions(+), 49 deletions(-) create mode 100644 languages/c/templates/codeblocks/setter.c create mode 100644 languages/c/templates/declarations/property.c rename languages/c/templates/methods/{clear.js => clear.c} (100%) create mode 100644 languages/c/templates/methods/setter.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index bbd74eec..0886d3dc 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -18,8 +18,8 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' -import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema } from './src/types/NativeHelpers.mjs' -import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getPropertyAccessorsImpl } from './src/types/ImplHelpers.mjs' +import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature } from './src/types/NativeHelpers.mjs' +import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation } from './src/types/ImplHelpers.mjs' import { getJsonContainerDefinition, getJsonDataStructName } from './src/types/JSONHelpers.mjs' const getSdkNameSpace = () => 'FireboltSDK' @@ -166,33 +166,65 @@ const deepMergeAll = (module, name, schema, schemas, options) => { return union } +const hasTag = (method, tag) => { + return method.tags && method.tags.filter(t => t.name === tag).length > 0 +} function getMethodSignature(method, module, { destination, isInterface = false }) { - const extraParam = '${method.result.type}* ${method.result.name}' - const prefix = method.tags.find(t => t.name.split(":")[0] === "property") ? "Get" : "" + let signature = '' + let paramList = [] + if(hasTag(method, 'property') || hasTag(method, 'property:readonly') || hasTag(method, 'property:immutable')) { + + method.params.map(param => { + /* + paramList = [{name='', nativeType='', jsonType='', required=boolean}] + */ + paramList['nativeType'] = getSchemaType(param.schema, module, { title: true, name: param.name }) + paramList['jsonType'] = getJsonType(param.schema, module, {name: param.name}) + paramList['name'] = param.name + paramList['required'] = param.required + + }) - return 'uint32_t ${info.title}_' + prefix + '${method.Name}(' + extraParam + ')' + let resultType = method.result && getSchemaType(method.result.schema, module, { title: true, name: method.result.name, resultSchema: true}) || '' + + signature = getPropertyGetterSignature(method, module, resultType, paramList) + ';\n\n' + + if(hasTag(method, 'property') || hasTag(method, 'property:readonly')) { + signature += getPropertyEventCallbackSignature(method, module, resultType, paramList) + ';\n\n' + signature += getPropertyEventRegisterSignature(method, module, paramList) + ';\n\n' + signature += getPropertyEventUnregisterSignature(method, module) + ';\n\n' + } + + if(hasTag(method, 'property')) { + signature += getPropertySetterSignature(method, module, resultType, paramList) + ';\n\n' + } + } + return signature } + function getMethodSignatureParams(method, module, { destination }) { - return method.params.map(param => param.name + (!param.required ? '?' : '') + ': ' + getSchemaType(param.schema, module, { name: param.name, title: true, destination })).join(', ') + return method.params.map(param => getSchemaType(param.schema, module, { name: param.name, title: true, destination }) + (!param.required ? '* ' : ' ') + param.name ).join(', ') } const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop -function getSchemaType(schema, module, { name, prefix = '', destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - let info = getSchemaTypeInfo(module, schema, name, module['x-schemas'], prefix, { title: title }) +function getSchemaType(schema, module, { name, prefix = '', destination, resultSchema = false, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { + let info = getSchemaTypeInfo(module, schema, name, module['x-schemas'], prefix, { title: title, resultSchema: resultSchema, event: event }) return info.type } -function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = {level: 0, descriptions: true, title: false}) { +function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = {level: 0, descriptions: true, title: false, resultSchema: false, event: false}) { if (json.schema) { json = json.schema } + let stringAsHandle = options.resultSchema || options.event + let structure = {} structure["type"] = '' structure["json"] = [] @@ -219,7 +251,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref } } else if (json.const) { - structure.type = getNativeType(json) + structure.type = getNativeType(json, stringAsHandle) structure.json = json return structure } @@ -240,7 +272,9 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref } else if (Array.isArray(json.type)) { let type = json.type.find(t => t !== 'null') - console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) + let sch = JSON.parse(JSON.stringify(json)) + sch.type = type + return getSchemaTypeInfo(module, sch, name, schemas, prefix, options) } else if (json.type === 'array' && json.items && (validJsonObjectProperties(json) === true)) { let res = '' @@ -300,7 +334,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref return structure } else if (json.type) { - structure.type = getNativeType(json) + structure.type = getNativeType(json, stringAsHandle) structure.json = json if (name || json.title) { structure.name = capitalize(name || json.title) @@ -534,6 +568,9 @@ const getJsonNativeType = json => { else if (jsonType === 'boolean') { type = 'WPEFramework::Core::JSON::Boolean' } + else if (jsonType === 'null') { + type = 'void' + } else { throw 'Unknown JSON Native Type !!!' } @@ -601,7 +638,9 @@ function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '' } else if (Array.isArray(json.type)) { let type = json.type.find(t => t !== 'null') - console.log(`WARNING UNHANDLED: type is an array containing ${json.type}`) + let sch = JSON.parse(JSON.stringify(json)) + sch.type = type + return getJsonTypeInfo(module, sch, name, schemas, prefix ) } else if (json.type === 'array' && json.items) { let res @@ -682,10 +721,41 @@ const enumReducer = (acc, val, i, arr) => { return acc } +function getSchemaInstantiation(schema, module, name, { instantiationType = '' } = {}) { + + if(instantiationType === 'params') { + if (schema.params.length > 0) { + let paramList = [] + schema.params.map(param => { + /* + paramList = [{name='', nativeType='', jsonType='', required=boolean}] + */ + const parameter = {} + parameter['nativeType'] = getSchemaType(param.schema, module, { title: true, name: param.name }) + parameter['jsonType'] = getJsonType(param.schema, module, {name: param.name}) + parameter['name'] = param.name + parameter['required'] = param.required + paramList.push(parameter) + + }) + return getParameterInstantiation(paramList) + } + } else if(instantiationType === 'result') { + let resultType = getSchemaType(schema, module, { title: true, name: name, resultSchema: true}) || '' + let resultJsonType = getJsonType(schema, module, {name: name}) || '' + + return getResultInstantiation(name, resultType, resultJsonType) + } + + return '' +} + + export default { getMethodSignature, getMethodSignatureParams, getSchemaShape, getSchemaType, - getJsonType + getJsonType, + getSchemaInstantiation } diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index 47852c9e..a39af0b6 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -1,3 +1,5 @@ +import { capitalize } from "./NativeHelpers.mjs" + const Indent = '\t' const getSdkNameSpace = () => 'FireboltSDK' @@ -288,9 +290,68 @@ const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPr return result } +/* +paramList = [{name='', nativeType='', jsonType='', required=boolean}] +*/ +function getParameterInstantiation(paramList, container = '') { + + let impl = ` ${container.length>0 ? container : 'JsonObject'} jsonParameters;\n` + paramList.forEach(param => { + impl += `\n` + const jsonType = param.jsonType + if (jsonType.length) { + if (param.required) { + if (param.nativeType.includes('FireboltTypes_StringHandle')) { + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = *(static_cast<${jsonType}*>(${param.name}));\n` + } + else { + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = ${param.name};\n` + } + impl += ` jsonParameters.Set(_T("${param.name}"), ${capitalize(param.name)});` + } + else { + impl += ` if (${param.name} != nullptr) {\n` + if (param.nativeType.includes('char*')) { + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = ${param.name};\n` + } else { + + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = *(${param.name});\n` + } + impl += ` jsonParameters.Set(_T("${param.name}"), ${capitalize(param.name)});\n` + impl += ` }` + } + } + }) + + return impl +} + +function getResultInstantiation (name, nativeType, container, indentLevel = 3) { + + let impl = '' + + if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + impl += `${' '.repeat(indentLevel)}${container}* strResult = new ${container}(jsonResult);` + '\n' + impl += `${' '.repeat(indentLevel)}*${name} = static_cast<${getFireboltStringType()}>(strResult);` + } else if (nativeType.includes('Handle')) { + impl += `${' '.repeat(indentLevel)}WPEFramework::Core::ProxyType<${container}>* resultPtr = new WPEFramework::Core::ProxyType<${container}>();\n` + impl += `${' '.repeat(indentLevel)}*resultPtr = WPEFramework::Core::ProxyType<${container}>::Create();\n` + impl += `${' '.repeat(indentLevel)}*(*resultPtr) = jsonResult;\n` + impl += `${' '.repeat(indentLevel)}*${name} = static_cast<${nativeType}>(resultPtr);` + } else { + impl += `${' '.repeat(indentLevel)}*${name} = jsonResult.Value();` + } + + return impl + +} + + export { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, - getPropertyAccessorsImpl + getPropertyAccessorsImpl, + getParameterInstantiation, + getResultInstantiation } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 489b3f52..65a78443 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -115,24 +115,32 @@ const getArrayElementSchema = (json, module, schemas = {}, name) => { return result } -const getNativeType = json => { - let type = '' +const getNativeType = (json, stringAsHandle = false) => { + let type let jsonType = json.const ? typeof json.const : json.type if (jsonType === 'string') { - type = 'char*' + type = 'char*' + if(stringAsHandle) { + type = getFireboltStringType() + } } else if (jsonType === 'number') { - type = 'float' + type = 'float' } else if (jsonType === 'integer') { - type = 'int32_t' + type = 'int32_t' + } else if (jsonType === 'boolean') { type = 'bool' } + else if (jsonType === 'null' ) { + type = 'void' + } return type } + const getObjectHandleManagement = varName => { let result = `typedef void* ${varName}Handle; @@ -211,24 +219,53 @@ const generateEnum = (schema, prefix)=> { } } -function getPropertyGetterSignature(method, module, paramType) { - let m = `${capitalize(getModuleName(module))}_Get${capitalize(method.name)}` - return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType}* ${method.result.name || method.name} )` +/* +paramList = [{name='', nativeType='', jsonType='', required=boolean}] +*/ + +const getContextParams = (paramList) => paramList.map(param => param.nativeType + (!param.required ? '*' : '') + ' ' + param.name).join(', ') + +function getPropertyGetterSignature(property, module, propType, paramList = []) { + + let contextParams = '' + contextParams = getContextParams(paramList) + return `uint32_t ${capitalize(getModuleName(module))}_Get${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType}* ${property.result.name || property.name})` +} + +function getPropertySetterSignature(property, module, propType, paramList = []) { + let contextParams = '' + contextParams = getContextParams(paramList) + return `uint32_t ${capitalize(getModuleName(module))}_Set${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType} ${property.result.name || property.name})` +} + +function getPropertyEventCallbackSignature(property, module, propType, paramList = []) { + + let contextParams = '' + contextParams = getContextParams(paramList) + return `/*Callback to listen to updates on ${property.Name} property*/\n` + + `typedef void (*On${capitalize(getModuleName(module))}${capitalize(property.name)}Changed)( ${contextParams}${contextParams.length > 0 ? ', ':''}const void* userData, ${propType} ${property.result.name || property.name})` } -function getPropertySetterSignature(method, module, paramType) { - let m = `${capitalize(getModuleName(module))}_Set${capitalize(method.name)}` - return `${description(method.name, method.summary)}\nuint32 ${m}( ${paramType} ${method.result.name || method.name} )` +function getPropertyEventInnerCallbackSignature(method, module, schemas) { + let signature = `static void ${capitalize(getModuleName(module)) + capitalize(method.name)}` } -function getPropertyEventCallbackSignature(method, module, paramType) { - return `typedef void (*On${capitalize(method.name)}Changed)(${paramType === 'char*' ? 'FireboltTypes_StringHandle' : paramType})` +function getPropertyEventRegisterSignature(property, module, paramList = []) { + let contextParams = '' + contextParams = getContextParams(paramList) + + return `/*Register to listen to updates on ${capitalize(property.name)} property*/\n` + + `uint32_t ${capitalize(getModuleName(module))}_Register_${capitalize(property.name)}Update( ${contextParams}${contextParams.length > 0 ? ', ':''}On${capitalize(getModuleName(module))}${capitalize(property.name)}Changed userCB, const void* userData )` + } -function getPropertyEventSignature(method, module) { - return `${description(method.name, 'Listen to updates')}\n` + `uint32_t ${capitalize(getModuleName(module))}_Listen${capitalize(method.name)}Update(On${capitalize(method.name)}Changed notification, uint16_t* listenerId)` +function getPropertyEventUnregisterSignature(property, module) { + return `/*Unregister to listen to updates on ${capitalize(property.name)} property*/\n` + + `uint32_t ${capitalize(getModuleName(module))}_Unregister_${capitalize(property.name)}Update( On${capitalize(getModuleName(module))}${capitalize(property.name)}Changed userCB )` + } + export { getHeaderText, getIncludeGuardOpen, @@ -240,7 +277,8 @@ export { getPropertyGetterSignature, getPropertySetterSignature, getPropertyEventCallbackSignature, - getPropertyEventSignature, + getPropertyEventRegisterSignature, + getPropertyEventUnregisterSignature, getMapAccessors, getArrayAccessors, capitalize, diff --git a/languages/c/templates/codeblocks/setter.c b/languages/c/templates/codeblocks/setter.c new file mode 100644 index 00000000..9f496543 --- /dev/null +++ b/languages/c/templates/codeblocks/setter.c @@ -0,0 +1,9 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.title}_${method.Name}( ${method.signature.params} ) +{ + const string method = _T("${info.title}.${method.name}"); + ${if.params} +${method.params.serialization} + ${end.if.params} + return FireboltSDK::Properties::Set(method, jsonParameters); +} diff --git a/languages/c/templates/declarations/default.c b/languages/c/templates/declarations/default.c index be0b1e14..e69de29b 100644 --- a/languages/c/templates/declarations/default.c +++ b/languages/c/templates/declarations/default.c @@ -1,5 +0,0 @@ -/* - * ${method.summary} - * ${method.params} - */ -${method.signature}; diff --git a/languages/c/templates/declarations/property.c b/languages/c/templates/declarations/property.c new file mode 100644 index 00000000..3550b45e --- /dev/null +++ b/languages/c/templates/declarations/property.c @@ -0,0 +1,5 @@ +/* + * ${method.summary} + * ${method.params} + */ +${method.signature} diff --git a/languages/c/templates/defaults/default.c b/languages/c/templates/defaults/default.c index e29085d1..e69de29b 100644 --- a/languages/c/templates/defaults/default.c +++ b/languages/c/templates/defaults/default.c @@ -1 +0,0 @@ - ${method.name}: ${method.example.value} \ No newline at end of file diff --git a/languages/c/templates/defaults/property.c b/languages/c/templates/defaults/property.c index 95ef20cf..e69de29b 100644 --- a/languages/c/templates/defaults/property.c +++ b/languages/c/templates/defaults/property.c @@ -1 +0,0 @@ - ${method.name}: function () { return MockProps.mock('${info.title}', '${method.name}', arguments, ${method.example.value}) } \ No newline at end of file diff --git a/languages/c/templates/methods/clear.js b/languages/c/templates/methods/clear.c similarity index 100% rename from languages/c/templates/methods/clear.js rename to languages/c/templates/methods/clear.c diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 1c70ba29..0b2843a8 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,12 +1,21 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_Get${method.Name}(${method.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { +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}"); - FireboltSDK::${info.title}::${method.result.type} jsonResult; + JsonObject jsonParameters; + ${if.params} +${method.params.serialization} + ${end.if.params} - uint32_t status = FireboltSDK::Properties::Get(method, jsonResult); + ${method.result.json} jsonResult; + + uint32_t status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { - WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); - *${method.result.name} = static_cast<${info.title}_${method.result.type}Handle>(resultPtr); + if (${method.result.name} != nullptr) { +${method.result.instantiation} + } } return status; } + +${method.setter} \ No newline at end of file diff --git a/languages/c/templates/methods/provide.c b/languages/c/templates/methods/provide.c index 8cb48885..e69de29b 100644 --- a/languages/c/templates/methods/provide.c +++ b/languages/c/templates/methods/provide.c @@ -1,3 +0,0 @@ -function provide(capability, provider) { - return ProvideManager.provide(capability, provider) -} diff --git a/languages/c/templates/methods/setter.c b/languages/c/templates/methods/setter.c new file mode 100644 index 00000000..e69de29b diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 03d6cf70..c00c69a5 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -47,13 +47,15 @@ const _inspector = obj => { // getSchemaType(schema, module, options = { destination: 'file.txt', title: true }) // getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) // getJsonType(schema, module, options = { name: 'Foo', prefix: '', descriptions: false, level: 0 }) +// getSchemaInstantiation(schema, module, options = {type: 'params' | 'result' | 'event' | 'callback'}) let types = { getMethodSignature: ()=>null, getMethodSignatureParams: ()=>null, getSchemaShape: ()=>null, getSchemaType: ()=>null, - getJsonType: ()=>null + getJsonType: ()=>null, + getSchemaInstantiation: ()=>null } let config = { @@ -1050,6 +1052,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, {instantiationType: 'params'}) + const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' } ) let seeAlso = '' if (isPolymorphicPullMethod(methodObj) && pullsForType) { @@ -1082,6 +1086,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\.context\}(.*?)\$\{end\.if\.context\}/gms, event.params.length ? '$1' : '') + .replace(/\$\{method\.params\.serialization\}/g, serializedParams) // Typed signature stuff .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination, section: state.section })) @@ -1108,9 +1113,11 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .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, title: true, asPath: false, destination: state.destination })) //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result.schema, json, {name: result.name, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name : result.name })) + .replace(/\$\{method\.result\.instantiation\}/g, resultInst) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) .replace(/\$\{method\.alternative.link\}/g, '#'+(method.alternative || "").toLowerCase()) @@ -1124,6 +1131,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{method\.setter\}/g, setterTemplate) // must be last!! .replace(/\$\{method\.subscriber\}/g, subscriberTemplate) // must be last!! + if (method.deprecated) { template = template.replace(/\$\{if\.deprecated\}(.*?)\$\{end\.if\.deprecated\}/gms, '$1') } diff --git a/src/shared/typescript.mjs b/src/shared/typescript.mjs index 79c3e022..5982137e 100644 --- a/src/shared/typescript.mjs +++ b/src/shared/typescript.mjs @@ -346,10 +346,14 @@ function getSchemaShape(schema = {}, module = {}, { name = '', level = 0, title, return acc } + function getSchemaInstantiation(schema, module, { instantiationType }) { + return '' + } export default { getMethodSignature, getMethodSignatureParams, getSchemaShape, getSchemaType, - getJsonType + getJsonType, + getSchemaInstantiation } \ No newline at end of file From 133f8e3ac0f9d0cebf556f434d268dd7fc1601bb Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 22 Jun 2023 08:25:31 +0530 Subject: [PATCH 077/137] Add support to keep original file permissions of template/sdk files (#99) --- languages/c/language.config.json | 5 ++- src/macrofier/index.mjs | 22 +++++++++-- src/sdk/index.mjs | 3 +- src/shared/filesystem.mjs | 63 +++++++++++++++++++++----------- 4 files changed, 66 insertions(+), 27 deletions(-) diff --git a/languages/c/language.config.json b/languages/c/language.config.json index 185b0370..97e90519 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -10,5 +10,6 @@ "/include/Common/Module.h", "/src/Module_Common.cpp", "/src/JsonData_Module.h" - ] -} \ No newline at end of file + ], + "persistPermission": true +} diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index f8acada8..b1d61ee4 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -18,7 +18,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { emptyDir, readDir, readFiles, readJson, writeFiles, writeText } from '../shared/filesystem.mjs' +import { emptyDir, readDir, readFiles, readFilesPermissions, readJson, + writeFiles, writeFilesPermissions, writeText } from '../shared/filesystem.mjs' import { getTemplate, getTemplateForModule } from '../shared/template.mjs' import { getModule, hasPublicAPIs } from '../shared/modules.mjs' import { logHeader, logSuccess } from '../shared/io.mjs' @@ -42,6 +43,7 @@ const macrofy = async ( staticContent, templatesPerModule, templatesPerSchema, + persistPermission, createModuleDirectories, copySchemasIntoModules, aggregateFile, @@ -87,6 +89,12 @@ const macrofy = async ( const sharedTemplateList = await readDir(sharedTemplates, { recursive: true }) const templates = Object.assign(await readFiles(sharedTemplateList, sharedTemplates), await readFiles(sdkTemplateList, template)) // sdkTemplates are second so they win ties + let templatesPermission = {} + if (persistPermission) { + templatesPermission = Object.assign(await readFilesPermissions(sharedTemplateList, sharedTemplates), + await readFilesPermissions(sdkTemplateList, template)) + } + const exampleTemplates = {} for (var i=0; i chmodSync(ref, mode) + const readText = ref => readFile(ref) .then(resp => resp.toString()) @@ -39,6 +41,34 @@ const readDir = async (ref, options) => { return results.sort() } +const getIndex = (refs, base) => { + let index = base ? base.length : 0 + if (base && !refs[0].startsWith(base)) { + refs = refs.map(v => path.relative(base, v)) + index = 0 + } + else if (index === 0 && refs.length !== 1) { + // find the common prefix of all the files + while ((new Set(refs.map(r => r[index]))).size === 1) { + index++ + } + // back up one dirctory from the common prefix + index = path.join(path.join(refs[0].substring(0, index)), '..').length + } + return index +} + +const readFilesPermissions = (refs, base) => Promise.all(refs.map(ref => stat(ref))) + .then(permissions => { + if (!refs || refs.length === 0) { + return Promise.resolve({}) + } + const results = refs.map(v => [v.substring(getIndex(refs, base)), null]) + for (let i=0; i Promise.all(refs.map(ref => readFile(ref))) if (!refs || refs.length === 0) { return Promise.resolve({}) } - - let index = base ? base.length : 0 - if (base && !refs[0].startsWith(base)) { - refs = refs.map(v => path.relative(base, v)) - index = 0 - } - else if (index === 0 && refs.length !== 1) { - // find the common prefix of all the files - while ((new Set(refs.map(r => r[index]))).size === 1) { - index++ - } - - // back up one dirctory from the common prefix - index = path.join(path.join(refs[0].substring(0, index)), '..').length - } - - const results = refs.map(v => [v.substring(index), null]) + const results = refs.map(v => [v.substring(getIndex(refs, base)), null]) for (let i=0; i refs[i].endsWith(suffix))) { results[i][1] = contents[i] @@ -83,6 +97,11 @@ const writeFiles = (files) => { .map( ([file, contents]) => writeText(file, contents))) } +const writeFilesPermissions = (files) => { + return Promise.all(Object.entries(files) + .map( ([file, mode]) => setPermission(file, mode))) +} + export { readText, writeText, @@ -91,5 +110,7 @@ export { readDir, readFiles, writeFiles, - emptyDir -} \ No newline at end of file + emptyDir, + readFilesPermissions, + writeFilesPermissions +} From b5528f8cd6f50a840d32a8e5dd29fc541fb24f5d Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 22 Jun 2023 08:25:52 +0530 Subject: [PATCH 078/137] Event template implementation added (#101) --- languages/c/Types.mjs | 92 ++++++------ languages/c/src/types/ImplHelpers.mjs | 132 +++++++++++++++++- languages/c/src/types/NativeHelpers.mjs | 13 +- languages/c/templates/declarations/event.c | 4 + languages/c/templates/methods/default.c | 2 +- languages/c/templates/methods/event.c | 26 ++++ languages/c/templates/methods/property.c | 13 +- languages/c/templates/modules/src/Module.cpp | 1 + .../c/templates/schemas/src/Module_Common.cpp | 1 + src/macrofier/engine.mjs | 59 +++++--- 10 files changed, 260 insertions(+), 83 deletions(-) create mode 100644 languages/c/templates/declarations/event.c create mode 100644 languages/c/templates/methods/event.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 0886d3dc..72912930 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -18,8 +18,8 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' -import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature } from './src/types/NativeHelpers.mjs' -import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation } from './src/types/ImplHelpers.mjs' +import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' +import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation, getCallbackParametersInstantiation, getCallbackResultInstantiation, getCallbackResponseInstantiation } from './src/types/ImplHelpers.mjs' import { getJsonContainerDefinition, getJsonDataStructName } from './src/types/JSONHelpers.mjs' const getSdkNameSpace = () => 'FireboltSDK' @@ -170,44 +170,50 @@ const hasTag = (method, tag) => { return method.tags && method.tags.filter(t => t.name === tag).length > 0 } -function getMethodSignature(method, module, { destination, isInterface = false }) { - - let signature = '' +function getParamList(schema, module) { let paramList = [] - if(hasTag(method, 'property') || hasTag(method, 'property:readonly') || hasTag(method, 'property:immutable')) { - - method.params.map(param => { + if (schema.params.length > 0) { + schema.params.map(p => { /* - paramList = [{name='', nativeType='', jsonType='', required=boolean}] + param = {name='', nativeType='', jsonType='', required=boolean} */ - paramList['nativeType'] = getSchemaType(param.schema, module, { title: true, name: param.name }) - paramList['jsonType'] = getJsonType(param.schema, module, {name: param.name}) - paramList['name'] = param.name - paramList['required'] = param.required - + let param = {} + param['nativeType'] = getSchemaType(p.schema, module, { title: true, name: p.name }) + param['jsonType'] = getJsonType(p.schema, module, {name: p.name}) + param['name'] = p.name + param['required'] = p.required + paramList.push(param) }) + } + return paramList +} + +function getMethodSignature(method, module, { destination, isInterface = false }) { + + let signature = '' + if (hasTag(method, 'property') || hasTag(method, 'property:readonly') || hasTag(method, 'property:immutable')) { + let paramList = getParamList(method, module) let resultType = method.result && getSchemaType(method.result.schema, module, { title: true, name: method.result.name, resultSchema: true}) || '' signature = getPropertyGetterSignature(method, module, resultType, paramList) + ';\n\n' - if(hasTag(method, 'property') || hasTag(method, 'property:readonly')) { - signature += getPropertyEventCallbackSignature(method, module, resultType, paramList) + ';\n\n' - signature += getPropertyEventRegisterSignature(method, module, paramList) + ';\n\n' - signature += getPropertyEventUnregisterSignature(method, module) + ';\n\n' - } - - if(hasTag(method, 'property')) { + if (hasTag(method, 'property')) { signature += getPropertySetterSignature(method, module, resultType, paramList) + ';\n\n' } } return signature } +function getMethodSignatureParams(method, module, { destination, callback= false } = {}) { -function getMethodSignatureParams(method, module, { destination }) { - - return method.params.map(param => getSchemaType(param.schema, module, { name: param.name, title: true, destination }) + (!param.required ? '* ' : ' ') + param.name ).join(', ') + return method.params.map(param => { + let type = getSchemaType(param.schema, module, { name: param.name, title: true, destination }) + if ((callback === true) && (type === 'char*')) { + type = getFireboltStringType() + } + return type + (!param.required ? '* ' : ' ') + param.name + }).join(', ') } const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop @@ -723,34 +729,32 @@ const enumReducer = (acc, val, i, arr) => { function getSchemaInstantiation(schema, module, name, { instantiationType = '' } = {}) { - if(instantiationType === 'params') { - if (schema.params.length > 0) { - let paramList = [] - schema.params.map(param => { - /* - paramList = [{name='', nativeType='', jsonType='', required=boolean}] - */ - const parameter = {} - parameter['nativeType'] = getSchemaType(param.schema, module, { title: true, name: param.name }) - parameter['jsonType'] = getJsonType(param.schema, module, {name: param.name}) - parameter['name'] = param.name - parameter['required'] = param.required - paramList.push(parameter) - - }) - return getParameterInstantiation(paramList) - } - } else if(instantiationType === 'result') { + if (instantiationType === 'params') { + return getParameterInstantiation(getParamList(schema, module)) + } + else if (instantiationType === 'result') { let resultType = getSchemaType(schema, module, { title: true, name: name, resultSchema: true}) || '' let resultJsonType = getJsonType(schema, module, {name: name}) || '' - return getResultInstantiation(name, resultType, resultJsonType) } + else if (instantiationType === 'callback.params') { + let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + return getCallbackParametersInstantiation(getParamList(schema, module), resultJsonType) + } + else if (instantiationType === 'callback.result') { + let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + return getCallbackResultInstantiation(resultType, resultJsonType) + } + else if (instantiationType === 'callback.response') { + let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + return getCallbackResponseInstantiation(getParamList(schema, module), resultType, resultJsonType) + } return '' } - export default { getMethodSignature, getMethodSignatureParams, diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index a39af0b6..6509375a 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -1,10 +1,9 @@ -import { capitalize } from "./NativeHelpers.mjs" +import { capitalize, getFireboltStringType } from "./NativeHelpers.mjs" const Indent = '\t' const getSdkNameSpace = () => 'FireboltSDK' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' -const getFireboltStringType = () => 'FireboltTypes_StringHandle' const getObjectHandleManagementImpl = (varName, jsonDataName) => { @@ -320,12 +319,138 @@ function getParameterInstantiation(paramList, container = '') { impl += ` jsonParameters.Set(_T("${param.name}"), ${capitalize(param.name)});\n` impl += ` }` } + impl += '\n' } }) return impl } +const isNativeType = (type) => (type === 'float' || type === 'char*' || type === 'int32_t' || type === 'bool') + +function getCallbackParametersInstantiation(paramList, container = '') { + + let impl = '' + + if (paramList.length > 0) { + paramList.forEach(param => { + if (param.required !== undefined) { + if (param.nativeType !== 'char*') { + impl += ` ${param.nativeType} ${param.name};\n` + if (param.required === false) { + impl += ` ${param.nativeType}* ${param.name}Ptr = nullptr;\n` + } + } + else { + impl += ` ${getFireboltStringType()} ${param.name};\n` + } + } + }) + impl += `\n WPEFramework::Core::ProxyType<${container}>* jsonResponse;\n` + impl += ` WPEFramework::Core::ProxyType& var = *(static_cast*>(response)); + + ASSERT(var.IsValid() == true); + if (var.IsValid() == true) { + WPEFramework::Core::JSON::VariantContainer::Iterator elements = var->Variants(); + + while (elements.Next()) { + if (strcmp(elements.Label(), "value") == 0) { + + jsonResponse = new WPEFramework::Core::ProxyType<${container}>(); + string objectStr; + elements.Current().Object().ToString(objectStr); + (*jsonResponse)->FromString(objectStr); + } else if (strcmp(elements.Label(), "context") == 0) { + + WPEFramework::Core::JSON::VariantContainer::Iterator params = elements.Current().Object().Variants(); + while (params.Next()) {\n` + let contextParams = '' + + paramList.forEach(param => { + if (param.required !== undefined) { + if (isNativeType(param.nativeType) === true) { + if (contextParams.length > 0) { + contextParams += ` else if (strcmp(elements.Label(), "${param.name}") == 0) {\n` + } + else { + contextParams += ` if (strcmp(elements.Label(), "${param.name}") == 0) {\n` + } + if (param.nativeType === 'char*') { + contextParams += ` ${getSdkNameSpace()}::JSON::String* ${param.name}Value = new ${getSdkNameSpace()}::JSON::String(); + *${param.name}Value = elements.Current().Value().c_str(); + ${param.name} = ${param.name}Value;\n` + } + else if (param.nativeType === 'bool') { + contextParams += ` ${param.name} = elements.Current().Boolean();\n` + } + else if ((param.nativeType === 'float') || (param.nativeType === 'int32_t')) { + contextParams += ` ${param.name} = elements.Current().Number();\n` + } + if ((param.nativeType !== 'char*') && (param.required === false)) { + contextParams += ` ${param.name}Ptr = &${param.name};\n` + } + contextParams += ` }\n` + } + } + }) + impl += contextParams + impl += ` } + } else { + ASSERT(false); + } + } + }\n` + } else { + + impl +=` WPEFramework::Core::ProxyType<${container}>* jsonResponse = static_cast*>(response);\n` + } + + return impl +} + +function getCallbackResultInstantiation(nativeType, container = '') { + let impl = '' + if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + impl +=` + ${container}* jsonStrResponse = new ${container}(); + *jsonStrResponse = *(*jsonResponse); + jsonResponse->Release();` + '\n' + } + return impl +} + +function getCallbackResponseInstantiation(paramList, nativeType, container = '') { + let impl = '' + + if (paramList.length > 0) { + paramList.forEach(param => { + if (param.required !== undefined) { + if (param.nativeType === 'char*') { + impl += `static_cast<${getFireboltStringType()}>(${param.name}), ` + } + else if (param.required === true) { + impl += `${param.name}, ` + } + else if (param.required === false) { + impl += `${param.name}Ptr, ` + } + } + }) + } + + if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + impl += `static_cast<${nativeType}>(jsonStrResponse)` + } + else if (nativeType.includes('Handle')) { + impl += `static_cast<${nativeType}>(jsonResponse)` + } + else { + impl += `static_cast<${nativeType}>((*jsonResponse)->Value())` + } + + return impl +} + function getResultInstantiation (name, nativeType, container, indentLevel = 3) { let impl = '' @@ -353,5 +478,8 @@ export { getObjectHandleManagementImpl, getPropertyAccessorsImpl, getParameterInstantiation, + getCallbackParametersInstantiation, + getCallbackResultInstantiation, + getCallbackResponseInstantiation, getResultInstantiation } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 65a78443..022437e8 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -120,7 +120,7 @@ const getNativeType = (json, stringAsHandle = false) => { let jsonType = json.const ? typeof json.const : json.type if (jsonType === 'string') { type = 'char*' - if(stringAsHandle) { + if (stringAsHandle) { type = getFireboltStringType() } } @@ -140,7 +140,6 @@ const getNativeType = (json, stringAsHandle = false) => { return type } - const getObjectHandleManagement = varName => { let result = `typedef void* ${varName}Handle; @@ -229,13 +228,16 @@ function getPropertyGetterSignature(property, module, propType, paramList = []) let contextParams = '' contextParams = getContextParams(paramList) - return `uint32_t ${capitalize(getModuleName(module))}_Get${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType}* ${property.result.name || property.name})` + return `uint32_t ${capitalize(getModuleName(module))}_Get${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType}* ${property.result.name || property.name} )` } function getPropertySetterSignature(property, module, propType, paramList = []) { let contextParams = '' contextParams = getContextParams(paramList) - return `uint32_t ${capitalize(getModuleName(module))}_Set${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType} ${property.result.name || property.name})` + if (propType === getFireboltStringType()) { + propType = 'char*' + } + return `uint32_t ${capitalize(getModuleName(module))}_Set${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType} ${property.result.name || property.name} )` } function getPropertyEventCallbackSignature(property, module, propType, paramList = []) { @@ -288,5 +290,6 @@ export { getPropertyAccessors, isOptional, generateEnum, - getArrayElementSchema + getArrayElementSchema, + getFireboltStringType } diff --git a/languages/c/templates/declarations/event.c b/languages/c/templates/declarations/event.c new file mode 100644 index 00000000..45e4b608 --- /dev/null +++ b/languages/c/templates/declarations/event.c @@ -0,0 +1,4 @@ +/* ${method.name} - ${method.description} */ +typedef void (*${info.Title}${method.Name}Callback)( const void* userData, ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${event.result.type} ); +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 ); +uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 49f76ce1..6a023534 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -21,4 +21,4 @@ uint32_t ${info.title}_${method.Name}(${method.params.list}${if.params}, ${end.i } return status; -} \ No newline at end of file +} diff --git a/languages/c/templates/methods/event.c b/languages/c/templates/methods/event.c new file mode 100644 index 00000000..ec868cd5 --- /dev/null +++ b/languages/c/templates/methods/event.c @@ -0,0 +1,26 @@ +/* ${method.name} - ${method.description} */ +static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) +{ +${event.callback.params.serialization} + ASSERT(jsonResponse->IsValid() == true); + if (jsonResponse->IsValid() == true) { +${event.callback.result.instantiation} + ${info.Title}${method.Name}Callback callback = reinterpret_cast<${info.Title}${method.Name}Callback>(userCB); + callback(userData, ${event.callback.response.instantiation}); + } +} +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}"); + uint32_t status = FireboltSDKErrorNone; + + if (userCB != nullptr) { + ${event.params.serialization} + status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${info.Title}${method.Name}InnerCallback, reinterpret_cast(userCB), userData); + } + return status; +} +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(userCB)); +} diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 0b2843a8..c7510da9 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -2,14 +2,10 @@ 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}"); - JsonObject jsonParameters; - ${if.params} -${method.params.serialization} - ${end.if.params} - +${if.params}${method.params.serialization}${end.if.params} ${method.result.json} jsonResult; - - uint32_t status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult); + ${if.params}uint32_t status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult);${end.if.params} + ${if.params.empty}uint32_t status = FireboltSDK::Properties::Get(method, jsonResult);${end.if.params.empty} if (status == FireboltSDKErrorNone) { if (${method.result.name} != nullptr) { ${method.result.instantiation} @@ -17,5 +13,4 @@ uint32_t ${info.title}_Get${method.Name}( ${method.signature.params}${if.params} } return status; } - -${method.setter} \ No newline at end of file +${method.setter} diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/Module.cpp index d34c1da5..65721f1e 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/Module.cpp @@ -35,6 +35,7 @@ extern "C" { /* ${ACCESSORS} */ /* ${METHODS} */ +/* ${EVENTS} */ #ifdef __cplusplus } diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/Module_Common.cpp index e2389d50..0ccdfc28 100644 --- a/languages/c/templates/schemas/src/Module_Common.cpp +++ b/languages/c/templates/schemas/src/Module_Common.cpp @@ -28,6 +28,7 @@ extern "C" { /* ${ACCESSORS} */ /* ${METHODS} */ + /* ${EVENTS} */ #ifdef __cplusplus } diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index c00c69a5..e07f5783 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -47,7 +47,7 @@ const _inspector = obj => { // getSchemaType(schema, module, options = { destination: 'file.txt', title: true }) // getSchemaShape(schema, module, options = { name: 'Foo', destination: 'file.txt' }) // getJsonType(schema, module, options = { name: 'Foo', prefix: '', descriptions: false, level: 0 }) -// getSchemaInstantiation(schema, module, options = {type: 'params' | 'result' | 'event' | 'callback'}) +// getSchemaInstantiation(schema, module, options = {type: 'params' | 'result' | 'callback.params'| 'callback.result' | 'callback.response'}) let types = { getMethodSignature: ()=>null, @@ -70,6 +70,19 @@ const state = { const capitalize = str => str[0].toUpperCase() + str.substr(1) const hasMethodsSchema = (json, options) => json.methods && json.methods.length +const indent = (str, padding) => { + let first = true + return str.split('\n').map(line => { + if (first) { + first = false + return line + } + else { + return padding + line + } + }).join('\n') +} + const setTyper = (t) => { types = t } @@ -1024,9 +1037,9 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const capabilities = getTemplate('/sections/capabilities', templates) + insertCapabilityMacros(getTemplate('/capabilities/default', templates), methodObj.tags.find(t => t.name === "capabilities"), methodObj, json) const result = JSON.parse(JSON.stringify(methodObj.result)) - const event = JSON.parse(JSON.stringify(methodObj)) + const event = isEventMethod(methodObj) ? JSON.parse(JSON.stringify(methodObj)) : '' - if (isEventMethod(methodObj)) { + if (event) { result.schema = JSON.parse(JSON.stringify(getPayloadFromEvent(methodObj))) event.result.schema = getPayloadFromEvent(event) event.params = event.params.filter(p => p.name !== 'listen') @@ -1054,6 +1067,12 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, {instantiationType: 'params'}) const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' } ) + const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'params'}), ' ') : '' + const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.params'}) : '' + const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.result'}) : '' + const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.response'}) : '' + const resultType = result.schema ? types.getSchemaType(result.schema, json, { name: result.name }) : '' + const resultJsonType = result.schema ? types.getJsonType(result.schema, json, { name: result.name }) : '' let seeAlso = '' if (isPolymorphicPullMethod(methodObj) && pullsForType) { @@ -1085,8 +1104,9 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{method\.params\.array\}/g, JSON.stringify(methodObj.params.map(p => p.name))) .replace(/\$\{method\.params\.count}/g, methodObj.params ? methodObj.params.length : 0) .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/gms, method.params.length ? '$1' : '') - .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event.params.length ? '$1' : '') - .replace(/\$\{method\.params\.serialization\}/g, serializedParams) + .replace(/\$\{if\.params.empty\}(.*?)\$\{end\.if\.params.empty\}/gms, method.params.length === 0 ? '$1' : '') + .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event && event.params.length ? '$1' : '') + .replace(/\$\{method\.params\.serialization\}/g, serializedParams) // Typed signature stuff .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination, section: state.section })) @@ -1098,8 +1118,15 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{event\.name\}/g, method.name.toLowerCase()[2] + method.name.substr(3)) .replace(/\$\{event\.params\}/g, eventParams) .replace(/\$\{event\.params\.table\.rows\}/g, eventParamsRows) - .replace(/\$\{event\.signature\.params\}/g, types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section })) + .replace(/\$\{if\.event\.params\}(.*?)\$\{end\.if\.event\.params\}/gms, event && event.params.length ? '$1' : '') + .replace(/\$\{event\.signature\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section }) : '') + .replace(/\$\{event\.signature\.callback\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section, callback: true }) : '') + .replace(/\$\{event\.params\.serialization\}/g, serializedEventParams) + .replace(/\$\{event\.callback\.params\.serialization\}/g, callbackSerializedParams) + .replace(/\$\{event\.callback\.result\.instantiation\}/g, callbackResultInst) + .replace(/\$\{event\.callback\.response\.instantiation\}/g, callbackResponseInst) .replace(/\$\{info\.title\}/g, info.title) + .replace(/\$\{info\.Title\}/g, capitalize(info.title)) .replace(/\$\{info\.TITLE\}/g, info.title.toUpperCase()) .replace(/\$\{method\.property\.immutable\}/g, hasTag(methodObj, 'property:immutable')) .replace(/\$\{method\.property\.readonly\}/g, !getSetterFor(methodObj.name, json)) @@ -1115,9 +1142,10 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .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, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, baseUrl: options.baseUrl .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') //, baseUrl: options.baseUrl + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') + .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name : result.name })) - .replace(/\$\{method\.result\.instantiation\}/g, resultInst) + .replace(/\$\{method\.result\.instantiation\}/g, resultInst) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) .replace(/\$\{method\.alternative.link\}/g, '#'+(method.alternative || "").toLowerCase()) @@ -1411,19 +1439,6 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te while (match = template.match(regex)) { let methodsBlock = '' - const indent = (str, padding) => { - let first = true - return str.split('\n').map(line => { - if (first) { - first = false - return line - } - else { - return padding + line - } - }).join('\n') - } - let i = 1 iface.forEach(method => { @@ -1492,7 +1507,7 @@ export { generateMacros, insertMacros, generateAggregateMacros, - insertAggregateMacros, + insertAggregateMacros } export default { From d08f0d2150c4aad6332b7bb34a46d11a2a0fd2f1 Mon Sep 17 00:00:00 2001 From: sramani-metro <71630728+sramani-metro@users.noreply.github.com> Date: Thu, 22 Jun 2023 12:19:00 +0530 Subject: [PATCH 079/137] Template for Polymorphic pull method (#102) * feat: Add method templates for properties * feat: Property setters using templates * fix: Macro name correction * feat: Add template for polymorphic-pull --- .../methods/polymorphic-pull-event.c | 0 .../c/templates/methods/polymorphic-pull.c | 21 +++++++++++++++++++ .../c/templates/methods/polymorphic-reducer.c | 11 ---------- 3 files changed, 21 insertions(+), 11 deletions(-) create mode 100644 languages/c/templates/methods/polymorphic-pull-event.c create mode 100644 languages/c/templates/methods/polymorphic-pull.c diff --git a/languages/c/templates/methods/polymorphic-pull-event.c b/languages/c/templates/methods/polymorphic-pull-event.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/c/templates/methods/polymorphic-pull.c b/languages/c/templates/methods/polymorphic-pull.c new file mode 100644 index 00000000..553b2946 --- /dev/null +++ b/languages/c/templates/methods/polymorphic-pull.c @@ -0,0 +1,21 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.title}_Push${method.Name}(${method.signature.params}) +{ + uint32_t status = FireboltSDKErrorUnavailable; + ${if.params} +${method.params.serialization} + ${end.if.params} + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + WPEFramework::Core::JSON::Boolean jsonResult; + status = transport->Invoke(_T("${info.title}.${method.name}"), jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; + } + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; +} diff --git a/languages/c/templates/methods/polymorphic-reducer.c b/languages/c/templates/methods/polymorphic-reducer.c index db07747f..e69de29b 100644 --- a/languages/c/templates/methods/polymorphic-reducer.c +++ b/languages/c/templates/methods/polymorphic-reducer.c @@ -1,11 +0,0 @@ - -function ${method.name}(${method.params.list}) { - const transforms = ${method.transforms} - - if (arguments.length === 1 && Array.isArray(arguments[0])) { - return Transport.send('${info.title}', '${method.name}', arguments[0], transforms) - } - else { - return Transport.send('${info.title}', '${method.name}', { ${method.params.list} }, transforms) - } -} \ No newline at end of file From 757fc46bfc0d99e1542e1c2fe0099fe01ad686ca Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 5 Jul 2023 14:54:52 -0400 Subject: [PATCH 080/137] fix: Promote and name sub-schemas in one place --- src/macrofier/engine.mjs | 549 ++++++++++++++++++++------------------- src/macrofier/index.mjs | 6 +- 2 files changed, 281 insertions(+), 274 deletions(-) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index e07f5783..98310c43 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -50,16 +50,17 @@ const _inspector = obj => { // getSchemaInstantiation(schema, module, options = {type: 'params' | 'result' | 'callback.params'| 'callback.result' | 'callback.response'}) let types = { - getMethodSignature: ()=>null, - getMethodSignatureParams: ()=>null, - getSchemaShape: ()=>null, - getSchemaType: ()=>null, - getJsonType: ()=>null, - getSchemaInstantiation: ()=>null + getMethodSignature: () => null, + getMethodSignatureParams: () => null, + getSchemaShape: () => null, + getSchemaType: () => null, + getJsonType: () => null, + getSchemaInstantiation: () => null } let config = { - copySchemasIntoModules: false + copySchemasIntoModules: false, + extractSubSchemas: false } const state = { @@ -68,7 +69,6 @@ const state = { } const capitalize = str => str[0].toUpperCase() + str.substr(1) -const hasMethodsSchema = (json, options) => json.methods && json.methods.length const indent = (str, padding) => { let first = true @@ -129,21 +129,21 @@ const getLinkForSchema = (schema, json, { name = '' } = {}) => { return `#\$\{LINK:schema:${type}\}` } else { - const [group, schema] = Object.entries(json['x-schemas']).find( ([key, value]) => json['x-schemas'][key] && json['x-schemas'][key][type]) || [null, null] - if (group && schema) { - if (copySchemasIntoModules) { - return `#\$\{LINK:schema:${type}\}` + const [group, schema] = Object.entries(json['x-schemas']).find(([key, value]) => json['x-schemas'][key] && json['x-schemas'][key][type]) || [null, null] + if (group && schema) { + if (copySchemasIntoModules) { + return `#\$\{LINK:schema:${type}\}` + } + else { + const base = dirs ? '..' : '.' + if (dirs) { + return `${base}/${group}/schemas/#${type}` } else { - const base = dirs ? '..' : '.' - if (dirs) { - return `${base}/${group}/schemas/#${type}` - } - else { - return `${base}/schemas/${group}.md#${type}` - } + return `${base}/schemas/${group}.md#${type}` } } + } } return '#' @@ -348,14 +348,74 @@ const generateAggregateMacros = (openrpc, modules, templates, library) => Object library: library }) +const addContentDescriptorSubSchema = (descriptor, prefix, obj) => { + const title = prefix.charAt(0).toUpperCase() + prefix.substring(1) + descriptor.name.charAt(0).toUpperCase() + descriptor.name.substring(1) + if (obj.components.schemas[title]) { + throw 'Generated name `' + title + '` already exists...' + } + obj.components.schemas[title] = descriptor.schema + obj.components.schemas[title].title = title + descriptor.schema = { + $ref: "#/components/schemas/" + title + } +} + +// only consider sub-objects and sub enums to be sub-schemas +const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) + +const promoteAndNameSubSchemas = (obj) => { + // make a copy so we don't polute our inputs + obj = JSON.parse(JSON.stringify(obj)) + // find anonymous method param or result schemas and name/promote them + obj.methods && obj.methods.forEach(method => { + method.params && method.params.forEach(param => { + if (isSubSchema(param.schema)) { + addContentDescriptorSubSchema(param, method.name, obj) + } + }) + if (isSubSchema(method.result.schema)) { + addContentDescriptorSubSchema(method.result, method.name, obj) + } + }) + + // find non-primative sub-schemas of components.schemas and name/promote them + if (obj.components && obj.components.schemas) { + let more = true + while (more) { + more = false + Object.entries(obj.components.schemas).forEach(([key, schema]) => { + if (schema.type === "object" && schema.properties) { + Object.entries(schema.properties).forEach(([name, propSchema]) => { + if (isSubSchema(propSchema)) { + more = true + const descriptor = { + name: name, + schema: propSchema + } + addContentDescriptorSubSchema(descriptor, key, obj) + schema.properties[name] = descriptor.schema + } + }) + } + }) + } + } + + return obj +} + const generateMacros = (obj, templates, languages, options = {}) => { + // for languages that don't support nested schemas, let's promote them to first-class schemas w/ titles + if (config.extractSubSchemas) { + obj = promoteAndNameSubSchemas(obj) + } // grab the options so we don't have to pass them from method to method Object.assign(state, options) - const imports = generateImports(obj, templates, { destination : (options.destination ? options.destination : '') }) + const imports = generateImports(obj, templates, { destination: (options.destination ? options.destination : '') }) const initialization = generateInitialization(obj, templates) - const enums = generateEnums(obj, templates, { destination : (options.destination ? options.destination : '') }) + const enums = generateEnums(obj, templates, { destination: (options.destination ? options.destination : '') }) const eventsEnum = generateEvents(obj, templates) const examples = generateExamples(obj, templates, languages) @@ -367,10 +427,6 @@ const generateMacros = (obj, templates, languages, options = {}) => { const declarations = declarationsArray.length ? getTemplate('/sections/declarations', templates).replace(/\$\{declaration\.list\}/g, declarationsArray.map(m => m.declaration).join('\n')) : '' 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 methodTypesArray = generateSchemas(obj, templates, { baseUrl: '', section: 'methods_schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) - const methodTypes = methodTypesArray.length ? getTemplate('/sections/methods_types', templates).replace(/\$\{schema.list\}/g, methodTypesArray.map(s => s.body).filter(body => body).join('\n')) : '' - const methodAccessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'methods_accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) - const methodAccessors = methodAccessorsArray.length ? getTemplate('/sections/methods_accessors', templates).replace(/\$\{schema.list\}/g, methodAccessorsArray.map(s => s.body).filter(body => body).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')) : '' @@ -380,9 +436,9 @@ const generateMacros = (obj, templates, languages, options = {}) => { const accessorsArray = generateSchemas(obj, templates, { baseUrl: '', section: 'accessors' }).filter(s => (options.copySchemasIntoModules || !s.uri)) const schemas = schemasArray.length ? getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).filter(body => body).join('\n')) : '' const typesArray = schemasArray.length ? schemasArray.filter(x => !x.enum) : [] - const types = (typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodTypes + const types = (typesArray.length ? getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, typesArray.map(s => s.body).filter(body => body).join('\n')) : '') - const accessors = (accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).filter(body => body).join('\n')) : '') + methodAccessors + const accessors = (accessorsArray.length ? getTemplate('/sections/accessors', templates).replace(/\$\{schema.list\}/g, accessorsArray.map(s => s.body).filter(body => body).join('\n')) : '') const module = getTemplate('/codeblocks/module', templates) const macros = { @@ -425,7 +481,7 @@ const insertMacros = (fContents = '', macros = {}) => { if (macros.append) { fContents += '\n' + macros.module } - + const quote = config.operators ? config.operators.stringQuotation : '"' const or = config.operators ? config.operators.or : ' | ' @@ -453,7 +509,7 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{info\.TITLE\}/g, macros.title.toUpperCase()) fContents = fContents.replace(/\$\{info\.description\}/g, macros.description) fContents = fContents.replace(/\$\{info\.version\}/g, macros.version.readable) - + if (macros.public) { fContents = fContents.replace(/\$\{if\.public\}(.*?)\$\{end\.if\.public\}/gms, '$1') } @@ -498,7 +554,7 @@ function insertTableofContents(content) { count[slug] = 0 } const link = '#' + slug + (count[slug] ? `-${count[slug]}` : '') - toc += ' ' + ' '.repeat(level-1) + `- [${title}](${link})\n` + toc += ' ' + ' '.repeat(level - 1) + `- [${title}](${link})\n` } } }).join('\n') @@ -511,7 +567,7 @@ function insertTableofContents(content) { const index = candidates.findIndex(line => line.indexOf(`- [${match[2]}](`) >= 0) let extra = '' - + // add '-1' to schemas when there's more than once match if (index > 0 && match[1] === 'schema') { extra = '-1' @@ -525,51 +581,14 @@ function insertTableofContents(content) { return content } -const isEnumType = x => x.type !== 'undefined' && x.type === 'string' && Array.isArray(x.enum) - -const getProperties = x => { - return Array.isArray(x.properties) ? x.properties[0] : x.properties -} - -const isEnumProperties = schema => compose( - getProperties, - filter(enm => enm), - map(filter(enm => enm)), - map(props => props.map(([k, v]) => ((v.type === 'object') ? isEnumProperties(v) : ((v.type === 'array') ? isEnumType(v.items[0] ? v.items[0] : v.items): isEnumType(v))))), - map(Object.entries), - filter(schema => isObject(schema)) -)(schema) - -const getEnumProperties = schema => compose( - getProperties, - filter(enm => enm), - map(filter(isEnumType)), - map(props => props.map(([k, v]) => { - let enm = v - if (isEnumType(v) == true) { - enm = Object.assign({}, v) - enm.title = k - } else if (v.type === 'object') { - enm = getEnumProperties(v) - } else if (v.type === 'array') { - enm = Object.assign({}, (v.items[0] ? v.items[0] : v.items)) - enm.title = k - } - return enm - })), - map(Object.entries), - filter(schema => isObject(schema)) -)(schema) - -const convertEnumTemplate = (sch, templateName, templates) => { +const convertEnumTemplate = (schema, templateName, templates) => { const template = getTemplate(templateName, templates).split('\n') - let schema = isEnumType(sch) ? sch : getEnumProperties(sch) for (var i = 0; i < template.length; i++) { if (template[i].indexOf('${key}') >= 0) { template[i] = schema.enum.map(value => { const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() return template[i].replace(/\$\{key\}/g, safeName) - .replace(/\$\{value\}/g, value) + .replace(/\$\{value\}/g, value) }).join('\n') if (!templateName.includes(".cpp")) { template[i] = template[i].replace(/,*$/, ''); @@ -577,14 +596,14 @@ const convertEnumTemplate = (sch, templateName, templates) => { } } return template.join('\n') - .replace(/\$\{title\}/g, capitalize(schema.title)) - .replace(/\$\{description\}/g, schema.description ? ('- ' + schema.description) : '') - .replace(/\$\{name\}/g, schema.title) - .replace(/\$\{NAME\}/g, schema.title.toUpperCase()) + .replace(/\$\{title\}/g, capitalize(schema.title)) + .replace(/\$\{description\}/g, schema.description ? ('- ' + schema.description) : '') + .replace(/\$\{name\}/g, schema.title) + .replace(/\$\{NAME\}/g, schema.title.toUpperCase()) } const enumFinder = compose( - filter(x => ((isEnumType(x) && x.title) || isEnumProperties(x))), + filter(x => isEnum(x)), map(([_, val]) => val), filter(([_key, val]) => isObject(val)) ) @@ -661,24 +680,24 @@ const isEnum = x => x.type && x.type === 'string' && Array.isArray(x.enum) && x. function generateSchemas(json, templates, options) { let results = [] - const schemas = (options.section.includes('methods') ? (hasMethodsSchema(json) ? json.methods : '') : (json.definitions || (json.components && json.components.schemas) || {})) + const schemas = JSON.parse(JSON.stringify(json.definitions || (json.components && json.components.schemas) || {})) const generate = (name, schema, uri, { prefix = '' } = {}) => { // these are internal schemas used by the firebolt-openrpc tooling, and not meant to be used in code/doc generation if (['ListenResponse', 'ProviderRequest', 'ProviderResponse', 'FederatedResponse', 'FederatedRequest'].includes(name)) { return - } + } let content = getTemplate('/schemas/default', templates) if (!schema.examples || schema.examples.length === 0) { - content = content.replace(/\$\{if\.examples\}.*?\{end\.if\.examples\}/gms, '') + content = content.replace(/\$\{if\.examples\}.*?\{end\.if\.examples\}/gms, '') } else { content = content.replace(/\$\{if\.examples\}(.*?)\{end\.if\.examples\}/gms, '$1') } if (!schema.description) { - content = content.replace(/\$\{if\.description\}.*?\{end\.if\.description\}/gms, '') + content = content.replace(/\$\{if\.description\}.*?\{end\.if\.description\}/gms, '') } else { content = content.replace(/\$\{if\.description\}(.*?)\{end\.if\.description\}/gms, '$1') @@ -686,20 +705,20 @@ function generateSchemas(json, templates, options) { const schemaShape = types.getSchemaShape(schema, json, { name, prefix, destination: state.destination, section: options.section }) content = content - .replace(/\$\{schema.title\}/, (schema.title || name)) - .replace(/\$\{schema.description\}/, schema.description || '') - .replace(/\$\{schema.shape\}/, schemaShape) + .replace(/\$\{schema.title\}/, (schema.title || name)) + .replace(/\$\{schema.description\}/, schema.description || '') + .replace(/\$\{schema.shape\}/, schemaShape) if (schema.examples) { - content = content.replace(/\$\{schema.example\}/, schema.examples.map(ex => JSON.stringify(ex, null, ' ')).join('\n\n')) + content = content.replace(/\$\{schema.example\}/, schema.examples.map(ex => JSON.stringify(ex, null, ' ')).join('\n\n')) } let seeAlso = getRelatedSchemaLinks(schema, json, templates, options) if (seeAlso) { - content = content.replace(/\$\{schema.seeAlso\}/, '\n\n' + seeAlso) + content = content.replace(/\$\{schema.seeAlso\}/, '\n\n' + seeAlso) } else { - content = content.replace(/.*\$\{schema.seeAlso\}/, '') + content = content.replace(/.*\$\{schema.seeAlso\}/, '') } content = content.trim().length ? content.trimEnd() : content.trim() @@ -722,30 +741,18 @@ function generateSchemas(json, templates, options) { const list = [] // schemas may be 1 or 2 levels deeps - Object.entries(schemas).forEach( ([name, schema]) => { + Object.entries(schemas).forEach(([name, schema]) => { if (isSchema(schema)) { list.push([name, schema]) } - else if (schema.tags) { - if (!isDeprecatedMethod(schema)) { - schema.params.forEach(param => { - if (param.schema && (param.schema.type === 'object')) { - list.push([param.name, param.schema, '', { prefix : schema.name }]) - } - }) - if (schema.result.schema && (schema.result.schema.type === 'object')) { - list.push([schema.result.name, schema.result.schema, '', { prefix : schema.name }]) - } - } - } }) list.sort((a, b) => { const aInB = isDefinitionReferencedBySchema('#/components/schemas/' + a[0], b[1]) const bInA = isDefinitionReferencedBySchema('#/components/schemas/' + b[0], a[1]) - if(isEnum(a[1]) || (aInB && !bInA)) { + if (isEnum(a[1]) || (aInB && !bInA)) { return -1 - } else if(isEnum(b[1]) || (!aInB && bInA)) { + } else if (isEnum(b[1]) || (!aInB && bInA)) { return 1 } return 0; @@ -764,14 +771,14 @@ function getRelatedSchemaLinks(schema = {}, json = {}, templates = {}, options = // - convert them to the $ref value (which are paths to other schema files), instead of the path to the ref node itself // - convert those into markdown links of the form [Schema](Schema#/link/to/element) let links = getLinkedSchemaPaths(schema) - .map(path => getPathOr(null, path, schema)) - .filter(path => seen.hasOwnProperty(path) ? false : (seen[path] = true)) - .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, 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') + .map(path => getPathOr(null, path, schema)) + .filter(path => seen.hasOwnProperty(path) ? false : (seen[path] = true)) + .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, 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') return links } @@ -884,13 +891,13 @@ function generateExamples(json = {}, mainTemplates = {}, languages = {}) { examples[method.name] = method.examples.map(example => ({ json: example, value: example.result.value, - languages: Object.fromEntries(Object.entries(languages).map( ([lang, templates]) => ([lang, { + languages: Object.fromEntries(Object.entries(languages).map(([lang, templates]) => ([lang, { langcode: templates['__config'].langcode, code: getTemplateForExample(method, templates) - .replace(/\$\{rpc\.example\.params\}/g, JSON.stringify(Object.fromEntries(example.params.map(param => [param.name, param.value])))), + .replace(/\$\{rpc\.example\.params\}/g, JSON.stringify(Object.fromEntries(example.params.map(param => [param.name, param.value])))), result: getTemplateForExampleResult(method, templates) - .replace(/\$\{example\.result\}/g, JSON.stringify(example.result.value, null, '\t')) - .replace(/\$\{example\.result\.item\}/g, Array.isArray(example.result.value) ? JSON.stringify(example.result.value[0], null, '\t') : ''), + .replace(/\$\{example\.result\}/g, JSON.stringify(example.result.value, null, '\t')) + .replace(/\$\{example\.result\.item\}/g, Array.isArray(example.result.value) ? JSON.stringify(example.result.value[0], null, '\t') : ''), template: lang === 'JSON-RPC' ? getTemplate('/examples/jsonrpc', mainTemplates) : getTemplateForExample(method, mainTemplates) // getTemplate('/examples/default', mainTemplates) }]))) })) @@ -900,7 +907,7 @@ function generateExamples(json = {}, mainTemplates = {}, languages = {}) { examples[method.name] = examples[method.name].map(example => ({ json: example.json, value: example.value, - languages: Object.fromEntries(Object.entries(example.languages).filter( ([k, v]) => k === 'JSON-RPC')) + languages: Object.fromEntries(Object.entries(example.languages).filter(([k, v]) => k === 'JSON-RPC')) })) } @@ -911,7 +918,7 @@ function generateExamples(json = {}, mainTemplates = {}, languages = {}) { example.languages['JSON-RPC'].code = JSON.stringify(JSON.parse(example.languages['JSON-RPC'].code), null, '\t') example.languages['JSON-RPC'].result = JSON.stringify(JSON.parse(example.languages['JSON-RPC'].result), null, '\t') } - catch (error) {} + catch (error) { } } }) }) @@ -976,12 +983,12 @@ function generateMethods(json = {}, examples = {}, templates = {}) { body: getTemplate('/methods/once', templates), declaration: getTemplate('/declarations/once', templates) }) - + results.push({ name: "clear", body: getTemplate('/methods/clear', templates), declaration: getTemplate('/declarations/clear', templates) - }) + }) } results.sort((a, b) => a.name.localeCompare(b.name)) @@ -990,7 +997,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, examples = {}) { const moduleName = getModuleName(json) const info = { @@ -1038,12 +1045,12 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const result = JSON.parse(JSON.stringify(methodObj.result)) const event = isEventMethod(methodObj) ? JSON.parse(JSON.stringify(methodObj)) : '' - + if (event) { result.schema = JSON.parse(JSON.stringify(getPayloadFromEvent(methodObj))) event.result.schema = getPayloadFromEvent(event) event.params = event.params.filter(p => p.name !== 'listen') - } + } const eventParams = event.params && event.params.length ? getTemplate('/sections/parameters', templates) + event.params.map(p => insertParameterMacros(getTemplate('/parameters/default', templates), p, event, json)).join('') : '' const eventParamsRows = event.params && event.params.length ? event.params.map(p => insertParameterMacros(getTemplate('/parameters/default', templates), p, event, json)).join('') : '' @@ -1061,16 +1068,16 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { const subscriberTemplate = (subscriber ? insertMethodMacros(getTemplate('/codeblocks/subscriber', templates), subscriber, json, templates, 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 + const pullsParams = (puller || pullsFor) ? localizeDependencies(getPayloadFromEvent(puller || methodObj), json, null, { mergeAllOfs: true }).properties.parameters : null const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) - const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) - const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' - const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, {instantiationType: 'params'}) - const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' } ) - const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'params'}), ' ') : '' - const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.params'}) : '' - const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.result'}) : '' - const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, {instantiationType: 'callback.response'}) : '' + const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) + const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, { instantiationType: 'params' }) + const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' }) + const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'params' }), ' ') : '' + const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.params' }) : '' + const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.result' }) : '' + const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.response' }) : '' const resultType = result.schema ? types.getSchemaType(result.schema, json, { name: result.name }) : '' const resultJsonType = result.schema ? types.getJsonType(result.schema, json, { name: result.name }) : '' @@ -1084,9 +1091,9 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { } if (isTemporalSetMethod(methodObj)) { - itemName = result.schema.items.title || 'item' - itemName = itemName.charAt(0).toLowerCase() + itemName.substring(1) - itemType = types.getSchemaType(result.schema.items, json, { destination: state.destination, section: state.section }) + itemName = result.schema.items.title || 'item' + itemName = itemName.charAt(0).toLowerCase() + itemName.substring(1) + itemType = types.getSchemaType(result.schema.items, json, { destination: state.destination, section: state.section }) } template = insertExampleMacros(template, examples[methodObj.name] || [], methodObj, json, templates) @@ -1094,7 +1101,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { template = template.replace(/\$\{method\.name\}/g, method.name) .replace(/\$\{method\.summary\}/g, methodObj.summary) .replace(/\$\{method\.description\}/g, methodObj.description - || methodObj.summary) + || methodObj.summary) // Parameter stuff .replace(/\$\{method\.params\}/g, params) .replace(/\$\{method\.params\.table\.rows\}/g, paramsRows) @@ -1108,8 +1115,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event && event.params.length ? '$1' : '') .replace(/\$\{method\.params\.serialization\}/g, serializedParams) // Typed signature stuff - .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) - .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination, section: state.section })) + .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) + .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(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) @@ -1119,7 +1126,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { .replace(/\$\{event\.params\}/g, eventParams) .replace(/\$\{event\.params\.table\.rows\}/g, eventParamsRows) .replace(/\$\{if\.event\.params\}(.*?)\$\{end\.if\.event\.params\}/gms, event && event.params.length ? '$1' : '') - .replace(/\$\{event\.signature\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section }) : '') + .replace(/\$\{event\.signature\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section }) : '') .replace(/\$\{event\.signature\.callback\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section, callback: true }) : '') .replace(/\$\{event\.params\.serialization\}/g, serializedEventParams) .replace(/\$\{event\.callback\.params\.serialization\}/g, callbackSerializedParams) @@ -1139,22 +1146,22 @@ 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, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }): '') + .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, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) - .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name : result.name })) + .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) .replace(/\$\{method\.result\.instantiation\}/g, resultInst) - .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) + .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) - .replace(/\$\{method\.alternative.link\}/g, '#'+(method.alternative || "").toLowerCase()) - .replace(/\$\{method\.pulls\.for\}/g, pullsFor ? pullsFor.name : '' ) + .replace(/\$\{method\.alternative.link\}/g, '#' + (method.alternative || "").toLowerCase()) + .replace(/\$\{method\.pulls\.for\}/g, pullsFor ? pullsFor.name : '') .replace(/\$\{method\.pulls\.type\}/g, pullsForType) .replace(/\$\{method\.pulls\.result\}/g, pullsResultType) .replace(/\$\{method\.pulls\.params.type\}/g, pullsParams ? pullsParams.title : '') .replace(/\$\{method\.pulls\.params\}/g, pullsParamsType) - .replace(/\$\{method\.setter\.for\}/g, setterFor ) + .replace(/\$\{method\.setter\.for\}/g, setterFor) .replace(/\$\{method\.puller\}/g, pullerTemplate) // must be last!! .replace(/\$\{method\.setter\}/g, setterTemplate) // must be last!! .replace(/\$\{method\.subscriber\}/g, subscriberTemplate) // must be last!! @@ -1174,7 +1181,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples={}) { template = template.replace(/\$\{method\.params\[([0-9]+)\]\.type\}/g, types.getSchemaType(methodObj.params[index].schema, json, { destination: state.destination })) template = template.replace(/\$\{method\.params\[([0-9]+)\]\.name\}/g, methodObj.params[index].name) }) - + // Note that we do this twice to ensure all recursive macros are resolved template = insertExampleMacros(template, examples[methodObj.name] || [], methodObj, json, templates) @@ -1212,38 +1219,38 @@ function insertExampleMacros(template, examples, method, json, templates) { let indent = ' '.repeat(json.info.title.length + method.name.length + 2) let params = formatParams(method.params, ', ') if (params.length + indent > 80) { - params = formatParams(method.params, ',\n', true) - params = params.split('\n') - let first = params.shift() - params = params.map(p => indent + p) - params.unshift(first) - params = params.join('\n') + params = formatParams(method.params, ',\n', true) + params = params.split('\n') + let first = params.shift() + params = params.map(p => indent + p) + params.unshift(first) + params = params.join('\n') } languageContent = languageContent - .replace(/\$\{example\.code\}/g, language.code) - .replace(/\$\{example\.name\}/g, example.json.name) - .replace(/\$\{example\.language\}/g, name) - .replace(/\$\{example\.langcode\}/g, language.langcode) - - .replace(/\$\{method\.result\.name\}/g, method.result.name) - .replace(/\$\{method\.name\}/g, method.name) - .replace(/\$\{example\.params\}/g, params) - .replace(/\$\{example\.result\}/g, language.result) - .replace(/\$\{example\.result\.item\}/g, Array.isArray(example.json.result.value) ? JSON.stringify(example.json.result.value[0], null, '\t') : '') - .replace(/\$\{module\}/g, json.info.title) + .replace(/\$\{example\.code\}/g, language.code) + .replace(/\$\{example\.name\}/g, example.json.name) + .replace(/\$\{example\.language\}/g, name) + .replace(/\$\{example\.langcode\}/g, language.langcode) + + .replace(/\$\{method\.result\.name\}/g, method.result.name) + .replace(/\$\{method\.name\}/g, method.name) + .replace(/\$\{example\.params\}/g, params) + .replace(/\$\{example\.result\}/g, language.result) + .replace(/\$\{example\.result\.item\}/g, Array.isArray(example.json.result.value) ? JSON.stringify(example.json.result.value[0], null, '\t') : '') + .replace(/\$\{module\}/g, json.info.title) const matches = [...languageContent.matchAll(/\$\{method\.params\[([0-9]+)\]\.example\.value\}/g)] matches.forEach(match => { const paramIndex = parseInt(match[1]) let indent = 0 - while (match.index-indent >= 0 && match.input[match.index-indent] !== '\n') { + while (match.index - indent >= 0 && match.input[match.index - indent] !== '\n') { indent++ } - const value = JSON.stringify(method.examples[index].params[paramIndex].value, null, '\t').split('\n').map( (line, i) => i > 0 ? ' '.repeat(indent) + line : line).join('\n') + const value = JSON.stringify(method.examples[index].params[paramIndex].value, null, '\t').split('\n').map((line, i) => i > 0 ? ' '.repeat(indent) + line : line).join('\n') languageContent = languageContent.replace(/\$\{method\.params\[([0-9]+)\]\.example\.value\}/g, value) }) - + if (originator) { const originalExample = originator.examples.length > index ? originator.examples[index] : originator.examples[0] @@ -1251,10 +1258,10 @@ function insertExampleMacros(template, examples, method, json, templates) { matches.forEach(match => { const paramIndex = parseInt(match[1]) let indent = 0 - while (match.index-indent >= 0 && match.input[match.index-indent] !== '\n') { + while (match.index - indent >= 0 && match.input[match.index - indent] !== '\n') { indent++ } - const value = JSON.stringify(originalExample.params[paramIndex].value, null, '\t').split('\n').map( (line, i) => i > 0 ? ' '.repeat(indent) + line : line).join('\n') + const value = JSON.stringify(originalExample.params[paramIndex].value, null, '\t').split('\n').map((line, i) => i > 0 ? ' '.repeat(indent) + line : line).join('\n') languageContent = languageContent.replace(/\$\{originator\.params\[([0-9]+)\]\.example\.value\}/g, value) }) } @@ -1276,12 +1283,12 @@ function insertExampleMacros(template, examples, method, json, templates) { function generateResult(result, json, templates, { name = '' } = {}) { - const type = types.getSchemaType(result, json, { name: name, destination: state.destination, section: state.section }) + const type = types.getSchemaType(result, json, { name: name, destination: state.destination, section: state.section }) if (result.type === 'object' && result.properties) { let content = getTemplate('/types/object', templates).split('\n') - for (var i=0; i= 0) { content[i] = Object.entries(result.properties).map(([title, property]) => insertSchemaMacros(content[i], title, property, json)).join('\n') } @@ -1293,17 +1300,17 @@ 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, { name: name }) // if we get a real link use it if (link !== '#') { - return `[${types.getSchemaType(result, json, { destination: state.destination, section: state.section })}](${link})` + return `[${types.getSchemaType(result, json, { destination: state.destination, section: state.section })}](${link})` } // otherwise this was a schema with no title, and we'll just copy it here else { const schema = localizeDependencies(result, json) return getTemplate('/types/default', templates) - .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { name: result.$ref.split("/").pop() })) + .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { name: result.$ref.split("/").pop() })) } } else { @@ -1313,15 +1320,15 @@ function generateResult(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, destination: state.destination, section: state.section, code: false })) - .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module, { name: title })) - .replace(/\$\{description\}/g, schema.description || '') - .replace(/\$\{name\}/g, title || '') + .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { name: title, destination: state.destination, section: state.section, code: false })) + .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module, { name: title })) + .replace(/\$\{description\}/g, schema.description || '') + .replace(/\$\{name\}/g, title || '') } function insertParameterMacros(template, param, method, module) { -//| `${method.param.name}` | ${method.param.type} | ${method.param.required} | ${method.param.summary} ${method.param.constraints} | + //| `${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, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl @@ -1329,18 +1336,18 @@ function insertParameterMacros(template, param, method, module) { let jsonType = types.getJsonType(param.schema, module, { name: param.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false }) if (constraints && type) { - constraints = '
' + constraints + constraints = '
' + constraints } return template - .replace(/\$\{method.param.name\}/g, param.name) - .replace(/\$\{method.param.Name\}/g, param.name[0].toUpperCase() + param.name.substring(1)) - .replace(/\$\{method.param.summary\}/g, param.summary || '') - .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.constraints\}/g, constraints) //getType(param)) + .replace(/\$\{method.param.name\}/g, param.name) + .replace(/\$\{method.param.Name\}/g, param.name[0].toUpperCase() + param.name.substring(1)) + .replace(/\$\{method.param.summary\}/g, param.summary || '') + .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.constraints\}/g, constraints) //getType(param)) } function insertCapabilityMacros(template, capabilities, method, module) { @@ -1350,18 +1357,18 @@ function insertCapabilityMacros(template, capabilities, method, module) { roles.forEach(role => { if (capabilities[role] && capabilities[role].length) { content.push(template.replace(/\$\{role\}/g, role.split('-').pop()) - .replace(/\$\{capability\}/g, capabilities[role].join('
'))) // Warning, hack! + .replace(/\$\{capability\}/g, capabilities[role].join('
'))) // Warning, hack! } }) if (capabilities['x-provides']) { content.push(template.replace(/\$\{role\}/g, 'provides') - .replace(/\$\{capability\}/g, capabilities['x-provides'])) -} + .replace(/\$\{capability\}/g, capabilities['x-provides'])) + } return content.join() } - + function generateProviderInterfaces(json, templates) { const interfaces = getProvidedCapabilities(json) let template = getTemplate('/sections/provider-interfaces', templates) @@ -1387,83 +1394,83 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te let interfaceShape = getTemplate('/codeblocks/interface', templates) interfaceShape = interfaceShape.replace(/\$\{name\}/g, name) - .replace(/\$\{capability\}/g, capability) - .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => `\t${types.getMethodSignature(method, moduleJson, { destination: state.destination, section: state.section, isInterface: true })}`).join('\n') + '\n') + .replace(/\$\{capability\}/g, capability) + .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => `\t${types.getMethodSignature(method, moduleJson, { destination: state.destination, section: state.section, isInterface: true })}`).join('\n') + '\n') if (iface.length === 0) { - template = template.replace(/\$\{provider\.methods\}/gms, '') + template = template.replace(/\$\{provider\.methods\}/gms, '') } else { - let regex = /\$\{provider\.methods\}/gms - let match = template.match(regex) + let regex = /\$\{provider\.methods\}/gms + let match = template.match(regex) + + let methodsBlock = '' + + // insert the standard method templates for each provider + if (match) { + iface.forEach(method => { + // add a tag to pick the correct template + method.tags.unshift({ + name: 'provider' + }) + const parametersSchema = method.params[0].schema + const parametersShape = types.getSchemaShape(parametersSchema, moduleJson, { destination: state.destination, section: state.section }) + let methodBlock = insertMethodMacros(getTemplateForMethod(method, templates), method, moduleJson, templates) + methodBlock = methodBlock.replace(/\${parameters\.shape\}/g, parametersShape) + const hasProviderParameters = parametersSchema && parametersSchema.properties && Object.keys(parametersSchema.properties).length > 0 + if (hasProviderParameters) { + const lines = methodBlock.split('\n') + for (let i = lines.length - 1; i >= 0; i--) { + if (lines[i].match(/\$\{provider\.param\.[a-zA-Z]+\}/)) { + let line = lines[i] + lines.splice(i, 1) + line = insertProviderParameterMacros(line, method.params[0].schema, moduleJson) + lines.splice(i++, 0, line) + } + } + methodBlock = lines.join('\n') + } + else { + methodBlock = methodBlock.replace(/\$\{if\.provider\.params\}.*?\$\{end\.if\.provider\.params\}/gms, '') + } + methodsBlock += methodBlock + }) + + match = template.match(regex) + template = template.replace(regex, methodsBlock) + } + regex = /\$\{provider\.interface\.start\}.*?\$\{provider\.interface\.end\}/s + + // insert the granular method details for any ${provider.method.start} loops + while (match = template.match(regex)) { let methodsBlock = '' - - // insert the standard method templates for each provider - if (match) { - iface.forEach(method => { - // add a tag to pick the correct template - method.tags.unshift({ - name: 'provider' - }) - const parametersSchema = method.params[0].schema - const parametersShape = types.getSchemaShape(parametersSchema, moduleJson, { destination: state.destination, section: state.section }) - let methodBlock = insertMethodMacros(getTemplateForMethod(method, templates), method, moduleJson, templates) - methodBlock = methodBlock.replace(/\${parameters\.shape\}/g, parametersShape) - const hasProviderParameters = parametersSchema && parametersSchema.properties && Object.keys(parametersSchema.properties).length > 0 - if (hasProviderParameters) { - const lines = methodBlock.split('\n') - for (let i = lines.length - 1; i >= 0; i--) { - if (lines[i].match(/\$\{provider\.param\.[a-zA-Z]+\}/)) { - let line = lines[i] - lines.splice(i, 1) - line = insertProviderParameterMacros(line, method.params[0].schema, moduleJson) - lines.splice(i++, 0, line) - } - } - methodBlock = lines.join('\n') - } - else { - methodBlock = methodBlock.replace(/\$\{if\.provider\.params\}.*?\$\{end\.if\.provider\.params\}/gms, '') - } - methodsBlock += methodBlock - }) - match = template.match(regex) - template = template.replace(regex, methodsBlock) - } + let i = 1 + iface.forEach(method => { - regex = /\$\{provider\.interface\.start\}.*?\$\{provider\.interface\.end\}/s - - // insert the granular method details for any ${provider.method.start} loops - while (match = template.match(regex)) { - let methodsBlock = '' - - let i = 1 - iface.forEach(method => { - - methodsBlock += match[0].replace(/\$\{provider\.interface\.name\}/g, method.name) - .replace(/\$\{provider\.interface\.Name\}/g, method.name.charAt(0).toUpperCase() + method.name.substr(1)) - - // first check for indented lines, and do the fancy indented replacement - .replace(/^([ \t]+)(.*?)\$\{provider\.interface\.example\.result\}/gm, '$1$2' + indent(JSON.stringify(method.examples[0].result.value, null, ' '), '$1')) - .replace(/^([ \t]+)(.*?)\$\{provider\.interface\.example\.parameters\}/gm, '$1$2' + indent(JSON.stringify(method.examples[0].params[0].value, null, ' '), '$1')) - // okay now just do the basic replacement (a single regex for both was not fun) - .replace(/\$\{provider\.interface\.example\.result\}/g, JSON.stringify(method.examples[0].result.value)) - .replace(/\$\{provider\.interface\.example\.parameters\}/g, JSON.stringify(method.examples[0].params[0].value)) - - .replace(/\$\{provider\.interface\.example\.correlationId\}/g, JSON.stringify(method.examples[0].params[1].value.correlationId)) - - // a set of up to three RPC "id" values for generating intersting examples with matching ids - .replace(/\$\{provider\.interface\.i\}/g, i) - .replace(/\$\{provider\.interface\.j\}/g, (i+iface.length)) - .replace(/\$\{provider\.interface\.k\}/g, (i+2*iface.length)) - - i++ - }) - methodsBlock = methodsBlock.replace(/\$\{provider\.interface\.[a-zA-Z]+\}/g, '') - template = template.replace(regex, methodsBlock) - } + methodsBlock += match[0].replace(/\$\{provider\.interface\.name\}/g, method.name) + .replace(/\$\{provider\.interface\.Name\}/g, method.name.charAt(0).toUpperCase() + method.name.substr(1)) + + // first check for indented lines, and do the fancy indented replacement + .replace(/^([ \t]+)(.*?)\$\{provider\.interface\.example\.result\}/gm, '$1$2' + indent(JSON.stringify(method.examples[0].result.value, null, ' '), '$1')) + .replace(/^([ \t]+)(.*?)\$\{provider\.interface\.example\.parameters\}/gm, '$1$2' + indent(JSON.stringify(method.examples[0].params[0].value, null, ' '), '$1')) + // okay now just do the basic replacement (a single regex for both was not fun) + .replace(/\$\{provider\.interface\.example\.result\}/g, JSON.stringify(method.examples[0].result.value)) + .replace(/\$\{provider\.interface\.example\.parameters\}/g, JSON.stringify(method.examples[0].params[0].value)) + + .replace(/\$\{provider\.interface\.example\.correlationId\}/g, JSON.stringify(method.examples[0].params[1].value.correlationId)) + + // a set of up to three RPC "id" values for generating intersting examples with matching ids + .replace(/\$\{provider\.interface\.i\}/g, i) + .replace(/\$\{provider\.interface\.j\}/g, (i + iface.length)) + .replace(/\$\{provider\.interface\.k\}/g, (i + 2 * iface.length)) + + i++ + }) + methodsBlock = methodsBlock.replace(/\$\{provider\.interface\.[a-zA-Z]+\}/g, '') + template = template.replace(regex, methodsBlock) + } } // TODO: JSON-RPC examples need to use ${provider.interface} macros, but we're replacing them globally instead of each block @@ -1479,25 +1486,25 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te function insertProviderParameterMacros(data = '', parameters, module = {}, options = {}) { if (!parameters || !parameters.properties) { - return '' + return '' } let result = '' Object.entries(parameters.properties).forEach(([name, param]) => { - let constraints = getSchemaConstraints(param, module) - let type = types.getSchemaType(param, module, { destination: state.destination, section: state.section, code: true, link: true, title: true, asPath: options.asPath, baseUrl: options.baseUrl }) + let constraints = getSchemaConstraints(param, module) + let type = types.getSchemaType(param, module, { destination: state.destination, section: state.section, code: true, link: true, title: true, asPath: options.asPath, baseUrl: options.baseUrl }) - if (constraints && type) { - constraints = '
' + constraints - } + if (constraints && type) { + constraints = '
' + constraints + } - result += data - .replace(/\$\{provider.param.name\}/, name) - .replace(/\$\{provider.param.summary\}/, param.description || '') - .replace(/\$\{provider.param.required\}/, (parameters.required && parameters.required.includes(name)) || 'false') - .replace(/\$\{provider.param.type\}/, type) - .replace(/\$\{provider.param.constraints\}/, constraints) + '\n' + result += data + .replace(/\$\{provider.param.name\}/, name) + .replace(/\$\{provider.param.summary\}/, param.description || '') + .replace(/\$\{provider.param.required\}/, (parameters.required && parameters.required.includes(name)) || 'false') + .replace(/\$\{provider.param.type\}/, type) + .replace(/\$\{provider.param.constraints\}/, constraints) + '\n' }) return result diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index b1d61ee4..58a9e7e2 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -46,6 +46,7 @@ const macrofy = async ( persistPermission, createModuleDirectories, copySchemasIntoModules, + extractSubSchemas = true, aggregateFile, operators, hidePrivate = true, @@ -63,8 +64,6 @@ const macrofy = async ( return new Promise( async (resolve, reject) => { const openrpc = await readJson(input) - - logHeader(`Generating ${headline} for version ${openrpc.info.title} ${openrpc.info.version}`) let typer @@ -81,6 +80,7 @@ const macrofy = async ( engine.setConfig({ copySchemasIntoModules, createModuleDirectories, + extractSubSchemas, operators }) @@ -277,7 +277,7 @@ const macrofy = async ( await writeFiles(outputFiles) if (persistPermission) { - await writeFilesPermissions(templatesPermission) + //await writeFilesPermissions(templatesPermission) } logSuccess(`Wrote ${Object.keys(outputFiles).length} files.`) From 1186b960f11000c401ce5b4f1fa56d9924466816 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 5 Jul 2023 15:32:58 -0400 Subject: [PATCH 081/137] fix: Add extractSubSchemas flag to C language --- languages/c/language.config.json | 1 + src/macrofier/index.mjs | 2 +- src/sdk/index.mjs | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/languages/c/language.config.json b/languages/c/language.config.json index 97e90519..77cde389 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -2,6 +2,7 @@ "name": "C", "langcode": "c", "createModuleDirectories": false, + "extractSubSchemas": true, "templatesPerModule": [ "/include/Module.h", "/src/Module.cpp" diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 58a9e7e2..0012d86a 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -46,7 +46,7 @@ const macrofy = async ( persistPermission, createModuleDirectories, copySchemasIntoModules, - extractSubSchemas = true, + extractSubSchemas, aggregateFile, operators, hidePrivate = true, diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index c5727cfc..7e85fab9 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -61,6 +61,7 @@ const run = async ({ operators: config.operators, createModuleDirectories: config.createModuleDirectories, copySchemasIntoModules: config.copySchemasIntoModules, + extractSubSchemas: config.extractSubSchemas, staticModuleNames: staticModuleNames, hideExcluded: true, aggregateFile: config.aggregateFile, From b1dbf180e6ac434249170effab35a714aac365b1 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Wed, 5 Jul 2023 15:39:25 -0400 Subject: [PATCH 082/137] fix: Uncomment writeFilePermissions --- src/macrofier/index.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 0012d86a..3db5d17a 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -277,7 +277,7 @@ const macrofy = async ( await writeFiles(outputFiles) if (persistPermission) { - //await writeFilesPermissions(templatesPermission) + await writeFilesPermissions(templatesPermission) } logSuccess(`Wrote ${Object.keys(outputFiles).length} files.`) From aa321aa4fad18002b084bd0493064df156222d30 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 10 Jul 2023 10:12:50 +0530 Subject: [PATCH 083/137] polymorphic-pull: method and event implementation added (#107) --- languages/c/Types.mjs | 26 ++++++--- .../declarations/polymorphic-pull-event.c | 4 ++ .../templates/declarations/polymorphic-pull.c | 2 + .../methods/polymorphic-pull-event.c | 54 +++++++++++++++++++ .../c/templates/methods/polymorphic-pull.c | 12 ++--- src/macrofier/engine.mjs | 16 ++++-- 6 files changed, 97 insertions(+), 17 deletions(-) create mode 100644 languages/c/templates/declarations/polymorphic-pull-event.c create mode 100644 languages/c/templates/declarations/polymorphic-pull.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 72912930..edf817c9 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -205,15 +205,21 @@ function getMethodSignature(method, module, { destination, isInterface = false } return signature } -function getMethodSignatureParams(method, module, { destination, callback= false } = {}) { - - return method.params.map(param => { +function getMethodSignatureParams(method, module, { destination, callback = false } = {}) { + let signatureParams = '' + let polymorphicPull = method.tags.find(t => t.name === 'polymorphic-pull') + method.params.map(param => { + if (polymorphicPull && (param.name === 'correlationId')) { + return + } + signatureParams += (signatureParams.length > 0) ? ', ' : '' let type = getSchemaType(param.schema, module, { name: param.name, title: true, destination }) if ((callback === true) && (type === 'char*')) { type = getFireboltStringType() } - return type + (!param.required ? '* ' : ' ') + param.name - }).join(', ') + signatureParams += type + (!param.required ? '* ' : ' ') + param.name + }) + return signatureParams } const safeName = prop => prop.match(/[.+]/) ? '"' + prop + '"' : prop @@ -738,19 +744,23 @@ function getSchemaInstantiation(schema, module, name, { instantiationType = '' } return getResultInstantiation(name, resultType, resultJsonType) } else if (instantiationType === 'callback.params') { - let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' return getCallbackParametersInstantiation(getParamList(schema, module), resultJsonType) } else if (instantiationType === 'callback.result') { let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' - let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' return getCallbackResultInstantiation(resultType, resultJsonType) } else if (instantiationType === 'callback.response') { let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' - let resultJsonType = getJsonType(schema.result.schema, module, {name: schema.result.name}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' return getCallbackResponseInstantiation(getParamList(schema, module), resultType, resultJsonType) } + else if (instantiationType === 'pull.param.name') { + let resultJsonType = getJsonType(schema, module, { name: name }) || '' + return resultJsonType && resultJsonType[0].split('_')[1] || '' + } return '' } diff --git a/languages/c/templates/declarations/polymorphic-pull-event.c b/languages/c/templates/declarations/polymorphic-pull-event.c new file mode 100644 index 00000000..26f1f1c4 --- /dev/null +++ b/languages/c/templates/declarations/polymorphic-pull-event.c @@ -0,0 +1,4 @@ +/* ${method.name} - ${method.description} */ +typedef void* (*${info.Title}${method.Name}Callback)( const void* userData, ${method.pulls.param.type} ); +uint32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callback userCB, const void* userData ); +uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); diff --git a/languages/c/templates/declarations/polymorphic-pull.c b/languages/c/templates/declarations/polymorphic-pull.c new file mode 100644 index 00000000..fbf74697 --- /dev/null +++ b/languages/c/templates/declarations/polymorphic-pull.c @@ -0,0 +1,2 @@ +/* ${method.name} - ${method.description} */ +uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ); diff --git a/languages/c/templates/methods/polymorphic-pull-event.c b/languages/c/templates/methods/polymorphic-pull-event.c index e69de29b..d2f5ef4c 100644 --- a/languages/c/templates/methods/polymorphic-pull-event.c +++ b/languages/c/templates/methods/polymorphic-pull-event.c @@ -0,0 +1,54 @@ +/* ${method.name} - ${method.description} */ +static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) +{ +${event.callback.params.serialization} + ASSERT(jsonResponse->IsValid() == true); + if (jsonResponse->IsValid() == true) { + + ${info.Title}${method.Name}Callback callback = reinterpret_cast<${info.Title}${method.Name}Callback>(userCB); + + WPEFramework::Core::ProxyType<${method.pulls.param.json.type}>* requestParam = new WPEFramework::Core::ProxyType<${method.pulls.param.json.type}>(); + *requestParam = WPEFramework::Core::ProxyType<${method.pulls.param.json.type}>::Create(); + *(*requestParam) = (*jsonResponse)->${event.pulls.param.name}Parameters; + + ${method.pulls.type} result = reinterpret_cast<${method.pulls.type}>(callback(userData, reinterpret_cast<${method.pulls.param.type}>(requestParam))); + + JsonObject jsonParameters; + WPEFramework::Core::JSON::Variant CorrelationId = (*jsonResponse)->CorrelationId.Value(); + jsonParameters.Set(_T("correlationId"), CorrelationId); + + ${method.pulls.json.type}& resultObj = *(*(reinterpret_cast*>(result))); + string resultStr; + resultObj.ToString(resultStr); + WPEFramework::Core::JSON::VariantContainer resultContainer(resultStr); + WPEFramework::Core::JSON::Variant Result = resultContainer; + jsonParameters.Set(_T("result"), Result); + + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + 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(), "${info.Title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; + } + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport"); + } + } +} +uint32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callback userCB, const void* userData ) +{ + const string eventName = _T("${info.title}.${method.name}"); + uint32_t status = FireboltSDKErrorNone; + + if (userCB != nullptr) { + ${event.params.serialization} + status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${info.Title}${method.Name}InnerCallback, reinterpret_cast(userCB), userData); + } + return status; +} +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(userCB)); +} diff --git a/languages/c/templates/methods/polymorphic-pull.c b/languages/c/templates/methods/polymorphic-pull.c index 553b2946..ec052e64 100644 --- a/languages/c/templates/methods/polymorphic-pull.c +++ b/languages/c/templates/methods/polymorphic-pull.c @@ -1,20 +1,20 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_Push${method.Name}(${method.signature.params}) +uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ) { uint32_t status = FireboltSDKErrorUnavailable; - ${if.params} + + string correlationId = ""; ${method.params.serialization} - ${end.if.params} FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); - if (transport != nullptr) { + if (transport != nullptr) { WPEFramework::Core::JSON::Boolean jsonResult; status = transport->Invoke(_T("${info.title}.${method.name}"), jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; } } else { - FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport"); } return status; diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 98310c43..8ad2eb06 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -1070,10 +1070,16 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) 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 const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, section: state.section }) - const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) - const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, section: state.section }) + + const pullsForJsonType = pullsResult ? types.getJsonType(pullsResult, json, { name: pullsResult.name }) : '' + const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const pullsForParamType = pullsParams ? types.getSchemaType(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const pullsForParamJsonType = pullsParams ? types.getJsonType(pullsParams, json, { name: pullsParams.title }) : '' + const pullsEventParamName = event ? types.getSchemaInstantiation(event.result, json, event.name, { instantiationType: 'pull.param.name' }) : '' + const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, { instantiationType: 'params' }) - const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' }) + const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' } ) const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'params' }), ' ') : '' const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.params' }) : '' const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.result' }) : '' @@ -1151,6 +1157,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) + .replace(/\$\{event\.pulls\.param\.name\}/g, pullsEventParamName) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) .replace(/\$\{method\.result\.instantiation\}/g, resultInst) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) @@ -1158,9 +1165,12 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.alternative.link\}/g, '#' + (method.alternative || "").toLowerCase()) .replace(/\$\{method\.pulls\.for\}/g, pullsFor ? pullsFor.name : '') .replace(/\$\{method\.pulls\.type\}/g, pullsForType) + .replace(/\$\{method\.pulls\.json\.type\}/g, pullsForJsonType) .replace(/\$\{method\.pulls\.result\}/g, pullsResultType) .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\.setter\.for\}/g, setterFor) .replace(/\$\{method\.puller\}/g, pullerTemplate) // must be last!! .replace(/\$\{method\.setter\}/g, setterTemplate) // must be last!! From e73a67a992f8f6005c9674e243d6b33b9b068eaf Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 10 Jul 2023 10:13:28 +0530 Subject: [PATCH 084/137] SchemaSorting: logic updated to consider all schemas (#106) --- src/macrofier/engine.mjs | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 8ad2eb06..54b0e184 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -675,6 +675,24 @@ function generateDefaults(json = {}, templates) { return reducer(json) } +function sortSchemasByReference(schemas = []) { + let indexA = 0; + while (indexA < schemas.length) { + + let swapped = false + for (let indexB = indexA + 1; indexB < schemas.length; ++indexB) { + const bInA = isDefinitionReferencedBySchema('#/components/schemas/' + schemas[indexB][0], schemas[indexA][1]) + if ((isEnum(schemas[indexB][1]) && !isEnum(schemas[indexA][1])) || (bInA === true)) { + [schemas[indexA], schemas[indexB]] = [schemas[indexB], schemas[indexA]] + swapped = true + break + } + } + indexA = swapped ? indexA : ++indexA + } + return schemas +} + const isEnum = x => x.type && x.type === 'string' && Array.isArray(x.enum) && x.title function generateSchemas(json, templates, options) { @@ -738,7 +756,7 @@ function generateSchemas(json, templates, options) { results.push(result) } - const list = [] + let list = [] // schemas may be 1 or 2 levels deeps Object.entries(schemas).forEach(([name, schema]) => { @@ -747,17 +765,7 @@ function generateSchemas(json, templates, options) { } }) - list.sort((a, b) => { - const aInB = isDefinitionReferencedBySchema('#/components/schemas/' + a[0], b[1]) - const bInA = isDefinitionReferencedBySchema('#/components/schemas/' + b[0], a[1]) - if (isEnum(a[1]) || (aInB && !bInA)) { - return -1 - } else if (isEnum(b[1]) || (!aInB && bInA)) { - return 1 - } - return 0; - }) - + list = sortSchemasByReference(list) list.forEach(item => generate(...item)) return results From 6015cafa52d1abf7b8a5de9fe1df18ecc35b0839 Mon Sep 17 00:00:00 2001 From: sramani-metro <71630728+sramani-metro@users.noreply.github.com> Date: Tue, 11 Jul 2023 13:23:11 +0530 Subject: [PATCH 085/137] fix: Fix the reentrancy of methods from callback (#105) --- languages/c/templates/sdk/src/Transport/Transport.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/languages/c/templates/sdk/src/Transport/Transport.h b/languages/c/templates/sdk/src/Transport/Transport.h index 2aff350d..d12312a5 100644 --- a/languages/c/templates/sdk/src/Transport/Transport.h +++ b/languages/c/templates/sdk/src/Transport/Transport.h @@ -668,15 +668,15 @@ namespace FireboltSDK { } result = WPEFramework::Core::ERROR_NONE; + _adminLock.Unlock(); } else { - + _adminLock.Unlock(); string eventName; if (IsEvent(inbound->Id.Value(), eventName)) { _eventHandler->Dispatch(eventName, inbound); } } - _adminLock.Unlock(); } return (result); From 2f3b237b7a01d57f64cb67a7fc18759cb849d7b2 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Tue, 11 Jul 2023 21:58:32 +0530 Subject: [PATCH 086/137] Default template implementation added (#103) Default template implementation added --- languages/c/Types.mjs | 62 ++++++++++++-------- languages/c/src/types/ImplHelpers.mjs | 26 ++++---- languages/c/src/types/NativeHelpers.mjs | 4 +- languages/c/templates/codeblocks/setter.c | 6 +- languages/c/templates/declarations/default.c | 3 + languages/c/templates/methods/default.c | 33 +++++------ languages/c/templates/methods/property.c | 2 +- src/macrofier/engine.mjs | 6 +- 8 files changed, 83 insertions(+), 59 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index edf817c9..2a8f5aa0 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -170,6 +170,9 @@ const hasTag = (method, tag) => { return method.tags && method.tags.filter(t => t.name === tag).length > 0 } +const IsResultConstNullSuccess = (schema, name) => (name === 'success' && !schema.const && !schema.type) +const IsResultBooleanSuccess = (schema, name) => (name === 'success' && schema.type === 'boolean') + function getParamList(schema, module) { let paramList = [] if (schema.params.length > 0) { @@ -229,13 +232,13 @@ function getSchemaType(schema, module, { name, prefix = '', destination, resultS return info.type } -function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = {level: 0, descriptions: true, title: false, resultSchema: false, event: false}) { +function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, prefix = '', options = { level: 0, descriptions: true, title: false, resultSchema: false, event: false}) { if (json.schema) { json = json.schema } - let stringAsHandle = options.resultSchema || options.event + let fireboltString = options.resultSchema || options.event let structure = {} structure["type"] = '' @@ -263,7 +266,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref } } else if (json.const) { - structure.type = getNativeType(json, stringAsHandle) + structure.type = getNativeType(json, fireboltString) structure.json = json return structure } @@ -320,7 +323,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref return getSchemaTypeInfo(module, union, '', schemas, '', options) } else if (json.oneOf) { - structure.type = 'char*' + structure.type = fireboltString ? getFireboltStringType() : 'char*' structure.json.type = 'string' return structure } @@ -337,7 +340,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref structure.namespace = (json.namespace ? json.namespace : getModuleName(module)) } else { - structure.type = 'char*' + structure.type = fireboltString ? getFireboltStringType() : 'char*' } if (name) { structure.name = capitalize(name) @@ -346,14 +349,14 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref return structure } else if (json.type) { - structure.type = getNativeType(json, stringAsHandle) - structure.json = json - if (name || json.title) { - structure.name = capitalize(name || json.title) + if (!IsResultBooleanSuccess(json, name) && !IsResultConstNullSuccess(json, name)) { + structure.type = getNativeType(json, fireboltString) + structure.json = json + if (name || json.title) { + structure.name = capitalize(name || json.title) + } + structure.namespace = getModuleName(module) } - structure.namespace = getModuleName(module) - - return structure } return structure } @@ -377,13 +380,12 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' if (json['$ref'][0] === '#') { //Ref points to local schema //Get Path to ref in this module and getSchemaType - const schema = getPath(json['$ref'], module, schemas) - const tname = schema.title || json['$ref'].split('/').pop() + let schema = getPath(json['$ref'], module, schemas) + const tName = schema.title || json['$ref'].split('/').pop() if (json['$ref'].includes('x-schemas')) { schema = (getRefModule(json['$ref'].split('/')[2])) } - - shape = getSchemaShapeInfo(schema, module, schemas, { name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) + shape = getSchemaShapeInfo(schema, module, schemas, { name: tName, prefix, merged, level, title, summary, descriptions, destination, section, enums }) } } //If the schema is a const, @@ -429,7 +431,6 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' let info = getSchemaTypeInfo(module, items, items.name || pname, schemas, prefix, {level : level, descriptions: descriptions, title: true}) if (info.type && info.type.length > 0) { let objName = tName + '_' + capitalize(prop.title || pname) - let moduleName = info.namespace info.json.namespace = info.namespace let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) let prefixName = ((prefix.length > 0) && items['$ref']) ? '' : prefix @@ -539,10 +540,14 @@ 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(name) + capitalize(type.type) - let objName = getTypeName(info.namespace, arrayName, prefix) + let arrayName = capitalize(info.name) + capitalize(type.type) + let namespace = info.namespace + if (type && type.type === 'object') { + namespace = getModuleName(module) + } + let objName = getTypeName(namespace, arrayName, prefix) let tName = objName + 'Array' - let moduleName = info.namespace + info.json.namespace = info.namespace let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) let subModuleProperty = getJsonTypeInfo(module, j, j.title, schemas, prefix) @@ -712,6 +717,9 @@ function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '' structure.type = getJsonNativeType(json) return structure } + else { + structure.type = 'JsonObject' + } return structure } @@ -739,9 +747,17 @@ function getSchemaInstantiation(schema, module, name, { instantiationType = '' } return getParameterInstantiation(getParamList(schema, module)) } else if (instantiationType === 'result') { - let resultType = getSchemaType(schema, module, { title: true, name: name, resultSchema: true}) || '' - let resultJsonType = getJsonType(schema, module, {name: name}) || '' - return getResultInstantiation(name, resultType, resultJsonType) + let result = '' + + if (!IsResultConstNullSuccess(schema, name)) { + let resultJsonType = getJsonType(schema, module, {name: name}) || '' + let resultType = '' + if (!IsResultBooleanSuccess(schema, name)) { + resultType = getSchemaType(schema, module, { title: true, name: name, resultSchema: true}) || '' + } + result = getResultInstantiation(name, resultType, resultJsonType) + } + return result } else if (instantiationType === 'callback.params') { let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index 6509375a..3d5403d4 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -455,16 +455,22 @@ function getResultInstantiation (name, nativeType, container, indentLevel = 3) { let impl = '' - if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { - impl += `${' '.repeat(indentLevel)}${container}* strResult = new ${container}(jsonResult);` + '\n' - impl += `${' '.repeat(indentLevel)}*${name} = static_cast<${getFireboltStringType()}>(strResult);` - } else if (nativeType.includes('Handle')) { - impl += `${' '.repeat(indentLevel)}WPEFramework::Core::ProxyType<${container}>* resultPtr = new WPEFramework::Core::ProxyType<${container}>();\n` - impl += `${' '.repeat(indentLevel)}*resultPtr = WPEFramework::Core::ProxyType<${container}>::Create();\n` - impl += `${' '.repeat(indentLevel)}*(*resultPtr) = jsonResult;\n` - impl += `${' '.repeat(indentLevel)}*${name} = static_cast<${nativeType}>(resultPtr);` - } else { - impl += `${' '.repeat(indentLevel)}*${name} = jsonResult.Value();` + if (nativeType) { + impl += `${' '.repeat(indentLevel)}if (${name} != nullptr) {` + '\n' + if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + impl += `${' '.repeat(indentLevel + 1)}${container}* strResult = new ${container}(jsonResult);` + '\n' + impl += `${' '.repeat(indentLevel + 1)}*${name} = static_cast<${getFireboltStringType()}>(strResult);` + } else if (nativeType.includes('Handle')) { + impl += `${' '.repeat(indentLevel + 1)}WPEFramework::Core::ProxyType<${container}>* resultPtr = new WPEFramework::Core::ProxyType<${container}>();\n` + impl += `${' '.repeat(indentLevel + 1)}*resultPtr = WPEFramework::Core::ProxyType<${container}>::Create();\n` + impl += `${' '.repeat(indentLevel + 1)}*(*resultPtr) = jsonResult;\n` + impl += `${' '.repeat(indentLevel + 1)}*${name} = static_cast<${nativeType}>(resultPtr);` + } else { + impl += `${' '.repeat(indentLevel + 1)}*${name} = jsonResult.Value();` + } + impl += `${' '.repeat(indentLevel)}}` + '\n' + } else if (name === 'success') { + impl += `${' '.repeat(indentLevel)}status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported;` } return impl diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 022437e8..1460e22e 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -115,12 +115,12 @@ const getArrayElementSchema = (json, module, schemas = {}, name) => { return result } -const getNativeType = (json, stringAsHandle = false) => { +const getNativeType = (json, fireboltString = false) => { let type let jsonType = json.const ? typeof json.const : json.type if (jsonType === 'string') { type = 'char*' - if (stringAsHandle) { + if (fireboltString) { type = getFireboltStringType() } } diff --git a/languages/c/templates/codeblocks/setter.c b/languages/c/templates/codeblocks/setter.c index 9f496543..342a98d6 100644 --- a/languages/c/templates/codeblocks/setter.c +++ b/languages/c/templates/codeblocks/setter.c @@ -1,9 +1,7 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_${method.Name}( ${method.signature.params} ) +uint32_t ${info.Title}_${method.Name}( ${method.signature.params} ) { const string method = _T("${info.title}.${method.name}"); - ${if.params} -${method.params.serialization} - ${end.if.params} +${if.params}${method.params.serialization}${end.if.params} return FireboltSDK::Properties::Set(method, jsonParameters); } diff --git a/languages/c/templates/declarations/default.c b/languages/c/templates/declarations/default.c index e69de29b..ac4e7f78 100644 --- a/languages/c/templates/declarations/default.c +++ b/languages/c/templates/declarations/default.c @@ -0,0 +1,3 @@ +/* ${method.name} - ${method.description} +${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation}${end.if.deprecated} */ +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} ); diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 6a023534..6fbca47e 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -1,24 +1,21 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_${method.Name}(${method.params.list}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}) { - uint32_t status = FireboltSDKErrorUnavailable; - FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); - if (transport != nullptr) { - - JsonObject jsonParameters; +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} ) { - ${if.params} -${method.params.json} - ${end.if.params} + uint32_t status = FireboltSDKErrorUnavailable; + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { - WPEFramework::Core::JSON::Boolean jsonResult; - status = transport->Invoke("${info.title}.${method.name}", jsonParameters, jsonResult); - if (status == FireboltSDKErrorNone) { - *success = jsonResult.Value(); - } + ${method.params.serialization.with.indent} + ${method.result.json.type} jsonResult; + status = transport->Invoke("${info.title}.${method.name}", jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully invoked"); +${method.result.instantiation} + } - } else { - FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); - } + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } - return status; + return status; } diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index c7510da9..9a92dce4 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,5 +1,5 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.title}_Get${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name} ) +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}"); ${if.params}${method.params.serialization}${end.if.params} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 54b0e184..c316088d 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -1125,9 +1125,12 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.params\.array\}/g, JSON.stringify(methodObj.params.map(p => p.name))) .replace(/\$\{method\.params\.count}/g, methodObj.params ? methodObj.params.length : 0) .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/gms, method.params.length ? '$1' : '') - .replace(/\$\{if\.params.empty\}(.*?)\$\{end\.if\.params.empty\}/gms, method.params.length === 0 ? '$1' : '') + .replace(/\$\{if\.result\}(.*?)\$\{end\.if\.result\}/gms, resultType ? '$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' : '') .replace(/\$\{if\.context\}(.*?)\$\{end\.if\.context\}/gms, event && event.params.length ? '$1' : '') .replace(/\$\{method\.params\.serialization\}/g, serializedParams) + .replace(/\$\{method\.params\.serialization\.with\.indent\}/g, indent(serializedParams, ' ')) // Typed signature stuff .replace(/\$\{method\.signature\}/g, types.getMethodSignature(methodObj, json, { isInterface: false, destination: state.destination, section: state.section })) .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination, section: state.section })) @@ -1167,6 +1170,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{event\.pulls\.param\.name\}/g, pullsEventParamName) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) + .replace(/\$\{method\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{method\.result\.instantiation\}/g, resultInst) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) From 8b1e5fcc6eef748f834301a41865defebb9b0719 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Wed, 12 Jul 2023 09:16:41 +0530 Subject: [PATCH 087/137] Naming + void* to struct* changes based on sky review, removed redundant code, array handling fix (#109) Naming + void* to struct* changes based on sky review, removed redundant code, array handling fix --- languages/c/Types.mjs | 34 ++- languages/c/language.config.json | 10 +- languages/c/src/types/ImplHelpers.mjs | 141 +++++++------ languages/c/src/types/JSONHelpers.mjs | 3 +- languages/c/src/types/NativeHelpers.mjs | 74 ++----- languages/c/templates/imports/default.cpp | 2 +- languages/c/templates/imports/default.h | 2 +- .../c/templates/imports/default.jsondata | 2 +- .../modules/include/{Module.h => module.h} | 6 +- .../modules/src/{Module.cpp => module.cpp} | 4 +- .../{Common/Module.h => common/module.h} | 6 +- .../{JsonData_Module.h => jsondata_module.h} | 4 +- .../{Module_Common.cpp => module_common.cpp} | 2 +- .../sdk/include/{Error.h => error.h} | 6 +- .../sdk/include/{Firebolt.h => firebolt.h} | 10 +- .../sdk/include/{Types.h => types.h} | 12 +- languages/c/templates/sdk/scripts/build.sh | 42 +++- languages/c/templates/sdk/src/CMakeLists.txt | 5 - languages/c/templates/sdk/src/FireboltSDK.h | 2 +- .../c/templates/sdk/src/Logger/Logger.cpp | 2 +- languages/c/templates/sdk/src/Logger/Logger.h | 2 +- .../c/templates/sdk/src/Transport/Transport.h | 2 +- languages/c/templates/sdk/src/Types.cpp | 10 +- .../sdk/src/{Firebolt.cpp => firebolt.cpp} | 0 languages/c/templates/sdk/test/CMakeLists.txt | 2 +- languages/c/templates/sdk/test/Main.c | 1 + languages/c/templates/sdk/test/Module.h | 1 - .../c/templates/sdk/test/OpenRPCCTests.h | 11 +- .../c/templates/sdk/test/OpenRPCTests.cpp | 199 ++++++++++++++---- languages/c/templates/sdk/test/OpenRPCTests.h | 23 +- languages/c/templates/sdk/test/TestUtils.h | 10 +- languages/c/templates/types/enum.cpp | 4 +- languages/c/templates/types/enum.h | 2 +- src/macrofier/engine.mjs | 7 +- src/macrofier/index.mjs | 4 +- 35 files changed, 392 insertions(+), 255 deletions(-) rename languages/c/templates/modules/include/{Module.h => module.h} (92%) rename languages/c/templates/modules/src/{Module.cpp => module.cpp} (93%) rename languages/c/templates/schemas/include/{Common/Module.h => common/module.h} (90%) rename languages/c/templates/schemas/src/{JsonData_Module.h => jsondata_module.h} (91%) rename languages/c/templates/schemas/src/{Module_Common.cpp => module_common.cpp} (94%) rename languages/c/templates/sdk/include/{Error.h => error.h} (93%) rename languages/c/templates/sdk/include/{Firebolt.h => firebolt.h} (93%) rename languages/c/templates/sdk/include/{Types.h => types.h} (73%) rename languages/c/templates/sdk/src/{Firebolt.cpp => firebolt.cpp} (100%) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 2a8f5aa0..1ed84940 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -20,7 +20,7 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation, getCallbackParametersInstantiation, getCallbackResultInstantiation, getCallbackResponseInstantiation } from './src/types/ImplHelpers.mjs' -import { getJsonContainerDefinition, getJsonDataStructName } from './src/types/JSONHelpers.mjs' +import { getJsonContainerDefinition, getJsonDataStructName, getJsonDataPrefix } from './src/types/JSONHelpers.mjs' const getSdkNameSpace = () => 'FireboltSDK' const getJsonNativeTypeForOpaqueString = () => getSdkNameSpace() + '::JSON::String' @@ -262,17 +262,14 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref structure.json = res.json structure.name = res.name structure.namespace = res.namespace - return structure } } else if (json.const) { structure.type = getNativeType(json, fireboltString) structure.json = json - return structure } else if (json['x-method']) { console.log(`WARNING UNHANDLED: x-method in ${name}`) - return structure //throw "x-methods not supported yet" } else if (json.type === 'string' && json.enum) { @@ -283,13 +280,12 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref structure.json = json structure.type = typeName structure.namespace = getModuleName(module) - return structure } else if (Array.isArray(json.type)) { let type = json.type.find(t => t !== 'null') let sch = JSON.parse(JSON.stringify(json)) sch.type = type - return getSchemaTypeInfo(module, sch, name, schemas, prefix, options) + structure = getSchemaTypeInfo(module, sch, name, schemas, prefix, options) } else if (json.type === 'array' && json.items && (validJsonObjectProperties(json) === true)) { let res = '' @@ -306,13 +302,11 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref res = getSchemaTypeInfo(module, json.items, json.items.name || name, schemas, prefix) } - let arrayName = capitalize(res.name) + capitalize(res.json.type) - let n = getTypeName(getModuleName(module), arrayName, prefix) + let n = getTypeName(getModuleName(module), capitalize(res.name), prefix) structure.name = res.name || name && (capitalize(name)) - structure.type = n + 'ArrayHandle' + structure.type = n + 'Array_t' structure.json = json structure.namespace = getModuleName(module) - return structure } else if (json.allOf) { let title = json.title ? json.title : name @@ -320,22 +314,21 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref union['title'] = title delete union['$ref'] - return getSchemaTypeInfo(module, union, '', schemas, '', options) + structure = getSchemaTypeInfo(module, union, '', schemas, '', options) } else if (json.oneOf) { structure.type = fireboltString ? getFireboltStringType() : 'char*' structure.json.type = 'string' - return structure } else if (json.anyOf) { let mergedSchema = getMergedSchema(module, json, name, schemas) let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) - return getSchemaTypeInfo(module, mergedSchema, '', schemas, prefixName, options) + structure = getSchemaTypeInfo(module, mergedSchema, '', schemas, prefixName, options) } else if (json.type === 'object') { structure.json = json if (hasProperties(json)) { - structure.type = getTypeName(getModuleName(module), json.title || name, prefix) + 'Handle' + structure.type = getTypeName(getModuleName(module), json.title || name, prefix) + '_t' structure.name = (json.name ? json.name : (json.title ? json.title : name)) structure.namespace = (json.namespace ? json.namespace : getModuleName(module)) } @@ -345,8 +338,6 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref if (name) { structure.name = capitalize(name) } - - return structure } else if (json.type) { if (!IsResultBooleanSuccess(json, name) && !IsResultConstNullSuccess(json, name)) { @@ -370,8 +361,9 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' let shape = '' if (destination && section) { - const isHeader = (destination.includes("JsonData_") !== true) && destination.endsWith(".h") - const isCPP = ((destination.endsWith(".cpp") || destination.includes("JsonData_")) && (section.includes('accessors') !== true)) + const isHeader = (destination.includes(getJsonDataPrefix().toLowerCase()) !== true) && destination.endsWith(".h") + const isCPP = ((destination.endsWith(".cpp") || destination.includes(getJsonDataPrefix().toLowerCase())) && (section.includes('accessors') !== true)) + json = JSON.parse(JSON.stringify(json)) name = json.title || name @@ -437,7 +429,7 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, schemas, prefix) let t = description(capitalize(info.name), json.description) + '\n' - t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(tName, moduleProperty.type, (tName + '_t'), subModuleProperty.type, capitalize(pname || prop.title), info.type, info.json)) c_shape += '\n' + t props.push({name: `${pname}`, type: `WPEFramework::Core::JSON::ArrayType<${subModuleProperty.type}>`}) } @@ -556,7 +548,7 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' t += description(capitalize(info.name), json.description) + '\n' t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, moduleProperty.type)) } - t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + 'Handle'), subModuleProperty.type, '', info.type, info.json)) + t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + '_t'), subModuleProperty.type, '', info.type, info.json)) shape += '\n' + t } } @@ -775,7 +767,7 @@ function getSchemaInstantiation(schema, module, name, { instantiationType = '' } } else if (instantiationType === 'pull.param.name') { let resultJsonType = getJsonType(schema, module, { name: name }) || '' - return resultJsonType && resultJsonType[0].split('_')[1] || '' + return resultJsonType.length && resultJsonType[0].split('_')[1] || '' } return '' diff --git a/languages/c/language.config.json b/languages/c/language.config.json index 77cde389..ee3604d7 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -4,13 +4,13 @@ "createModuleDirectories": false, "extractSubSchemas": true, "templatesPerModule": [ - "/include/Module.h", - "/src/Module.cpp" + "/include/module.h", + "/src/module.cpp" ], "templatesPerSchema": [ - "/include/Common/Module.h", - "/src/Module_Common.cpp", - "/src/JsonData_Module.h" + "/include/common/module.h", + "/src/module_common.cpp", + "/src/jsondata_module.h" ], "persistPermission": true } diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index 3d5403d4..5b373377 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -4,35 +4,36 @@ const Indent = '\t' const getSdkNameSpace = () => 'FireboltSDK' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' +const camelcase = str => str[0].toLowerCase() + str.substr(1) const getObjectHandleManagementImpl = (varName, jsonDataName) => { - let result = `${varName}Handle ${varName}Handle_Create(void) + let result = `${varName}_t ${varName}Handle_Acquire(void) { WPEFramework::Core::ProxyType<${jsonDataName}>* type = new WPEFramework::Core::ProxyType<${jsonDataName}>(); *type = WPEFramework::Core::ProxyType<${jsonDataName}>::Create(); - return (static_cast<${varName}Handle>(type)); + return (reinterpret_cast<${varName}_t>(type)); } -void ${varName}Handle_Addref(${varName}Handle handle) +void ${varName}Handle_Addref(${varName}_t handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); var->AddRef(); } -void ${varName}Handle_Release(${varName}Handle handle) +void ${varName}Handle_Release(${varName}_t handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = reinterpret_cast*>(handle); var->Release(); if (var->IsValid() != true) { delete var; } } -bool ${varName}Handle_IsValid(${varName}Handle handle) +bool ${varName}Handle_IsValid(${varName}_t handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${jsonDataName}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${jsonDataName}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); return var->IsValid(); } @@ -42,17 +43,17 @@ bool ${varName}Handle_IsValid(${varName}Handle handle) const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, subPropertyName, accessorPropertyType, json = {}, options = {readonly:false, optional:false}) => { let result = '' - result += `${accessorPropertyType} ${objName}_Get_${subPropertyName}(${objName}Handle handle) + result += `${accessorPropertyType} ${objName}_Get_${subPropertyName}(${objName}_t handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ` + '\n' if ((json.type === 'object') && (accessorPropertyType !== 'char*')) { result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); *(*element) = (*var)->${subPropertyName}; - return (static_cast<${accessorPropertyType}>(element));` + '\n' + return (reinterpret_cast<${accessorPropertyType}>(element));` + '\n' } else { if ((typeof json.const === 'string') || (json.type === 'string' && !json.enum) || (accessorPropertyType === 'char*')) { @@ -66,14 +67,14 @@ const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, if (!options.readonly) { let type = (accessorPropertyType === getFireboltStringType()) ? 'char*' : accessorPropertyType - result += `void ${objName}_Set_${subPropertyName}(${objName}Handle handle, ${type} value)\n{ + result += `void ${objName}_Set_${subPropertyName}(${objName}_t handle, ${type} value)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ` + '\n' if (json.type === 'object' && (accessorPropertyType !== 'char*')) { - result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* object = static_cast*>(value); + result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* object = reinterpret_cast*>(value); (*var)->${subPropertyName} = *(*object);` + '\n' } else { @@ -83,16 +84,16 @@ const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, } if (options.optional === true) { - result += `bool ${objName}_Has_${subPropertyName}(${objName}Handle handle)\n{ + result += `bool ${objName}_Has_${subPropertyName}(${objName}_t handle)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); return ((*var)->${subPropertyName}.IsSet()); }` + '\n' - result += `void ${objName}_Clear_${subPropertyName}(${objName}Handle handle)\n{ + result += `void ${objName}_Clear_${subPropertyName}(${objName}_t handle)\n{ ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ((*var)->${subPropertyName}.Clear()); }` + '\n' @@ -113,7 +114,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr let result = `uint32_t ${objName}Array_Size(${objHandleType} handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); return (${propertyName}.Length()); @@ -122,7 +123,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr result += `${accessorPropertyType} ${objName}Array_Get(${objHandleType} handle, uint32_t index) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid());` + '\n' if ((json.type === 'object') || (json.type === 'array')) { @@ -130,7 +131,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr *object = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); *(*object) = ${propertyName}.Get(index); - return (static_cast<${accessorPropertyType}>(object));` + '\n' + return (reinterpret_cast<${accessorPropertyType}>(object));` + '\n' } else { if ((typeof json.const === 'string') || (json.type === 'string' && !json.enum)) { @@ -146,23 +147,25 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr result += `void ${objName}Array_Add(${objHandleType} handle, ${type} value) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid());` + '\n' if ((json.type === 'object') || (json.type === 'array')) { - result += ` ${subPropertyType}& element = *(*(static_cast*>(value)));` + '\n' + result += ` ${subPropertyType} element; + element = *(*(reinterpret_cast*>(value)));` + '\n' } else { - result += ` ${subPropertyType} element(value);` + '\n' + result += ` ${subPropertyType} element;` + '\n' + result += ` element = value;` + '\n' } result += ` - ${propertyName}.Add(element); + ${propertyName}.Add() = element; }` + '\n' result += `void ${objName}Array_Clear(${objHandleType} handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${modulePropertyType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ${propertyName}.Clear(); @@ -172,10 +175,10 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr } const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPropertyType, json = {}, options = {readonly:false, optional:false}) => { - let result = `uint32_t ${objName}_KeysCount(${objName}Handle handle) + let result = `uint32_t ${objName}_KeysCount(${objName}_t handle) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ${containerType}::Iterator elements = (*var)->Variants(); uint32_t count = 0; @@ -184,10 +187,10 @@ const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPr } return (count); }` + '\n' - result += `void ${objName}_AddKey(${objName}Handle handle, char* key, ${accessorPropertyType} value) + result += `void ${objName}_AddKey(${objName}_t handle, char* key, ${accessorPropertyType} value) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ` + '\n' let elementContainer = subPropertyType @@ -196,14 +199,14 @@ const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPr } if ((json.type === 'object') || (json.type === 'array' && json.items)) { if (containerType.includes('VariantContainer')) { - result += ` ${subPropertyType}& container = *(*(static_cast*>(value)));` + '\n' + result += ` ${subPropertyType}& container = *(*(reinterpret_cast*>(value)));` + '\n' result += ` string containerStr;` + '\n' result += ` element.ToString(containerStr);` + '\n' result += ` WPEFramework::Core::JSON::VariantContainer containerVariant(containerStr);` + '\n' result += ` WPEFramework::Core::JSON::Variant element = containerVariant;` + '\n' } else { - result += ` ${subPropertyType}& element = *(*(static_cast*>(value)));` + '\n' + result += ` ${subPropertyType}& element = *(*(reinterpret_cast*>(value)));` + '\n' } } else { result += ` ${elementContainer} element(value);` + '\n' @@ -211,19 +214,19 @@ const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPr result += ` (*var)->Set(const_cast(key), element); }` + '\n' - result += `void ${objName}_RemoveKey(${objName}Handle handle, char* key) + result += `void ${objName}_RemoveKey(${objName}_t handle, char* key) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); (*var)->Remove(key); }` + '\n' - result += `${accessorPropertyType} ${objName}_FindKey(${objName}Handle handle, char* key) + result += `${accessorPropertyType} ${objName}_FindKey(${objName}_t handle, char* key) { ASSERT(handle != NULL); - WPEFramework::Core::ProxyType<${containerType}>* var = static_cast*>(handle); + WPEFramework::Core::ProxyType<${containerType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid());` + '\n' if ((json.type === 'object') || (json.type === 'array') || ((json.type === 'string' || (typeof json.const === 'string')) && !json.enum)) { @@ -249,14 +252,14 @@ const getMapAccessorsImpl = (objName, containerType, subPropertyType, accessorPr *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); *(*element) = objectMap; - status = (static_cast<${accessorPropertyType}>(element));` + '\n' + status = (reinterpret_cast<${accessorPropertyType}>(element));` + '\n' } else if (json.type === 'array' && json.items) { result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); *(*element) = (*var)->Get(key).Array(); - status = (static_cast<${accessorPropertyType}>(element));` + '\n' + status = (reinterpret_cast<${accessorPropertyType}>(element));` + '\n' } else { if (json.type === 'string' || (typeof json.const === 'string')) { @@ -298,25 +301,41 @@ function getParameterInstantiation(paramList, container = '') { paramList.forEach(param => { impl += `\n` const jsonType = param.jsonType + const name = param.name if (jsonType.length) { if (param.required) { - if (param.nativeType.includes('FireboltTypes_StringHandle')) { - impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = *(static_cast<${jsonType}*>(${param.name}));\n` + if (param.nativeType.includes('FireboltTypes_String_t')) { + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = *(reinterpret_cast<${jsonType}*>(${name}));\n` + } + else if (param.nativeType.includes('_t')) { + impl += ` ${jsonType}& ${capitalize(name)}Container = *(*(reinterpret_cast*>(${camelcase(name)})));\n` + impl += ` string ${capitalize(name)}Str;\n` + impl += ` ${capitalize(name)}Container.ToString(${capitalize(name)}Str);\n` + impl += ` WPEFramework::Core::JSON::VariantContainer ${capitalize(name)}VariantContainer(${capitalize(name)}Str);\n` + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = ${capitalize(name)}VariantContainer;\n` } else { - impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = ${param.name};\n` + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = ${name};\n` } - impl += ` jsonParameters.Set(_T("${param.name}"), ${capitalize(param.name)});` + impl += ` jsonParameters.Set(_T("${name}"), ${capitalize(name)});` } else { - impl += ` if (${param.name} != nullptr) {\n` + + impl += ` if (${name} != nullptr) {\n` if (param.nativeType.includes('char*')) { - impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = ${param.name};\n` + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = ${name};\n` + } + else if (param.nativeType.includes('_t')) { + impl += ` ${jsonType}& ${capitalize(name)}Container = *(*(reinterpret_cast*>(${camelcase(name)})));\n` + impl += ` string ${capitalize(name)}Str;\n` + impl += ` ${capitalize(name)}Container.ToString(${capitalize(name)}Str);\n` + impl += ` WPEFramework::Core::JSON::VariantContainer ${capitalize(name)}VariantContainer(${capitalize(name)}Str);\n` + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = ${capitalize(name)}VariantContainer;\n` } else { - impl += ` WPEFramework::Core::JSON::Variant ${capitalize(param.name)} = *(${param.name});\n` + impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = *(${name});\n` } - impl += ` jsonParameters.Set(_T("${param.name}"), ${capitalize(param.name)});\n` + impl += ` jsonParameters.Set(_T("${name}"), ${capitalize(name)});\n` impl += ` }` } impl += '\n' @@ -347,7 +366,7 @@ function getCallbackParametersInstantiation(paramList, container = '') { } }) impl += `\n WPEFramework::Core::ProxyType<${container}>* jsonResponse;\n` - impl += ` WPEFramework::Core::ProxyType& var = *(static_cast*>(response)); + impl += ` WPEFramework::Core::ProxyType& var = *(reinterpret_cast*>(response)); ASSERT(var.IsValid() == true); if (var.IsValid() == true) { @@ -378,7 +397,7 @@ function getCallbackParametersInstantiation(paramList, container = '') { if (param.nativeType === 'char*') { contextParams += ` ${getSdkNameSpace()}::JSON::String* ${param.name}Value = new ${getSdkNameSpace()}::JSON::String(); *${param.name}Value = elements.Current().Value().c_str(); - ${param.name} = ${param.name}Value;\n` + ${param.name} = reinterpret_cast<${getFireboltStringType()}>(${param.name}Value);\n` } else if (param.nativeType === 'bool') { contextParams += ` ${param.name} = elements.Current().Boolean();\n` @@ -402,7 +421,7 @@ function getCallbackParametersInstantiation(paramList, container = '') { }\n` } else { - impl +=` WPEFramework::Core::ProxyType<${container}>* jsonResponse = static_cast*>(response);\n` + impl +=` WPEFramework::Core::ProxyType<${container}>* jsonResponse = reinterpret_cast*>(response);\n` } return impl @@ -410,7 +429,7 @@ function getCallbackParametersInstantiation(paramList, container = '') { function getCallbackResultInstantiation(nativeType, container = '') { let impl = '' - if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + if (nativeType === 'char*' || nativeType === 'FireboltTypes_String_t') { impl +=` ${container}* jsonStrResponse = new ${container}(); *jsonStrResponse = *(*jsonResponse); @@ -426,7 +445,7 @@ function getCallbackResponseInstantiation(paramList, nativeType, container = '') paramList.forEach(param => { if (param.required !== undefined) { if (param.nativeType === 'char*') { - impl += `static_cast<${getFireboltStringType()}>(${param.name}), ` + impl += `reinterpret_cast<${getFireboltStringType()}>(${param.name}), ` } else if (param.required === true) { impl += `${param.name}, ` @@ -438,11 +457,11 @@ function getCallbackResponseInstantiation(paramList, nativeType, container = '') }) } - if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { - impl += `static_cast<${nativeType}>(jsonStrResponse)` + if (nativeType === 'char*' || nativeType === 'FireboltTypes_String_t') { + impl += `reinterpret_cast<${nativeType}>(jsonStrResponse)` } - else if (nativeType.includes('Handle')) { - impl += `static_cast<${nativeType}>(jsonResponse)` + else if (nativeType.includes('_t')) { + impl += `reinterpret_cast<${nativeType}>(jsonResponse)` } else { impl += `static_cast<${nativeType}>((*jsonResponse)->Value())` @@ -457,16 +476,16 @@ function getResultInstantiation (name, nativeType, container, indentLevel = 3) { if (nativeType) { impl += `${' '.repeat(indentLevel)}if (${name} != nullptr) {` + '\n' - if (nativeType === 'char*' || nativeType === 'FireboltTypes_StringHandle') { + if (nativeType === 'char*' || nativeType === 'FireboltTypes_String_t') { impl += `${' '.repeat(indentLevel + 1)}${container}* strResult = new ${container}(jsonResult);` + '\n' - impl += `${' '.repeat(indentLevel + 1)}*${name} = static_cast<${getFireboltStringType()}>(strResult);` - } else if (nativeType.includes('Handle')) { + impl += `${' '.repeat(indentLevel + 1)}*${name} = reinterpret_cast<${getFireboltStringType()}>(strResult);` + '\n' + } else if (nativeType.includes('_t')) { impl += `${' '.repeat(indentLevel + 1)}WPEFramework::Core::ProxyType<${container}>* resultPtr = new WPEFramework::Core::ProxyType<${container}>();\n` impl += `${' '.repeat(indentLevel + 1)}*resultPtr = WPEFramework::Core::ProxyType<${container}>::Create();\n` impl += `${' '.repeat(indentLevel + 1)}*(*resultPtr) = jsonResult;\n` - impl += `${' '.repeat(indentLevel + 1)}*${name} = static_cast<${nativeType}>(resultPtr);` - } else { - impl += `${' '.repeat(indentLevel + 1)}*${name} = jsonResult.Value();` + impl += `${' '.repeat(indentLevel + 1)}*${name} = reinterpret_cast<${nativeType}>(resultPtr);` + '\n' + } else { + impl += `${' '.repeat(indentLevel + 1)}*${name} = jsonResult.Value();` + '\n' } impl += `${' '.repeat(indentLevel)}}` + '\n' } else if (name === 'success') { diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index b2a260b5..cc31b14a 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -52,5 +52,6 @@ function getJsonContainerDefinition (schema, name, props) { export { getJsonContainerDefinition, - getJsonDataStructName + getJsonDataStructName, + getJsonDataPrefix } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 1460e22e..7bfef987 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -29,7 +29,7 @@ const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = pre const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' -const getFireboltStringType = () => 'FireboltTypes_StringHandle' +const getFireboltStringType = () => 'FireboltTypes_String_t' const getHeaderText = () => { return `/* @@ -42,40 +42,6 @@ const getHeaderText = () => { ` } -const getIncludeGuardOpen = (json, prefix=null) => { - prefix = prefix ? `${prefix.toUpperCase()}_` : '' - return ` -#ifndef _${prefix}${getModuleName(json).toUpperCase()}_H -#define _${prefix}${getModuleName(json).toUpperCase()}_H - -` -} - -const getStyleGuardOpen = () => { - return ` -#ifdef __cplusplus -extern "C" { -#endif - -` -} - -const getStyleGuardClose = () => { - return ` - -#ifdef __cplusplus -} -#endif - -` -} - -const getIncludeGuardClose = () => { - return ` -#endif // Header Include Guard -` -} - const capitalize = str => str[0].toUpperCase() + str.substr(1) const description = (title, str='') => '/* ' + title + (str.length > 0 ? ' - ' + str : '') + ' */' const isOptional = (prop, json) => (!json.required || !json.required.includes(prop)) @@ -142,26 +108,26 @@ const getNativeType = (json, fireboltString = false) => { const getObjectHandleManagement = varName => { - let result = `typedef void* ${varName}Handle; -${varName}Handle ${varName}Handle_Create(void); -void ${varName}Handle_Addref(${varName}Handle handle); -void ${varName}Handle_Release(${varName}Handle handle); -bool ${varName}Handle_IsValid(${varName}Handle handle); + let result = `typedef struct ${varName}_s* ${varName}_t; +${varName}_t ${varName}Handle_Acquire(void); +void ${varName}Handle_Addref(${varName}_t handle); +void ${varName}Handle_Release(${varName}_t handle); +bool ${varName}Handle_IsValid(${varName}_t handle); ` return result } const getPropertyAccessors = (objName, propertyName, propertyType, options = {level:0, readonly:false, optional:false}) => { - let result = `${Indent.repeat(options.level)}${propertyType} ${objName}_Get_${propertyName}(${objName}Handle handle);` + '\n' + let result = `${Indent.repeat(options.level)}${propertyType} ${objName}_Get_${propertyName}(${objName}_t handle);` + '\n' if (!options.readonly) { let type = (propertyType === getFireboltStringType()) ? 'char*' : propertyType - result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}Handle handle, ${type} ${propertyName.toLowerCase()});` + '\n' + result += `${Indent.repeat(options.level)}void ${objName}_Set_${propertyName}(${objName}_t handle, ${type} ${propertyName.toLowerCase()});` + '\n' } if (options.optional === true) { - result += `${Indent.repeat(options.level)}bool ${objName}_Has_${propertyName}(${objName}Handle handle);` + '\n' - result += `${Indent.repeat(options.level)}void ${objName}_Clear_${propertyName}(${objName}Handle handle);` + '\n' + result += `${Indent.repeat(options.level)}bool ${objName}_Has_${propertyName}(${objName}_t handle);` + '\n' + result += `${Indent.repeat(options.level)}void ${objName}_Clear_${propertyName}(${objName}_t handle);` + '\n' } return result @@ -171,10 +137,10 @@ const getMapAccessors = (typeName, accessorPropertyType, level = 0) => { let res - res = `${Indent.repeat(level)}uint32_t ${typeName}_KeysCount(${typeName}Handle handle);` + '\n' - res += `${Indent.repeat(level)}void ${typeName}_AddKey(${typeName}Handle handle, char* key, ${accessorPropertyType} value);` + '\n' - res += `${Indent.repeat(level)}void ${typeName}_RemoveKey(${typeName}Handle handle, char* key);` + '\n' - res += `${Indent.repeat(level)}${accessorPropertyType} ${typeName}_FindKey(${typeName}Handle handle, char* key);` + '\n' + res = `${Indent.repeat(level)}uint32_t ${typeName}_KeysCount(${typeName}_t handle);` + '\n' + res += `${Indent.repeat(level)}void ${typeName}_AddKey(${typeName}_t handle, char* key, ${accessorPropertyType} value);` + '\n' + res += `${Indent.repeat(level)}void ${typeName}_RemoveKey(${typeName}_t handle, char* key);` + '\n' + res += `${Indent.repeat(level)}${accessorPropertyType} ${typeName}_FindKey(${typeName}_t handle, char* key);` + '\n' return res } @@ -193,10 +159,10 @@ const getTypeName = (moduleName, varName, prefix = '', upperCase = false, capita const getArrayAccessors = (arrayName, propertyType, valueType) => { - let res = `uint32_t ${arrayName}Array_Size(${propertyType}Handle handle);` + '\n' - res += `${valueType} ${arrayName}Array_Get(${propertyType}Handle handle, uint32_t index);` + '\n' - res += `void ${arrayName}Array_Add(${propertyType}Handle handle, ${valueType} value);` + '\n' - res += `void ${arrayName}Array_Clear(${propertyType}Handle handle);` + '\n' + let res = `uint32_t ${arrayName}Array_Size(${propertyType}_t handle);` + '\n' + res += `${valueType} ${arrayName}Array_Get(${propertyType}_t handle, uint32_t index);` + '\n' + res += `void ${arrayName}Array_Add(${propertyType}_t handle, ${valueType} value);` + '\n' + res += `void ${arrayName}Array_Clear(${propertyType}_t handle);` + '\n' return res } @@ -270,10 +236,6 @@ function getPropertyEventUnregisterSignature(property, module) { export { getHeaderText, - getIncludeGuardOpen, - getStyleGuardOpen, - getStyleGuardClose, - getIncludeGuardClose, getNativeType, getModuleName, getPropertyGetterSignature, diff --git a/languages/c/templates/imports/default.cpp b/languages/c/templates/imports/default.cpp index 69e241f9..caf84bc9 100644 --- a/languages/c/templates/imports/default.cpp +++ b/languages/c/templates/imports/default.cpp @@ -1 +1 @@ -#include "JsonData_${info.title}.h" +#include "jsondata_${info.title.lowercase}.h" diff --git a/languages/c/templates/imports/default.h b/languages/c/templates/imports/default.h index a38b58ef..56a97a40 100644 --- a/languages/c/templates/imports/default.h +++ b/languages/c/templates/imports/default.h @@ -1 +1 @@ -#include "Common/${info.title}.h" +#include "common/${info.title.lowercase}.h" diff --git a/languages/c/templates/imports/default.jsondata b/languages/c/templates/imports/default.jsondata index 69e241f9..caf84bc9 100644 --- a/languages/c/templates/imports/default.jsondata +++ b/languages/c/templates/imports/default.jsondata @@ -1 +1 @@ -#include "JsonData_${info.title}.h" +#include "jsondata_${info.title.lowercase}.h" diff --git a/languages/c/templates/modules/include/Module.h b/languages/c/templates/modules/include/module.h similarity index 92% rename from languages/c/templates/modules/include/Module.h rename to languages/c/templates/modules/include/module.h index a202f643..00c5d595 100644 --- a/languages/c/templates/modules/include/Module.h +++ b/languages/c/templates/modules/include/module.h @@ -16,10 +16,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _${info.TITLE}_H -#define _${info.TITLE}_H +#ifndef ${info.TITLE}_H +#define ${info.TITLE}_H -#include "Firebolt.h" +#include /* ${IMPORTS} */ #ifdef __cplusplus diff --git a/languages/c/templates/modules/src/Module.cpp b/languages/c/templates/modules/src/module.cpp similarity index 93% rename from languages/c/templates/modules/src/Module.cpp rename to languages/c/templates/modules/src/module.cpp index 65721f1e..2b467ae1 100644 --- a/languages/c/templates/modules/src/Module.cpp +++ b/languages/c/templates/modules/src/module.cpp @@ -18,10 +18,10 @@ #include "FireboltSDK.h" /* ${IMPORTS} */ -#include "${info.title}.h" +#include "${info.title.lowercase}.h" namespace FireboltSDK { - namespace ${info.title} { + namespace ${info.Title} { // Types /* ${TYPES} */ } diff --git a/languages/c/templates/schemas/include/Common/Module.h b/languages/c/templates/schemas/include/common/module.h similarity index 90% rename from languages/c/templates/schemas/include/Common/Module.h rename to languages/c/templates/schemas/include/common/module.h index ff037fba..939b3988 100644 --- a/languages/c/templates/schemas/include/Common/Module.h +++ b/languages/c/templates/schemas/include/common/module.h @@ -16,10 +16,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _COMMON_${info.TITLE}_H -#define _COMMON_${info.TITLE}_H +#ifndef COMMON_${info.TITLE}_H +#define COMMON_${info.TITLE}_H -#include "Firebolt.h" +#include /* ${IMPORTS} */ #ifdef __cplusplus diff --git a/languages/c/templates/schemas/src/JsonData_Module.h b/languages/c/templates/schemas/src/jsondata_module.h similarity index 91% rename from languages/c/templates/schemas/src/JsonData_Module.h rename to languages/c/templates/schemas/src/jsondata_module.h index d0ecbbac..f80be03e 100644 --- a/languages/c/templates/schemas/src/JsonData_Module.h +++ b/languages/c/templates/schemas/src/jsondata_module.h @@ -19,10 +19,10 @@ #pragma once /* ${IMPORTS} */ -#include "Common/${info.title}.h" +#include "common/${info.title.lowercase}.h" namespace FireboltSDK { - namespace ${info.title} { + namespace ${info.Title} { // Types /* ${SCHEMAS} */ diff --git a/languages/c/templates/schemas/src/Module_Common.cpp b/languages/c/templates/schemas/src/module_common.cpp similarity index 94% rename from languages/c/templates/schemas/src/Module_Common.cpp rename to languages/c/templates/schemas/src/module_common.cpp index 0ccdfc28..0d8c74d2 100644 --- a/languages/c/templates/schemas/src/Module_Common.cpp +++ b/languages/c/templates/schemas/src/module_common.cpp @@ -18,7 +18,7 @@ #include "FireboltSDK.h" /* ${IMPORTS} */ -#include "JsonData_${info.title}.h" +#include "jsondata_${info.title.lowercase}.h" /* ${ENUMS} */ diff --git a/languages/c/templates/sdk/include/Error.h b/languages/c/templates/sdk/include/error.h similarity index 93% rename from languages/c/templates/sdk/include/Error.h rename to languages/c/templates/sdk/include/error.h index 87cda9dd..07d6268a 100644 --- a/languages/c/templates/sdk/include/Error.h +++ b/languages/c/templates/sdk/include/error.h @@ -16,8 +16,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _FIREBOLT_ERROR_H -#define _FIREBOLT_ERROR_H +#ifndef FIREBOLT_ERROR_H +#define FIREBOLT_ERROR_H #ifdef __cplusplus extern "C" { @@ -38,4 +38,4 @@ typedef enum FireboltSDKError { } #endif -#endif // _FIREBOLT_ERROR_H +#endif // FIREBOLT_ERROR_H diff --git a/languages/c/templates/sdk/include/Firebolt.h b/languages/c/templates/sdk/include/firebolt.h similarity index 93% rename from languages/c/templates/sdk/include/Firebolt.h rename to languages/c/templates/sdk/include/firebolt.h index 2223bad3..0957973f 100644 --- a/languages/c/templates/sdk/include/Firebolt.h +++ b/languages/c/templates/sdk/include/firebolt.h @@ -16,11 +16,11 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _FIREBOLT_H -#define _FIREBOLT_H +#ifndef FIREBOLT_H +#define FIREBOLT_H -#include "Error.h" -#include "Types.h" +#include "error.h" +#include "types.h" #ifdef __cplusplus extern "C" { @@ -62,4 +62,4 @@ uint32_t FireboltSDK_Deinitialize(void); #endif -#endif // _FIREBOLT_H +#endif // FIREBOLT_H diff --git a/languages/c/templates/sdk/include/Types.h b/languages/c/templates/sdk/include/types.h similarity index 73% rename from languages/c/templates/sdk/include/Types.h rename to languages/c/templates/sdk/include/types.h index 4fd16256..26efc54f 100644 --- a/languages/c/templates/sdk/include/Types.h +++ b/languages/c/templates/sdk/include/types.h @@ -16,8 +16,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _FIREBOLT_TYPES_H -#define _FIREBOLT_TYPES_H +#ifndef FIREBOLT_TYPES_H +#define FIREBOLT_TYPES_H #include #include @@ -26,12 +26,12 @@ extern "C" { #endif -typedef void* FireboltTypes_StringHandle; -const char* FireboltTypes_String(FireboltTypes_StringHandle handle); -void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle); +typedef struct FireboltTypes_String_s* FireboltTypes_String_t; +const char* FireboltTypes_String(FireboltTypes_String_t handle); +void FireboltTypes_StringHandle_Release(FireboltTypes_String_t handle); #ifdef __cplusplus } #endif -#endif // _FIREBOLT_TYPES_H +#endif // FIREBOLT_TYPES_H diff --git a/languages/c/templates/sdk/scripts/build.sh b/languages/c/templates/sdk/scripts/build.sh index e9b01f20..d50295a6 100755 --- a/languages/c/templates/sdk/scripts/build.sh +++ b/languages/c/templates/sdk/scripts/build.sh @@ -1,11 +1,37 @@ #!/bin/bash -SDK_PATH="." -if [ "$1" != "" ] +usage() +{ + echo "options:" + echo " -p sdk path" + echo " -s sysroot path" + echo " -t enable test" + echo " -c clear build" + echo " -h : help" + echo + echo "usage: " + echo " ./build.sh -p path -tc" +} + +SdkPath="." +EnableTest="OFF" +SysrootPath=${SYSROOT_PATH} +ClearBuild="N" +while getopts p:s:tch flag +do + case "${flag}" in + p) SdkPath="${OPTARG}";; + s) SysrootPath="${OPTARG}";; + t) EnableTest="ON";; + c) ClearBuild="Y";; + h) usage && exit 1;; + esac +done + +if [ "${ClearBuild}" == "Y" ]; then - SDK_PATH=$1 - echo "inside ${1}" + rm -rf ${SdkPath}/build fi -echo ${SDK_PATH} -rm -rf ${SDK_PATH}/build -cmake -B${SDK_PATH}/build -S${SDK_PATH} -DSYSROOT_PATH=${SYSROOT_PATH} -cmake --build ${SDK_PATH}/build + +cmake -B${SdkPath}/build -S${SdkPath} -DSYSROOT_PATH=${SysrootPath} -DENABLE_TESTS=${EnableTest} +cmake --build ${SdkPath}/build +cmake --install ${SdkPath}/build --prefix=${SdkPath}/build/Firebolt diff --git a/languages/c/templates/sdk/src/CMakeLists.txt b/languages/c/templates/sdk/src/CMakeLists.txt index 2f00bdf1..b565d6b1 100644 --- a/languages/c/templates/sdk/src/CMakeLists.txt +++ b/languages/c/templates/sdk/src/CMakeLists.txt @@ -20,7 +20,6 @@ project(FireboltSDK) project_version(1.0.0) set(TARGET ${PROJECT_NAME}) message("Setup ${TARGET} v${PROJECT_VERSION}") -file(GLOB GENERATED_SOURCES "${GENERATED_CODE_PATH}/src/*.cpp") file(GLOB SOURCES *.cpp) add_library(${TARGET} ${FIREBOLT_LIBRARY_TYPE} @@ -41,8 +40,6 @@ target_link_libraries(${TARGET} target_include_directories(${TARGET} PRIVATE - $ - $ $ $ ) @@ -64,8 +61,6 @@ install( ) InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION ${FIREBOLT_NAMESPACE}SDK) -InstallHeaders(TARGET ${TARGET} EXCLUDE_ROOT_DIR HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} - SOURCE ${GENERATED_CODE_PATH}/include DESTINATION ${FIREBOLT_NAMESPACE}/generated) InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../include DESTINATION ${FIREBOLT_NAMESPACE}) diff --git a/languages/c/templates/sdk/src/FireboltSDK.h b/languages/c/templates/sdk/src/FireboltSDK.h index 19946126..d78687dc 100644 --- a/languages/c/templates/sdk/src/FireboltSDK.h +++ b/languages/c/templates/sdk/src/FireboltSDK.h @@ -23,4 +23,4 @@ #include "Accessor/Accessor.h" #include "Logger/Logger.h" #include "TypesPriv.h" -#include "Types.h" +#include "types.h" diff --git a/languages/c/templates/sdk/src/Logger/Logger.cpp b/languages/c/templates/sdk/src/Logger/Logger.cpp index 0e49dfce..a9750a6e 100644 --- a/languages/c/templates/sdk/src/Logger/Logger.cpp +++ b/languages/c/templates/sdk/src/Logger/Logger.cpp @@ -17,7 +17,7 @@ */ #include "Module.h" -#include "Error.h" +#include "error.h" #include "Logger.h" namespace WPEFramework { diff --git a/languages/c/templates/sdk/src/Logger/Logger.h b/languages/c/templates/sdk/src/Logger/Logger.h index cffeff54..2c864c7b 100644 --- a/languages/c/templates/sdk/src/Logger/Logger.h +++ b/languages/c/templates/sdk/src/Logger/Logger.h @@ -18,7 +18,7 @@ #pragma once -#include "Types.h" +#include "types.h" namespace FireboltSDK { diff --git a/languages/c/templates/sdk/src/Transport/Transport.h b/languages/c/templates/sdk/src/Transport/Transport.h index d12312a5..109e2431 100644 --- a/languages/c/templates/sdk/src/Transport/Transport.h +++ b/languages/c/templates/sdk/src/Transport/Transport.h @@ -19,7 +19,7 @@ #pragma once #include "Module.h" -#include "Error.h" +#include "error.h" namespace FireboltSDK { diff --git a/languages/c/templates/sdk/src/Types.cpp b/languages/c/templates/sdk/src/Types.cpp index f19cfe63..b9620436 100644 --- a/languages/c/templates/sdk/src/Types.cpp +++ b/languages/c/templates/sdk/src/Types.cpp @@ -17,7 +17,7 @@ */ #include "Module.h" -#include "Types.h" +#include "types.h" #include "TypesPriv.h" #ifdef __cplusplus @@ -25,14 +25,14 @@ extern "C" { #endif // String Type Handler Interfaces -const char* FireboltTypes_String(FireboltTypes_StringHandle handle) +const char* FireboltTypes_String(FireboltTypes_String_t handle) { - return ((static_cast(handle))->Value().c_str()); + return ((reinterpret_cast(handle))->Value().c_str()); } -void FireboltTypes_StringHandle_Release(FireboltTypes_StringHandle handle) +void FireboltTypes_StringHandle_Release(FireboltTypes_String_t handle) { - delete static_cast(handle); + delete reinterpret_cast(handle); } #ifdef __cplusplus diff --git a/languages/c/templates/sdk/src/Firebolt.cpp b/languages/c/templates/sdk/src/firebolt.cpp similarity index 100% rename from languages/c/templates/sdk/src/Firebolt.cpp rename to languages/c/templates/sdk/src/firebolt.cpp diff --git a/languages/c/templates/sdk/test/CMakeLists.txt b/languages/c/templates/sdk/test/CMakeLists.txt index a56ca20a..21ee1f55 100644 --- a/languages/c/templates/sdk/test/CMakeLists.txt +++ b/languages/c/templates/sdk/test/CMakeLists.txt @@ -57,7 +57,7 @@ install( InstallCMakeConfig(TARGETS ${TESTLIB}) InstallCMakeConfigs(TARGET ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) InstallHeaders(TARGET ${TESTLIB} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION FireboltTest) -InstallLibraries(TARGET ${TESTLIB} LIBRARIES ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallLibraries(TARGET ${TESTLIB} STATIC LIBRARIES ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) set(TESTAPP "FireboltSDKTestApp") diff --git a/languages/c/templates/sdk/test/Main.c b/languages/c/templates/sdk/test/Main.c index 7c4c94a5..6161792e 100644 --- a/languages/c/templates/sdk/test/Main.c +++ b/languages/c/templates/sdk/test/Main.c @@ -35,6 +35,7 @@ int main() EXECUTE("test_properties_set", test_properties_set); EXECUTE("test_eventregister_by_providing_callback", test_eventregister_by_providing_callback); EXECUTE("test_eventregister", test_eventregister); + EXECUTE("test_eventregister_with_same_callback", test_eventregister_with_same_callback); EXECUTE("test_string_set_get_value", test_string_set_get_value); test_firebolt_dispose_instance(); diff --git a/languages/c/templates/sdk/test/Module.h b/languages/c/templates/sdk/test/Module.h index d5340b68..a147ff75 100644 --- a/languages/c/templates/sdk/test/Module.h +++ b/languages/c/templates/sdk/test/Module.h @@ -23,7 +23,6 @@ #endif #include -#include #undef EXTERNAL #define EXTERNAL diff --git a/languages/c/templates/sdk/test/OpenRPCCTests.h b/languages/c/templates/sdk/test/OpenRPCCTests.h index 7f2fb59e..4fe5eb5b 100644 --- a/languages/c/templates/sdk/test/OpenRPCCTests.h +++ b/languages/c/templates/sdk/test/OpenRPCCTests.h @@ -16,8 +16,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef _OPENRPC_C_TESTS_H -#define _OPENRPC_C_TESTS_H +#ifndef OPENRPC_C_TESTS_H +#define OPENRPC_C_TESTS_H #include "TestUtils.h" @@ -25,13 +25,14 @@ extern "C" { #endif -uint32_t test_firebolt_create_instance(); -uint32_t test_firebolt_dispose_instance(); +void test_firebolt_create_instance(); +void test_firebolt_dispose_instance(); uint32_t test_firebolt_main(); uint32_t test_properties_get_device_id(); uint32_t test_properties_set(); uint32_t test_eventregister(); +uint32_t test_eventregister_with_same_callback(); uint32_t test_eventregister_by_providing_callback(); uint32_t test_string_set_get_value(); @@ -39,4 +40,4 @@ uint32_t test_string_set_get_value(); } #endif -#endif // _OPENRPC_C_TESTS_H +#endif // OPENRPC_C_TESTS_H diff --git a/languages/c/templates/sdk/test/OpenRPCTests.cpp b/languages/c/templates/sdk/test/OpenRPCTests.cpp index cf9ea5a0..b74f17ae 100644 --- a/languages/c/templates/sdk/test/OpenRPCTests.cpp +++ b/languages/c/templates/sdk/test/OpenRPCTests.cpp @@ -38,11 +38,20 @@ ENUM_CONVERSION_BEGIN(TestEnum) { TestEnum::Test4, _TXT("Test4ValueCheck") }, ENUM_CONVERSION_END(TestEnum) } + +typedef void (*OnNotifyDeviceNameChanged)(const void* userData, const char* data); +static void NotifyEvent(const void* userData, const char* data) +{ + printf("NotifyEvent data : %s\n", data); +} + namespace FireboltSDK { Tests::Tests() { _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEventWithMultipleCallback"), std::forward_as_tuple(&SubscribeEventWithMultipleCallback)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEventwithSameCallback"), + std::forward_as_tuple(&SubscribeEventwithSameCallback)); _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEvent"), std::forward_as_tuple(&SubscribeEvent)); @@ -147,25 +156,55 @@ namespace FireboltSDK { return status; } - static void deviceNameChangeCallback(const void* userData, void* response) + static void deviceNameChangeCallback(void* userCB, const void* userData, void* response) { - WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + WPEFramework::Core::ProxyType& jsonResponse = *(reinterpret_cast*>(response)); FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Received a new event: %s", jsonResponse->Value().c_str()); - jsonResponse.Release(); FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + OnNotifyDeviceNameChanged notifyDeviceNameChanged = reinterpret_cast(userCB); + notifyDeviceNameChanged(userData, jsonResponse->Value().c_str()); eventControl->NotifyEvent(); + jsonResponse.Release(); } /* static */ uint32_t Tests::SubscribeEvent() { - FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl("EventControl"); const string eventName = _T("device.Name"); const void* userdata = static_cast(eventControl); - uint32_t id = 0; + eventControl->ResetEvent(); + + JsonObject jsonParameters; + uint32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), + "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered successfully, Waiting for event...", __func__); + + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + delete eventControl; + + return status; + } + + /* static */ uint32_t Tests::SubscribeEventwithSameCallback() + { + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl("EventControl"); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); eventControl->ResetEvent(); - uint32_t status = Properties::Subscribe(eventName, deviceNameChangeCallback, userdata, id); + + JsonObject jsonParameters; + uint32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -174,40 +213,71 @@ namespace FireboltSDK { } else { FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "%s Yes registered successfully", __func__); - eventControl->WaitForEvent(WPEFramework::Core::infinite); + + status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback, reinterpret_cast(NotifyEvent), userdata); + EXPECT_EQ(status, FireboltSDKErrorInUse); + if (status == FireboltSDKErrorInUse) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes this device.name event is already registered with same callback", __func__); + } + status = ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone : status); } - EXPECT_EQ(Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); delete eventControl; return status; } + + static void NotifyEvent1(const void* userData, const char* data) + { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent1 data : %s", data); + if (userData) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent1 userData : %s\n", reinterpret_cast(userData)->Name().c_str()); + } + } + static void NotifyEvent2(const void* userData, const char* data) + { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent2 data : %s", data); + if (userData) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent2 userData : %s\n", reinterpret_cast(userData)->Name().c_str()); + } + } + template - /* static */ uint32_t Tests::SubscribeEventForC(const string& eventName, CALLBACK& callbackFunc, const void* userdata, uint32_t& id) + /* static */ uint32_t Tests::SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata) { - return Properties::Subscribe(eventName, callbackFunc, userdata, id);; + return Properties::Subscribe(eventName, jsonParameters, callbackFunc, usercb, userdata); } - static void deviceNameChangeMultipleCallback(const void* userData, void* response) + static void deviceNameChangeMultipleCallback(void* userCB, const void* userData, void* response) { - WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + WPEFramework::Core::ProxyType& jsonResponse = *(reinterpret_cast*>(response)); FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Received a new event from deviceNameChangeMultipleCallback: %s", jsonResponse->Value().c_str()); - jsonResponse.Release(); FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + OnNotifyDeviceNameChanged notifyDeviceNameChanged = reinterpret_cast(userCB); + notifyDeviceNameChanged(userData, jsonResponse->Value().c_str()); + eventControl->NotifyEvent(); + jsonResponse.Release(); } /* static */ uint32_t Tests::SubscribeEventWithMultipleCallback() { - FireboltSDK::Tests::EventControl* eventControl1 = new FireboltSDK::Tests::EventControl(); + FireboltSDK::Tests::EventControl* eventControl1 = new FireboltSDK::Tests::EventControl("EventControl1"); const string eventName = _T("device.Name"); const void* userdata = static_cast(eventControl1); - uint32_t id1 = 0, id2 = 0; eventControl1->ResetEvent(); - uint32_t status = Properties::Subscribe(eventName, deviceNameChangeCallback, userdata, id1); + + JsonObject jsonParameters; + uint32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent1), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -215,28 +285,33 @@ namespace FireboltSDK { "Set %s status = %d", eventName.c_str(), status); } else { FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), - "%s Yes registered successfully", __func__); + "%s Yes registered successfully, Waiting for event...", __func__); } if (status == FireboltSDKErrorNone) { - FireboltSDK::Tests::EventControl* eventControl2 = new FireboltSDK::Tests::EventControl(); + FireboltSDK::Tests::EventControl* eventControl2 = new FireboltSDK::Tests::EventControl("EventControl2"); userdata = static_cast(eventControl2); - status = Properties::Subscribe(eventName, deviceNameChangeMultipleCallback, userdata, id2); + status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent2), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", eventName.c_str(), status); } else { + status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent2), userdata); + EXPECT_EQ(status, FireboltSDKErrorInUse); + status = ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone : status); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), - "%s Yes registered second callback also successfully", __func__); + "%s Yes registered second callback also successfully, waiting for events...\n", __func__); + eventControl1->WaitForEvent(WPEFramework::Core::infinite); eventControl2->WaitForEvent(WPEFramework::Core::infinite); } - EXPECT_EQ(Properties::Unsubscribe(eventName, id1), FireboltSDKErrorNone); + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent2)), FireboltSDKErrorNone); delete eventControl2; } - EXPECT_EQ(Properties::Unsubscribe(eventName, id2), FireboltSDKErrorNone); + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent1)), FireboltSDKErrorNone); delete eventControl1; return status; @@ -248,12 +323,21 @@ namespace FireboltSDK { extern "C" { #endif -uint32_t test_firebolt_create_instance() +void test_firebolt_create_instance() { - FireboltSDK::Accessor::Instance(); + 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); } -uint32_t test_firebolt_dispose_instance() +void test_firebolt_dispose_instance() { FireboltSDK::Accessor::Dispose(); } @@ -297,28 +381,27 @@ uint32_t test_properties_set() return status; } -static void deviceNameChangeCallbackForC(const void* userData, void* response) +static void deviceNameChangeCallbackForC(void* userCB, const void* userData, void* response) { - WPEFramework::Core::ProxyType& jsonResponse = *(static_cast*>(response)); + WPEFramework::Core::ProxyType& jsonResponse = *(reinterpret_cast*>(response)); FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", "Received a new event--->: %s", jsonResponse->Value().c_str()); - jsonResponse.Release(); FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); eventControl->NotifyEvent(); + jsonResponse.Release(); } uint32_t test_eventregister() { FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); - JsonObject parameters; - const string eventName = _T("device.Name"); const void* userdata = static_cast(eventControl); - uint32_t id = 0; eventControl->ResetEvent(); - uint32_t status = FireboltSDK::Properties::Subscribe(eventName, deviceNameChangeCallbackForC, userdata, id); + + JsonObject jsonParameters; + uint32_t status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -326,26 +409,60 @@ uint32_t test_eventregister() "%s Set %s status = %d", __func__, eventName.c_str(), status); } else { FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "%s Yes registered successfully", __func__); + "%s Yes registered successfully, Waiting for event...", __func__); eventControl->WaitForEvent(WPEFramework::Core::infinite); } delete eventControl; - EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); return status; } +uint32_t test_eventregister_with_same_callback() +{ + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + + eventControl->ResetEvent(); + + JsonObject jsonParameters; + uint32_t status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Set %s status = %d", __func__, eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes registered successfully", __func__); + + status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); + EXPECT_EQ(status, FireboltSDKErrorInUse); + if (status == FireboltSDKErrorInUse) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes this device.name event is already registered with same callback", __func__); + } + status = ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone : status); + } + + delete eventControl; + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + + return status; +} uint32_t test_eventregister_by_providing_callback() { FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); const string eventName = _T("device.Name"); const void* userdata = static_cast(eventControl); - uint32_t id = 0; eventControl->ResetEvent(); - uint32_t status = FireboltSDK::Tests::SubscribeEventForC(eventName, deviceNameChangeCallbackForC, userdata, id); + + JsonObject jsonParameters; + uint32_t status = FireboltSDK::Tests::SubscribeEventForC(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -353,20 +470,22 @@ uint32_t test_eventregister_by_providing_callback() "%s Set %s status = %d", __func__, eventName.c_str(), status); } else { FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "%s Yes registered successfully", __func__); + "%s Yes registered successfully, Waiting for event...", __func__); eventControl->WaitForEvent(WPEFramework::Core::infinite); } delete eventControl; - EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, id), FireboltSDKErrorNone); + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + return status; } #include "TypesPriv.h" uint32_t test_string_set_get_value() { uint32_t status = FireboltSDKErrorNone; - FireboltSDK::String* str = new FireboltSDK::String("testString"); - void* handle = static_cast(str); + FireboltSDK::JSON::String* str = new FireboltSDK::JSON::String(); + WPEFramework::Core::JSON::String wpeJsonStr("TestString"); + FireboltTypes_String_t handle = reinterpret_cast(str); const char* value = FireboltTypes_String(handle); EXPECT_EQ(strncmp(value, str->Value().c_str(), str->Value().length()), 0); diff --git a/languages/c/templates/sdk/test/OpenRPCTests.h b/languages/c/templates/sdk/test/OpenRPCTests.h index 00abd364..e82665d0 100644 --- a/languages/c/templates/sdk/test/OpenRPCTests.h +++ b/languages/c/templates/sdk/test/OpenRPCTests.h @@ -18,8 +18,15 @@ #pragma once +#include "FireboltSDK.h" #include "TestUtils.h" -#include "Firebolt.h" + +typedef enum { + Test1, + Test2, + Test3, + Test4 +} TestEnum; namespace FireboltSDK { typedef uint32_t (*Func)(); @@ -30,6 +37,12 @@ namespace FireboltSDK { public: EventControl() : _event(false, true) + , _name("EventControl") + { + } + EventControl(string name) + : _event(false, true) + , _name(name) { } ~EventControl() = default; @@ -47,8 +60,13 @@ namespace FireboltSDK { { _event.ResetEvent(); } + string Name() const + { + return _name; + } private: WPEFramework::Core::Event _event; + string _name; }; private: @@ -84,10 +102,11 @@ namespace FireboltSDK { static uint32_t SetUnKnownMethod(); static uint32_t SubscribeEvent(); + static uint32_t SubscribeEventwithSameCallback(); static uint32_t SubscribeEventWithMultipleCallback(); template - static uint32_t SubscribeEventForC(const string& eventName, CALLBACK& callbackFunc, const void* userdata, uint32_t& id); + static uint32_t SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata); protected: static void PrintJsonObject(const JsonObject::Iterator& iterator); diff --git a/languages/c/templates/sdk/test/TestUtils.h b/languages/c/templates/sdk/test/TestUtils.h index 8c3cb732..c54db9f0 100644 --- a/languages/c/templates/sdk/test/TestUtils.h +++ b/languages/c/templates/sdk/test/TestUtils.h @@ -1,5 +1,5 @@ -#ifndef _TEST_UTILS_H -#define _TEST_UTILS_H +#ifndef TEST_UTILS_H +#define TEST_UTILS_H #include #include @@ -8,8 +8,8 @@ #define MAX(x, y) (((x) > (y)) ? (x) : (y)) #define MIN(x, y) (((x) < (y)) ? (x) : (y)) -#define _RESULT(expr, exprorig, result) if (expr) { printf(" SUCCESS: %s\n", #exprorig); __pass++; } else printf(" FAILED: %s, actual: %u\n", #exprorig, result) -#define _EVAL(result, expected, op) do { __cnt++; uint32_t resval = ((uint32_t)(result)); uint32_t expval = ((uint32_t)(expected)); _RESULT(resval op expval, result op expected, resval); } while(0) +#define _RESULT(expr, exprorig, result) if (expr) { printf("TestStatus: SUCCESS: %s\n", #exprorig); __pass++; } else printf("TestStatus: FAILED: %s, actual: %lu\n", #exprorig, result) +#define _EVAL(result, expected, op) do { __cnt++; long resval = ((long)(result)); long expval = ((long)(expected)); _RESULT(resval op expval, result op expected, resval); } while(0) #define _HEAD(name) printf("\n======== %s\n", name); __cnt = 0; __pass = 0 #define _FOOT(name) printf("\n======== %s - %i PASSED, %i FAILED\n", name, __pass, (__cnt - __pass)); TotalTests += __cnt; TotalTestsPassed += __pass; @@ -35,4 +35,4 @@ extern int TotalTestsPassed; } #endif -#endif // _TEST_UTILS_H +#endif // TEST_UTILS_H diff --git a/languages/c/templates/types/enum.cpp b/languages/c/templates/types/enum.cpp index ddda2ae9..9c98f888 100644 --- a/languages/c/templates/types/enum.cpp +++ b/languages/c/templates/types/enum.cpp @@ -1,4 +1,4 @@ /* ${title} ${description} */ - ENUM_CONVERSION_BEGIN(${info.title}_${name}) + ENUM_CONVERSION_BEGIN(${info.Title}_${name}) { ${info.TITLE}_${NAME}_${key}, _T("${value}") }, - ENUM_CONVERSION_END(${info.title}_${name}) + ENUM_CONVERSION_END(${info.Title}_${name}) diff --git a/languages/c/templates/types/enum.h b/languages/c/templates/types/enum.h index 6926fa77..906d908d 100644 --- a/languages/c/templates/types/enum.h +++ b/languages/c/templates/types/enum.h @@ -1,4 +1,4 @@ /* ${title} ${description} */ typedef enum { ${info.TITLE}_${NAME}_${key}, -} ${info.title}_${name}; +} ${info.Title}_${name}; diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index c316088d..09c50b85 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -506,6 +506,8 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{minor\}/g, macros.version.minor) fContents = fContents.replace(/\$\{patch\}/g, macros.version.patch) fContents = fContents.replace(/\$\{info\.title\}/g, macros.title) + fContents = fContents.replace(/\$\{info\.title\.lowercase\}/g, macros.title.toLowerCase()) + fContents = fContents.replace(/\$\{info\.Title\}/g, capitalize(macros.title)) fContents = fContents.replace(/\$\{info\.TITLE\}/g, macros.title.toUpperCase()) fContents = fContents.replace(/\$\{info\.description\}/g, macros.description) fContents = fContents.replace(/\$\{info\.version\}/g, macros.version.readable) @@ -830,12 +832,12 @@ const generateImports = (json, templates, options = { destination: '' }) => { } if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0 && !json.info['x-uri-titles']) { - imports += Object.keys(json['x-schemas']).map(shared => template.replace(/\$\{info.title\}/g, shared)).join('') + imports += Object.keys(json['x-schemas']).map(shared => template.replace(/\$\{info.title.lowercase\}/g, shared.toLowerCase())).join('') } let componentExternalSchema = getComponentExternalSchema(json) if (componentExternalSchema.length && json.info['x-uri-titles']) { - imports += componentExternalSchema.map(shared => template.replace(/\$\{info.title\}/g, shared)).join('') + imports += componentExternalSchema.map(shared => template.replace(/\$\{info.title.lowercase\}/g, shared.toLowerCase())).join('') } return imports } @@ -1149,6 +1151,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{event\.callback\.params\.serialization\}/g, callbackSerializedParams) .replace(/\$\{event\.callback\.result\.instantiation\}/g, callbackResultInst) .replace(/\$\{event\.callback\.response\.instantiation\}/g, callbackResponseInst) + .replace(/\$\{info\.title\.lowercase\}/g, info.title.toLowerCase()) .replace(/\$\{info\.title\}/g, info.title) .replace(/\$\{info\.Title\}/g, capitalize(info.title)) .replace(/\$\{info\.TITLE\}/g, info.title.toUpperCase()) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 3db5d17a..dc5f30e8 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -167,7 +167,7 @@ const macrofy = async ( content = engine.insertMacros(content, macros) content = engine.insertAggregateMacros(content, aggregateMacros) - const location = createModuleDirectories ? path.join(output, module.info.title, t) : path.join(output, t.replace(/Module/, module.info.title).replace(/index/, module.info.title)) + const location = createModuleDirectories ? path.join(output, module.info.title, t) : path.join(output, t.replace(/module/, module.info.title.toLowerCase()).replace(/index/, module.info.title)) outputFiles[location] = content logSuccess(`Generated macros for module ${path.relative(output, location)}`) @@ -262,7 +262,7 @@ const macrofy = async ( // NOTE: whichever insert is called first also needs to be called again last, so each phase can insert recursive macros from the other content = engine.insertMacros(content, macros) - const location = createModuleDirectories ? path.join(output, document.info.title, t) : path.join(output, t.replace(/Module/, document.info.title).replace(/index/, document.info.title)) + const location = createModuleDirectories ? path.join(output, document.info.title, t) : path.join(output, t.replace(/module/, document.info.title.toLowerCase()).replace(/index/, document.info.title)) outputFiles[location] = content logSuccess(`Generated macros for schema ${path.relative(output, location)}`) From 76d90098925600585e743efb8e310d2195814b11 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 09:15:34 +0530 Subject: [PATCH 088/137] language-c: re-arrange files locations (#112) language-c: re-arrange files locations --- .../sdk => src/shared}/CMakeLists.txt | 0 .../shared}/cmake/HelperFunctions.cmake | 0 .../sdk => src/shared}/cmake/project.cmake.in | 0 .../sdk => src/shared}/include/error.h | 0 .../sdk => src/shared}/include/firebolt.h | 0 .../sdk => src/shared}/include/types.h | 0 .../shared}/src/Accessor/Accessor.cpp | 0 .../shared}/src/Accessor/Accessor.h | 0 .../shared}/src/Accessor/WorkerPool.h | 0 .../sdk => src/shared}/src/CMakeLists.txt | 0 .../sdk => src/shared}/src/Event/Event.cpp | 0 .../sdk => src/shared}/src/Event/Event.h | 0 .../shared}/src/FireboltSDK.conf.in | 0 .../sdk => src/shared}/src/FireboltSDK.h | 0 .../sdk => src/shared}/src/Logger/Logger.cpp | 0 .../sdk => src/shared}/src/Logger/Logger.h | 0 .../sdk => src/shared}/src/Module.cpp | 0 .../sdk => src/shared}/src/Module.h | 0 .../shared}/src/Properties/Properties.h | 0 .../shared}/src/Transport/Transport.cpp | 0 .../shared}/src/Transport/Transport.h | 0 .../sdk => src/shared}/src/Types.cpp | 0 .../sdk => src/shared}/src/TypesPriv.h | 0 .../sdk => src/shared}/src/firebolt.cpp | 0 .../sdk => src/shared}/test/CMakeLists.txt | 0 .../{templates/sdk => src/shared}/test/Main.c | 0 .../sdk => src/shared}/test/Module.cpp | 0 .../sdk => src/shared}/test/Module.h | 0 .../sdk => src/shared}/test/OpenRPCCTests.h | 0 .../sdk => src/shared}/test/OpenRPCTests.cpp | 0 .../sdk => src/shared}/test/OpenRPCTests.h | 0 .../sdk => src/shared}/test/TestUtils.h | 0 languages/c/templates/sdk/scripts/install.js | 32 --------- languages/c/templates/sdk/scripts/install.sh | 65 +++++++++++++++++++ 34 files changed, 65 insertions(+), 32 deletions(-) rename languages/c/{templates/sdk => src/shared}/CMakeLists.txt (100%) rename languages/c/{templates/sdk => src/shared}/cmake/HelperFunctions.cmake (100%) rename languages/c/{templates/sdk => src/shared}/cmake/project.cmake.in (100%) rename languages/c/{templates/sdk => src/shared}/include/error.h (100%) rename languages/c/{templates/sdk => src/shared}/include/firebolt.h (100%) rename languages/c/{templates/sdk => src/shared}/include/types.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Accessor/Accessor.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/Accessor/Accessor.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Accessor/WorkerPool.h (100%) rename languages/c/{templates/sdk => src/shared}/src/CMakeLists.txt (100%) rename languages/c/{templates/sdk => src/shared}/src/Event/Event.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/Event/Event.h (100%) rename languages/c/{templates/sdk => src/shared}/src/FireboltSDK.conf.in (100%) rename languages/c/{templates/sdk => src/shared}/src/FireboltSDK.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Logger/Logger.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/Logger/Logger.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Module.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/Module.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Properties/Properties.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Transport/Transport.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/Transport/Transport.h (100%) rename languages/c/{templates/sdk => src/shared}/src/Types.cpp (100%) rename languages/c/{templates/sdk => src/shared}/src/TypesPriv.h (100%) rename languages/c/{templates/sdk => src/shared}/src/firebolt.cpp (100%) rename languages/c/{templates/sdk => src/shared}/test/CMakeLists.txt (100%) rename languages/c/{templates/sdk => src/shared}/test/Main.c (100%) rename languages/c/{templates/sdk => src/shared}/test/Module.cpp (100%) rename languages/c/{templates/sdk => src/shared}/test/Module.h (100%) rename languages/c/{templates/sdk => src/shared}/test/OpenRPCCTests.h (100%) rename languages/c/{templates/sdk => src/shared}/test/OpenRPCTests.cpp (100%) rename languages/c/{templates/sdk => src/shared}/test/OpenRPCTests.h (100%) rename languages/c/{templates/sdk => src/shared}/test/TestUtils.h (100%) delete mode 100644 languages/c/templates/sdk/scripts/install.js create mode 100755 languages/c/templates/sdk/scripts/install.sh diff --git a/languages/c/templates/sdk/CMakeLists.txt b/languages/c/src/shared/CMakeLists.txt similarity index 100% rename from languages/c/templates/sdk/CMakeLists.txt rename to languages/c/src/shared/CMakeLists.txt diff --git a/languages/c/templates/sdk/cmake/HelperFunctions.cmake b/languages/c/src/shared/cmake/HelperFunctions.cmake similarity index 100% rename from languages/c/templates/sdk/cmake/HelperFunctions.cmake rename to languages/c/src/shared/cmake/HelperFunctions.cmake diff --git a/languages/c/templates/sdk/cmake/project.cmake.in b/languages/c/src/shared/cmake/project.cmake.in similarity index 100% rename from languages/c/templates/sdk/cmake/project.cmake.in rename to languages/c/src/shared/cmake/project.cmake.in diff --git a/languages/c/templates/sdk/include/error.h b/languages/c/src/shared/include/error.h similarity index 100% rename from languages/c/templates/sdk/include/error.h rename to languages/c/src/shared/include/error.h diff --git a/languages/c/templates/sdk/include/firebolt.h b/languages/c/src/shared/include/firebolt.h similarity index 100% rename from languages/c/templates/sdk/include/firebolt.h rename to languages/c/src/shared/include/firebolt.h diff --git a/languages/c/templates/sdk/include/types.h b/languages/c/src/shared/include/types.h similarity index 100% rename from languages/c/templates/sdk/include/types.h rename to languages/c/src/shared/include/types.h diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.cpp b/languages/c/src/shared/src/Accessor/Accessor.cpp similarity index 100% rename from languages/c/templates/sdk/src/Accessor/Accessor.cpp rename to languages/c/src/shared/src/Accessor/Accessor.cpp diff --git a/languages/c/templates/sdk/src/Accessor/Accessor.h b/languages/c/src/shared/src/Accessor/Accessor.h similarity index 100% rename from languages/c/templates/sdk/src/Accessor/Accessor.h rename to languages/c/src/shared/src/Accessor/Accessor.h diff --git a/languages/c/templates/sdk/src/Accessor/WorkerPool.h b/languages/c/src/shared/src/Accessor/WorkerPool.h similarity index 100% rename from languages/c/templates/sdk/src/Accessor/WorkerPool.h rename to languages/c/src/shared/src/Accessor/WorkerPool.h diff --git a/languages/c/templates/sdk/src/CMakeLists.txt b/languages/c/src/shared/src/CMakeLists.txt similarity index 100% rename from languages/c/templates/sdk/src/CMakeLists.txt rename to languages/c/src/shared/src/CMakeLists.txt diff --git a/languages/c/templates/sdk/src/Event/Event.cpp b/languages/c/src/shared/src/Event/Event.cpp similarity index 100% rename from languages/c/templates/sdk/src/Event/Event.cpp rename to languages/c/src/shared/src/Event/Event.cpp diff --git a/languages/c/templates/sdk/src/Event/Event.h b/languages/c/src/shared/src/Event/Event.h similarity index 100% rename from languages/c/templates/sdk/src/Event/Event.h rename to languages/c/src/shared/src/Event/Event.h diff --git a/languages/c/templates/sdk/src/FireboltSDK.conf.in b/languages/c/src/shared/src/FireboltSDK.conf.in similarity index 100% rename from languages/c/templates/sdk/src/FireboltSDK.conf.in rename to languages/c/src/shared/src/FireboltSDK.conf.in diff --git a/languages/c/templates/sdk/src/FireboltSDK.h b/languages/c/src/shared/src/FireboltSDK.h similarity index 100% rename from languages/c/templates/sdk/src/FireboltSDK.h rename to languages/c/src/shared/src/FireboltSDK.h diff --git a/languages/c/templates/sdk/src/Logger/Logger.cpp b/languages/c/src/shared/src/Logger/Logger.cpp similarity index 100% rename from languages/c/templates/sdk/src/Logger/Logger.cpp rename to languages/c/src/shared/src/Logger/Logger.cpp diff --git a/languages/c/templates/sdk/src/Logger/Logger.h b/languages/c/src/shared/src/Logger/Logger.h similarity index 100% rename from languages/c/templates/sdk/src/Logger/Logger.h rename to languages/c/src/shared/src/Logger/Logger.h diff --git a/languages/c/templates/sdk/src/Module.cpp b/languages/c/src/shared/src/Module.cpp similarity index 100% rename from languages/c/templates/sdk/src/Module.cpp rename to languages/c/src/shared/src/Module.cpp diff --git a/languages/c/templates/sdk/src/Module.h b/languages/c/src/shared/src/Module.h similarity index 100% rename from languages/c/templates/sdk/src/Module.h rename to languages/c/src/shared/src/Module.h diff --git a/languages/c/templates/sdk/src/Properties/Properties.h b/languages/c/src/shared/src/Properties/Properties.h similarity index 100% rename from languages/c/templates/sdk/src/Properties/Properties.h rename to languages/c/src/shared/src/Properties/Properties.h diff --git a/languages/c/templates/sdk/src/Transport/Transport.cpp b/languages/c/src/shared/src/Transport/Transport.cpp similarity index 100% rename from languages/c/templates/sdk/src/Transport/Transport.cpp rename to languages/c/src/shared/src/Transport/Transport.cpp diff --git a/languages/c/templates/sdk/src/Transport/Transport.h b/languages/c/src/shared/src/Transport/Transport.h similarity index 100% rename from languages/c/templates/sdk/src/Transport/Transport.h rename to languages/c/src/shared/src/Transport/Transport.h diff --git a/languages/c/templates/sdk/src/Types.cpp b/languages/c/src/shared/src/Types.cpp similarity index 100% rename from languages/c/templates/sdk/src/Types.cpp rename to languages/c/src/shared/src/Types.cpp diff --git a/languages/c/templates/sdk/src/TypesPriv.h b/languages/c/src/shared/src/TypesPriv.h similarity index 100% rename from languages/c/templates/sdk/src/TypesPriv.h rename to languages/c/src/shared/src/TypesPriv.h diff --git a/languages/c/templates/sdk/src/firebolt.cpp b/languages/c/src/shared/src/firebolt.cpp similarity index 100% rename from languages/c/templates/sdk/src/firebolt.cpp rename to languages/c/src/shared/src/firebolt.cpp diff --git a/languages/c/templates/sdk/test/CMakeLists.txt b/languages/c/src/shared/test/CMakeLists.txt similarity index 100% rename from languages/c/templates/sdk/test/CMakeLists.txt rename to languages/c/src/shared/test/CMakeLists.txt diff --git a/languages/c/templates/sdk/test/Main.c b/languages/c/src/shared/test/Main.c similarity index 100% rename from languages/c/templates/sdk/test/Main.c rename to languages/c/src/shared/test/Main.c diff --git a/languages/c/templates/sdk/test/Module.cpp b/languages/c/src/shared/test/Module.cpp similarity index 100% rename from languages/c/templates/sdk/test/Module.cpp rename to languages/c/src/shared/test/Module.cpp diff --git a/languages/c/templates/sdk/test/Module.h b/languages/c/src/shared/test/Module.h similarity index 100% rename from languages/c/templates/sdk/test/Module.h rename to languages/c/src/shared/test/Module.h diff --git a/languages/c/templates/sdk/test/OpenRPCCTests.h b/languages/c/src/shared/test/OpenRPCCTests.h similarity index 100% rename from languages/c/templates/sdk/test/OpenRPCCTests.h rename to languages/c/src/shared/test/OpenRPCCTests.h diff --git a/languages/c/templates/sdk/test/OpenRPCTests.cpp b/languages/c/src/shared/test/OpenRPCTests.cpp similarity index 100% rename from languages/c/templates/sdk/test/OpenRPCTests.cpp rename to languages/c/src/shared/test/OpenRPCTests.cpp diff --git a/languages/c/templates/sdk/test/OpenRPCTests.h b/languages/c/src/shared/test/OpenRPCTests.h similarity index 100% rename from languages/c/templates/sdk/test/OpenRPCTests.h rename to languages/c/src/shared/test/OpenRPCTests.h diff --git a/languages/c/templates/sdk/test/TestUtils.h b/languages/c/src/shared/test/TestUtils.h similarity index 100% rename from languages/c/templates/sdk/test/TestUtils.h rename to languages/c/src/shared/test/TestUtils.h diff --git a/languages/c/templates/sdk/scripts/install.js b/languages/c/templates/sdk/scripts/install.js deleted file mode 100644 index 5c332ceb..00000000 --- a/languages/c/templates/sdk/scripts/install.js +++ /dev/null @@ -1,32 +0,0 @@ -import { createRequire } from 'module'; -const require = createRequire(import.meta.url); -const fs = require('fs'); -const path = require('path'); - -var dest = process.env.NODE_INSTALL_PATH; -var src = 'src/native/build/' + process.env.TARGET_NAME; - -installFiles(src, dest); -function installFiles(src, dest) { - if (!fs.existsSync(dest)) { - fs.mkdirSync(dest); - } - - var entries = fs.readdirSync(src); - entries.forEach((entry) => { - const srcPath = path.join(src, entry); - const destPath = path.join(dest, entry); - const stat = fs.lstatSync(srcPath); - - if (stat.isFile()) { - fs.copyFileSync(srcPath, destPath); - } else if (stat.isDirectory()) { - installFiles(srcPath, destPath); - } else if (stat.isSymbolicLink()) { - if (fs.existsSync(destPath)) { - fs.unlinkSync(destPath); - } - fs.symlinkSync(fs.readlinkSync(srcPath), destPath); - } - }); -} diff --git a/languages/c/templates/sdk/scripts/install.sh b/languages/c/templates/sdk/scripts/install.sh new file mode 100755 index 00000000..69c2d66a --- /dev/null +++ b/languages/c/templates/sdk/scripts/install.sh @@ -0,0 +1,65 @@ +#!/bin/bash +usage() +{ + echo "options:" + echo " -i install path" + echo " -s sdk path" + echo " -t include test" + echo " -m module name. i.e, core/manage" + echo + echo "usage: " + echo " ./install.sh -p path" +} + +SdkPath=".." +InstallPath=".." +IncludeTest="OFF" +ModuleName="core" +while getopts i:s:m:th flag +do + case "${flag}" in + i) InstallPath="${OPTARG}";; + s) SdkPath="${OPTARG}";; + m) ModuleName="${OPTARG}";; + t) IncludeTest="ON";; + h) usage && exit 1;; + esac +done + +GetVersion() +{ + PackagePath=${SdkPath}/../../../../../../package-lock.json + InputKey="name\": \"@firebolt-js/openrpc" + LineNo="$(grep -n "${InputKey}" ${PackagePath} | head -n 1 | cut -d: -f1)" + VersionLine=$((LineNo++)) + eval "array=(`sed -n "${LineNo}p" < ${PackagePath} | sed 's/\"/\n/g'`)" + Version=${array[2]} +} + +Version=0.0 +GetVersion +ReleaseName=firebolt-${ModuleName}-native-sdk-${Version} +ReleasePath=${InstallPath}/${ReleaseName} + +rm -rf ${ReleasePath} +mkdir -p ${ReleasePath} +cp -ar ${SdkPath}/src ${ReleasePath} +cp -ar ${SdkPath}/include ${ReleasePath} +cp -ar ${SdkPath}/cmake ${ReleasePath} +cp -ar ${SdkPath}/scripts/build.sh ${ReleasePath} +cp -ar ${SdkPath}/CMakeLists.txt ${ReleasePath} + +if [ "${IncludeTest}" == "ON" ]; +then + cp -ar ${SdkPath}/ctest ${ReleasePath}/test +fi + +sed -i '/EnableTest="ON";;/d' ${ReleasePath}/build.sh +sed -i 's/getopts p:s:tch/getopts p:s:ch/g' ${ReleasePath}/build.sh +sed -i '/enable test/d' ${ReleasePath}/build.sh +sed -i '/EnableTest="OFF"/d' ${ReleasePath}/build.sh +sed -i 's/ -DENABLE_TESTS=${EnableTest}//g' ${ReleasePath}/build.sh + +cd ${ReleasePath}/../ +tar -cvzf ${ReleaseName}.tgz ${ReleaseName}/* +cd - From 2f866c22738e9c0d7dd9f20871df3cacbd5bfee0 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 09:16:03 +0530 Subject: [PATCH 089/137] fixes to generate array inside subschemas (#111) --- languages/c/Types.mjs | 35 ++++++++--------- languages/c/src/types/ImplHelpers.mjs | 4 +- languages/c/src/types/JSONHelpers.mjs | 2 +- languages/c/src/types/NativeHelpers.mjs | 48 +---------------------- languages/c/templates/codeblocks/export.c | 1 - src/macrofier/engine.mjs | 25 +++++++----- 6 files changed, 38 insertions(+), 77 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 1ed84940..d8cae205 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -18,7 +18,7 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' -import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getArrayElementSchema, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' +import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation, getCallbackParametersInstantiation, getCallbackResultInstantiation, getCallbackResponseInstantiation } from './src/types/ImplHelpers.mjs' import { getJsonContainerDefinition, getJsonDataStructName, getJsonDataPrefix } from './src/types/JSONHelpers.mjs' @@ -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 } @@ -302,8 +303,10 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref res = getSchemaTypeInfo(module, json.items, json.items.name || name, schemas, prefix) } + + prefix = prefix ? prefix + name : name let n = getTypeName(getModuleName(module), capitalize(res.name), prefix) - structure.name = res.name || name && (capitalize(name)) + structure.name = name ? name + capitalize(res.name) : res.name structure.type = n + 'Array_t' structure.json = json structure.namespace = getModuleName(module) @@ -525,24 +528,19 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' else { j = json.items } - shape += getSchemaShapeInfo(j, module, schemas, { name: j.title || name, prefix, merged, level, title, summary, descriptions, destination, section, enums }) if (!isCPP) { - let info = getSchemaTypeInfo(module, j, j.title || name, schemas, prefix, {level : level, descriptions: descriptions, title: true}) + let subPrefix = prefix ? prefix + name : name + let info = getSchemaTypeInfo(module, j, j.title || name, schemas, subPrefix, {level : level, descriptions: descriptions, title: true}) if (info.type && info.type.length > 0) { - let type = getArrayElementSchema(json, module, schemas, info.name) - let arrayName = capitalize(info.name) + capitalize(type.type) - let namespace = info.namespace - if (type && type.type === 'object') { - namespace = getModuleName(module) - } - let objName = getTypeName(namespace, arrayName, prefix) + let arrayName = capitalize(info.name); + let objName = getTypeName(getModuleName(module), arrayName, subPrefix) let tName = objName + 'Array' info.json.namespace = info.namespace let moduleProperty = getJsonTypeInfo(module, json, json.title || name, schemas, prefix) - let subModuleProperty = getJsonTypeInfo(module, j, j.title, schemas, prefix) + let subModuleProperty = getJsonTypeInfo(module, j, j.title || name, schemas, prefix) let t = '' if (level === 0) { t += description(capitalize(info.name), json.description) + '\n' @@ -666,6 +664,7 @@ function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '' items = json.items // grab the type for the non-array schema } + res = getJsonTypeInfo(module, items, items.name || name, schemas, prefix) structure.deps = res.deps structure.type.push(`WPEFramework::Core::JSON::ArrayType<${res.type}>`) @@ -733,7 +732,7 @@ const enumReducer = (acc, val, i, arr) => { return acc } -function getSchemaInstantiation(schema, module, name, { instantiationType = '' } = {}) { +function getSchemaInstantiation(schema, module, name, { instantiationType = '', prefix = '' } = {}) { if (instantiationType === 'params') { return getParameterInstantiation(getParamList(schema, module)) @@ -752,17 +751,17 @@ function getSchemaInstantiation(schema, module, name, { instantiationType = '' } return result } else if (instantiationType === 'callback.params') { - let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' + let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name, prefix }) || '' return getCallbackParametersInstantiation(getParamList(schema, module), resultJsonType) } else if (instantiationType === 'callback.result') { - let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' + let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, prefix, resultSchema: true}) || '' let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' return getCallbackResultInstantiation(resultType, resultJsonType) } else if (instantiationType === 'callback.response') { - let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, resultSchema: true}) || '' - let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name }) || '' + let resultType = getSchemaType(schema.result.schema, module, { title: true, name: schema.result.name, prefix, resultSchema: true}) || '' + let resultJsonType = getJsonType(schema.result.schema, module, { name: schema.result.name, prefix }) || '' return getCallbackResponseInstantiation(getParamList(schema, module), resultType, resultJsonType) } else if (instantiationType === 'pull.param.name') { diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index 5b373377..8dbe8f08 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -49,7 +49,7 @@ const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); ` + '\n' - if ((json.type === 'object') && (accessorPropertyType !== 'char*')) { + if (((json.type === 'object') || (json.type === 'array')) && (accessorPropertyType !== 'char*')) { result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* element = new WPEFramework::Core::ProxyType<${subPropertyType}>(); *element = WPEFramework::Core::ProxyType<${subPropertyType}>::Create(); *(*element) = (*var)->${subPropertyName}; @@ -73,7 +73,7 @@ const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, ASSERT(var->IsValid()); ` + '\n' - if (json.type === 'object' && (accessorPropertyType !== 'char*')) { + if (((json.type === 'object') || (json.type === 'array')) && (accessorPropertyType !== 'char*')) { result += ` WPEFramework::Core::ProxyType<${subPropertyType}>* object = reinterpret_cast*>(value); (*var)->${subPropertyName} = *(*object);` + '\n' } diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index cc31b14a..009beb99 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -4,7 +4,7 @@ const getJsonDataPrefix = () => 'JsonData_' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' const getJsonDataStructName = (modName, name, prefix = '') => { - let result =((prefix.length > 0) && (!name.startsWith(prefix))) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}_${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` + let result =((prefix.length > 0) && (prefix !== name)) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` return ((result.includes(wpeJsonNameSpace()) === true) ? result : `${getSdkNameSpace()}::${result}`) } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 7bfef987..8d00199e 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -30,18 +30,7 @@ const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = pre const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' const getFireboltStringType = () => 'FireboltTypes_String_t' -const getHeaderText = () => { - return `/* -* Copyright 2022 Comcast -* -* Auto Generated using firebolt-openrpc tools. DO NOT EDIT. -* -*/ - -` -} - const capitalize = str => str[0].toUpperCase() + str.substr(1) const description = (title, str='') => '/* ' + title + (str.length > 0 ? ' - ' + str : '') + ' */' const isOptional = (prop, json) => (!json.required || !json.required.includes(prop)) @@ -50,37 +39,6 @@ const SdkTypesPrefix = 'Firebolt' const Indent = ' ' -const getArrayElementSchema = (json, module, schemas = {}, name) => { - let result = '' - if (json.type === 'array' && json.items) { - if (Array.isArray(json.items)) { - result = json.items[0] - } - else { - // grab the type for the non-array schema - result = json.items - } - if (result['$ref']) { - result = getPath(result['$ref'], module, schemas) - } - } - else if (json.type == 'object') { - if (json.properties) { - Object.entries(json.properties).every(([pname, prop]) => { - if (prop.type === 'array') { - result = getArrayElementSchema(prop, module, schemas) - if (name === capitalize(pname)) { - return false - } - } - return true - }) - } - } - - return result -} - const getNativeType = (json, fireboltString = false) => { let type let jsonType = json.const ? typeof json.const : json.type @@ -150,10 +108,10 @@ const getTypeName = (moduleName, varName, prefix = '', upperCase = false, capita let mName = upperCase ? moduleName.toUpperCase() : capitalize(moduleName) let vName = upperCase ? varName.toUpperCase() : capitalCase ? capitalize(varName) : varName if (prefix.length > 0) { - prefix = (!varName.startsWith(prefix)) ? (upperCase ? prefix.toUpperCase() : capitalize(prefix)) : '' + prefix = (prefix !== varName) ? (upperCase ? prefix.toUpperCase() : capitalize(prefix)) : '' } prefix = (prefix.length > 0) ?(upperCase ? prefix.toUpperCase() : capitalize(prefix)) : prefix - let name = (prefix.length > 0) ? `${mName}_${prefix}_${vName}` : `${mName}_${vName}` + let name = (prefix.length > 0) ? `${mName}_${prefix}${vName}` : `${mName}_${vName}` return name } @@ -235,7 +193,6 @@ function getPropertyEventUnregisterSignature(property, module) { export { - getHeaderText, getNativeType, getModuleName, getPropertyGetterSignature, @@ -252,6 +209,5 @@ export { getPropertyAccessors, isOptional, generateEnum, - getArrayElementSchema, getFireboltStringType } diff --git a/languages/c/templates/codeblocks/export.c b/languages/c/templates/codeblocks/export.c index c98498e4..e69de29b 100644 --- a/languages/c/templates/codeblocks/export.c +++ b/languages/c/templates/codeblocks/export.c @@ -1 +0,0 @@ -export { default as ${info.title} } from './${info.title}/index.mjs' \ No newline at end of file diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 09c50b85..73661d53 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -361,7 +361,7 @@ const addContentDescriptorSubSchema = (descriptor, prefix, obj) => { } // only consider sub-objects and sub enums to be sub-schemas -const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) +const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) || (schema.type === 'array' && schema.items) const promoteAndNameSubSchemas = (obj) => { // make a copy so we don't polute our inputs @@ -384,7 +384,7 @@ const promoteAndNameSubSchemas = (obj) => { while (more) { more = false Object.entries(obj.components.schemas).forEach(([key, schema]) => { - if (schema.type === "object" && schema.properties) { + if ((schema.type === "object") && schema.properties) { Object.entries(schema.properties).forEach(([name, propSchema]) => { if (isSubSchema(propSchema)) { more = true @@ -584,10 +584,11 @@ function insertTableofContents(content) { } const convertEnumTemplate = (schema, templateName, templates) => { + let enumSchema = isArraySchema(schema) ? schema.items : schema const template = getTemplate(templateName, templates).split('\n') for (var i = 0; i < template.length; i++) { if (template[i].indexOf('${key}') >= 0) { - template[i] = schema.enum.map(value => { + template[i] = enumSchema.enum.map(value => { const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() return template[i].replace(/\$\{key\}/g, safeName) .replace(/\$\{value\}/g, value) @@ -695,7 +696,12 @@ function sortSchemasByReference(schemas = []) { return schemas } -const isEnum = x => x.type && x.type === 'string' && Array.isArray(x.enum) && x.title +const isArraySchema = x => x.type && x.type === 'array' && x.items + +const isEnum = x => { + let schema = isArraySchema(x) ? x.items : x + return schema.type && schema.type === 'string' && Array.isArray(schema.enum) && x.title +} function generateSchemas(json, templates, options) { let results = [] @@ -1091,9 +1097,10 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) const serializedParams = types.getSchemaInstantiation(methodObj, json, methodObj.name, { instantiationType: 'params' }) const resultInst = types.getSchemaInstantiation(result.schema, json, result.name, { instantiationType: 'result' } ) const serializedEventParams = event ? indent(types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'params' }), ' ') : '' - const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.params' }) : '' - const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.result' }) : '' - const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.response' }) : '' + const callbackSerializedParams = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.params', prefix: method.alternative }) : '' + const callbackResultInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.result', prefix: method.alternative }) : '' + const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.response', prefix: method.alternative }) : '' + const callbackResultJsonType = event && result.schema ? types.getJsonType(result.schema, json, { name: result.name, prefix: method.alternative }) : '' const resultType = result.schema ? types.getSchemaType(result.schema, json, { name: result.name }) : '' const resultJsonType = result.schema ? types.getJsonType(result.schema, json, { name: result.name }) : '' @@ -1169,8 +1176,8 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .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, title: true, asPath: false, destination: state.destination, resultSchema: true })) //, baseUrl: options.baseUrl .replace(/\$\{method\.result\.json\}/, types.getJsonType(result.schema, json, { name: result.name, destination: state.destination, section: state.section, code: false, link: false, title: true, asPath: false, expandEnums: false })) - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') - .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) + .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, prefix: method.alternative, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') + .replace(/\$\{event\.result\.json\.type\}/g, callbackResultJsonType) .replace(/\$\{event\.pulls\.param\.name\}/g, pullsEventParamName) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) .replace(/\$\{method\.result\.json\.type\}/g, resultJsonType) From f9c324e85c91da8c39a9b5b009905add211aea91 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 20:09:16 +0530 Subject: [PATCH 090/137] include test always (#113) --- languages/c/templates/sdk/scripts/install.sh | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/languages/c/templates/sdk/scripts/install.sh b/languages/c/templates/sdk/scripts/install.sh index 69c2d66a..15596524 100755 --- a/languages/c/templates/sdk/scripts/install.sh +++ b/languages/c/templates/sdk/scripts/install.sh @@ -4,24 +4,21 @@ usage() echo "options:" echo " -i install path" echo " -s sdk path" - echo " -t include test" echo " -m module name. i.e, core/manage" echo echo "usage: " - echo " ./install.sh -p path" + echo " ./install.sh -i path -s sdk path-m core" } SdkPath=".." InstallPath=".." -IncludeTest="OFF" ModuleName="core" -while getopts i:s:m:th flag +while getopts i:s:m:h flag do case "${flag}" in i) InstallPath="${OPTARG}";; s) SdkPath="${OPTARG}";; m) ModuleName="${OPTARG}";; - t) IncludeTest="ON";; h) usage && exit 1;; esac done @@ -48,11 +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} - -if [ "${IncludeTest}" == "ON" ]; -then - cp -ar ${SdkPath}/ctest ${ReleasePath}/test -fi +cp -ar ${SdkPath}/ctest ${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 From 31ddf5e0a8c016360a9b84117ed03a5903b58c2a Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 20:09:40 +0530 Subject: [PATCH 091/137] use String type if there is any issue with anyOf merge (#114) --- languages/c/Types.mjs | 27 ++++++++++++++++++------- languages/c/src/types/JSONHelpers.mjs | 2 +- languages/c/src/types/NativeHelpers.mjs | 6 +++--- 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index d8cae205..1ee99224 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -82,7 +82,7 @@ function union(schemas, module, commonSchemas) { //console.warn(`Ignoring "${key}" that is already present and same`) } else { console.warn(`ERROR "${key}" is not same -${JSON.stringify(result, null, 4)} ${key} ${result[key]} - ${value}`); - throw "ERROR: type is not same" + return {} } } else { //If the Key is a const then merge them into an enum @@ -325,8 +325,14 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref } else if (json.anyOf) { let mergedSchema = getMergedSchema(module, json, name, schemas) - let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) - structure = getSchemaTypeInfo(module, mergedSchema, '', schemas, prefixName, options) + if (mergedSchema.type) { + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + structure = getSchemaTypeInfo(module, mergedSchema, '', schemas, prefixName, options) + } + else { + structure.type = fireboltString ? getFireboltStringType() : 'char*' + structure.json.type = 'string' + } } else if (json.type === 'object') { structure.json = json @@ -499,8 +505,10 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' else if (json.anyOf) { if (level > 0) { let mergedSchema = getMergedSchema(module, json, name, schemas) - let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) - shape += getSchemaShapeInfo(mergedSchema, module, schemas, { name, prefix: prefixName, merged, level, title, summary, descriptions, destination, section, enums }) + if (mergedSchema.type) { + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + shape += getSchemaShapeInfo(mergedSchema, module, schemas, { name, prefix: prefixName, merged, level, title, summary, descriptions, destination, section, enums }) + } } } else if (json.oneOf) { @@ -689,8 +697,13 @@ function getJsonTypeInfo(module = {}, json = {}, name = '', schemas, prefix = '' } else if (json.anyOf) { let mergedSchema = getMergedSchema(module, json, name, schemas) - let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) - structure = getJsonTypeInfo(module, mergedSchema, name, schemas, prefixName, {descriptions, level}) + if (mergedSchema.type) { + let prefixName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? prefix : capitalize(name) + structure = getJsonTypeInfo(module, mergedSchema, name, schemas, prefixName, {descriptions, level}) + } + else { + structure.type = getJsonNativeTypeForOpaqueString() + } } else if (json.type === 'object') { if (hasProperties(json) !== true) { diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index 009beb99..954ac50d 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -4,7 +4,7 @@ const getJsonDataPrefix = () => 'JsonData_' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' const getJsonDataStructName = (modName, name, prefix = '') => { - let result =((prefix.length > 0) && (prefix !== name)) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` + let result =((prefix && prefix.length > 0) && (prefix !== name)) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` return ((result.includes(wpeJsonNameSpace()) === true) ? result : `${getSdkNameSpace()}::${result}`) } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 8d00199e..3437c3f4 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -107,11 +107,11 @@ const getTypeName = (moduleName, varName, prefix = '', upperCase = false, capita let mName = upperCase ? moduleName.toUpperCase() : capitalize(moduleName) let vName = upperCase ? varName.toUpperCase() : capitalCase ? capitalize(varName) : varName - if (prefix.length > 0) { + if (prefix && prefix.length > 0) { prefix = (prefix !== varName) ? (upperCase ? prefix.toUpperCase() : capitalize(prefix)) : '' } - prefix = (prefix.length > 0) ?(upperCase ? prefix.toUpperCase() : capitalize(prefix)) : prefix - let name = (prefix.length > 0) ? `${mName}_${prefix}${vName}` : `${mName}_${vName}` + prefix = (prefix && prefix.length > 0) ?(upperCase ? prefix.toUpperCase() : capitalize(prefix)) : prefix + let name = (prefix && prefix.length > 0) ? `${mName}_${prefix}${vName}` : `${mName}_${vName}` return name } From eb0023b70638b4c0686ab6886d6a068d5f7e71bb Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 21:10:37 +0530 Subject: [PATCH 092/137] calls-metrics: support added (#115) --- languages/c/templates/declarations/rpc-only.c | 0 .../c/templates/imports/calls-metrics.cpp | 1 + languages/c/templates/methods/calls-metrics.c | 30 +++++++++++++++++++ languages/c/templates/methods/rpc-only.c | 0 src/macrofier/engine.mjs | 13 +++++++- src/shared/modules.mjs | 8 +++++ 6 files changed, 51 insertions(+), 1 deletion(-) delete mode 100644 languages/c/templates/declarations/rpc-only.c create mode 100644 languages/c/templates/imports/calls-metrics.cpp create mode 100644 languages/c/templates/methods/calls-metrics.c delete mode 100644 languages/c/templates/methods/rpc-only.c diff --git a/languages/c/templates/declarations/rpc-only.c b/languages/c/templates/declarations/rpc-only.c deleted file mode 100644 index e69de29b..00000000 diff --git a/languages/c/templates/imports/calls-metrics.cpp b/languages/c/templates/imports/calls-metrics.cpp new file mode 100644 index 00000000..4ba289b3 --- /dev/null +++ b/languages/c/templates/imports/calls-metrics.cpp @@ -0,0 +1 @@ +#include "metrics.h" diff --git a/languages/c/templates/methods/calls-metrics.c b/languages/c/templates/methods/calls-metrics.c new file mode 100644 index 00000000..91831a3c --- /dev/null +++ b/languages/c/templates/methods/calls-metrics.c @@ -0,0 +1,30 @@ +/* ${method.rpc.name} - ${method.description} */ +void Metrics_${method.Name}Dispatcher(const void*${if.result} result${end.if.result}) { + Metrics_${method.Name}(${if.result}(static_cast<${method.result.json.type}>(const_cast(result)))${end.if.result}); +} + +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; + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + + ${method.params.serialization.with.indent} + ${method.result.json.type} jsonResult; + status = transport->Invoke("${info.title}.${method.rpc.name}", jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); +${method.result.instantiation} + + void* result = nullptr; + ${if.result}result = static_cast(new ${method.result.json.type});${end.if.result} + WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(Metrics_${method.Name}Dispatcher, result)); + WPEFramework::Core::IWorkerPool::Instance().Submit(job); + } + + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; +} diff --git a/languages/c/templates/methods/rpc-only.c b/languages/c/templates/methods/rpc-only.c deleted file mode 100644 index e69de29b..00000000 diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 73661d53..3f301ede 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -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, isCallsMetricsMethod, isExcludedMethod, hasMethodAttributes, getMethodAttributes, isEventMethodWithContext, getSemanticVersion, getSetterFor, getProvidedCapabilities, isPolymorphicPullMethod, hasPublicAPIs } from '../shared/modules.mjs' import isEmpty from 'crocks/core/isEmpty.js' import { getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies, isDefinitionReferencedBySchema } from '../shared/json-schema.mjs' @@ -282,6 +282,13 @@ const temporalSets = compose( getMethods ) +const callsMetrics = compose( + option([]), + map(filter(not(isExcludedMethod))), + map(filter(isCallsMetricsMethod)), + getMethods +) + const methodsWithXMethodsInResult = compose( option([]), map(filter(hasMethodAttributes)), @@ -832,6 +839,10 @@ const generateImports = (json, templates, options = { destination: '' }) => { const suffix = options.destination.split('.').pop() const prefix = options.destination.split('/').pop().split('_')[0].toLowerCase() + if (callsMetrics(json).length) { + imports += getTemplate(suffix ? `/imports/calls-metrics.${suffix}` : '/imports/calls-metrics', templates) + } + let template = prefix ? getTemplate(`/imports/default.${prefix}`, templates) : '' if (!template) { template = getTemplate(suffix ? `/imports/default.${suffix}` : '/imports/default', templates) diff --git a/src/shared/modules.mjs b/src/shared/modules.mjs index 386b9d6d..a91c076b 100644 --- a/src/shared/modules.mjs +++ b/src/shared/modules.mjs @@ -227,6 +227,13 @@ const isTemporalSetMethod = compose( getPath(['tags']) ) +const isCallsMetricsMethod = compose( + option(false), + map(_ => true), + chain(find(propEq('name', 'calls-metrics'))), + getPath(['tags']) +) + const getMethodAttributes = compose( option(null), map(props => props.reduce( (val, item) => { @@ -1148,6 +1155,7 @@ export { isPolymorphicReducer, isPolymorphicPullMethod, isTemporalSetMethod, + isCallsMetricsMethod, isExcludedMethod, isRPCOnlyMethod, isProviderInterfaceMethod, From 06f0f39fcd679441522f9670a4a3f07f2657eefa Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 17 Jul 2023 21:13:35 +0530 Subject: [PATCH 093/137] Generate polymorphci methods for anyOf param/result case (#110) --- languages/c/Types.mjs | 1 + languages/c/language.config.json | 3 +- languages/c/templates/codeblocks/setter.c | 4 +- languages/c/templates/methods/default.c | 6 +- languages/c/templates/methods/event.c | 6 +- .../methods/polymorphic-pull-event.c | 10 +- .../c/templates/methods/polymorphic-pull.c | 11 +- languages/c/templates/methods/property.c | 4 +- src/macrofier/engine.mjs | 20 ++- src/macrofier/index.mjs | 7 +- src/sdk/index.mjs | 1 + src/shared/modules.mjs | 137 +++++++++++++++++- 12 files changed, 182 insertions(+), 28 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 1ee99224..4c092a92 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -358,6 +358,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref structure.namespace = getModuleName(module) } } + return structure } diff --git a/languages/c/language.config.json b/languages/c/language.config.json index ee3604d7..b684e11b 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -12,5 +12,6 @@ "/src/module_common.cpp", "/src/jsondata_module.h" ], - "persistPermission": true + "persistPermission": true, + "createPolymorphicMethods": true } diff --git a/languages/c/templates/codeblocks/setter.c b/languages/c/templates/codeblocks/setter.c index 342a98d6..411d4542 100644 --- a/languages/c/templates/codeblocks/setter.c +++ b/languages/c/templates/codeblocks/setter.c @@ -1,7 +1,7 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.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.lowercase}.${method.rpc.name}"); ${if.params}${method.params.serialization}${end.if.params} return FireboltSDK::Properties::Set(method, jsonParameters); } diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 6fbca47e..881b592c 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -1,4 +1,4 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.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; @@ -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.lowercase}.${method.rpc.name}", jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully invoked"); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); ${method.result.instantiation} } diff --git a/languages/c/templates/methods/event.c b/languages/c/templates/methods/event.c index ec868cd5..c02e74c4 100644 --- a/languages/c/templates/methods/event.c +++ b/languages/c/templates/methods/event.c @@ -1,4 +1,4 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.name} - ${method.description} */ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) { ${event.callback.params.serialization} @@ -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.lowercase}.${method.rpc.name}"); uint32_t status = FireboltSDKErrorNone; if (userCB != nullptr) { @@ -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(userCB)); + return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); } diff --git a/languages/c/templates/methods/polymorphic-pull-event.c b/languages/c/templates/methods/polymorphic-pull-event.c index d2f5ef4c..7c833b71 100644 --- a/languages/c/templates/methods/polymorphic-pull-event.c +++ b/languages/c/templates/methods/polymorphic-pull-event.c @@ -1,4 +1,4 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.name} - ${method.description} */ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) { ${event.callback.params.serialization} @@ -27,9 +27,9 @@ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { WPEFramework::Core::JSON::Boolean jsonResult; - uint32_t status = transport->Invoke(_T("${info.title}.${method.pulls.for}"), jsonParameters, jsonResult); + uint32_t status = transport->Invoke(_T("${info.title.lowercase}.${method.pulls.for}"), jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully pushed with status as %d", jsonResult.Value()); status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; } } else { @@ -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.lowercase}.${method.rpc.name}"); uint32_t status = FireboltSDKErrorNone; if (userCB != nullptr) { @@ -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(userCB)); + return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); } diff --git a/languages/c/templates/methods/polymorphic-pull.c b/languages/c/templates/methods/polymorphic-pull.c index ec052e64..759b0ae9 100644 --- a/languages/c/templates/methods/polymorphic-pull.c +++ b/languages/c/templates/methods/polymorphic-pull.c @@ -1,16 +1,17 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.name} - ${method.description} */ uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ) { uint32_t status = FireboltSDKErrorUnavailable; - string correlationId = ""; -${method.params.serialization} FireboltSDK::Transport* 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.lowercase}.${method.rpc.name}"), jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully pushed with status as %d", jsonResult.Value()); status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; } } else { diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 9a92dce4..7fb5b148 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,7 +1,7 @@ -/* ${method.name} - ${method.description} */ +/* ${method.rpc.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.lowercase}.${method.rpc.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} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 3f301ede..0bd85366 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -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, isCallsMetricsMethod, isExcludedMethod, 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' @@ -416,6 +416,21 @@ const generateMacros = (obj, templates, languages, options = {}) => { if (config.extractSubSchemas) { obj = promoteAndNameSubSchemas(obj) } + if (options.createPolymorphicMethods) { + let methods = [] + obj.methods && obj.methods.forEach(method => { + let polymorphicMethods = createPolymorphicMethods(method, obj) + if (polymorphicMethods.length > 1) { + polymorphicMethods.forEach(polymorphicMethod => { + methods.push(polymorphicMethod) + }) + } + else { + methods.push(method) + } + }) + obj.methods = methods + } // grab the options so we don't have to pass them from method to method Object.assign(state, options) @@ -1024,7 +1039,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, examples={}) { const moduleName = getModuleName(json) const info = { @@ -1133,6 +1148,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\.rpc\.name\}/g, methodObj.title || methodObj.name) .replace(/\$\{method\.summary\}/g, methodObj.summary) .replace(/\$\{method\.description\}/g, methodObj.description || methodObj.summary) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index dc5f30e8..86483fad 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -44,6 +44,7 @@ const macrofy = async ( templatesPerModule, templatesPerSchema, persistPermission, + createPolymorphicMethods, createModuleDirectories, copySchemasIntoModules, extractSubSchemas, @@ -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 @@ -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) } @@ -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 diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index 7e85fab9..2e72ba9b 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -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, diff --git a/src/shared/modules.mjs b/src/shared/modules.mjs index a91c076b..927092c2 100644 --- a/src/shared/modules.mjs +++ b/src/shared/modules.mjs @@ -29,6 +29,7 @@ const { and, not } = logic import isString from 'crocks/core/isString.js' import predicates from 'crocks/predicates/index.js' import { getExternalSchemaPaths, isDefinitionReferencedBySchema, isNull, localizeDependencies, isSchema, getLocalSchemaPaths, replaceRef } from './json-schema.mjs' +import { getPath as getRefDefinition } from './json-schema.mjs' const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = predicates // util for visually debugging crocks ADTs @@ -861,6 +862,137 @@ const generateEventListenResponse = json => { return json } +const getAnyOfSchema = (inType, json) => { + let anyOfTypes = [] + let outType = localizeDependencies(inType, json) + if (outType.schema.anyOf) { + let definition = '' + if (inType.schema['$ref'] && (inType.schema['$ref'][0] === '#')) { + definition = getRefDefinition(inType.schema['$ref'], json, json['x-schemas']) + } + else { + definition = outType.schema + } + definition.anyOf.forEach(anyOf => { + anyOfTypes.push(anyOf) + }) + outType.schema.anyOf = anyOfTypes + } + return outType +} + +const generateAnyOfSchema = (anyOf, name, summary) => { + let anyOfType = {} + anyOfType["name"] = name[0].toLowerCase() + name.substr(1) + anyOfType["summary"] = summary + anyOfType["schema"] = anyOf + return anyOfType +} + +const generateParamsAnyOfSchema = (methodParams, anyOf, anyOfTypes, title, summary) => { + let params = [] + methodParams.forEach(p => { + if (p.schema.anyOf === anyOfTypes) { + let anyOfType = generateAnyOfSchema(anyOf, title, summary) + anyOfType.required = p.required + params.push(anyOfType) + } + else { + params.push(p) + } + }) + return params +} + +const generateResultAnyOfSchema = (method, methodResult, anyOf, anyOfTypes, title, summary) => { + let methodResultSchema = {} + if (methodResult.schema.anyOf === anyOfTypes) { + let anyOfType = generateAnyOfSchema(anyOf, title, summary) + let index = 0 + if (isEventMethod(method)) { + index = (method.result.schema.anyOf || method.result.schema.oneOf).indexOf(getPayloadFromEvent(method)) + } + else { + index = (method.result.schema.anyOf || method.result.schema.oneOf).indexOf(anyOfType) + } + if (method.result.schema.anyOf) { + methodResultSchema["anyOf"] = Object.assign([], method.result.schema.anyOf) + methodResultSchema.anyOf[index] = anyOfType.schema + } + else if (method.result.schema.oneOf) { + methodResultSchema["oneOf"] = Object.assign([], method.result.schema.oneOf) + methodResultSchema.oneOf[index] = anyOfType.schema + } + else { + methodResultSchema = anyOfType.schema + } + } + return methodResultSchema +} + +const createPolymorphicMethods = (method, json) => { + let anyOfTypes + let methodParams = [] + let methodResult = Object.assign({}, method.result) + method.params.forEach(p => { + if (p.schema) { + let param = getAnyOfSchema(p, json) + if (param.schema.anyOf && anyOfTypes) { + //anyOf is allowed with only one param in the params list + throw `WARNING anyOf is repeated with param:${p}` + } + else if (param.schema.anyOf) { + anyOfTypes = param.schema.anyOf + } + methodParams.push(param) + } + }) + let foundAnyOfParams = anyOfTypes ? true : false + + if (isEventMethod(method)) { + methodResult.schema = getPayloadFromEvent(method) + } + methodResult = getAnyOfSchema(methodResult, json) + let foundAnyOfResult = methodResult.schema.anyOf ? true : false + if (foundAnyOfParams === true && foundAnyOfResult === true) { + throw `WARNING anyOf is already with param schema, it is repeated with ${method.name} result too` + } + else if (foundAnyOfResult === true) { + anyOfTypes = methodResult.schema.anyOf + } + let polymorphicMethodSchemas = [] + //anyOfTypes will be allowed either in any one of the params or in result + if (anyOfTypes) { + let polymorphicMethodSchema = { + name: {}, + tags: {}, + summary: `${method.summary}`, + params: {}, + result: {}, + examples: {} + } + anyOfTypes.forEach(anyOf => { + + let localized = localizeDependencies(anyOf, json) + let title = localized.title || localized.name || '' + let summary = localized.summary || localized.description || '' + polymorphicMethodSchema.title = method.name + polymorphicMethodSchema.name = foundAnyOfParams ? `${method.name}With${title}` : `${method.name}${title}` + polymorphicMethodSchema.tags = method.tags + polymorphicMethodSchema.params = foundAnyOfParams ? generateParamsAnyOfSchema(methodParams, anyOf, anyOfTypes, title, summary) : methodParams + polymorphicMethodSchema.result = Object.assign({}, method.result) + polymorphicMethodSchema.result.schema = foundAnyOfResult ? generateResultAnyOfSchema(method, methodResult, anyOf, anyOfTypes, title, summary) : methodResult + polymorphicMethodSchema.examples = method.examples + polymorphicMethodSchemas.push(Object.assign({}, polymorphicMethodSchema)) + }) + } + else { + polymorphicMethodSchemas = method + } + + return polymorphicMethodSchemas +} + const getPathFromModule = (module, path) => { console.error("DEPRECATED: getPathFromModule") @@ -1183,5 +1315,6 @@ export { getSemanticVersion, addExternalMarkdown, addExternalSchemas, - getExternalMarkdownPaths -} \ No newline at end of file + getExternalMarkdownPaths, + createPolymorphicMethods +} From 260fa6544d8fc4381892522d3fd3485cb5da5621 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 24 Jul 2023 09:11:31 +0530 Subject: [PATCH 094/137] Create namespaces only if there is value to put (#117) --- languages/c/templates/modules/include/module.h | 7 ++++--- languages/c/templates/modules/src/module.cpp | 13 +++++++++---- .../c/templates/schemas/include/common/module.h | 6 +++--- languages/c/templates/schemas/src/jsondata_module.h | 4 ++-- languages/c/templates/schemas/src/module_common.cpp | 9 +++++++-- languages/c/templates/sections/accessors.c | 1 - languages/c/templates/sections/methods.c | 3 --- src/macrofier/engine.mjs | 11 ++++++++--- 8 files changed, 33 insertions(+), 21 deletions(-) diff --git a/languages/c/templates/modules/include/module.h b/languages/c/templates/modules/include/module.h index 00c5d595..176ff9c1 100644 --- a/languages/c/templates/modules/include/module.h +++ b/languages/c/templates/modules/include/module.h @@ -22,20 +22,21 @@ #include /* ${IMPORTS} */ -#ifdef __cplusplus +${if.declarations}#ifdef __cplusplus extern "C" { #endif // Enums - /* ${ENUMS} */ +// Accessors /* ${ACCESSORS} */ +// Methods & Events /* ${DECLARATIONS} */ #ifdef __cplusplus } -#endif +#endif${end.if.declarations} #endif // Header Include Guard diff --git a/languages/c/templates/modules/src/module.cpp b/languages/c/templates/modules/src/module.cpp index 2b467ae1..737d38df 100644 --- a/languages/c/templates/modules/src/module.cpp +++ b/languages/c/templates/modules/src/module.cpp @@ -20,23 +20,28 @@ /* ${IMPORTS} */ #include "${info.title.lowercase}.h" -namespace FireboltSDK { +${if.types}namespace FireboltSDK { namespace ${info.Title} { // Types /* ${TYPES} */ } -} +}${end.if.types} /* ${ENUMS} */ -#ifdef __cplusplus +${if.definitions}#ifdef __cplusplus extern "C" { #endif +// Accessors /* ${ACCESSORS} */ + +// Methods /* ${METHODS} */ + +// Events /* ${EVENTS} */ #ifdef __cplusplus } -#endif +#endif${end.if.definitions} diff --git a/languages/c/templates/schemas/include/common/module.h b/languages/c/templates/schemas/include/common/module.h index 939b3988..90f1f031 100644 --- a/languages/c/templates/schemas/include/common/module.h +++ b/languages/c/templates/schemas/include/common/module.h @@ -22,18 +22,18 @@ #include /* ${IMPORTS} */ -#ifdef __cplusplus +${if.declarations}#ifdef __cplusplus extern "C" { #endif // Enums - /* ${ENUMS} */ +// Types /* ${TYPES} */ #ifdef __cplusplus } -#endif +#endif${end.if.declarations} #endif // Header Include Guard diff --git a/languages/c/templates/schemas/src/jsondata_module.h b/languages/c/templates/schemas/src/jsondata_module.h index f80be03e..81084440 100644 --- a/languages/c/templates/schemas/src/jsondata_module.h +++ b/languages/c/templates/schemas/src/jsondata_module.h @@ -21,10 +21,10 @@ /* ${IMPORTS} */ #include "common/${info.title.lowercase}.h" -namespace FireboltSDK { +${if.schemas}namespace FireboltSDK { namespace ${info.Title} { // Types /* ${SCHEMAS} */ } -} +}${end.if.schemas} diff --git a/languages/c/templates/schemas/src/module_common.cpp b/languages/c/templates/schemas/src/module_common.cpp index 0d8c74d2..582a650b 100644 --- a/languages/c/templates/schemas/src/module_common.cpp +++ b/languages/c/templates/schemas/src/module_common.cpp @@ -22,14 +22,19 @@ /* ${ENUMS} */ -#ifdef __cplusplus +${if.definitions}#ifdef __cplusplus extern "C" { #endif + // Accessors /* ${ACCESSORS} */ + + // Methods /* ${METHODS} */ + + // Events /* ${EVENTS} */ #ifdef __cplusplus } -#endif +#endif${end.if.definitions} diff --git a/languages/c/templates/sections/accessors.c b/languages/c/templates/sections/accessors.c index 1c790810..9295133c 100644 --- a/languages/c/templates/sections/accessors.c +++ b/languages/c/templates/sections/accessors.c @@ -1,2 +1 @@ -// Accessors ${schema.list} diff --git a/languages/c/templates/sections/methods.c b/languages/c/templates/sections/methods.c index 3ab606c0..e8200eb0 100644 --- a/languages/c/templates/sections/methods.c +++ b/languages/c/templates/sections/methods.c @@ -1,4 +1 @@ - -// Methods - ${method.list} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 0bd85366..b71dbba3 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -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, createPolymorphicMethods } from '../shared/modules.mjs' +import { isRPCOnlyMethod, isProviderInterfaceMethod, getProviderInterface, getPayloadFromEvent, providerHasNoParameters, isTemporalSetMethod, isCallsMetricsMethod, isExcludedMethod, 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' @@ -507,6 +507,11 @@ const insertMacros = (fContents = '', macros = {}) => { const quote = config.operators ? config.operators.stringQuotation : '"' const or = config.operators ? config.operators.or : ' | ' + fContents = fContents.replace(/\$\{if\.types\}(.*?)\$\{end\.if\.types\}/gms, macros.types.trim() ? '$1' : '') + fContents = fContents.replace(/\$\{if\.schemas\}(.*?)\$\{end\.if\.schemas\}/gms, macros.schemas.trim() ? '$1' : '') + fContents = fContents.replace(/\$\{if\.declarations\}(.*?)\$\{end\.if\.declarations\}/gms, (macros.accessors.trim() || macros.declarations.trim() || macros.enums.trim()) ? '$1' : '') + fContents = fContents.replace(/\$\{if\.definitions\}(.*?)\$\{end\.if\.definitions\}/gms, (macros.accessors.trim() || 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]*\/\* \$\{ACCESSORS\} \*\/[ \t]*\n/, macros.accessors) @@ -638,7 +643,7 @@ const generateEnums = (json, templates, options = { destination: '' }) => { return compose( option(''), map(val => { - let template = getTemplate(`/sections/enum.${suffix}`, templates) + let template = val ? getTemplate(`/sections/enum.${suffix}`, templates) : val return template ? template.replace(/\$\{schema.list\}/g, val.trimEnd()) : val }), map(reduce((acc, val) => acc.concat(val).concat('\n'), '')), @@ -1039,7 +1044,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, examples = {}) { const moduleName = getModuleName(json) const info = { From a6eb5df7b37b7f1a1d0bd68f1827a0dbab1f15aa Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 24 Jul 2023 09:12:21 +0530 Subject: [PATCH 095/137] Changes to avoid duplication of sub-array schema with same reference (#116) --- languages/c/Types.mjs | 2 ++ src/macrofier/engine.mjs | 23 +++++++++++++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 4c092a92..c4465bfe 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -304,6 +304,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref } + name = name.endsWith("_ArrayType") ? name.split('_ArrayType')[0] : name prefix = prefix ? prefix + name : name let n = getTypeName(getModuleName(module), capitalize(res.name), prefix) structure.name = name ? name + capitalize(res.name) : res.name @@ -539,6 +540,7 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' } if (!isCPP) { + name = name.endsWith("_ArrayType") ? name.split('_ArrayType')[0] : name let subPrefix = prefix ? prefix + name : name let info = getSchemaTypeInfo(module, j, j.title || name, schemas, subPrefix, {level : level, descriptions: descriptions, title: true}) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index b71dbba3..d8daa16e 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -356,9 +356,24 @@ const generateAggregateMacros = (openrpc, modules, templates, library) => Object }) const addContentDescriptorSubSchema = (descriptor, prefix, obj) => { - const title = prefix.charAt(0).toUpperCase() + prefix.substring(1) + descriptor.name.charAt(0).toUpperCase() + descriptor.name.substring(1) - if (obj.components.schemas[title]) { - throw 'Generated name `' + title + '` already exists...' + let title = '' + if (descriptor.schema.type === 'array' && descriptor.schema.items && descriptor.schema.items['$ref']) { + let refName = descriptor.schema.items['$ref'].split('/').pop() + title = refName.charAt(0).toUpperCase() + refName.substring(1) + '_ArrayType' + if (obj.components.schemas[title]) { + descriptor.schema = { + $ref: "#/components/schemas/" + title + } + return + } + } + else { + let descriptorName = capitalize(descriptor.name) + let prefixName = capitalize(prefix) + title = (prefixName !== descriptorName) ? prefixName + descriptorName : descriptorName + if (obj.components.schemas[title]) { + throw 'Generated name `' + title + '` already exists...' + } } obj.components.schemas[title] = descriptor.schema obj.components.schemas[title].title = title @@ -367,7 +382,7 @@ const addContentDescriptorSubSchema = (descriptor, prefix, obj) => { } } -// only consider sub-objects and sub enums to be sub-schemas +// only consider sub-objects, sub-array and sub-enums to be sub-schemas const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) || (schema.type === 'array' && schema.items) const promoteAndNameSubSchemas = (obj) => { From f8faf1f9b816088cbe0c4b237e59b81b8fff271e Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Wed, 26 Jul 2023 09:19:20 +0530 Subject: [PATCH 096/137] =?UTF-8?q?detach=20setter=20declaration=20from=20?= =?UTF-8?q?property=20template=20and=20add=20setter=20templ=E2=80=A6=20(#1?= =?UTF-8?q?18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Detach setter declaration from property template and add setter template, remove unredundant warnings Cleanup changes, add separator between prefix and subSchema name generation Introduce excludeDeclarations flag to handle declaration exclusion specific to language Alignement changes + cleanup + OUT params support added to differentiate method signature parameters Update in static code --- languages/c/Types.mjs | 28 +++------ languages/c/language.config.json | 3 +- languages/c/src/shared/include/firebolt.h | 3 + languages/c/src/shared/include/types.h | 6 +- languages/c/src/shared/src/Logger/Logger.cpp | 7 ++- .../c/src/shared/src/Transport/Transport.h | 2 +- languages/c/src/shared/src/Types.cpp | 4 +- languages/c/src/shared/test/OpenRPCTests.cpp | 6 +- languages/c/src/types/ImplHelpers.mjs | 32 +++++------ languages/c/src/types/JSONHelpers.mjs | 2 +- languages/c/src/types/NativeHelpers.mjs | 57 +++---------------- languages/c/templates/declarations/default.c | 3 +- languages/c/templates/declarations/event.c | 1 + .../declarations/polymorphic-pull-event.c | 1 + .../templates/declarations/polymorphic-pull.c | 1 + languages/c/templates/declarations/setter.c | 2 + languages/c/templates/methods/calls-metrics.c | 6 +- languages/c/templates/methods/default.c | 5 +- languages/c/templates/methods/event.c | 1 + .../methods/polymorphic-pull-event.c | 1 + .../c/templates/methods/polymorphic-pull.c | 3 +- languages/c/templates/methods/property.c | 4 +- .../c/templates/modules/include/module.h | 2 + languages/c/templates/modules/src/module.cpp | 2 + .../c/templates/schemas/src/module_common.cpp | 14 +++-- languages/c/templates/sdk/scripts/install.sh | 2 +- src/macrofier/engine.mjs | 28 +++++---- src/macrofier/index.mjs | 2 + src/sdk/index.mjs | 1 + 29 files changed, 103 insertions(+), 126 deletions(-) create mode 100644 languages/c/templates/declarations/setter.c diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index c4465bfe..6c3c8311 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -18,8 +18,8 @@ import deepmerge from 'deepmerge' import { getPath } from '../../src/shared/json-schema.mjs' -import { getTypeName, getModuleName, description, getObjectHandleManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getPropertyGetterSignature, getPropertyEventCallbackSignature, getPropertyEventRegisterSignature, getPropertyEventUnregisterSignature, getPropertySetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' -import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectHandleManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation, getCallbackParametersInstantiation, getCallbackResultInstantiation, getCallbackResponseInstantiation } from './src/types/ImplHelpers.mjs' +import { getTypeName, getModuleName, description, getObjectManagement, getNativeType, getPropertyAccessors, capitalize, isOptional, generateEnum, getMapAccessors, getArrayAccessors, getPropertyGetterSignature, getFireboltStringType } from './src/types/NativeHelpers.mjs' +import { getArrayAccessorsImpl, getMapAccessorsImpl, getObjectManagementImpl, getParameterInstantiation, getPropertyAccessorsImpl, getResultInstantiation, getCallbackParametersInstantiation, getCallbackResultInstantiation, getCallbackResponseInstantiation } from './src/types/ImplHelpers.mjs' import { getJsonContainerDefinition, getJsonDataStructName, getJsonDataPrefix } from './src/types/JSONHelpers.mjs' const getSdkNameSpace = () => 'FireboltSDK' @@ -199,11 +199,7 @@ function getMethodSignature(method, module, { destination, isInterface = false } let paramList = getParamList(method, module) let resultType = method.result && getSchemaType(method.result.schema, module, { title: true, name: method.result.name, resultSchema: true}) || '' - signature = getPropertyGetterSignature(method, module, resultType, paramList) + ';\n\n' - - if (hasTag(method, 'property')) { - signature += getPropertySetterSignature(method, module, resultType, paramList) + ';\n\n' - } + signature = getPropertyGetterSignature(method, module, resultType, paramList) + ';\n' } return signature } @@ -408,10 +404,10 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' shape = '' } else if (json.properties && (validJsonObjectProperties(json) === true)) { - let c_shape = description(capitalize(name), json.description) + let c_shape = '\n' + description(capitalize(name), json.description) let cpp_shape = '' let tName = getTypeName(getModuleName(module), name, prefix) - c_shape += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, getJsonType(json, module, { name }))) + c_shape += '\n' + (isHeader ? getObjectManagement(tName) : getObjectManagementImpl(tName, getJsonType(json, module, { name }))) let props = [] let containerName = ((prefix.length > 0) && (!name.startsWith(prefix))) ? (prefix + '_' + capitalize(name)) : capitalize(name) Object.entries(json.properties).forEach(([pname, prop]) => { @@ -461,9 +457,6 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' let property = getJsonType(prop, module, { name : pname, prefix }) props.push({name: `${pname}`, type: `${property}`}) } - else { - console.log(`b. WARNING: Type undetermined for ${name}:${pname}`) - } } }) @@ -488,7 +481,7 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' } let tName = getTypeName(getModuleName(module), name, prefix) - let t = description(capitalize(name), json.description) + '\n' + let t = '\n' + description(capitalize(name), json.description) let containerType = 'WPEFramework::Core::JSON::VariantContainer' let subModuleProperty = getJsonTypeInfo(module, info.json, info.name, module['x-schemas']) @@ -496,13 +489,10 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' // Handle Container generation here } - t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, containerType)) + t += '\n' + (isHeader ? getObjectManagement(tName) : getObjectManagementImpl(tName, containerType)) t += (isHeader ? getMapAccessors(tName, info.type, { descriptions: descriptions, level: level }) : getMapAccessorsImpl(tName, containerType, subModuleProperty.type, info.type, info.json, { readonly: true, optional: false })) shape += '\n' + t } - else if (json.patternProperties) { - console.log(`WARNING: patternProperties are not supported by Firebolt(inside getModuleName(module):${name})`) - } } else if (json.anyOf) { if (level > 0) { @@ -554,8 +544,8 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = '' let subModuleProperty = getJsonTypeInfo(module, j, j.title || name, schemas, prefix) let t = '' if (level === 0) { - t += description(capitalize(info.name), json.description) + '\n' - t += '\n' + (isHeader ? getObjectHandleManagement(tName) : getObjectHandleManagementImpl(tName, moduleProperty.type)) + t += '\n' + description(capitalize(info.name), json.description) + t += '\n' + (isHeader ? getObjectManagement(tName) : getObjectManagementImpl(tName, moduleProperty.type)) } t += '\n' + (isHeader ? getArrayAccessors(objName, tName, info.type) : getArrayAccessorsImpl(objName, moduleProperty.type, (tName + '_t'), subModuleProperty.type, '', info.type, info.json)) shape += '\n' + t diff --git a/languages/c/language.config.json b/languages/c/language.config.json index b684e11b..b19eddb8 100644 --- a/languages/c/language.config.json +++ b/languages/c/language.config.json @@ -13,5 +13,6 @@ "/src/jsondata_module.h" ], "persistPermission": true, - "createPolymorphicMethods": true + "createPolymorphicMethods": true, + "excludeDeclarations":true } diff --git a/languages/c/src/shared/include/firebolt.h b/languages/c/src/shared/include/firebolt.h index 0957973f..565b363c 100644 --- a/languages/c/src/shared/include/firebolt.h +++ b/languages/c/src/shared/include/firebolt.h @@ -26,6 +26,9 @@ extern "C" { #endif +#define IN +#define OUT + /** * @brief Intitialize the Firebolt SDK * diff --git a/languages/c/src/shared/include/types.h b/languages/c/src/shared/include/types.h index 26efc54f..8333f0eb 100644 --- a/languages/c/src/shared/include/types.h +++ b/languages/c/src/shared/include/types.h @@ -26,9 +26,9 @@ extern "C" { #endif -typedef struct FireboltTypes_String_s* FireboltTypes_String_t; -const char* FireboltTypes_String(FireboltTypes_String_t handle); -void FireboltTypes_StringHandle_Release(FireboltTypes_String_t handle); +typedef struct Firebolt_String_s* Firebolt_String_t; +const char* Firebolt_String(Firebolt_String_t handle); +void Firebolt_String_Release(Firebolt_String_t handle); #ifdef __cplusplus } diff --git a/languages/c/src/shared/src/Logger/Logger.cpp b/languages/c/src/shared/src/Logger/Logger.cpp index a9750a6e..a16764f2 100644 --- a/languages/c/src/shared/src/Logger/Logger.cpp +++ b/languages/c/src/shared/src/Logger/Logger.cpp @@ -71,11 +71,14 @@ namespace FireboltSDK { char formattedMsg[Logger::MaxBufSize]; const string time = WPEFramework::Core::Time::Now().ToTimeOnly(true); const string categoryName = WPEFramework::Core::EnumerateType(category).Data(); +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-truncation" if (categoryName.empty() != true) { - sprintf(formattedMsg, "--->\033[1;32m[%s]:[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), categoryName.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); + snprintf(formattedMsg, sizeof(formattedMsg), "--->\033[1;32m[%s]:[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), categoryName.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); } else { - sprintf(formattedMsg, "--->\033[1;32m[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); + snprintf(formattedMsg, sizeof(formattedMsg), "--->\033[1;32m[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); } +#pragma GCC diagnostic pop LOG_MESSAGE(formattedMsg); } } diff --git a/languages/c/src/shared/src/Transport/Transport.h b/languages/c/src/shared/src/Transport/Transport.h index 109e2431..b3405b9c 100644 --- a/languages/c/src/shared/src/Transport/Transport.h +++ b/languages/c/src/shared/src/Transport/Transport.h @@ -254,7 +254,7 @@ namespace FireboltSDK { public: ChannelImpl(CommunicationChannel* parent, const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask) - : BaseClass(5, FactoryImpl::Instance(), path, _T("JSON"), query, "", false, mask, false, remoteNode.AnyInterface(), remoteNode, 1024 * 2, 1024 * 2) //TODO Relook this size issue + : BaseClass(5, FactoryImpl::Instance(), path, _T("JSON"), query, "", false, mask, false, remoteNode.AnyInterface(), remoteNode, 512, 512) , _parent(*parent) { } diff --git a/languages/c/src/shared/src/Types.cpp b/languages/c/src/shared/src/Types.cpp index b9620436..93f6a8d8 100644 --- a/languages/c/src/shared/src/Types.cpp +++ b/languages/c/src/shared/src/Types.cpp @@ -25,12 +25,12 @@ extern "C" { #endif // String Type Handler Interfaces -const char* FireboltTypes_String(FireboltTypes_String_t handle) +const char* Firebolt_String(Firebolt_String_t handle) { return ((reinterpret_cast(handle))->Value().c_str()); } -void FireboltTypes_StringHandle_Release(FireboltTypes_String_t handle) +void Firebolt_String_Release(Firebolt_String_t handle) { delete reinterpret_cast(handle); } diff --git a/languages/c/src/shared/test/OpenRPCTests.cpp b/languages/c/src/shared/test/OpenRPCTests.cpp index b74f17ae..11170c15 100644 --- a/languages/c/src/shared/test/OpenRPCTests.cpp +++ b/languages/c/src/shared/test/OpenRPCTests.cpp @@ -485,9 +485,9 @@ uint32_t test_string_set_get_value() uint32_t status = FireboltSDKErrorNone; FireboltSDK::JSON::String* str = new FireboltSDK::JSON::String(); WPEFramework::Core::JSON::String wpeJsonStr("TestString"); - FireboltTypes_String_t handle = reinterpret_cast(str); + Firebolt_String_t handle = reinterpret_cast(str); - const char* value = FireboltTypes_String(handle); + const char* value = Firebolt_String(handle); EXPECT_EQ(strncmp(value, str->Value().c_str(), str->Value().length()), 0); FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", " ---> type name = %s %s", str->Value().c_str(), value); @@ -495,7 +495,7 @@ uint32_t test_string_set_get_value() WPEFramework::Core::JSON::EnumType<::TestEnum> testEnum = Test4; FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", " EnumTest = %d %s", testEnum.Value(), testEnum.Data()); - FireboltTypes_StringHandle_Release(handle); + Firebolt_String_Release(handle); return status; } diff --git a/languages/c/src/types/ImplHelpers.mjs b/languages/c/src/types/ImplHelpers.mjs index 8dbe8f08..0ac77dd6 100644 --- a/languages/c/src/types/ImplHelpers.mjs +++ b/languages/c/src/types/ImplHelpers.mjs @@ -6,22 +6,22 @@ const getSdkNameSpace = () => 'FireboltSDK' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' const camelcase = str => str[0].toLowerCase() + str.substr(1) -const getObjectHandleManagementImpl = (varName, jsonDataName) => { +const getObjectManagementImpl = (varName, jsonDataName) => { - let result = `${varName}_t ${varName}Handle_Acquire(void) + let result = `${varName}_t ${varName}_Acquire(void) { WPEFramework::Core::ProxyType<${jsonDataName}>* type = new WPEFramework::Core::ProxyType<${jsonDataName}>(); *type = WPEFramework::Core::ProxyType<${jsonDataName}>::Create(); return (reinterpret_cast<${varName}_t>(type)); } -void ${varName}Handle_Addref(${varName}_t handle) +void ${varName}_Addref(${varName}_t handle) { ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${jsonDataName}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); var->AddRef(); } -void ${varName}Handle_Release(${varName}_t handle) +void ${varName}_Release(${varName}_t handle) { ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${jsonDataName}>* var = reinterpret_cast*>(handle); @@ -30,7 +30,7 @@ void ${varName}Handle_Release(${varName}_t handle) delete var; } } -bool ${varName}Handle_IsValid(${varName}_t handle) +bool ${varName}_IsValid(${varName}_t handle) { ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${jsonDataName}>* var = reinterpret_cast*>(handle); @@ -101,7 +101,7 @@ const getPropertyAccessorsImpl = (objName, modulePropertyType, subPropertyType, return result } -const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPropertyType, subPropertyName, accessorPropertyType, json = {}) => { +const getArrayAccessorsImpl = (objName, modulePropertyType, objType, subPropertyType, subPropertyName, accessorPropertyType, json = {}) => { let propertyName if (subPropertyName) { @@ -112,7 +112,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr propertyName = '(*(*var))' } - let result = `uint32_t ${objName}Array_Size(${objHandleType} handle) { + let result = `uint32_t ${objName}Array_Size(${objType} handle) { ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); ASSERT(var->IsValid()); @@ -120,7 +120,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr return (${propertyName}.Length()); }` + '\n' - result += `${accessorPropertyType} ${objName}Array_Get(${objHandleType} handle, uint32_t index) + result += `${accessorPropertyType} ${objName}Array_Get(${objType} handle, uint32_t index) { ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); @@ -144,7 +144,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr result += `}` + '\n' let type = (accessorPropertyType === getFireboltStringType()) ? 'char*' : accessorPropertyType - result += `void ${objName}Array_Add(${objHandleType} handle, ${type} value) + result += `void ${objName}Array_Add(${objType} handle, ${type} value) { ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); @@ -162,7 +162,7 @@ const getArrayAccessorsImpl = (objName, modulePropertyType, objHandleType, subPr ${propertyName}.Add() = element; }` + '\n' - result += `void ${objName}Array_Clear(${objHandleType} handle) + result += `void ${objName}Array_Clear(${objType} handle) { ASSERT(handle != NULL); WPEFramework::Core::ProxyType<${modulePropertyType}>* var = reinterpret_cast*>(handle); @@ -304,7 +304,7 @@ function getParameterInstantiation(paramList, container = '') { const name = param.name if (jsonType.length) { if (param.required) { - if (param.nativeType.includes('FireboltTypes_String_t')) { + if (param.nativeType.includes('Firebolt_String_t')) { impl += ` WPEFramework::Core::JSON::Variant ${capitalize(name)} = *(reinterpret_cast<${jsonType}*>(${name}));\n` } else if (param.nativeType.includes('_t')) { @@ -429,7 +429,7 @@ function getCallbackParametersInstantiation(paramList, container = '') { function getCallbackResultInstantiation(nativeType, container = '') { let impl = '' - if (nativeType === 'char*' || nativeType === 'FireboltTypes_String_t') { + if (nativeType === 'char*' || nativeType === 'Firebolt_String_t') { impl +=` ${container}* jsonStrResponse = new ${container}(); *jsonStrResponse = *(*jsonResponse); @@ -457,7 +457,7 @@ function getCallbackResponseInstantiation(paramList, nativeType, container = '') }) } - if (nativeType === 'char*' || nativeType === 'FireboltTypes_String_t') { + if (nativeType === 'char*' || nativeType === 'Firebolt_String_t') { impl += `reinterpret_cast<${nativeType}>(jsonStrResponse)` } else if (nativeType.includes('_t')) { @@ -470,13 +470,13 @@ function getCallbackResponseInstantiation(paramList, nativeType, container = '') return impl } -function getResultInstantiation (name, nativeType, container, indentLevel = 3) { +function getResultInstantiation (name, nativeType, container, indentLevel = 2) { let impl = '' if (nativeType) { impl += `${' '.repeat(indentLevel)}if (${name} != nullptr) {` + '\n' - if (nativeType === 'char*' || nativeType === 'FireboltTypes_String_t') { + if (nativeType === 'char*' || nativeType === 'Firebolt_String_t') { impl += `${' '.repeat(indentLevel + 1)}${container}* strResult = new ${container}(jsonResult);` + '\n' impl += `${' '.repeat(indentLevel + 1)}*${name} = reinterpret_cast<${getFireboltStringType()}>(strResult);` + '\n' } else if (nativeType.includes('_t')) { @@ -500,7 +500,7 @@ function getResultInstantiation (name, nativeType, container, indentLevel = 3) { export { getArrayAccessorsImpl, getMapAccessorsImpl, - getObjectHandleManagementImpl, + getObjectManagementImpl, getPropertyAccessorsImpl, getParameterInstantiation, getCallbackParametersInstantiation, diff --git a/languages/c/src/types/JSONHelpers.mjs b/languages/c/src/types/JSONHelpers.mjs index 954ac50d..1c5e3ea4 100644 --- a/languages/c/src/types/JSONHelpers.mjs +++ b/languages/c/src/types/JSONHelpers.mjs @@ -4,7 +4,7 @@ const getJsonDataPrefix = () => 'JsonData_' const wpeJsonNameSpace = () => 'WPEFramework::Core::JSON' const getJsonDataStructName = (modName, name, prefix = '') => { - let result =((prefix && prefix.length > 0) && (prefix !== name)) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` + let result =((prefix && prefix.length > 0) && (prefix !== name)) ? `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(prefix)}_${capitalize(name)}` : `${capitalize(modName)}::${getJsonDataPrefix()}${capitalize(name)}` return ((result.includes(wpeJsonNameSpace()) === true) ? result : `${getSdkNameSpace()}::${result}`) } diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index 3437c3f4..cc7ac662 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -29,7 +29,7 @@ const { isObject, isArray, propEq, pathSatisfies, hasProp, propSatisfies } = pre const getModuleName = json => getPathOr(null, ['info', 'title'], json) || json.title || 'missing' -const getFireboltStringType = () => 'FireboltTypes_String_t' +const getFireboltStringType = () => 'Firebolt_String_t' const capitalize = str => str[0].toUpperCase() + str.substr(1) const description = (title, str='') => '/* ' + title + (str.length > 0 ? ' - ' + str : '') + ' */' @@ -64,13 +64,13 @@ const getNativeType = (json, fireboltString = false) => { return type } -const getObjectHandleManagement = varName => { +const getObjectManagement = varName => { let result = `typedef struct ${varName}_s* ${varName}_t; -${varName}_t ${varName}Handle_Acquire(void); -void ${varName}Handle_Addref(${varName}_t handle); -void ${varName}Handle_Release(${varName}_t handle); -bool ${varName}Handle_IsValid(${varName}_t handle); +${varName}_t ${varName}_Acquire(void); +void ${varName}_Addref(${varName}_t handle); +void ${varName}_Release(${varName}_t handle); +bool ${varName}_IsValid(${varName}_t handle); ` return result } @@ -111,7 +111,7 @@ const getTypeName = (moduleName, varName, prefix = '', upperCase = false, capita prefix = (prefix !== varName) ? (upperCase ? prefix.toUpperCase() : capitalize(prefix)) : '' } prefix = (prefix && prefix.length > 0) ?(upperCase ? prefix.toUpperCase() : capitalize(prefix)) : prefix - let name = (prefix && prefix.length > 0) ? `${mName}_${prefix}${vName}` : `${mName}_${vName}` + let name = (prefix && prefix.length > 0) ? `${mName}_${prefix}_${vName}` : `${mName}_${vName}` return name } @@ -155,57 +155,16 @@ function getPropertyGetterSignature(property, module, propType, paramList = []) return `uint32_t ${capitalize(getModuleName(module))}_Get${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType}* ${property.result.name || property.name} )` } -function getPropertySetterSignature(property, module, propType, paramList = []) { - let contextParams = '' - contextParams = getContextParams(paramList) - if (propType === getFireboltStringType()) { - propType = 'char*' - } - return `uint32_t ${capitalize(getModuleName(module))}_Set${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType} ${property.result.name || property.name} )` -} - -function getPropertyEventCallbackSignature(property, module, propType, paramList = []) { - - let contextParams = '' - contextParams = getContextParams(paramList) - return `/*Callback to listen to updates on ${property.Name} property*/\n` + - `typedef void (*On${capitalize(getModuleName(module))}${capitalize(property.name)}Changed)( ${contextParams}${contextParams.length > 0 ? ', ':''}const void* userData, ${propType} ${property.result.name || property.name})` -} - -function getPropertyEventInnerCallbackSignature(method, module, schemas) { - let signature = `static void ${capitalize(getModuleName(module)) + capitalize(method.name)}` -} - -function getPropertyEventRegisterSignature(property, module, paramList = []) { - let contextParams = '' - contextParams = getContextParams(paramList) - - return `/*Register to listen to updates on ${capitalize(property.name)} property*/\n` + - `uint32_t ${capitalize(getModuleName(module))}_Register_${capitalize(property.name)}Update( ${contextParams}${contextParams.length > 0 ? ', ':''}On${capitalize(getModuleName(module))}${capitalize(property.name)}Changed userCB, const void* userData )` - -} - -function getPropertyEventUnregisterSignature(property, module) { - return `/*Unregister to listen to updates on ${capitalize(property.name)} property*/\n` + - `uint32_t ${capitalize(getModuleName(module))}_Unregister_${capitalize(property.name)}Update( On${capitalize(getModuleName(module))}${capitalize(property.name)}Changed userCB )` - -} - - export { getNativeType, getModuleName, getPropertyGetterSignature, - getPropertySetterSignature, - getPropertyEventCallbackSignature, - getPropertyEventRegisterSignature, - getPropertyEventUnregisterSignature, getMapAccessors, getArrayAccessors, capitalize, description, getTypeName, - getObjectHandleManagement, + getObjectManagement, getPropertyAccessors, isOptional, generateEnum, diff --git a/languages/c/templates/declarations/default.c b/languages/c/templates/declarations/default.c index ac4e7f78..8879378d 100644 --- a/languages/c/templates/declarations/default.c +++ b/languages/c/templates/declarations/default.c @@ -1,3 +1,4 @@ /* ${method.name} - ${method.description} ${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation}${end.if.deprecated} */ -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 ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name}${end.if.result}${if.signature.empty}void${end.if.signature.empty} ); + diff --git a/languages/c/templates/declarations/event.c b/languages/c/templates/declarations/event.c index 45e4b608..4dc59c4a 100644 --- a/languages/c/templates/declarations/event.c +++ b/languages/c/templates/declarations/event.c @@ -2,3 +2,4 @@ typedef void (*${info.Title}${method.Name}Callback)( const void* userData, ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${event.result.type} ); 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 ); uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); + diff --git a/languages/c/templates/declarations/polymorphic-pull-event.c b/languages/c/templates/declarations/polymorphic-pull-event.c index 26f1f1c4..9b22619e 100644 --- a/languages/c/templates/declarations/polymorphic-pull-event.c +++ b/languages/c/templates/declarations/polymorphic-pull-event.c @@ -2,3 +2,4 @@ typedef void* (*${info.Title}${method.Name}Callback)( const void* userData, ${method.pulls.param.type} ); uint32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callback userCB, const void* userData ); uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); + diff --git a/languages/c/templates/declarations/polymorphic-pull.c b/languages/c/templates/declarations/polymorphic-pull.c index fbf74697..ca08d823 100644 --- a/languages/c/templates/declarations/polymorphic-pull.c +++ b/languages/c/templates/declarations/polymorphic-pull.c @@ -1,2 +1,3 @@ /* ${method.name} - ${method.description} */ uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ); + diff --git a/languages/c/templates/declarations/setter.c b/languages/c/templates/declarations/setter.c new file mode 100644 index 00000000..9fcd86a2 --- /dev/null +++ b/languages/c/templates/declarations/setter.c @@ -0,0 +1,2 @@ +/* ${method.rpc.name} - ${method.description} */ +uint32_t ${info.Title}_${method.Name}( ${method.signature.params} ); diff --git a/languages/c/templates/methods/calls-metrics.c b/languages/c/templates/methods/calls-metrics.c index 91831a3c..c8caa238 100644 --- a/languages/c/templates/methods/calls-metrics.c +++ b/languages/c/templates/methods/calls-metrics.c @@ -2,8 +2,7 @@ void Metrics_${method.Name}Dispatcher(const void*${if.result} result${end.if.result}) { Metrics_${method.Name}(${if.result}(static_cast<${method.result.json.type}>(const_cast(result)))${end.if.result}); } - -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 ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name}${end.if.result}${if.signature.empty}void${end.if.signature.empty} ) { uint32_t status = FireboltSDKErrorUnavailable; FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); @@ -14,7 +13,7 @@ uint32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${i status = transport->Invoke("${info.title}.${method.rpc.name}", jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); -${method.result.instantiation} + ${method.result.instantiation.with.indent} void* result = nullptr; ${if.result}result = static_cast(new ${method.result.json.type});${end.if.result} @@ -28,3 +27,4 @@ uint32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${i return status; } + diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index 881b592c..d8f619c5 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -1,5 +1,5 @@ /* ${method.rpc.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 ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name}${end.if.result}${if.signature.empty}void${end.if.signature.empty} ) { uint32_t status = FireboltSDKErrorUnavailable; FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); @@ -10,7 +10,7 @@ uint32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${i status = transport->Invoke("${info.title.lowercase}.${method.rpc.name}", jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); -${method.result.instantiation} + ${method.result.instantiation.with.indent} } } else { @@ -19,3 +19,4 @@ uint32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${i return status; } + diff --git a/languages/c/templates/methods/event.c b/languages/c/templates/methods/event.c index c02e74c4..2a2de707 100644 --- a/languages/c/templates/methods/event.c +++ b/languages/c/templates/methods/event.c @@ -24,3 +24,4 @@ uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Cal { return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); } + diff --git a/languages/c/templates/methods/polymorphic-pull-event.c b/languages/c/templates/methods/polymorphic-pull-event.c index 7c833b71..5bf302b5 100644 --- a/languages/c/templates/methods/polymorphic-pull-event.c +++ b/languages/c/templates/methods/polymorphic-pull-event.c @@ -52,3 +52,4 @@ uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Cal { return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); } + diff --git a/languages/c/templates/methods/polymorphic-pull.c b/languages/c/templates/methods/polymorphic-pull.c index 759b0ae9..d543e3ce 100644 --- a/languages/c/templates/methods/polymorphic-pull.c +++ b/languages/c/templates/methods/polymorphic-pull.c @@ -5,7 +5,7 @@ uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ) FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { - string correlationId = ""; + string correlationId = ""; ${method.params.serialization.with.indent} WPEFramework::Core::JSON::Boolean jsonResult; @@ -20,3 +20,4 @@ uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ) return status; } + diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index 7fb5b148..af6200c9 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,5 +1,5 @@ /* ${method.rpc.name} - ${method.description} */ -uint32_t ${info.Title}_Get${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name} ) +uint32_t ${info.Title}_Get${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name} ) { const string method = _T("${info.title.lowercase}.${method.rpc.name}"); ${if.params}${method.params.serialization}${end.if.params} @@ -7,9 +7,7 @@ uint32_t ${info.Title}_Get${method.Name}( ${method.signature.params}${if.params} ${if.params}uint32_t status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult);${end.if.params} ${if.params.empty}uint32_t status = FireboltSDK::Properties::Get(method, jsonResult);${end.if.params.empty} if (status == FireboltSDKErrorNone) { - if (${method.result.name} != nullptr) { ${method.result.instantiation} - } } return status; } diff --git a/languages/c/templates/modules/include/module.h b/languages/c/templates/modules/include/module.h index 176ff9c1..1c8d427b 100644 --- a/languages/c/templates/modules/include/module.h +++ b/languages/c/templates/modules/include/module.h @@ -32,6 +32,8 @@ extern "C" { // Accessors /* ${ACCESSORS} */ + + // Methods & Events /* ${DECLARATIONS} */ diff --git a/languages/c/templates/modules/src/module.cpp b/languages/c/templates/modules/src/module.cpp index 737d38df..19727924 100644 --- a/languages/c/templates/modules/src/module.cpp +++ b/languages/c/templates/modules/src/module.cpp @@ -36,6 +36,8 @@ extern "C" { // Accessors /* ${ACCESSORS} */ + + // Methods /* ${METHODS} */ diff --git a/languages/c/templates/schemas/src/module_common.cpp b/languages/c/templates/schemas/src/module_common.cpp index 582a650b..5bfa7719 100644 --- a/languages/c/templates/schemas/src/module_common.cpp +++ b/languages/c/templates/schemas/src/module_common.cpp @@ -26,14 +26,16 @@ extern "C" { #endif - // Accessors - /* ${ACCESSORS} */ +// Accessors +/* ${ACCESSORS} */ - // Methods - /* ${METHODS} */ - // Events - /* ${EVENTS} */ + +// Methods +/* ${METHODS} */ + +// Events +/* ${EVENTS} */ #ifdef __cplusplus } diff --git a/languages/c/templates/sdk/scripts/install.sh b/languages/c/templates/sdk/scripts/install.sh index 15596524..24bd1c4c 100755 --- a/languages/c/templates/sdk/scripts/install.sh +++ b/languages/c/templates/sdk/scripts/install.sh @@ -7,7 +7,7 @@ usage() echo " -m module name. i.e, core/manage" echo echo "usage: " - echo " ./install.sh -i path -s sdk path-m core" + echo " ./install.sh -i path -s sdk path -m core" } SdkPath=".." diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index d8daa16e..d0535d00 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -60,7 +60,8 @@ let types = { let config = { copySchemasIntoModules: false, - extractSubSchemas: false + extractSubSchemas: false, + excludeDeclarations: false } const state = { @@ -370,7 +371,7 @@ const addContentDescriptorSubSchema = (descriptor, prefix, obj) => { else { let descriptorName = capitalize(descriptor.name) let prefixName = capitalize(prefix) - title = (prefixName !== descriptorName) ? prefixName + descriptorName : descriptorName + title = (prefixName !== descriptorName) ? prefixName + '_' +descriptorName : descriptorName if (obj.components.schemas[title]) { throw 'Generated name `' + title + '` already exists...' } @@ -390,13 +391,15 @@ const promoteAndNameSubSchemas = (obj) => { obj = JSON.parse(JSON.stringify(obj)) // find anonymous method param or result schemas and name/promote them obj.methods && obj.methods.forEach(method => { - method.params && method.params.forEach(param => { - if (isSubSchema(param.schema)) { - addContentDescriptorSubSchema(param, method.name, obj) + if (!isExcludedMethod(method)) { + method.params && method.params.forEach(param => { + if (isSubSchema(param.schema)) { + addContentDescriptorSubSchema(param, method.name, obj) + } + }) + if (isSubSchema(method.result.schema)) { + addContentDescriptorSubSchema(method.result, method.name, obj) } - }) - if (isSubSchema(method.result.schema)) { - addContentDescriptorSubSchema(method.result, method.name, obj) } }) @@ -457,9 +460,9 @@ const generateMacros = (obj, templates, languages, options = {}) => { const examples = generateExamples(obj, templates, languages) const allMethodsArray = generateMethods(obj, examples, templates) - 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) + 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 declarations = declarationsArray.length ? getTemplate('/sections/declarations', templates).replace(/\$\{declaration\.list\}/g, declarationsArray.map(m => m.declaration).join('\n')) : '' const methods = methodsArray.length ? getTemplate('/sections/methods', templates).replace(/\$\{method.list\}/g, methodsArray.map(m => m.body).join('\n')) : '' @@ -529,7 +532,7 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{module.list\}/g, macros.module) fContents = fContents.replace(/[ \t]*\/\* \$\{METHODS\} \*\/[ \t]*\n/, macros.methods) - fContents = fContents.replace(/[ \t]*\/\* \$\{ACCESSORS\} \*\/[ \t]*\n/, macros.accessors) + fContents = fContents.replace(/[ \t]*\/\* \$\{ACCESSORS\} \*\/[ \t]*\n/, macros.accessors.trimStart('\n')) fContents = fContents.replace(/[ \t]*\/\* \$\{DECLARATIONS\} \*\/[ \t]*\n/, macros.declarations) fContents = fContents.replace(/[ \t]*\/\* \$\{METHOD_LIST\} \*\/[ \t]*\n/, macros.methodList.join(',\n')) fContents = fContents.replace(/[ \t]*\/\* \$\{EVENTS\} \*\/[ \t]*\n/, macros.events) @@ -1229,6 +1232,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) .replace(/\$\{method\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{method\.result\.instantiation\}/g, resultInst) + .replace(/\$\{method\.result\.instantiation\.with\.indent\}/g, indent(resultInst, ' ')) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) .replace(/\$\{method\.alternative\}/g, method.alternative) .replace(/\$\{method\.alternative.link\}/g, '#' + (method.alternative || "").toLowerCase()) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 86483fad..ce8d3d8d 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -48,6 +48,7 @@ const macrofy = async ( createModuleDirectories, copySchemasIntoModules, extractSubSchemas, + excludeDeclarations, aggregateFile, operators, hidePrivate = true, @@ -82,6 +83,7 @@ const macrofy = async ( copySchemasIntoModules, createModuleDirectories, extractSubSchemas, + excludeDeclarations, operators }) diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index 2e72ba9b..5d7effa2 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -63,6 +63,7 @@ const run = async ({ createModuleDirectories: config.createModuleDirectories, copySchemasIntoModules: config.copySchemasIntoModules, extractSubSchemas: config.extractSubSchemas, + excludeDeclarations: config.excludeDeclarations, staticModuleNames: staticModuleNames, hideExcluded: true, aggregateFile: config.aggregateFile, From 1563c64045d004871243f7371457ea6ad8413987 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 7 Aug 2023 10:10:55 +0530 Subject: [PATCH 097/137] SubArray generation issue fix (#121) --- languages/c/Types.mjs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/languages/c/Types.mjs b/languages/c/Types.mjs index 6c3c8311..8b14f4c3 100644 --- a/languages/c/Types.mjs +++ b/languages/c/Types.mjs @@ -299,11 +299,12 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref res = getSchemaTypeInfo(module, json.items, json.items.name || name, schemas, prefix) } - name = name.endsWith("_ArrayType") ? name.split('_ArrayType')[0] : name - prefix = prefix ? prefix + name : name - let n = getTypeName(getModuleName(module), capitalize(res.name), prefix) - structure.name = name ? name + capitalize(res.name) : res.name + name = capitalize(name) + res.name = capitalize(res.name) + prefix = prefix ? prefix + ((name !== res.name) ? name : '') : name + let n = getTypeName(getModuleName(module), res.name, prefix) + structure.name = (name && (name !== res.name)) ? name + capitalize(res.name) : res.name structure.type = n + 'Array_t' structure.json = json structure.namespace = getModuleName(module) From 3c9a909d22448acb37861f8bea462eb7781d4988 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 7 Aug 2023 10:11:35 +0530 Subject: [PATCH 098/137] cmake changes to install proper files (#119) --- languages/c/src/shared/CMakeLists.txt | 5 -- .../c/src/shared/cmake/HelperFunctions.cmake | 90 ++----------------- languages/c/src/shared/src/CMakeLists.txt | 28 +++--- languages/c/templates/sdk/scripts/build.sh | 13 +-- 4 files changed, 28 insertions(+), 108 deletions(-) diff --git a/languages/c/src/shared/CMakeLists.txt b/languages/c/src/shared/CMakeLists.txt index 5efcad1a..fe7a0085 100644 --- a/languages/c/src/shared/CMakeLists.txt +++ b/languages/c/src/shared/CMakeLists.txt @@ -23,11 +23,6 @@ set(FIREBOLT_LOGLEVEL "Info" CACHE STRING "Log level to be enabled") option(FIREBOLT_ENABLE_STATIC_LIB "Create Firebolt library as Static library" OFF) option(ENABLE_TESTS "Build openrpc native test" OFF) -if (NOT SYSROOT_PATH) - # Set sysroot to support PC builds, sysroot_path not configured case - set(SYSROOT_PATH "${CMAKE_SOURCE_DIR}/../../firebolt") -endif() - if (FIREBOLT_ENABLE_STATIC_LIB) set(FIREBOLT_LIBRARY_TYPE STATIC) else () diff --git a/languages/c/src/shared/cmake/HelperFunctions.cmake b/languages/c/src/shared/cmake/HelperFunctions.cmake index b3647c16..eb2ae296 100644 --- a/languages/c/src/shared/cmake/HelperFunctions.cmake +++ b/languages/c/src/shared/cmake/HelperFunctions.cmake @@ -56,89 +56,17 @@ function(InstallHeaders) list(APPEND subdirs ${directory}) foreach(subdir ${subdirs}) - set(dest ${destination}/${subdir}) - file(GLOB headers "${source}/${directory}/${subdir}/*.h") - if (headers) - add_custom_command( - TARGET ${Argument_TARGET} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_NAMESPACE}/usr/include/${dest} - COMMAND ${CMAKE_COMMAND} -E copy ${source}/${directory}/${subdir}/*.h ${CMAKE_BINARY_DIR}/${Argument_NAMESPACE}/usr/include/${dest} - ) + if (NOT subdir STREQUAL ".") + set(dest ${destination}/${subdir}) + file(GLOB headers "${source}/${directory}/${subdir}/*.h") + if (headers) + install( + DIRECTORY "${source}/${directory}/${subdir}" + DESTINATION include/${dest} + FILES_MATCHING PATTERN "*.h") + endif() endif() endforeach(subdir) endforeach(directory) endif() endfunction(InstallHeaders) - -function(InstallLibraries) - set(optionsArgs SHARED STATIC) - set(oneValueArgs TARGET DESTINATION LIBDIR) - set(multiValueArgs LIBRARIES) - - cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) - if (Argument_UNPARSED_ARGUMENTS) - message(FATAL_ERROR "Unknown keywords given to InstallLibraries(): \"${Argument_UNPARSED_ARGUMENTS}\"") - endif() - if (Argument_LIBRARIES) - add_custom_command( - TARGET ${Argument_TARGET} - POST_BUILD - COMMENT "=================== Installing Libraries ======================" - ) - foreach(LIBRARY ${Argument_LIBRARIES}) - if (Argument_SHARED) - add_custom_command( - TARGET ${Argument_TARGET} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_LIBDIR}/lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib - COMMAND ${CMAKE_COMMAND} -E create_symlink lib${LIBRARY}.so.${PROJECT_VERSION} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR} - COMMAND ${CMAKE_COMMAND} -E create_symlink lib${LIBRARY}.so.${PROJECT_VERSION_MAJOR} ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/lib${LIBRARY}.so - ) - elseif (Argument_STATIC) - add_custom_command( - TARGET ${Argument_TARGET} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/lib${LIBRARY}.a ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib - ) - - endif() - endforeach(LIBRARY) - endif() -endfunction(InstallLibraries) - -function(InstallCMakeConfigs) - set(optionsArgs) - set(oneValueArgs TARGET DESTINATION) - set(multiValueArgs) - - cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) - if (Argument_UNPARSED_ARGUMENTS) - message(FATAL_ERROR "Unknown keywords given to InstallCMakeConfigs(): \"${Argument_UNPARSED_ARGUMENTS}\"") - endif() - if (Argument_TARGET) - if (${CMAKE_VERSION} VERSION_LESS "3.25.0") - set(EXPORT_CONFIG_PATH "lib/cmake/${Argument_TARGET}") - else () - set(EXPORT_CONFIG_PATH "*") - endif () - add_custom_command( - TARGET ${Argument_TARGET} - POST_BUILD - COMMENT "=================== Installing CMakeConfigs ======================" - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}Config*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/Export/${EXPORT_CONFIG_PATH}/${Argument_TARGET}Targets*.cmake ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/cmake/${Argument_TARGET} - ) - if (EXISTS ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}.pc) - add_custom_command( - TARGET ${Argument_TARGET} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/pkgconfig - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${Argument_TARGET}.pc ${CMAKE_BINARY_DIR}/${Argument_DESTINATION}/usr/lib/pkgconfig - ) - endif() - endif() -endfunction(InstallCMakeConfigs) diff --git a/languages/c/src/shared/src/CMakeLists.txt b/languages/c/src/shared/src/CMakeLists.txt index b565d6b1..ecaf4efb 100644 --- a/languages/c/src/shared/src/CMakeLists.txt +++ b/languages/c/src/shared/src/CMakeLists.txt @@ -55,25 +55,19 @@ set_target_properties(${TARGET} PROPERTIES install( TARGETS ${TARGET} EXPORT ${TARGET}Targets - LIBRARY DESTINATION lib COMPONENT libs - PUBLIC_HEADER DESTINATION include/${TARGET} COMPONENT devel # headers for mac (note the different component -> different package) - INCLUDES DESTINATION include/${TARGET} # headers + ARCHIVE DESTINATION lib COMPONENT libs # static lib + LIBRARY DESTINATION lib COMPONENT libs # shared lib ) -InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION ${FIREBOLT_NAMESPACE}SDK) -InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} - SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../include DESTINATION ${FIREBOLT_NAMESPACE}) +install( + DIRECTORY ${CMAKE_SOURCE_DIR}/include/ + DESTINATION include/${FIREBOLT_NAMESPACE}SDK + FILES_MATCHING PATTERN "*.h") + +install( + FILES ${CMAKE_BINARY_DIR}/FireboltConfig.cmake + DESTINATION lib/cmake/${FIREBOLT_NAMESPACE}) -InstallLibraries(TARGET ${TARGET} ${FIREBOLT_LIBRARY_TYPE} LIBDIR ${LIBDIR} LIBRARIES ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION ${FIREBOLT_NAMESPACE}SDK) InstallCMakeConfig(TARGETS ${TARGET}) InstallPackageConfig(TARGETS ${TARGET} DESCRIPTION "Firebolt SDK Library") -InstallCMakeConfigs(TARGET ${TARGET} DESTINATION ${FIREBOLT_NAMESPACE}) - -add_custom_command( - TARGET ${TARGET} - POST_BUILD - COMMENT "=================== Installing FireboltConfig & Helper CMakes ======================" - COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} - COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/cmake/*.cmake ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/lib/cmake/${FIREBOLT_NAMESPACE} -) diff --git a/languages/c/templates/sdk/scripts/build.sh b/languages/c/templates/sdk/scripts/build.sh index d50295a6..149cd1ae 100755 --- a/languages/c/templates/sdk/scripts/build.sh +++ b/languages/c/templates/sdk/scripts/build.sh @@ -4,8 +4,9 @@ usage() echo "options:" echo " -p sdk path" echo " -s sysroot path" - echo " -t enable test" echo " -c clear build" + echo " -l enable static build" + echo " -t enable test" echo " -h : help" echo echo "usage: " @@ -16,13 +17,15 @@ SdkPath="." EnableTest="OFF" SysrootPath=${SYSROOT_PATH} ClearBuild="N" -while getopts p:s:tch flag +EnableStaticLib="OFF" +while getopts p:s:clth flag do case "${flag}" in p) SdkPath="${OPTARG}";; s) SysrootPath="${OPTARG}";; - t) EnableTest="ON";; c) ClearBuild="Y";; + l) EnableStaticLib="ON";; + t) EnableTest="ON";; h) usage && exit 1;; esac done @@ -32,6 +35,6 @@ then rm -rf ${SdkPath}/build fi -cmake -B${SdkPath}/build -S${SdkPath} -DSYSROOT_PATH=${SysrootPath} -DENABLE_TESTS=${EnableTest} +cmake -B${SdkPath}/build -S${SdkPath} -DSYSROOT_PATH=${SysrootPath} -DENABLE_TESTS=${EnableTest} -DHIDE_NON_EXTERNAL_SYMBOLS=OFF -DFIREBOLT_ENABLE_STATIC_LIB=${EnableStaticLib} cmake --build ${SdkPath}/build -cmake --install ${SdkPath}/build --prefix=${SdkPath}/build/Firebolt +cmake --install ${SdkPath}/build --prefix=${SdkPath}/build/Firebolt/usr From 6a0f4e68b95a14e9edbbbacb025237ed9dc41b97 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Tue, 15 Aug 2023 19:14:25 +0530 Subject: [PATCH 099/137] native code: changed return type from uint32_t to int32_t (#127) --- .../c/src/shared/src/Accessor/Accessor.cpp | 10 ++-- .../c/src/shared/src/Accessor/Accessor.h | 10 ++-- languages/c/src/shared/src/Event/Event.cpp | 14 ++--- languages/c/src/shared/src/Event/Event.h | 22 +++---- languages/c/src/shared/src/Logger/Logger.cpp | 4 +- languages/c/src/shared/src/Logger/Logger.h | 2 +- .../c/src/shared/src/Properties/Properties.h | 24 ++++---- .../c/src/shared/src/Transport/Transport.h | 44 +++++++------- languages/c/src/shared/src/firebolt.cpp | 5 +- languages/c/src/shared/test/OpenRPCCTests.h | 14 ++--- languages/c/src/shared/test/OpenRPCTests.cpp | 60 +++++++++---------- languages/c/src/shared/test/OpenRPCTests.h | 22 +++---- languages/c/src/types/NativeHelpers.mjs | 2 +- languages/c/templates/codeblocks/setter.c | 2 +- languages/c/templates/declarations/default.c | 2 +- languages/c/templates/declarations/event.c | 4 +- .../declarations/polymorphic-pull-event.c | 4 +- .../templates/declarations/polymorphic-pull.c | 2 +- languages/c/templates/declarations/setter.c | 2 +- languages/c/templates/methods/calls-metrics.c | 4 +- languages/c/templates/methods/default.c | 4 +- languages/c/templates/methods/event.c | 6 +- .../methods/polymorphic-pull-event.c | 9 ++- .../c/templates/methods/polymorphic-pull.c | 4 +- languages/c/templates/methods/property.c | 6 +- 25 files changed, 140 insertions(+), 142 deletions(-) diff --git a/languages/c/src/shared/src/Accessor/Accessor.cpp b/languages/c/src/shared/src/Accessor/Accessor.cpp index e4a5df32..6d4aceae 100644 --- a/languages/c/src/shared/src/Accessor/Accessor.cpp +++ b/languages/c/src/shared/src/Accessor/Accessor.cpp @@ -50,13 +50,13 @@ namespace FireboltSDK { _singleton = nullptr; } - uint32_t Accessor::CreateEventHandler() + int32_t Accessor::CreateEventHandler() { Event::Instance().Configure(_transport); return FireboltSDKErrorNone; } - uint32_t Accessor::DestroyEventHandler() + int32_t Accessor::DestroyEventHandler() { Event::Dispose(); return FireboltSDKErrorNone; @@ -67,7 +67,7 @@ namespace FireboltSDK { return Event::Instance(); } - uint32_t Accessor::CreateTransport(const string& url, const uint32_t waitTime = DefaultWaitTime) + int32_t Accessor::CreateTransport(const string& url, const uint32_t waitTime = DefaultWaitTime) { if (_transport != nullptr) { delete _transport; @@ -83,7 +83,7 @@ namespace FireboltSDK { return ((_transport != nullptr) ? FireboltSDKErrorNone : FireboltSDKErrorUnavailable); } - uint32_t Accessor::DestroyTransport() + int32_t Accessor::DestroyTransport() { if (_transport != nullptr) { delete _transport; @@ -98,7 +98,7 @@ namespace FireboltSDK { return _transport; } - uint32_t Accessor::WaitForLinkReady(Transport* transport, const uint32_t waitTime = DefaultWaitTime) { + int32_t Accessor::WaitForLinkReady(Transport* transport, const uint32_t waitTime = DefaultWaitTime) { uint32_t waiting = (waitTime == WPEFramework::Core::infinite ? WPEFramework::Core::infinite : waitTime); static constexpr uint32_t SLEEPSLOT_TIME = 100; diff --git a/languages/c/src/shared/src/Accessor/Accessor.h b/languages/c/src/shared/src/Accessor/Accessor.h index f12dc51c..e247df98 100644 --- a/languages/c/src/shared/src/Accessor/Accessor.h +++ b/languages/c/src/shared/src/Accessor/Accessor.h @@ -107,11 +107,11 @@ namespace FireboltSDK { Transport* GetTransport(); private: - uint32_t CreateEventHandler(); - uint32_t DestroyEventHandler(); - uint32_t CreateTransport(const string& url, const uint32_t waitTime); - uint32_t DestroyTransport(); - uint32_t WaitForLinkReady(Transport* transport, const uint32_t waitTime); + int32_t CreateEventHandler(); + int32_t DestroyEventHandler(); + int32_t CreateTransport(const string& url, const uint32_t waitTime); + int32_t DestroyTransport(); + int32_t WaitForLinkReady(Transport* transport, const uint32_t waitTime); private: WPEFramework::Core::ProxyType _workerPool; diff --git a/languages/c/src/shared/src/Event/Event.cpp b/languages/c/src/shared/src/Event/Event.cpp index 5e98a36f..c1fdff6f 100644 --- a/languages/c/src/shared/src/Event/Event.cpp +++ b/languages/c/src/shared/src/Event/Event.cpp @@ -60,9 +60,9 @@ namespace FireboltSDK { _transport->SetEventHandler(this); } - uint32_t Event::Unsubscribe(const string& eventName, void* usercb) + int32_t Event::Unsubscribe(const string& eventName, void* usercb) { - uint32_t status = Revoke(eventName, usercb); + int32_t status = Revoke(eventName, usercb); if (status == FireboltSDKErrorNone) { if (_transport != nullptr) { @@ -74,9 +74,9 @@ namespace FireboltSDK { return ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone: status); } - uint32_t Event::ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) /* override */ + int32_t Event::ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) /* override */ { - uint32_t result = FireboltSDKErrorGeneral; + int32_t result = FireboltSDKErrorGeneral; Response response; _transport->FromMessage((WPEFramework::Core::JSON::IElement*)&response, *jsonResponse); if (response.Listening.IsSet() == true) { @@ -86,7 +86,7 @@ namespace FireboltSDK { return result; } - uint32_t Event::Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) /* override */ + int32_t Event::Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) /* override */ { string response = jsonResponse->Result.Value(); _adminLock.Lock(); @@ -120,9 +120,9 @@ namespace FireboltSDK { return FireboltSDKErrorNone;; } - uint32_t Event::Revoke(const string& eventName, void* usercb) + int32_t Event::Revoke(const string& eventName, void* usercb) { - uint32_t status = FireboltSDKErrorNone; + int32_t status = FireboltSDKErrorNone; _adminLock.Lock(); EventMap::iterator eventIndex = _eventMap.find(eventName); if (eventIndex != _eventMap.end()) { diff --git a/languages/c/src/shared/src/Event/Event.h b/languages/c/src/shared/src/Event/Event.h index efa8457a..dd65cb53 100644 --- a/languages/c/src/shared/src/Event/Event.h +++ b/languages/c/src/shared/src/Event/Event.h @@ -26,7 +26,7 @@ namespace FireboltSDK { class Event : public IEventHandler { public: - typedef std::function DispatchFunction; + typedef std::function DispatchFunction; private: enum State : uint8_t { IDLE, @@ -73,16 +73,16 @@ namespace FireboltSDK { public: template - uint32_t Subscribe(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) + int32_t Subscribe(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) { JsonObject jsonParameters; return Subscribe(eventName, jsonParameters, callback, usercb, userdata); } template - uint32_t Subscribe(const string& eventName, JsonObject& jsonParameters, const CALLBACK& callback, void* usercb, const void* userdata) + int32_t Subscribe(const string& eventName, JsonObject& jsonParameters, const CALLBACK& callback, void* usercb, const void* userdata) { - uint32_t status = FireboltSDKErrorUnavailable; + int32_t status = FireboltSDKErrorUnavailable; if (_transport != nullptr) { status = Assign(eventName, callback, usercb, userdata); @@ -110,15 +110,15 @@ namespace FireboltSDK { return status; } - uint32_t Unsubscribe(const string& eventName, void* usercb); + int32_t Unsubscribe(const string& eventName, void* usercb); private: template - uint32_t Assign(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) + int32_t Assign(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) { - uint32_t status = FireboltSDKErrorNone; + int32_t status = FireboltSDKErrorNone; std::function actualCallback = callback; - DispatchFunction implementation = [actualCallback](void* usercb, const void* userdata, const string& parameters) -> uint32_t { + DispatchFunction implementation = [actualCallback](void* usercb, const void* userdata, const string& parameters) -> int32_t { WPEFramework::Core::ProxyType* inbound = new WPEFramework::Core::ProxyType(); *inbound = WPEFramework::Core::ProxyType::Create(); @@ -149,11 +149,11 @@ namespace FireboltSDK { _adminLock.Unlock(); return status; } - uint32_t Revoke(const string& eventName, void* usercb); + int32_t Revoke(const string& eventName, void* usercb); private: - uint32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) override; - uint32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) override; + int32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) override; + int32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) override; private: EventMap _eventMap; diff --git a/languages/c/src/shared/src/Logger/Logger.cpp b/languages/c/src/shared/src/Logger/Logger.cpp index a16764f2..44ebaba8 100644 --- a/languages/c/src/shared/src/Logger/Logger.cpp +++ b/languages/c/src/shared/src/Logger/Logger.cpp @@ -45,10 +45,10 @@ ENUM_CONVERSION_END(FireboltSDK::Logger::Category) namespace FireboltSDK { /* static */ Logger::LogLevel Logger::_logLevel = Logger::LogLevel::Error; - uint32_t Logger::SetLogLevel(Logger::LogLevel logLevel) + int32_t Logger::SetLogLevel(Logger::LogLevel logLevel) { ASSERT(logLevel < Logger::LogLevel::MaxLevel); - uint32_t status = FireboltSDKErrorNotSupported; + int32_t status = FireboltSDKErrorNotSupported; if (logLevel < Logger::LogLevel::MaxLevel) { _logLevel = logLevel; status = FireboltSDKErrorNone; diff --git a/languages/c/src/shared/src/Logger/Logger.h b/languages/c/src/shared/src/Logger/Logger.h index 2c864c7b..b8e42031 100644 --- a/languages/c/src/shared/src/Logger/Logger.h +++ b/languages/c/src/shared/src/Logger/Logger.h @@ -49,7 +49,7 @@ namespace FireboltSDK { ~Logger() = default; public: - static uint32_t SetLogLevel(LogLevel logLevel); + static int32_t SetLogLevel(LogLevel logLevel); static void Log(LogLevel logLevel, Category category, const std::string& module, const std::string file, const std::string function, const uint16_t line, const std::string& format, ...); public: diff --git a/languages/c/src/shared/src/Properties/Properties.h b/languages/c/src/shared/src/Properties/Properties.h index d75c3ba5..eaf6c1a4 100644 --- a/languages/c/src/shared/src/Properties/Properties.h +++ b/languages/c/src/shared/src/Properties/Properties.h @@ -33,9 +33,9 @@ namespace FireboltSDK { public: template - static uint32_t Get(const string& propertyName, WPEFramework::Core::ProxyType& response) + static int32_t Get(const string& propertyName, WPEFramework::Core::ProxyType& response) { - uint32_t status = FireboltSDKErrorUnavailable; + int32_t status = FireboltSDKErrorUnavailable; Transport* transport = Accessor::Instance().GetTransport(); if (transport != nullptr) { JsonObject parameters; @@ -57,9 +57,9 @@ namespace FireboltSDK { } template - static uint32_t Get(const string& propertyName, const PARAMETERS& parameters, WPEFramework::Core::ProxyType& response) + static int32_t Get(const string& propertyName, const PARAMETERS& parameters, WPEFramework::Core::ProxyType& response) { - uint32_t status = FireboltSDKErrorUnavailable; + int32_t status = FireboltSDKErrorUnavailable; Transport* transport = Accessor::Instance().GetTransport(); if (transport != nullptr) { RESPONSETYPE responseType; @@ -81,9 +81,9 @@ namespace FireboltSDK { template - static uint32_t Get(const string& propertyName, RESPONSETYPE& response) + static int32_t Get(const string& propertyName, RESPONSETYPE& response) { - uint32_t status = FireboltSDKErrorUnavailable; + int32_t status = FireboltSDKErrorUnavailable; Transport* transport = Accessor::Instance().GetTransport(); if (transport != nullptr) { JsonObject parameters; @@ -96,9 +96,9 @@ namespace FireboltSDK { } template - static uint32_t Get(const string& propertyName, const PARAMETERS& parameters, RESPONSETYPE& response) + static int32_t Get(const string& propertyName, const PARAMETERS& parameters, RESPONSETYPE& response) { - uint32_t status = FireboltSDKErrorUnavailable; + int32_t status = FireboltSDKErrorUnavailable; Transport* transport = Accessor::Instance().GetTransport(); if (transport != nullptr) { status = transport->Invoke(propertyName, parameters, response); @@ -110,9 +110,9 @@ namespace FireboltSDK { } template - static uint32_t Set(const string& propertyName, const PARAMETERS& parameters) + static int32_t Set(const string& propertyName, const PARAMETERS& parameters) { - uint32_t status = FireboltSDKErrorUnavailable; + int32_t status = FireboltSDKErrorUnavailable; Transport* transport = Accessor::Instance().GetTransport(); if (transport != nullptr) { JsonObject responseType; @@ -125,12 +125,12 @@ namespace FireboltSDK { } template - static uint32_t Subscribe(const string& propertyName, JsonObject& paramsters, const CALLBACK& callback, void* usercb, const void* userdata) + static int32_t Subscribe(const string& propertyName, JsonObject& paramsters, const CALLBACK& callback, void* usercb, const void* userdata) { return Event::Instance().Subscribe(EventName(propertyName), paramsters, callback, usercb, userdata); } - static uint32_t Unsubscribe(const string& propertyName, void* usercb) + static int32_t Unsubscribe(const string& propertyName, void* usercb) { return Event::Instance().Unsubscribe(EventName(propertyName), usercb); } diff --git a/languages/c/src/shared/src/Transport/Transport.h b/languages/c/src/shared/src/Transport/Transport.h index b3405b9c..6b80cd25 100644 --- a/languages/c/src/shared/src/Transport/Transport.h +++ b/languages/c/src/shared/src/Transport/Transport.h @@ -418,9 +418,9 @@ namespace FireboltSDK { } private: - uint32_t Inbound(const WPEFramework::Core::ProxyType& inbound) + int32_t Inbound(const WPEFramework::Core::ProxyType& inbound) { - uint32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + int32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; _adminLock.Lock(); typename std::list::iterator index(_observers.begin()); while ((result != WPEFramework::Core::ERROR_NONE) && (index != _observers.end())) { @@ -441,8 +441,8 @@ namespace FireboltSDK { class IEventHandler { public: - virtual uint32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) = 0; - virtual uint32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) = 0; + virtual int32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) = 0; + virtual int32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) = 0; virtual ~IEventHandler() = default; }; @@ -536,11 +536,11 @@ namespace FireboltSDK { } template - uint32_t Invoke(const string& method, const PARAMETERS& parameters, RESPONSE& response) + int32_t Invoke(const string& method, const PARAMETERS& parameters, RESPONSE& response) { Entry slot; uint32_t id = _channel->Sequence(); - uint32_t result = Send(method, parameters, id); + int32_t result = Send(method, parameters, id); if (result == WPEFramework::Core::ERROR_NONE) { result = WaitForResponse(id, response, _waitTime); } @@ -549,11 +549,11 @@ namespace FireboltSDK { } template - uint32_t Subscribe(const string& eventName, const string& parameters, RESPONSE& response) + int32_t Subscribe(const string& eventName, const string& parameters, RESPONSE& response) { Entry slot; uint32_t id = _channel->Sequence(); - uint32_t result = Send(eventName, parameters, id); + int32_t result = Send(eventName, parameters, id); if (result == WPEFramework::Core::ERROR_NONE) { _adminLock.Lock(); _eventMap.emplace(std::piecewise_construct, @@ -567,12 +567,12 @@ namespace FireboltSDK { return (FireboltErrorValue(result)); } - uint32_t Unsubscribe(const string& eventName, const string& parameters) + int32_t Unsubscribe(const string& eventName, const string& parameters) { Revoke(eventName); Entry slot; uint32_t id = _channel->Sequence(); - uint32_t result = Send(eventName, parameters, id); + int32_t result = Send(eventName, parameters, id); return (FireboltErrorValue(result)); } @@ -637,17 +637,17 @@ namespace FireboltSDK { _adminLock.Unlock(); } - uint32_t Submit(const WPEFramework::Core::ProxyType& inbound) + int32_t Submit(const WPEFramework::Core::ProxyType& inbound) { - uint32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + int32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(inbound, this)); WPEFramework::Core::IWorkerPool::Instance().Submit(job); return result; } - uint32_t Inbound(const WPEFramework::Core::ProxyType& inbound) + int32_t Inbound(const WPEFramework::Core::ProxyType& inbound) { - uint32_t result = WPEFramework::Core::ERROR_INVALID_SIGNATURE; + int32_t result = WPEFramework::Core::ERROR_INVALID_SIGNATURE; ASSERT(inbound.IsValid() == true); @@ -684,9 +684,9 @@ namespace FireboltSDK { template - uint32_t Send(const string& method, const PARAMETERS& parameters, const uint32_t& id) + int32_t Send(const string& method, const PARAMETERS& parameters, const uint32_t& id) { - uint32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + int32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; if ((_channel.IsValid() == true) && (_channel->IsSuspended() == true)) { result = WPEFramework::Core::ERROR_ASYNC_FAILED; @@ -722,9 +722,9 @@ namespace FireboltSDK { } template - uint32_t WaitForResponse(const uint32_t& id, RESPONSE& response, const uint32_t waitTime) + int32_t WaitForResponse(const uint32_t& id, RESPONSE& response, const uint32_t waitTime) { - uint32_t result = WPEFramework::Core::ERROR_TIMEDOUT; + int32_t result = WPEFramework::Core::ERROR_TIMEDOUT; _adminLock.Lock(); typename PendingMap::iterator index = _pendingQueue.find(id); Entry& slot(index->second); @@ -758,9 +758,9 @@ namespace FireboltSDK { static constexpr uint32_t WAITSLOT_TIME = 100; template - uint32_t WaitForEventResponse(const uint32_t& id, const string& eventName, RESPONSE& response, const uint32_t waitTime) + int32_t WaitForEventResponse(const uint32_t& id, const string& eventName, RESPONSE& response, const uint32_t waitTime) { - uint32_t result = WPEFramework::Core::ERROR_TIMEDOUT; + int32_t result = WPEFramework::Core::ERROR_TIMEDOUT; _adminLock.Lock(); typename PendingMap::iterator index = _pendingQueue.find(id); Entry& slot(index->second); @@ -860,10 +860,10 @@ namespace FireboltSDK { return; } - uint32_t FireboltErrorValue(const uint32_t error) + int32_t FireboltErrorValue(const uint32_t error) { - uint32_t fireboltError = FireboltSDKErrorUnknown; + int32_t fireboltError = error; switch (error) { case WPEFramework::Core::ERROR_NONE: fireboltError = FireboltSDKErrorNone; diff --git a/languages/c/src/shared/src/firebolt.cpp b/languages/c/src/shared/src/firebolt.cpp index ffc1369a..90c54c5c 100644 --- a/languages/c/src/shared/src/firebolt.cpp +++ b/languages/c/src/shared/src/firebolt.cpp @@ -24,13 +24,12 @@ extern "C" { #endif - -uint32_t FireboltSDK_Initialize(char* configLine) { +int32_t FireboltSDK_Initialize(char* configLine) { FireboltSDK::Accessor::Instance(configLine); return FireboltSDKErrorNone; } -uint32_t FireboltSDK_Deinitialize(void) { +int32_t FireboltSDK_Deinitialize(void) { FireboltSDK::Accessor::Dispose(); return FireboltSDKErrorNone; } diff --git a/languages/c/src/shared/test/OpenRPCCTests.h b/languages/c/src/shared/test/OpenRPCCTests.h index 4fe5eb5b..936a1ff9 100644 --- a/languages/c/src/shared/test/OpenRPCCTests.h +++ b/languages/c/src/shared/test/OpenRPCCTests.h @@ -28,13 +28,13 @@ extern "C" { void test_firebolt_create_instance(); void test_firebolt_dispose_instance(); -uint32_t test_firebolt_main(); -uint32_t test_properties_get_device_id(); -uint32_t test_properties_set(); -uint32_t test_eventregister(); -uint32_t test_eventregister_with_same_callback(); -uint32_t test_eventregister_by_providing_callback(); -uint32_t test_string_set_get_value(); +int32_t test_firebolt_main(); +int32_t test_properties_get_device_id(); +int32_t test_properties_set(); +int32_t test_eventregister(); +int32_t test_eventregister_with_same_callback(); +int32_t test_eventregister_by_providing_callback(); +int32_t test_string_set_get_value(); #ifdef __cplusplus } diff --git a/languages/c/src/shared/test/OpenRPCTests.cpp b/languages/c/src/shared/test/OpenRPCTests.cpp index 11170c15..03fd2645 100644 --- a/languages/c/src/shared/test/OpenRPCTests.cpp +++ b/languages/c/src/shared/test/OpenRPCTests.cpp @@ -80,11 +80,11 @@ namespace FireboltSDK { } } - /* static */ uint32_t Tests::GetDeviceId() + /* static */ int32_t Tests::GetDeviceId() { const string method = _T("device.id"); WPEFramework::Core::ProxyType response; - uint32_t status = FireboltSDK::Properties::Get(method, response); + int32_t status = FireboltSDK::Properties::Get(method, response); EXPECT_EQ(status, FireboltSDKErrorNone); if (status == FireboltSDKErrorNone) { @@ -96,11 +96,11 @@ namespace FireboltSDK { return status; } - /*static */ uint32_t Tests::GetDeviceVersion() + /*static */ int32_t Tests::GetDeviceVersion() { const string method = _T("device.version"); WPEFramework::Core::ProxyType response; - uint32_t status = FireboltSDK::Properties::Get(method, response); + int32_t status = FireboltSDK::Properties::Get(method, response); EXPECT_EQ(status, FireboltSDKErrorNone); if (status == FireboltSDKErrorNone) { @@ -113,11 +113,11 @@ namespace FireboltSDK { return status; } - /* static */ uint32_t Tests::GetUnKnownMethod() + /* static */ int32_t Tests::GetUnKnownMethod() { const string method = _T("get.unknownMethod"); WPEFramework::Core::ProxyType response; - uint32_t status = FireboltSDK::Properties::Get(method, response); + int32_t status = FireboltSDK::Properties::Get(method, response); EXPECT_NE(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -127,12 +127,12 @@ namespace FireboltSDK { return status; } - /* static */ uint32_t Tests::SetLifeCycleClose() + /* static */ int32_t Tests::SetLifeCycleClose() { const string method = _T("lifecycle.close"); JsonObject parameters; parameters["reason"] = "remoteButton"; - uint32_t status = FireboltSDK::Properties::Set(method, parameters); + int32_t status = FireboltSDK::Properties::Set(method, parameters); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -142,11 +142,11 @@ namespace FireboltSDK { return status; } - /* static */ uint32_t Tests::SetUnKnownMethod() + /* static */ int32_t Tests::SetUnKnownMethod() { const string method = _T("set.unknownMethod"); JsonObject parameters; - uint32_t status = FireboltSDK::Properties::Set(method, parameters); + int32_t status = FireboltSDK::Properties::Set(method, parameters); EXPECT_NE(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -167,7 +167,7 @@ namespace FireboltSDK { jsonResponse.Release(); } - /* static */ uint32_t Tests::SubscribeEvent() + /* static */ int32_t Tests::SubscribeEvent() { FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl("EventControl"); const string eventName = _T("device.Name"); @@ -176,7 +176,7 @@ namespace FireboltSDK { eventControl->ResetEvent(); JsonObject jsonParameters; - uint32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); + int32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -195,7 +195,7 @@ namespace FireboltSDK { return status; } - /* static */ uint32_t Tests::SubscribeEventwithSameCallback() + /* static */ int32_t Tests::SubscribeEventwithSameCallback() { FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl("EventControl"); const string eventName = _T("device.Name"); @@ -204,7 +204,7 @@ namespace FireboltSDK { eventControl->ResetEvent(); JsonObject jsonParameters; - uint32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); + int32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -250,7 +250,7 @@ namespace FireboltSDK { } template - /* static */ uint32_t Tests::SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata) + /* static */ int32_t Tests::SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata) { return Properties::Subscribe(eventName, jsonParameters, callbackFunc, usercb, userdata); } @@ -268,7 +268,7 @@ namespace FireboltSDK { jsonResponse.Release(); } - /* static */ uint32_t Tests::SubscribeEventWithMultipleCallback() + /* static */ int32_t Tests::SubscribeEventWithMultipleCallback() { FireboltSDK::Tests::EventControl* eventControl1 = new FireboltSDK::Tests::EventControl("EventControl1"); const string eventName = _T("device.Name"); @@ -277,7 +277,7 @@ namespace FireboltSDK { eventControl1->ResetEvent(); JsonObject jsonParameters; - uint32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent1), userdata); + int32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent1), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -342,16 +342,16 @@ void test_firebolt_dispose_instance() FireboltSDK::Accessor::Dispose(); } -uint32_t test_firebolt_main() +int32_t test_firebolt_main() { return FireboltSDK::Tests::Main(); } -uint32_t test_properties_get_device_id() +int32_t test_properties_get_device_id() { const string method = _T("device.id"); WPEFramework::Core::ProxyType response; - uint32_t status = FireboltSDK::Properties::Get(method, response); + int32_t status = FireboltSDK::Properties::Get(method, response); EXPECT_EQ(status, FireboltSDKErrorNone); if (status == FireboltSDKErrorNone) { @@ -365,12 +365,12 @@ uint32_t test_properties_get_device_id() return status; } -uint32_t test_properties_set() +int32_t test_properties_set() { const string method = _T("lifecycle.close"); JsonObject parameters; parameters["reason"] = "remoteButton"; - uint32_t status = FireboltSDK::Properties::Set(method, parameters); + int32_t status = FireboltSDK::Properties::Set(method, parameters); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -392,7 +392,7 @@ static void deviceNameChangeCallbackForC(void* userCB, const void* userData, voi jsonResponse.Release(); } -uint32_t test_eventregister() +int32_t test_eventregister() { FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); const string eventName = _T("device.Name"); @@ -401,7 +401,7 @@ uint32_t test_eventregister() eventControl->ResetEvent(); JsonObject jsonParameters; - uint32_t status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); + int32_t status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -419,7 +419,7 @@ uint32_t test_eventregister() return status; } -uint32_t test_eventregister_with_same_callback() +int32_t test_eventregister_with_same_callback() { FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); const string eventName = _T("device.Name"); @@ -428,7 +428,7 @@ uint32_t test_eventregister_with_same_callback() eventControl->ResetEvent(); JsonObject jsonParameters; - uint32_t status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); + int32_t status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -452,7 +452,7 @@ uint32_t test_eventregister_with_same_callback() return status; } -uint32_t test_eventregister_by_providing_callback() +int32_t test_eventregister_by_providing_callback() { FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); @@ -462,7 +462,7 @@ uint32_t test_eventregister_by_providing_callback() eventControl->ResetEvent(); JsonObject jsonParameters; - uint32_t status = FireboltSDK::Tests::SubscribeEventForC(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); + int32_t status = FireboltSDK::Tests::SubscribeEventForC(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); EXPECT_EQ(status, FireboltSDKErrorNone); if (status != FireboltSDKErrorNone) { @@ -480,9 +480,9 @@ uint32_t test_eventregister_by_providing_callback() } #include "TypesPriv.h" -uint32_t test_string_set_get_value() +int32_t test_string_set_get_value() { - uint32_t status = FireboltSDKErrorNone; + int32_t status = FireboltSDKErrorNone; FireboltSDK::JSON::String* str = new FireboltSDK::JSON::String(); WPEFramework::Core::JSON::String wpeJsonStr("TestString"); Firebolt_String_t handle = reinterpret_cast(str); diff --git a/languages/c/src/shared/test/OpenRPCTests.h b/languages/c/src/shared/test/OpenRPCTests.h index e82665d0..8eb7fd30 100644 --- a/languages/c/src/shared/test/OpenRPCTests.h +++ b/languages/c/src/shared/test/OpenRPCTests.h @@ -29,7 +29,7 @@ typedef enum { } TestEnum; namespace FireboltSDK { - typedef uint32_t (*Func)(); + typedef int32_t (*Func)(); class Tests { public: @@ -82,7 +82,7 @@ namespace FireboltSDK { } template - static uint32_t Main() + static int32_t Main() { TESTS fireboltTest; for (auto i = fireboltTest.TestList().begin(); i != fireboltTest.TestList().end(); i++) { @@ -94,19 +94,19 @@ namespace FireboltSDK { return 0; } - static uint32_t GetDeviceId(); - static uint32_t GetDeviceVersion(); - static uint32_t GetUnKnownMethod(); + static int32_t GetDeviceId(); + static int32_t GetDeviceVersion(); + static int32_t GetUnKnownMethod(); - static uint32_t SetLifeCycleClose(); - static uint32_t SetUnKnownMethod(); + static int32_t SetLifeCycleClose(); + static int32_t SetUnKnownMethod(); - static uint32_t SubscribeEvent(); - static uint32_t SubscribeEventwithSameCallback(); - static uint32_t SubscribeEventWithMultipleCallback(); + static int32_t SubscribeEvent(); + static int32_t SubscribeEventwithSameCallback(); + static int32_t SubscribeEventWithMultipleCallback(); template - static uint32_t SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata); + static int32_t SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata); protected: static void PrintJsonObject(const JsonObject::Iterator& iterator); diff --git a/languages/c/src/types/NativeHelpers.mjs b/languages/c/src/types/NativeHelpers.mjs index cc7ac662..d2540279 100644 --- a/languages/c/src/types/NativeHelpers.mjs +++ b/languages/c/src/types/NativeHelpers.mjs @@ -152,7 +152,7 @@ function getPropertyGetterSignature(property, module, propType, paramList = []) let contextParams = '' contextParams = getContextParams(paramList) - return `uint32_t ${capitalize(getModuleName(module))}_Get${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType}* ${property.result.name || property.name} )` + return `int32_t ${capitalize(getModuleName(module))}_Get${capitalize(property.name)}( ${contextParams}${contextParams.length > 0 ? ', ':''}${propType}* ${property.result.name || property.name} )` } export { diff --git a/languages/c/templates/codeblocks/setter.c b/languages/c/templates/codeblocks/setter.c index 411d4542..f62c8683 100644 --- a/languages/c/templates/codeblocks/setter.c +++ b/languages/c/templates/codeblocks/setter.c @@ -1,5 +1,5 @@ /* ${method.rpc.name} - ${method.description} */ -uint32_t ${info.Title}_${method.Name}( ${method.signature.params} ) +int32_t ${info.Title}_${method.Name}( ${method.signature.params} ) { const string method = _T("${info.title.lowercase}.${method.rpc.name}"); ${if.params}${method.params.serialization}${end.if.params} diff --git a/languages/c/templates/declarations/default.c b/languages/c/templates/declarations/default.c index 8879378d..e6b49808 100644 --- a/languages/c/templates/declarations/default.c +++ b/languages/c/templates/declarations/default.c @@ -1,4 +1,4 @@ /* ${method.name} - ${method.description} ${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation}${end.if.deprecated} */ -uint32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name}${end.if.result}${if.signature.empty}void${end.if.signature.empty} ); +int32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name}${end.if.result}${if.signature.empty}void${end.if.signature.empty} ); diff --git a/languages/c/templates/declarations/event.c b/languages/c/templates/declarations/event.c index 4dc59c4a..3638be52 100644 --- a/languages/c/templates/declarations/event.c +++ b/languages/c/templates/declarations/event.c @@ -1,5 +1,5 @@ /* ${method.name} - ${method.description} */ typedef void (*${info.Title}${method.Name}Callback)( const void* userData, ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${event.result.type} ); -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 ); -uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); +int32_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 ); +int32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); diff --git a/languages/c/templates/declarations/polymorphic-pull-event.c b/languages/c/templates/declarations/polymorphic-pull-event.c index 9b22619e..b9c7f424 100644 --- a/languages/c/templates/declarations/polymorphic-pull-event.c +++ b/languages/c/templates/declarations/polymorphic-pull-event.c @@ -1,5 +1,5 @@ /* ${method.name} - ${method.description} */ typedef void* (*${info.Title}${method.Name}Callback)( const void* userData, ${method.pulls.param.type} ); -uint32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callback userCB, const void* userData ); -uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); +int32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callback userCB, const void* userData ); +int32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB); diff --git a/languages/c/templates/declarations/polymorphic-pull.c b/languages/c/templates/declarations/polymorphic-pull.c index ca08d823..7956f87f 100644 --- a/languages/c/templates/declarations/polymorphic-pull.c +++ b/languages/c/templates/declarations/polymorphic-pull.c @@ -1,3 +1,3 @@ /* ${method.name} - ${method.description} */ -uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ); +int32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ); diff --git a/languages/c/templates/declarations/setter.c b/languages/c/templates/declarations/setter.c index 9fcd86a2..a40fd4fc 100644 --- a/languages/c/templates/declarations/setter.c +++ b/languages/c/templates/declarations/setter.c @@ -1,2 +1,2 @@ /* ${method.rpc.name} - ${method.description} */ -uint32_t ${info.Title}_${method.Name}( ${method.signature.params} ); +int32_t ${info.Title}_${method.Name}( ${method.signature.params} ); diff --git a/languages/c/templates/methods/calls-metrics.c b/languages/c/templates/methods/calls-metrics.c index c8caa238..3ad9ec0f 100644 --- a/languages/c/templates/methods/calls-metrics.c +++ b/languages/c/templates/methods/calls-metrics.c @@ -2,9 +2,9 @@ void Metrics_${method.Name}Dispatcher(const void*${if.result} result${end.if.result}) { Metrics_${method.Name}(${if.result}(static_cast<${method.result.json.type}>(const_cast(result)))${end.if.result}); } -uint32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name}${end.if.result}${if.signature.empty}void${end.if.signature.empty} ) { +int32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name}${end.if.result}${if.signature.empty}void${end.if.signature.empty} ) { - uint32_t status = FireboltSDKErrorUnavailable; + int32_t status = FireboltSDKErrorUnavailable; FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { diff --git a/languages/c/templates/methods/default.c b/languages/c/templates/methods/default.c index d8f619c5..e1d9e701 100644 --- a/languages/c/templates/methods/default.c +++ b/languages/c/templates/methods/default.c @@ -1,7 +1,7 @@ /* ${method.rpc.name} - ${method.description} */ -uint32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name}${end.if.result}${if.signature.empty}void${end.if.signature.empty} ) { +int32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name}${end.if.result}${if.signature.empty}void${end.if.signature.empty} ) { - uint32_t status = FireboltSDKErrorUnavailable; + int32_t status = FireboltSDKErrorUnavailable; FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { diff --git a/languages/c/templates/methods/event.c b/languages/c/templates/methods/event.c index 2a2de707..85ae3b48 100644 --- a/languages/c/templates/methods/event.c +++ b/languages/c/templates/methods/event.c @@ -9,10 +9,10 @@ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* callback(userData, ${event.callback.response.instantiation}); } } -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 ) +int32_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.lowercase}.${method.rpc.name}"); - uint32_t status = FireboltSDKErrorNone; + int32_t status = FireboltSDKErrorNone; if (userCB != nullptr) { ${event.params.serialization} @@ -20,7 +20,7 @@ uint32_t ${info.Title}_Register_${method.Name}( ${event.signature.params}${if.ev } return status; } -uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB) +int32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB) { return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); } diff --git a/languages/c/templates/methods/polymorphic-pull-event.c b/languages/c/templates/methods/polymorphic-pull-event.c index 5bf302b5..49aa1dba 100644 --- a/languages/c/templates/methods/polymorphic-pull-event.c +++ b/languages/c/templates/methods/polymorphic-pull-event.c @@ -27,20 +27,19 @@ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { WPEFramework::Core::JSON::Boolean jsonResult; - uint32_t status = transport->Invoke(_T("${info.title.lowercase}.${method.pulls.for}"), jsonParameters, jsonResult); + int32_t status = transport->Invoke(_T("${info.title.lowercase}.${method.pulls.for}"), jsonParameters, jsonResult); if (status == FireboltSDKErrorNone) { FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully pushed with status as %d", jsonResult.Value()); - status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; } } else { FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport"); } } } -uint32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callback userCB, const void* userData ) +int32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callback userCB, const void* userData ) { const string eventName = _T("${info.title.lowercase}.${method.rpc.name}"); - uint32_t status = FireboltSDKErrorNone; + int32_t status = FireboltSDKErrorNone; if (userCB != nullptr) { ${event.params.serialization} @@ -48,7 +47,7 @@ uint32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callb } return status; } -uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB) +int32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB) { return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); } diff --git a/languages/c/templates/methods/polymorphic-pull.c b/languages/c/templates/methods/polymorphic-pull.c index d543e3ce..d88b49aa 100644 --- a/languages/c/templates/methods/polymorphic-pull.c +++ b/languages/c/templates/methods/polymorphic-pull.c @@ -1,7 +1,7 @@ /* ${method.rpc.name} - ${method.description} */ -uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ) +int32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ) { - uint32_t status = FireboltSDKErrorUnavailable; + int32_t status = FireboltSDKErrorUnavailable; FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { diff --git a/languages/c/templates/methods/property.c b/languages/c/templates/methods/property.c index af6200c9..8bf6a516 100644 --- a/languages/c/templates/methods/property.c +++ b/languages/c/templates/methods/property.c @@ -1,11 +1,11 @@ /* ${method.rpc.name} - ${method.description} */ -uint32_t ${info.Title}_Get${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name} ) +int32_t ${info.Title}_Get${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name} ) { const string method = _T("${info.title.lowercase}.${method.rpc.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} - ${if.params.empty}uint32_t status = FireboltSDK::Properties::Get(method, jsonResult);${end.if.params.empty} + ${if.params}int32_t status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult);${end.if.params} + ${if.params.empty}int32_t status = FireboltSDK::Properties::Get(method, jsonResult);${end.if.params.empty} if (status == FireboltSDKErrorNone) { ${method.result.instantiation} } From efcbece4fddce4346e321a9850f1410c11ed6ba6 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Tue, 15 Aug 2023 15:22:12 -0400 Subject: [PATCH 100/137] fix: Provider Interfaces and Tuples in JS --- .../templates/interfaces/default.mjs | 1 + .../templates/interfaces/focusable.mjs | 1 + .../templates/sections/provider-interfaces.js | 20 +++++++++---------- .../javascript/templates/types/items.mjs | 2 +- src/macrofier/engine.mjs | 9 ++++++--- src/macrofier/types.mjs | 4 ++-- src/shared/modules.mjs | 13 +++--------- 7 files changed, 24 insertions(+), 26 deletions(-) create mode 100644 languages/javascript/templates/interfaces/default.mjs create mode 100644 languages/javascript/templates/interfaces/focusable.mjs diff --git a/languages/javascript/templates/interfaces/default.mjs b/languages/javascript/templates/interfaces/default.mjs new file mode 100644 index 00000000..63f63093 --- /dev/null +++ b/languages/javascript/templates/interfaces/default.mjs @@ -0,0 +1 @@ + ${method.name}(${method.signature.params}, session: ProviderSession): Promise<${method.result.type}> diff --git a/languages/javascript/templates/interfaces/focusable.mjs b/languages/javascript/templates/interfaces/focusable.mjs new file mode 100644 index 00000000..b81737b1 --- /dev/null +++ b/languages/javascript/templates/interfaces/focusable.mjs @@ -0,0 +1 @@ + ${method.name}(${method.signature.params}, session: FocusableProviderSession): Promise<${method.result.type}> diff --git a/languages/javascript/templates/sections/provider-interfaces.js b/languages/javascript/templates/sections/provider-interfaces.js index 418d7abf..0b77c87d 100644 --- a/languages/javascript/templates/sections/provider-interfaces.js +++ b/languages/javascript/templates/sections/provider-interfaces.js @@ -1,11 +1,11 @@ - // Provider Interfaces +// Provider Interfaces - interface ProviderSession { - correlationId(): string // Returns the correlation id of the current provider session - } - - interface FocusableProviderSession extends ProviderSession { - focus(): Promise // Requests that the provider app be moved into focus to prevent a user experience - } - - ${providers.list} \ No newline at end of file +interface ProviderSession { + correlationId(): string // Returns the correlation id of the current provider session +} + +interface FocusableProviderSession extends ProviderSession { + focus(): Promise // Requests that the provider app be moved into focus to prevent a user experience +} + +${providers.list} \ No newline at end of file diff --git a/languages/javascript/templates/types/items.mjs b/languages/javascript/templates/types/items.mjs index 56397819..9b964820 100644 --- a/languages/javascript/templates/types/items.mjs +++ b/languages/javascript/templates/types/items.mjs @@ -1 +1 @@ -${type}${delimiter},${end.delimiter} // ${property} ${summary} item \ No newline at end of file +${title}${delimiter},${end.delimiter} // ${property} ${summary} item \ No newline at end of file diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index e3bee7e5..c5055b91 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -1584,12 +1584,15 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te } let interfaceShape = getTemplate('/codeblocks/interface', templates) - let interfaceDeclaration = getTemplate('/declarations/interface', templates) interfaceShape = interfaceShape.replace(/\$\{name\}/g, name) .replace(/\$\{capability\}/g, capability) - .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => insertMethodMacros(interfaceDeclaration, method, moduleJson, { destination: state.destination, section: state.section, isInterface: true })).join('\n') + '\n') - + .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => { + const focusable = method.tags.find(t => t['x-allow-focus']) + const interfaceDeclaration = getTemplate('/interfaces/' + (focusable ? 'focusable' : 'default'), templates) + return insertMethodMacros(interfaceDeclaration, method, moduleJson, { destination: state.destination, section: state.section, isInterface: true }) + }).join('') + '\n') + if (iface.length === 0) { template = template.replace(/\$\{provider\.methods\}/gms, '') } diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index 3c53afcb..f8dad4bb 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -569,11 +569,11 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin // Normal Array else if (!isTuple(schema)) { template = insertArrayMacros(getTemplate(path.join(templateDir, 'array')), schema, module) - template = insertSchemaMacros(template, schema, module, '', '', '', false) + template = insertSchemaMacros(template, schema.items, module, getSchemaType(schema.items, module, {destination, templateDir, link, title, code, asPath, event, result, expandEnums, baseUrl, namespace }), '', '', true) } else { template = insertTupleMacros(getTemplate(path.join(templateDir, 'tuple')), schema, module, '', { templateDir }) - template = insertSchemaMacros(template, schema, module, '', '', '', false) + template = insertSchemaMacros(template, firstItem, module, '', '', '', false) } if (code) { diff --git a/src/shared/modules.mjs b/src/shared/modules.mjs index 927092c2..ed0f474a 100644 --- a/src/shared/modules.mjs +++ b/src/shared/modules.mjs @@ -99,13 +99,8 @@ function getProviderInterface(capability, module) { method.params = [ { "name": "parameters", + "required": true, "schema": payload.properties.parameters - }, - { - "name": "session", - "schema": { - "type": focusable ? "FocusableProviderSession" : "ProviderSession" - } } ] @@ -140,10 +135,8 @@ function getProviderInterface(capability, module) { value: example.result.value.parameters }, { - name: "session", - value: { - correlationId: example.result.value.correlationId - } + name: "correlationId", + value: example.result.value.correlationId } ], result: { From 8b37a49d10f773eb04fc8711461ca4a44da66594 Mon Sep 17 00:00:00 2001 From: Santhosh Ramani Date: Fri, 1 Sep 2023 18:14:50 +0530 Subject: [PATCH 101/137] feat: Initial commit of cpp sdk --- languages/cpp/language.config.json | 27 + languages/cpp/src/shared/CMakeLists.txt | 56 ++ .../src/shared/cmake/HelperFunctions.cmake | 72 ++ .../cpp/src/shared/cmake/project.cmake.in | 35 + languages/cpp/src/shared/include/error.h | 41 + languages/cpp/src/shared/include/firebolt.h | 68 ++ languages/cpp/src/shared/include/types.h | 37 + .../cpp/src/shared/src/Accessor/Accessor.cpp | 117 +++ .../cpp/src/shared/src/Accessor/Accessor.h | 122 +++ .../cpp/src/shared/src/Accessor/WorkerPool.h | 102 ++ languages/cpp/src/shared/src/CMakeLists.txt | 73 ++ languages/cpp/src/shared/src/Event/Event.cpp | 147 +++ languages/cpp/src/shared/src/Event/Event.h | 165 ++++ .../cpp/src/shared/src/FireboltSDK.conf.in | 3 + languages/cpp/src/shared/src/FireboltSDK.h | 26 + .../cpp/src/shared/src/Logger/Logger.cpp | 86 ++ languages/cpp/src/shared/src/Logger/Logger.h | 85 ++ languages/cpp/src/shared/src/Module.cpp | 21 + languages/cpp/src/shared/src/Module.h | 29 + .../src/shared/src/Properties/Properties.h | 148 +++ .../src/shared/src/Transport/Transport.cpp | 24 + .../cpp/src/shared/src/Transport/Transport.h | 897 ++++++++++++++++++ languages/cpp/src/shared/src/Types.cpp | 40 + languages/cpp/src/shared/src/TypesPriv.h | 56 ++ languages/cpp/src/shared/src/firebolt.cpp | 39 + languages/cpp/src/shared/test/CMakeLists.txt | 86 ++ languages/cpp/src/shared/test/Main.c | 45 + languages/cpp/src/shared/test/Module.cpp | 21 + languages/cpp/src/shared/test/Module.h | 28 + languages/cpp/src/shared/test/OpenRPCCTests.h | 43 + .../cpp/src/shared/test/OpenRPCTests.cpp | 504 ++++++++++ languages/cpp/src/shared/test/OpenRPCTests.h | 118 +++ languages/cpp/src/shared/test/TestUtils.h | 38 + languages/cpp/templates/codeblocks/export.c | 0 .../cpp/templates/codeblocks/mock-import.c | 1 + .../cpp/templates/codeblocks/mock-parameter.c | 1 + languages/cpp/templates/codeblocks/module.c | 0 languages/cpp/templates/codeblocks/setter.c | 7 + languages/cpp/templates/declarations/clear.c | 0 .../cpp/templates/declarations/default.c | 6 + languages/cpp/templates/declarations/event.c | 10 + languages/cpp/templates/declarations/listen.c | 0 languages/cpp/templates/declarations/once.c | 0 .../declarations/polymorphic-pull-event.c | 8 + .../templates/declarations/polymorphic-pull.c | 2 + .../declarations/polymorphic-reducer.c | 5 + .../cpp/templates/declarations/property.h | 5 + .../cpp/templates/declarations/provide.c | 0 languages/cpp/templates/declarations/setter.h | 5 + languages/cpp/templates/defaults/default.c | 0 languages/cpp/templates/defaults/property.c | 0 .../cpp/templates/imports/calls-metrics.cpp | 1 + languages/cpp/templates/imports/default.cpp | 1 + languages/cpp/templates/imports/default.h | 1 + .../cpp/templates/imports/default.jsondata | 1 + .../json-types/additionalProperties.c | 1 + languages/cpp/templates/json-types/anyOf.c | 1 + languages/cpp/templates/json-types/array.c | 4 + languages/cpp/templates/json-types/boolean.c | 1 + languages/cpp/templates/json-types/const.c | 0 .../cpp/templates/json-types/default.cpp | 1 + languages/cpp/templates/json-types/enum.cpp | 4 + languages/cpp/templates/json-types/enum.h | 4 + languages/cpp/templates/json-types/float.c | 1 + languages/cpp/templates/json-types/integer.c | 1 + .../cpp/templates/json-types/namespace.c | 1 + languages/cpp/templates/json-types/object.cpp | 25 + .../cpp/templates/json-types/primitive.c | 0 .../templates/json-types/property-assign.cpp | 2 + .../json-types/property-register.cpp | 2 + .../cpp/templates/json-types/property.cpp | 1 + languages/cpp/templates/json-types/ref.c | 1 + languages/cpp/templates/json-types/string.c | 1 + languages/cpp/templates/json-types/title.c | 1 + languages/cpp/templates/json-types/tuple.c | 25 + .../cpp/templates/json-types/types/object.c | 0 languages/cpp/templates/json-types/x-method.c | 1 + languages/cpp/templates/language/enum-item.c | 1 + languages/cpp/templates/language/enum.c | 3 + languages/cpp/templates/language/parameter.c | 1 + .../cpp/templates/language/schema-item.c | 1 + languages/cpp/templates/language/schema.c | 3 + .../cpp/templates/methods/calls-metrics.c | 29 + languages/cpp/templates/methods/clear.c | 0 languages/cpp/templates/methods/default.c | 21 + languages/cpp/templates/methods/event.c | 27 + languages/cpp/templates/methods/listen.c | 0 languages/cpp/templates/methods/once.c | 0 .../methods/polymorphic-pull-event.c | 54 ++ .../cpp/templates/methods/polymorphic-pull.c | 22 + .../templates/methods/polymorphic-reducer.c | 0 languages/cpp/templates/methods/property.c | 14 + languages/cpp/templates/methods/provide.c | 0 languages/cpp/templates/methods/setter.c | 0 .../cpp/templates/modules/include/module.h | 43 + .../cpp/templates/modules/src/module.cpp | 41 + .../parameter-serialization/boolean.cpp | 2 + .../parameter-serialization/default.cpp | 2 + .../parameter-serialization/object.cpp | 2 + .../parameter-serialization/primitive.cpp | 2 + .../parameter-serialization/string.cpp | 2 + languages/cpp/templates/parameters/default.c | 1 + languages/cpp/templates/parameters/json.c | 3 + languages/cpp/templates/parameters/object.c | 1 + languages/cpp/templates/parameters/optional.c | 1 + languages/cpp/templates/parameters/result.c | 1 + languages/cpp/templates/parameters/string.c | 1 + .../result-instantiation/boolean.cpp | 2 + .../result-instantiation/default.cpp | 1 + .../templates/result-instantiation/object.cpp | 4 + .../result-instantiation/primitive.cpp | 1 + .../templates/result-instantiation/string.cpp | 2 + languages/cpp/templates/schemas/default.cpp | 1 + .../templates/schemas/include/common/module.h | 36 + .../templates/schemas/src/jsondata_module.h | 30 + .../templates/schemas/src/module_common.cpp | 41 + languages/cpp/templates/sdk/scripts/build.sh | 40 + .../cpp/templates/sdk/scripts/install.sh | 58 ++ .../cpp/templates/sections/declarations.h | 1 + languages/cpp/templates/sections/enum.cpp | 5 + languages/cpp/templates/sections/enums.h | 1 + languages/cpp/templates/sections/events.h | 1 + languages/cpp/templates/sections/methods.h | 4 + .../cpp/templates/sections/methods_types.h | 1 + .../templates/sections/provider-interfaces.h | 11 + languages/cpp/templates/sections/schemas.h | 1 + languages/cpp/templates/sections/types.h | 1 + .../templates/types/additionalProperties.h | 1 + languages/cpp/templates/types/anyOf.c | 1 + languages/cpp/templates/types/array.h | 1 + languages/cpp/templates/types/const.h | 0 languages/cpp/templates/types/default.cpp | 4 + languages/cpp/templates/types/enum.cpp | 4 + languages/cpp/templates/types/enum.h | 4 + languages/cpp/templates/types/namespace.h | 1 + languages/cpp/templates/types/null.h | 1 + languages/cpp/templates/types/object.h | 5 + languages/cpp/templates/types/primitive.h | 1 + languages/cpp/templates/types/property.h | 1 + languages/cpp/templates/types/ref.h | 1 + languages/cpp/templates/types/title.h | 1 + languages/cpp/templates/types/tuple.h | 6 + languages/cpp/templates/types/x-method.h | 1 + src/macrofier/types.mjs | 8 +- 144 files changed, 4090 insertions(+), 2 deletions(-) create mode 100644 languages/cpp/language.config.json create mode 100644 languages/cpp/src/shared/CMakeLists.txt create mode 100644 languages/cpp/src/shared/cmake/HelperFunctions.cmake create mode 100644 languages/cpp/src/shared/cmake/project.cmake.in create mode 100644 languages/cpp/src/shared/include/error.h create mode 100644 languages/cpp/src/shared/include/firebolt.h create mode 100644 languages/cpp/src/shared/include/types.h create mode 100644 languages/cpp/src/shared/src/Accessor/Accessor.cpp create mode 100644 languages/cpp/src/shared/src/Accessor/Accessor.h create mode 100644 languages/cpp/src/shared/src/Accessor/WorkerPool.h create mode 100644 languages/cpp/src/shared/src/CMakeLists.txt create mode 100644 languages/cpp/src/shared/src/Event/Event.cpp create mode 100644 languages/cpp/src/shared/src/Event/Event.h create mode 100644 languages/cpp/src/shared/src/FireboltSDK.conf.in create mode 100644 languages/cpp/src/shared/src/FireboltSDK.h create mode 100644 languages/cpp/src/shared/src/Logger/Logger.cpp create mode 100644 languages/cpp/src/shared/src/Logger/Logger.h create mode 100644 languages/cpp/src/shared/src/Module.cpp create mode 100644 languages/cpp/src/shared/src/Module.h create mode 100644 languages/cpp/src/shared/src/Properties/Properties.h create mode 100644 languages/cpp/src/shared/src/Transport/Transport.cpp create mode 100644 languages/cpp/src/shared/src/Transport/Transport.h create mode 100644 languages/cpp/src/shared/src/Types.cpp create mode 100644 languages/cpp/src/shared/src/TypesPriv.h create mode 100644 languages/cpp/src/shared/src/firebolt.cpp create mode 100644 languages/cpp/src/shared/test/CMakeLists.txt create mode 100644 languages/cpp/src/shared/test/Main.c create mode 100644 languages/cpp/src/shared/test/Module.cpp create mode 100644 languages/cpp/src/shared/test/Module.h create mode 100644 languages/cpp/src/shared/test/OpenRPCCTests.h create mode 100644 languages/cpp/src/shared/test/OpenRPCTests.cpp create mode 100644 languages/cpp/src/shared/test/OpenRPCTests.h create mode 100644 languages/cpp/src/shared/test/TestUtils.h create mode 100644 languages/cpp/templates/codeblocks/export.c create mode 100644 languages/cpp/templates/codeblocks/mock-import.c create mode 100644 languages/cpp/templates/codeblocks/mock-parameter.c create mode 100644 languages/cpp/templates/codeblocks/module.c create mode 100644 languages/cpp/templates/codeblocks/setter.c create mode 100644 languages/cpp/templates/declarations/clear.c create mode 100644 languages/cpp/templates/declarations/default.c create mode 100644 languages/cpp/templates/declarations/event.c create mode 100644 languages/cpp/templates/declarations/listen.c create mode 100644 languages/cpp/templates/declarations/once.c create mode 100644 languages/cpp/templates/declarations/polymorphic-pull-event.c create mode 100644 languages/cpp/templates/declarations/polymorphic-pull.c create mode 100644 languages/cpp/templates/declarations/polymorphic-reducer.c create mode 100644 languages/cpp/templates/declarations/property.h create mode 100644 languages/cpp/templates/declarations/provide.c create mode 100644 languages/cpp/templates/declarations/setter.h create mode 100644 languages/cpp/templates/defaults/default.c create mode 100644 languages/cpp/templates/defaults/property.c create mode 100644 languages/cpp/templates/imports/calls-metrics.cpp create mode 100644 languages/cpp/templates/imports/default.cpp create mode 100644 languages/cpp/templates/imports/default.h create mode 100644 languages/cpp/templates/imports/default.jsondata create mode 100644 languages/cpp/templates/json-types/additionalProperties.c create mode 100644 languages/cpp/templates/json-types/anyOf.c create mode 100644 languages/cpp/templates/json-types/array.c create mode 100644 languages/cpp/templates/json-types/boolean.c create mode 100644 languages/cpp/templates/json-types/const.c create mode 100644 languages/cpp/templates/json-types/default.cpp create mode 100644 languages/cpp/templates/json-types/enum.cpp create mode 100644 languages/cpp/templates/json-types/enum.h create mode 100644 languages/cpp/templates/json-types/float.c create mode 100644 languages/cpp/templates/json-types/integer.c create mode 100644 languages/cpp/templates/json-types/namespace.c create mode 100644 languages/cpp/templates/json-types/object.cpp create mode 100644 languages/cpp/templates/json-types/primitive.c create mode 100644 languages/cpp/templates/json-types/property-assign.cpp create mode 100644 languages/cpp/templates/json-types/property-register.cpp create mode 100644 languages/cpp/templates/json-types/property.cpp create mode 100644 languages/cpp/templates/json-types/ref.c create mode 100644 languages/cpp/templates/json-types/string.c create mode 100644 languages/cpp/templates/json-types/title.c create mode 100644 languages/cpp/templates/json-types/tuple.c create mode 100644 languages/cpp/templates/json-types/types/object.c create mode 100644 languages/cpp/templates/json-types/x-method.c create mode 100644 languages/cpp/templates/language/enum-item.c create mode 100644 languages/cpp/templates/language/enum.c create mode 100644 languages/cpp/templates/language/parameter.c create mode 100644 languages/cpp/templates/language/schema-item.c create mode 100644 languages/cpp/templates/language/schema.c create mode 100644 languages/cpp/templates/methods/calls-metrics.c create mode 100644 languages/cpp/templates/methods/clear.c create mode 100644 languages/cpp/templates/methods/default.c create mode 100644 languages/cpp/templates/methods/event.c create mode 100644 languages/cpp/templates/methods/listen.c create mode 100644 languages/cpp/templates/methods/once.c create mode 100644 languages/cpp/templates/methods/polymorphic-pull-event.c create mode 100644 languages/cpp/templates/methods/polymorphic-pull.c create mode 100644 languages/cpp/templates/methods/polymorphic-reducer.c create mode 100644 languages/cpp/templates/methods/property.c create mode 100644 languages/cpp/templates/methods/provide.c create mode 100644 languages/cpp/templates/methods/setter.c create mode 100644 languages/cpp/templates/modules/include/module.h create mode 100644 languages/cpp/templates/modules/src/module.cpp create mode 100644 languages/cpp/templates/parameter-serialization/boolean.cpp create mode 100644 languages/cpp/templates/parameter-serialization/default.cpp create mode 100644 languages/cpp/templates/parameter-serialization/object.cpp create mode 100644 languages/cpp/templates/parameter-serialization/primitive.cpp create mode 100644 languages/cpp/templates/parameter-serialization/string.cpp create mode 100644 languages/cpp/templates/parameters/default.c create mode 100644 languages/cpp/templates/parameters/json.c create mode 100644 languages/cpp/templates/parameters/object.c create mode 100644 languages/cpp/templates/parameters/optional.c create mode 100644 languages/cpp/templates/parameters/result.c create mode 100644 languages/cpp/templates/parameters/string.c create mode 100644 languages/cpp/templates/result-instantiation/boolean.cpp create mode 100644 languages/cpp/templates/result-instantiation/default.cpp create mode 100644 languages/cpp/templates/result-instantiation/object.cpp create mode 100644 languages/cpp/templates/result-instantiation/primitive.cpp create mode 100644 languages/cpp/templates/result-instantiation/string.cpp create mode 100644 languages/cpp/templates/schemas/default.cpp create mode 100644 languages/cpp/templates/schemas/include/common/module.h create mode 100644 languages/cpp/templates/schemas/src/jsondata_module.h create mode 100644 languages/cpp/templates/schemas/src/module_common.cpp create mode 100755 languages/cpp/templates/sdk/scripts/build.sh create mode 100755 languages/cpp/templates/sdk/scripts/install.sh create mode 100644 languages/cpp/templates/sections/declarations.h create mode 100644 languages/cpp/templates/sections/enum.cpp create mode 100644 languages/cpp/templates/sections/enums.h create mode 100644 languages/cpp/templates/sections/events.h create mode 100644 languages/cpp/templates/sections/methods.h create mode 100644 languages/cpp/templates/sections/methods_types.h create mode 100644 languages/cpp/templates/sections/provider-interfaces.h create mode 100644 languages/cpp/templates/sections/schemas.h create mode 100644 languages/cpp/templates/sections/types.h create mode 100644 languages/cpp/templates/types/additionalProperties.h create mode 100644 languages/cpp/templates/types/anyOf.c create mode 100644 languages/cpp/templates/types/array.h create mode 100644 languages/cpp/templates/types/const.h create mode 100644 languages/cpp/templates/types/default.cpp create mode 100644 languages/cpp/templates/types/enum.cpp create mode 100644 languages/cpp/templates/types/enum.h create mode 100644 languages/cpp/templates/types/namespace.h create mode 100644 languages/cpp/templates/types/null.h create mode 100644 languages/cpp/templates/types/object.h create mode 100644 languages/cpp/templates/types/primitive.h create mode 100644 languages/cpp/templates/types/property.h create mode 100644 languages/cpp/templates/types/ref.h create mode 100644 languages/cpp/templates/types/title.h create mode 100644 languages/cpp/templates/types/tuple.h create mode 100644 languages/cpp/templates/types/x-method.h diff --git a/languages/cpp/language.config.json b/languages/cpp/language.config.json new file mode 100644 index 00000000..491e9559 --- /dev/null +++ b/languages/cpp/language.config.json @@ -0,0 +1,27 @@ +{ + "name": "CPlusPlus", + "langcode": "cpp", + "createModuleDirectories": false, + "extractSubSchemas": true, + "unwrapResultObjects": false, + "createPolymorphicMethods": true, + "excludeDeclarations":true, + "templatesPerModule": [ + "/include/module.h", + "/src/module.cpp" + ], + "templatesPerSchema": [ + "/include/common/module.h", + "/src/module_common.cpp", + "/src/jsondata_module.h" + ], + "persistPermission": true, + "primitives": { + "boolean": "bool", + "integer": "int32_t", + "number": "float", + "string": "std::string" + }, + "langVersion" : "c++17", + "additionalSchemaTemplates": [ "json-types" ] +} diff --git a/languages/cpp/src/shared/CMakeLists.txt b/languages/cpp/src/shared/CMakeLists.txt new file mode 100644 index 00000000..fe7a0085 --- /dev/null +++ b/languages/cpp/src/shared/CMakeLists.txt @@ -0,0 +1,56 @@ +# 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 + +cmake_minimum_required(VERSION 3.3) + +project(Firebolt) + +set(FIREBOLT_TRANSPORT_WAITTIME 1000 CACHE STRING "Maximum time to wait for Transport layer to get response") +set(FIREBOLT_LOGLEVEL "Info" CACHE STRING "Log level to be enabled") +option(FIREBOLT_ENABLE_STATIC_LIB "Create Firebolt library as Static library" OFF) +option(ENABLE_TESTS "Build openrpc native test" OFF) + +if (FIREBOLT_ENABLE_STATIC_LIB) + set(FIREBOLT_LIBRARY_TYPE STATIC) +else () + set(FIREBOLT_LIBRARY_TYPE SHARED) +endif () + +if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${SYSROOT_PATH}/usr" CACHE INTERNAL "" FORCE) + set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) +endif() + +list(APPEND CMAKE_MODULE_PATH + "${CMAKE_SOURCE_DIR}/cmake" + "${SYSROOT_PATH}/usr/lib/cmake" + "${SYSROOT_PATH}/tools/cmake") +include(HelperFunctions) + +set(FIREBOLT_NAMESPACE ${PROJECT_NAME} CACHE STRING "Namespace of the project") + +find_package(WPEFramework CONFIG REQUIRED) + +add_subdirectory(src) + +if (ENABLE_TESTS) + add_subdirectory(test) +endif() + +# make sure others can make use cmake settings of Firebolt OpenRPC +configure_file( "${CMAKE_SOURCE_DIR}/cmake/project.cmake.in" + "${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}Config.cmake" + @ONLY) diff --git a/languages/cpp/src/shared/cmake/HelperFunctions.cmake b/languages/cpp/src/shared/cmake/HelperFunctions.cmake new file mode 100644 index 00000000..eb2ae296 --- /dev/null +++ b/languages/cpp/src/shared/cmake/HelperFunctions.cmake @@ -0,0 +1,72 @@ +# 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 + +macro(GetSubDirs subdirs currentdir) + file(GLOB subdirectories RELATIVE ${currentdir} ${currentdir}/*) + set(subdirs "") + foreach(subdir ${subdirectories}) + if (IS_DIRECTORY ${currentdir}/${subdir}) + list(APPEND subdirs ${subdir}) + endif() + endforeach() +endmacro() + +function(InstallHeaders) + set(optionsArgs EXCLUDE_ROOT_DIR) + set(oneValueArgs TARGET NAMESPACE SOURCE DESTINATION) + set(multiValueArgs HEADERS) + + cmake_parse_arguments(Argument "${optionsArgs}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) + if (Argument_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to InstallHeaders(): \"${Argument_UNPARSED_ARGUMENTS}\"") + endif() + if (Argument_HEADERS) + add_custom_command( + TARGET ${Argument_TARGET} + POST_BUILD + COMMENT "=================== Installing Headers ======================" + ) + foreach(directory ${Argument_HEADERS}) + if (Argument_EXCLUDE_ROOT_DIR) + set(destination ${Argument_DESTINATION}) + else() + set(destination ${Argument_DESTINATION}/${directory}) + endif() + + if (Argument_SOURCE) + set(source ${Argument_SOURCE}) + else() + set(source ${CMAKE_CURRENT_LIST_DIR}) + endif() + + GetSubDirs(subdirs ${source}/${directory}) + list(APPEND subdirs ${directory}) + + foreach(subdir ${subdirs}) + if (NOT subdir STREQUAL ".") + set(dest ${destination}/${subdir}) + file(GLOB headers "${source}/${directory}/${subdir}/*.h") + if (headers) + install( + DIRECTORY "${source}/${directory}/${subdir}" + DESTINATION include/${dest} + FILES_MATCHING PATTERN "*.h") + endif() + endif() + endforeach(subdir) + endforeach(directory) + endif() +endfunction(InstallHeaders) diff --git a/languages/cpp/src/shared/cmake/project.cmake.in b/languages/cpp/src/shared/cmake/project.cmake.in new file mode 100644 index 00000000..eca32f8c --- /dev/null +++ b/languages/cpp/src/shared/cmake/project.cmake.in @@ -0,0 +1,35 @@ +# 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 + +set(FIREBOLT_NAMESPACE "@FIREBOLT_NAMESPACE@" CACHE INTERNAL "" FORCE) +set("${FIREBOLT_NAMESPACE}_FOUND" TRUE CACHE INTERNAL "" FORCE) + +list(APPEND CMAKE_MODULE_PATH + "${CMAKE_SOURCE_DIR}/cmake" + "${SYSROOT_PATH}/usr/lib/cmake" + "${SYSROOT_PATH}/usr/lib/cmake/Firebolt" + "${SYSROOT_PATH}/tools/cmake") + +if (NOT DEFINED CMAKE_PREFIX_PATH) + set(CMAKE_PREFIX_PATH ${SYSROOT_PATH}/usr/lib/cmake CACHE INTERNAL "" FORCE) +endif() + +if (FIREBOLT_ENABLE_STATIC_LIB) + set(FIREBOLT_LIBRARY_TYPE STATIC) +else () + set(FIREBOLT_LIBRARY_TYPE SHARED) +endif () + diff --git a/languages/cpp/src/shared/include/error.h b/languages/cpp/src/shared/include/error.h new file mode 100644 index 00000000..07d6268a --- /dev/null +++ b/languages/cpp/src/shared/include/error.h @@ -0,0 +1,41 @@ +/* + * 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 + */ + +#ifndef FIREBOLT_ERROR_H +#define FIREBOLT_ERROR_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum FireboltSDKError { + FireboltSDKErrorNone = 0, + FireboltSDKErrorGeneral = 1, + FireboltSDKErrorUnavailable = 2, + FireboltSDKErrorTimedout = 3, + FireboltSDKErrorNotSubscribed = 4, + FireboltSDKErrorUnknown = 5, + FireboltSDKErrorInUse = 6, + FireboltSDKErrorNotSupported = 7 +} FireboltSDKError_t; + +#ifdef __cplusplus +} +#endif + +#endif // FIREBOLT_ERROR_H diff --git a/languages/cpp/src/shared/include/firebolt.h b/languages/cpp/src/shared/include/firebolt.h new file mode 100644 index 00000000..565b363c --- /dev/null +++ b/languages/cpp/src/shared/include/firebolt.h @@ -0,0 +1,68 @@ +/* + * 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 + */ + +#ifndef FIREBOLT_H +#define FIREBOLT_H + +#include "error.h" +#include "types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define IN +#define OUT + +/** + * @brief Intitialize the Firebolt SDK + * + * @param configLine JSON String with configuration options + * + * CONFIG Format: + * { + * "waitTime": 1000, + * "logLevel": "Info", + * "workerPool":{ + * "queueSize": 8, + * "threadCount": 3 + * }, + * "wsUrl": "ws://127.0.0.1:9998" + * } + * + * + * @return FireboltSDKErrorNone if success, appropriate error otherwise. + * + */ +uint32_t FireboltSDK_Initialize(char* configLine); + + +/** + * @brief Deintitialize the Firebolt SDK + * + * @return FireboltSDKErrorNone if success, appropriate error otherwise. + * + */ +uint32_t FireboltSDK_Deinitialize(void); + +#ifdef __cplusplus +} +#endif + + +#endif // FIREBOLT_H diff --git a/languages/cpp/src/shared/include/types.h b/languages/cpp/src/shared/include/types.h new file mode 100644 index 00000000..8333f0eb --- /dev/null +++ b/languages/cpp/src/shared/include/types.h @@ -0,0 +1,37 @@ +/* + * 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 + */ + +#ifndef FIREBOLT_TYPES_H +#define FIREBOLT_TYPES_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Firebolt_String_s* Firebolt_String_t; +const char* Firebolt_String(Firebolt_String_t handle); +void Firebolt_String_Release(Firebolt_String_t handle); + +#ifdef __cplusplus +} +#endif + +#endif // FIREBOLT_TYPES_H diff --git a/languages/cpp/src/shared/src/Accessor/Accessor.cpp b/languages/cpp/src/shared/src/Accessor/Accessor.cpp new file mode 100644 index 00000000..6d4aceae --- /dev/null +++ b/languages/cpp/src/shared/src/Accessor/Accessor.cpp @@ -0,0 +1,117 @@ +/* + * 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 "Accessor.h" + +namespace FireboltSDK { + + Accessor* Accessor::_singleton = nullptr; + + Accessor::Accessor(const string& configLine) + : _workerPool() + , _transport(nullptr) + , _config() + { + _singleton = this; + _config.FromString(configLine); + + Logger::SetLogLevel(WPEFramework::Core::EnumerateType(_config.LogLevel.Value().c_str()).Value()); + + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Url = %s", _config.WsUrl.Value().c_str()); + CreateTransport(_config.WsUrl.Value().c_str(), _config.WaitTime.Value()); + CreateEventHandler(); + + _workerPool = WPEFramework::Core::ProxyType::Create(_config.WorkerPool.ThreadCount.Value(), _config.WorkerPool.StackSize.Value(), _config.WorkerPool.QueueSize.Value()); + WPEFramework::Core::WorkerPool::Assign(&(*_workerPool)); + _workerPool->Run(); + } + + Accessor::~Accessor() + { + DestroyTransport(); + DestroyEventHandler(); + WPEFramework::Core::IWorkerPool::Assign(nullptr); + _workerPool->Stop(); + _singleton = nullptr; + } + + int32_t Accessor::CreateEventHandler() + { + Event::Instance().Configure(_transport); + return FireboltSDKErrorNone; + } + + int32_t Accessor::DestroyEventHandler() + { + Event::Dispose(); + return FireboltSDKErrorNone; + } + + Event& Accessor::GetEventManager() + { + return Event::Instance(); + } + + int32_t Accessor::CreateTransport(const string& url, const uint32_t waitTime = DefaultWaitTime) + { + if (_transport != nullptr) { + delete _transport; + } + + _transport = new Transport(static_cast(url), waitTime); + if (WaitForLinkReady(_transport, waitTime) != FireboltSDKErrorNone) { + delete _transport; + _transport = nullptr; + } + + ASSERT(_transport != nullptr); + return ((_transport != nullptr) ? FireboltSDKErrorNone : FireboltSDKErrorUnavailable); + } + + int32_t Accessor::DestroyTransport() + { + if (_transport != nullptr) { + delete _transport; + _transport = nullptr; + } + return FireboltSDKErrorNone; + } + + Transport* Accessor::GetTransport() + { + ASSERT(_transport != nullptr); + return _transport; + } + + int32_t Accessor::WaitForLinkReady(Transport* transport, const uint32_t waitTime = DefaultWaitTime) { + uint32_t waiting = (waitTime == WPEFramework::Core::infinite ? WPEFramework::Core::infinite : waitTime); + static constexpr uint32_t SLEEPSLOT_TIME = 100; + + // Right, a wait till connection is closed is requested.. + while ((waiting > 0) && (transport->IsOpen() == false)) { + + uint32_t sleepSlot = (waiting > SLEEPSLOT_TIME ? SLEEPSLOT_TIME : waiting); + + // Right, lets sleep in slices of 100 ms + SleepMs(sleepSlot); + + waiting -= (waiting == WPEFramework::Core::infinite ? 0 : sleepSlot); + } + return (((waiting == 0) || (transport->IsOpen() == true)) ? FireboltSDKErrorNone : FireboltSDKErrorTimedout); + } +} diff --git a/languages/cpp/src/shared/src/Accessor/Accessor.h b/languages/cpp/src/shared/src/Accessor/Accessor.h new file mode 100644 index 00000000..e247df98 --- /dev/null +++ b/languages/cpp/src/shared/src/Accessor/Accessor.h @@ -0,0 +1,122 @@ +/* + * 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 "Module.h" +#include "WorkerPool.h" +#include "Transport/Transport.h" +#include "Event/Event.h" +#include "Logger/Logger.h" + +namespace FireboltSDK { + class Accessor { + private: + static constexpr uint8_t JSONVersion = 2; + + private: + //Singleton + Accessor(const string& configLine); + + public: + class EXTERNAL Config : public WPEFramework::Core::JSON::Container { + public: + Config(const Config&) = delete; + Config& operator=(const Config&) = delete; + + class WorkerPoolConfig : public WPEFramework::Core::JSON::Container { + public: + WorkerPoolConfig& operator=(const WorkerPoolConfig&); + + WorkerPoolConfig() + : WPEFramework::Core::JSON::Container() + , QueueSize(8) + , ThreadCount(3) + , StackSize(WPEFramework::Core::Thread::DefaultStackSize()) + { + Add("queueSize", &QueueSize); + Add("threadCount", &ThreadCount); + Add("stackSize", &StackSize); + } + + virtual ~WorkerPoolConfig() = default; + + public: + WPEFramework::Core::JSON::DecUInt32 QueueSize; + WPEFramework::Core::JSON::DecUInt32 ThreadCount; + WPEFramework::Core::JSON::DecUInt32 StackSize; + }; + + + Config() + : WPEFramework::Core::JSON::Container() + , WaitTime(1000) + , LogLevel(_T("Info")) + , WorkerPool() + , WsUrl(_T("ws://127.0.0.1:9998")) + { + Add(_T("waitTime"), &WaitTime); + Add(_T("logLevel"), &LogLevel); + Add(_T("workerPool"), &WorkerPool); + Add(_T("wsUrl"), &WsUrl); + } + + public: + WPEFramework::Core::JSON::DecUInt32 WaitTime; + WPEFramework::Core::JSON::String LogLevel; + WorkerPoolConfig WorkerPool; + WPEFramework::Core::JSON::String WsUrl; + }; + + Accessor(const Accessor&) = delete; + Accessor& operator= (const Accessor&) = delete; + Accessor() = delete; + ~Accessor(); + + static Accessor& Instance(const string& configLine = "") + { + static Accessor *instance = new Accessor(configLine); + ASSERT(instance != nullptr); + return *instance; + } + + static void Dispose() + { + ASSERT(_singleton != nullptr); + + if (_singleton != nullptr) { + delete _singleton; + } + } + Event& GetEventManager(); + Transport* GetTransport(); + + private: + int32_t CreateEventHandler(); + int32_t DestroyEventHandler(); + int32_t CreateTransport(const string& url, const uint32_t waitTime); + int32_t DestroyTransport(); + int32_t WaitForLinkReady(Transport* transport, const uint32_t waitTime); + + private: + WPEFramework::Core::ProxyType _workerPool; + Transport* _transport; + static Accessor* _singleton; + Config _config; + }; +} diff --git a/languages/cpp/src/shared/src/Accessor/WorkerPool.h b/languages/cpp/src/shared/src/Accessor/WorkerPool.h new file mode 100644 index 00000000..69005a5e --- /dev/null +++ b/languages/cpp/src/shared/src/Accessor/WorkerPool.h @@ -0,0 +1,102 @@ +/* + * 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 "Module.h" + +namespace FireboltSDK { + + class WorkerPoolImplementation : public WPEFramework::Core::WorkerPool { + public: + WorkerPoolImplementation() = delete; + WorkerPoolImplementation(const WorkerPoolImplementation&) = delete; + WorkerPoolImplementation& operator=(const WorkerPoolImplementation&) = delete; + + WorkerPoolImplementation(const uint8_t threads, const uint32_t stackSize, const uint32_t queueSize) + : WorkerPool(threads, stackSize, queueSize, &_dispatcher) + { + } + + ~WorkerPoolImplementation() + { + // Diable the queue so the minions can stop, even if they are processing and waiting for work.. + Stop(); + } + + public: + void Stop() + { + WPEFramework::Core::WorkerPool::Stop(); + } + + void Run() + { + WPEFramework::Core::WorkerPool::Run(); + } + + private: + class Dispatcher : public WPEFramework::Core::ThreadPool::IDispatcher { + public: + Dispatcher(const Dispatcher&) = delete; + Dispatcher& operator=(const Dispatcher&) = delete; + + Dispatcher() = default; + ~Dispatcher() override = default; + + private: + void Initialize() override { } + void Deinitialize() override { } + void Dispatch(WPEFramework::Core::IDispatch* job) override + { job->Dispatch(); } + }; + + Dispatcher _dispatcher; + }; + + class Worker : public WPEFramework::Core::IDispatch { + public: + typedef std::function Dispatcher; + + protected: + Worker(const Dispatcher& dispatcher, const void* userData) + : _dispatcher(dispatcher) + , _userData(userData) + { + } + + public: + Worker() = delete; + Worker(const Worker&) = delete; + Worker& operator=(const Worker&) = delete; + + ~Worker() = default; + + public: + static WPEFramework::Core::ProxyType Create(const Dispatcher& dispatcher, const void* userData); + + void Dispatch() override + { + _dispatcher(_userData); + } + + private: + Dispatcher _dispatcher; + const void* _userData; + }; +} diff --git a/languages/cpp/src/shared/src/CMakeLists.txt b/languages/cpp/src/shared/src/CMakeLists.txt new file mode 100644 index 00000000..ecaf4efb --- /dev/null +++ b/languages/cpp/src/shared/src/CMakeLists.txt @@ -0,0 +1,73 @@ +# 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 + +cmake_minimum_required(VERSION 3.3) + +project(FireboltSDK) +project_version(1.0.0) +set(TARGET ${PROJECT_NAME}) +message("Setup ${TARGET} v${PROJECT_VERSION}") + +file(GLOB SOURCES *.cpp) +add_library(${TARGET} ${FIREBOLT_LIBRARY_TYPE} + ${SOURCES} + Logger/Logger.cpp + Transport/Transport.cpp + Accessor/Accessor.cpp + Event/Event.cpp +) + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +find_package(${NAMESPACE}WebSocket CONFIG REQUIRED) + +target_link_libraries(${TARGET} + PUBLIC + ${NAMESPACE}WebSocket::${NAMESPACE}WebSocket +) + +target_include_directories(${TARGET} + PRIVATE + $ + $ +) + +set_target_properties(${TARGET} PROPERTIES + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED YES + FRAMEWORK FALSE + LINK_WHAT_YOU_USE TRUE + VERSION ${PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} +) + +install( + TARGETS ${TARGET} EXPORT ${TARGET}Targets + ARCHIVE DESTINATION lib COMPONENT libs # static lib + LIBRARY DESTINATION lib COMPONENT libs # shared lib +) + +install( + DIRECTORY ${CMAKE_SOURCE_DIR}/include/ + DESTINATION include/${FIREBOLT_NAMESPACE}SDK + FILES_MATCHING PATTERN "*.h") + +install( + FILES ${CMAKE_BINARY_DIR}/FireboltConfig.cmake + DESTINATION lib/cmake/${FIREBOLT_NAMESPACE}) + +InstallHeaders(TARGET ${TARGET} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION ${FIREBOLT_NAMESPACE}SDK) +InstallCMakeConfig(TARGETS ${TARGET}) +InstallPackageConfig(TARGETS ${TARGET} DESCRIPTION "Firebolt SDK Library") diff --git a/languages/cpp/src/shared/src/Event/Event.cpp b/languages/cpp/src/shared/src/Event/Event.cpp new file mode 100644 index 00000000..c1fdff6f --- /dev/null +++ b/languages/cpp/src/shared/src/Event/Event.cpp @@ -0,0 +1,147 @@ +/* + * 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 "Transport/Transport.h" +#include "Event.h" + +namespace FireboltSDK { + Event* Event::_singleton = nullptr; + Event::Event() + : _eventMap() + , _adminLock() + , _transport(nullptr) + { + ASSERT(_singleton == nullptr); + _singleton = this; + } + + Event::~Event() /* override */ + { + _transport->SetEventHandler(nullptr); + _transport = nullptr; + + _singleton = nullptr; + } + + /* static */ Event& Event::Instance() + { + static Event *instance = new Event(); + ASSERT(instance != nullptr); + return *instance; + } + + /* static */ void Event::Dispose() + { + ASSERT(_singleton != nullptr); + + if (_singleton != nullptr) { + delete _singleton; + } + } + + void Event::Configure(Transport* transport) + { + _transport = transport; + _transport->SetEventHandler(this); + } + + int32_t Event::Unsubscribe(const string& eventName, void* usercb) + { + int32_t status = Revoke(eventName, usercb); + + if (status == FireboltSDKErrorNone) { + if (_transport != nullptr) { + + const string parameters("{\"listen\":false}"); + status = _transport->Unsubscribe(eventName, parameters); + } + } + return ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone: status); + } + + int32_t Event::ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) /* override */ + { + int32_t result = FireboltSDKErrorGeneral; + Response response; + _transport->FromMessage((WPEFramework::Core::JSON::IElement*)&response, *jsonResponse); + if (response.Listening.IsSet() == true) { + result = FireboltSDKErrorNone; + enabled = response.Listening.Value(); + } + return result; + } + + int32_t Event::Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) /* override */ + { + string response = jsonResponse->Result.Value(); + _adminLock.Lock(); + EventMap::iterator eventIndex = _eventMap.find(eventName); + if (eventIndex != _eventMap.end()) { + CallbackMap::iterator callbackIndex = eventIndex->second.begin(); + while(callbackIndex != eventIndex->second.end()) { + State state; + if (callbackIndex->second.state != State::REVOKED) { + callbackIndex->second.state = State::EXECUTING; + } + state = callbackIndex->second.state; + _adminLock.Unlock(); + if (state == State::EXECUTING) { + callbackIndex->second.lambda(callbackIndex->first, callbackIndex->second.userdata, (jsonResponse->Result.Value())); + } + _adminLock.Lock(); + if (callbackIndex->second.state == State::REVOKED) { + callbackIndex = eventIndex->second.erase(callbackIndex); + if (eventIndex->second.size() == 0) { + _eventMap.erase(eventIndex); + } + } else { + callbackIndex->second.state = State::IDLE; + callbackIndex++; + } + } + } + _adminLock.Unlock(); + + return FireboltSDKErrorNone;; + } + + int32_t Event::Revoke(const string& eventName, void* usercb) + { + int32_t status = FireboltSDKErrorNone; + _adminLock.Lock(); + EventMap::iterator eventIndex = _eventMap.find(eventName); + if (eventIndex != _eventMap.end()) { + CallbackMap::iterator callbackIndex = eventIndex->second.find(usercb); + if (callbackIndex->second.state != State::EXECUTING) { + if (callbackIndex != eventIndex->second.end()) { + eventIndex->second.erase(callbackIndex); + } + } else { + callbackIndex->second.state = State::REVOKED; + } + if (eventIndex->second.size() == 0) { + _eventMap.erase(eventIndex); + } else { + status = FireboltSDKErrorInUse; + } + } + _adminLock.Unlock(); + + return status; + } +} diff --git a/languages/cpp/src/shared/src/Event/Event.h b/languages/cpp/src/shared/src/Event/Event.h new file mode 100644 index 00000000..dd65cb53 --- /dev/null +++ b/languages/cpp/src/shared/src/Event/Event.h @@ -0,0 +1,165 @@ +/* + * 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 "Module.h" + +namespace FireboltSDK { + + static constexpr uint32_t DefaultWaitTime = 1000; + + class Event : public IEventHandler { + public: + typedef std::function DispatchFunction; + private: + enum State : uint8_t { + IDLE, + EXECUTING, + REVOKED + }; + + struct CallbackData { + const DispatchFunction lambda; + const void* userdata; + State state; + }; + using CallbackMap = std::map; + using EventMap = std::map; + + class Response : public WPEFramework::Core::JSON::Container { + public: + Response& operator=(const Response&) = delete; + Response() + : WPEFramework::Core::JSON::Container() + , Listening(false) + { + Add(_T("listening"), &Listening); + } + Response(const Response& copy) + : WPEFramework::Core::JSON::Container() + , Listening(copy.Listening) + { + Add(_T("listening"), &Listening); + } + ~Response() override = default; + + public: + WPEFramework::Core::JSON::Boolean Listening; + }; + + private: + Event(); + public: + ~Event() override; + static Event& Instance(); + static void Dispose(); + void Configure(Transport* transport); + + public: + template + int32_t Subscribe(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) + { + JsonObject jsonParameters; + return Subscribe(eventName, jsonParameters, callback, usercb, userdata); + } + + template + int32_t Subscribe(const string& eventName, JsonObject& jsonParameters, const CALLBACK& callback, void* usercb, const void* userdata) + { + int32_t status = FireboltSDKErrorUnavailable; + if (_transport != nullptr) { + + status = Assign(eventName, callback, usercb, userdata); + if (status == FireboltSDKErrorNone) { + Response response; + + WPEFramework::Core::JSON::Variant Listen = true; + jsonParameters.Set(_T("listen"), Listen); + string parameters; + jsonParameters.ToString(parameters); + + status = _transport->Subscribe(eventName, parameters, response); + + if (status != FireboltSDKErrorNone) { + Revoke(eventName, usercb); + } else if ((response.Listening.IsSet() == true) && + (response.Listening.Value() == true)) { + status = FireboltSDKErrorNone; + } else { + status = FireboltSDKErrorNotSubscribed; + } + } + } + + return status; + } + + int32_t Unsubscribe(const string& eventName, void* usercb); + + private: + template + int32_t Assign(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) + { + int32_t status = FireboltSDKErrorNone; + std::function actualCallback = callback; + DispatchFunction implementation = [actualCallback](void* usercb, const void* userdata, const string& parameters) -> int32_t { + + WPEFramework::Core::ProxyType* inbound = new WPEFramework::Core::ProxyType(); + *inbound = WPEFramework::Core::ProxyType::Create(); + (*inbound)->FromString(parameters); + actualCallback(usercb, userdata, static_cast(inbound)); + return (FireboltSDKErrorNone); + }; + CallbackData callbackData = {implementation, userdata, State::IDLE}; + + _adminLock.Lock(); + EventMap::iterator eventIndex = _eventMap.find(eventName); + if (eventIndex != _eventMap.end()) { + CallbackMap::iterator callbackIndex = eventIndex->second.find(usercb); + if (callbackIndex == eventIndex->second.end()) { + eventIndex->second.emplace(std::piecewise_construct, std::forward_as_tuple(usercb), std::forward_as_tuple(callbackData)); + } else { + // Already registered, no need to register again; + status = FireboltSDKErrorInUse; + } + } else { + + CallbackMap callbackMap; + callbackMap.emplace(std::piecewise_construct, std::forward_as_tuple(usercb), std::forward_as_tuple(callbackData)); + _eventMap.emplace(std::piecewise_construct, std::forward_as_tuple(eventName), std::forward_as_tuple(callbackMap)); + + } + + _adminLock.Unlock(); + return status; + } + int32_t Revoke(const string& eventName, void* usercb); + + private: + int32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) override; + int32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) override; + + private: + EventMap _eventMap; + WPEFramework::Core::CriticalSection _adminLock; + Transport* _transport; + + static Event* _singleton; + }; +} diff --git a/languages/cpp/src/shared/src/FireboltSDK.conf.in b/languages/cpp/src/shared/src/FireboltSDK.conf.in new file mode 100644 index 00000000..6964a7bc --- /dev/null +++ b/languages/cpp/src/shared/src/FireboltSDK.conf.in @@ -0,0 +1,3 @@ +url = "@FIREBOLT_SERVER_URL@" +waittime = "@FIREBOLT_TRANSPORT_WAITTIME@" +loglevel = "@FIREBOLT_LOGLEVEL@" diff --git a/languages/cpp/src/shared/src/FireboltSDK.h b/languages/cpp/src/shared/src/FireboltSDK.h new file mode 100644 index 00000000..d78687dc --- /dev/null +++ b/languages/cpp/src/shared/src/FireboltSDK.h @@ -0,0 +1,26 @@ +/* + * 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 "Transport/Transport.h" +#include "Properties/Properties.h" +#include "Accessor/Accessor.h" +#include "Logger/Logger.h" +#include "TypesPriv.h" +#include "types.h" diff --git a/languages/cpp/src/shared/src/Logger/Logger.cpp b/languages/cpp/src/shared/src/Logger/Logger.cpp new file mode 100644 index 00000000..44ebaba8 --- /dev/null +++ b/languages/cpp/src/shared/src/Logger/Logger.cpp @@ -0,0 +1,86 @@ +/* + * 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 "Module.h" +#include "error.h" +#include "Logger.h" + +namespace WPEFramework { + +ENUM_CONVERSION_BEGIN(FireboltSDK::Logger::LogLevel) + + { FireboltSDK::Logger::LogLevel::Error, _TXT("Error") }, + { FireboltSDK::Logger::LogLevel::Warning, _TXT("Warning") }, + { FireboltSDK::Logger::LogLevel::Info, _TXT("Info") }, + { FireboltSDK::Logger::LogLevel::Debug, _TXT("Debug") }, + +ENUM_CONVERSION_END(FireboltSDK::Logger::LogLevel) + +ENUM_CONVERSION_BEGIN(FireboltSDK::Logger::Category) + + { FireboltSDK::Logger::Category::OpenRPC, _TXT("FireboltSDK::OpenRPC") }, + { FireboltSDK::Logger::Category::Core, _TXT("FireboltSDK::Core") }, + { FireboltSDK::Logger::Category::Management, _TXT("FireboltSDK::Management") }, + { FireboltSDK::Logger::Category::Discovery, _TXT("FireboltSDK::Discovery") }, + +ENUM_CONVERSION_END(FireboltSDK::Logger::Category) + +} + +namespace FireboltSDK { + /* static */ Logger::LogLevel Logger::_logLevel = Logger::LogLevel::Error; + + int32_t Logger::SetLogLevel(Logger::LogLevel logLevel) + { + ASSERT(logLevel < Logger::LogLevel::MaxLevel); + int32_t status = FireboltSDKErrorNotSupported; + if (logLevel < Logger::LogLevel::MaxLevel) { + _logLevel = logLevel; + status = FireboltSDKErrorNone; + } + return status; + } + + void Logger::Log(LogLevel logLevel, Category category, const std::string& module, const std::string file, const std::string function, const uint16_t line, const std::string& format, ...) + { + if (logLevel <= _logLevel) { + va_list arg; + char msg[Logger::MaxBufSize]; + va_start(arg, format); + int length = vsnprintf(msg, Logger::MaxBufSize, format.c_str(), arg); + va_end(arg); + + uint32_t position = (length >= Logger::MaxBufSize) ? (Logger::MaxBufSize - 1) : length; + msg[position] = '\0'; + + char formattedMsg[Logger::MaxBufSize]; + const string time = WPEFramework::Core::Time::Now().ToTimeOnly(true); + const string categoryName = WPEFramework::Core::EnumerateType(category).Data(); +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-truncation" + if (categoryName.empty() != true) { + snprintf(formattedMsg, sizeof(formattedMsg), "--->\033[1;32m[%s]:[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), categoryName.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); + } else { + snprintf(formattedMsg, sizeof(formattedMsg), "--->\033[1;32m[%s]:[%s][%s:%d](%s) : %s\n", time.c_str(), module.c_str(), WPEFramework::Core::File::FileName(file).c_str(), line, function.c_str(), TRACE_PROCESS_ID, TRACE_THREAD_ID, msg); + } +#pragma GCC diagnostic pop + LOG_MESSAGE(formattedMsg); + } + } +} + diff --git a/languages/cpp/src/shared/src/Logger/Logger.h b/languages/cpp/src/shared/src/Logger/Logger.h new file mode 100644 index 00000000..b8e42031 --- /dev/null +++ b/languages/cpp/src/shared/src/Logger/Logger.h @@ -0,0 +1,85 @@ +/* + * 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 "types.h" + +namespace FireboltSDK { + + class Logger { + private: + static constexpr uint16_t MaxBufSize = 512; + + public: + enum class LogLevel : uint8_t { + Error, + Warning, + Info, + Debug, + MaxLevel + }; + + enum class Category : uint8_t { + OpenRPC, + Core, + Management, + Discovery + }; + + public: + Logger() = default; + Logger(const Logger&) = delete; + Logger& operator=(const Logger&) = delete; + ~Logger() = default; + + public: + static int32_t SetLogLevel(LogLevel logLevel); + static void Log(LogLevel logLevel, Category category, const std::string& module, const std::string file, const std::string function, const uint16_t line, const std::string& format, ...); + + public: + template + static const string Module() + { + return WPEFramework::Core::ClassNameOnly(typeid(CLASS).name()).Text(); + } + + private: + static LogLevel _logLevel; + }; +} + +#define FIREBOLT_LOG(level, category, module, ...) \ + FireboltSDK::Logger::Log(level, category, module, __FILE__, __func__, __LINE__, __VA_ARGS__) + +#define FIREBOLT_LOG_ERROR(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Error, category, module, __VA_ARGS__) +#define FIREBOLT_LOG_WARNING(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Warning, category, module, __VA_ARGS__) +#define FIREBOLT_LOG_INFO(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Info, category, module, __VA_ARGS__) +#define FIREBOLT_LOG_DEBUG(category, module, ...) \ + FIREBOLT_LOG(FireboltSDK::Logger::LogLevel::Debug, category, module, __VA_ARGS__) + +#ifdef ENABLE_SYSLOG +#define LOG_MESSAGE(message) \ + syslog(sLOG_NOTIC, "%s", message); +#else +#define LOG_MESSAGE(message) \ + fprintf(stderr, "%s", message); fflush(stdout); +#endif diff --git a/languages/cpp/src/shared/src/Module.cpp b/languages/cpp/src/shared/src/Module.cpp new file mode 100644 index 00000000..d63badc4 --- /dev/null +++ b/languages/cpp/src/shared/src/Module.cpp @@ -0,0 +1,21 @@ +/* + * 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 "Module.h" + +MODULE_NAME_DECLARATION(BUILD_REFERENCE) diff --git a/languages/cpp/src/shared/src/Module.h b/languages/cpp/src/shared/src/Module.h new file mode 100644 index 00000000..00ea64bb --- /dev/null +++ b/languages/cpp/src/shared/src/Module.h @@ -0,0 +1,29 @@ +/* + * 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 + +#ifndef MODULE_NAME +#define MODULE_NAME OpenRPCNativeSDK +#endif + +#include +#include + +#undef EXTERNAL +#define EXTERNAL diff --git a/languages/cpp/src/shared/src/Properties/Properties.h b/languages/cpp/src/shared/src/Properties/Properties.h new file mode 100644 index 00000000..eaf6c1a4 --- /dev/null +++ b/languages/cpp/src/shared/src/Properties/Properties.h @@ -0,0 +1,148 @@ +/* + * 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 "Accessor/Accessor.h" +#include "Event/Event.h" + +namespace FireboltSDK { + + class Properties { + public: + Properties(const Properties&) = delete; + Properties& operator= (const Properties&) = delete; + + Properties() = default; + ~Properties() = default; + + public: + template + static int32_t Get(const string& propertyName, WPEFramework::Core::ProxyType& response) + { + int32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject parameters; + RESPONSETYPE responseType; + status = transport->Invoke(propertyName, parameters, responseType); + if (status == FireboltSDKErrorNone) { + ASSERT(response.IsValid() == false); + if (response.IsValid() == true) { + response.Release(); + } + response = WPEFramework::Core::ProxyType::Create(); + (*response) = responseType; + } + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static int32_t Get(const string& propertyName, const PARAMETERS& parameters, WPEFramework::Core::ProxyType& response) + { + int32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + RESPONSETYPE responseType; + status = transport->Invoke(propertyName, parameters, responseType); + if (status == FireboltSDKErrorNone) { + ASSERT(response.IsValid() == false); + if (response.IsValid() == true) { + response.Release(); + } + response = WPEFramework::Core::ProxyType::Create(); + (*response) = responseType; + } + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + + template + static int32_t Get(const string& propertyName, RESPONSETYPE& response) + { + int32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject parameters; + status = transport->Invoke(propertyName, parameters, response); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static int32_t Get(const string& propertyName, const PARAMETERS& parameters, RESPONSETYPE& response) + { + int32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + status = transport->Invoke(propertyName, parameters, response); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static int32_t Set(const string& propertyName, const PARAMETERS& parameters) + { + int32_t status = FireboltSDKErrorUnavailable; + Transport* transport = Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject responseType; + status = transport->Invoke(propertyName, parameters, responseType); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; + } + + template + static int32_t Subscribe(const string& propertyName, JsonObject& paramsters, const CALLBACK& callback, void* usercb, const void* userdata) + { + return Event::Instance().Subscribe(EventName(propertyName), paramsters, callback, usercb, userdata); + } + + static int32_t Unsubscribe(const string& propertyName, void* usercb) + { + return Event::Instance().Unsubscribe(EventName(propertyName), usercb); + } + private: + static inline string EventName(const string& propertyName) { + size_t pos = propertyName.find_first_of('.'); + string eventName = propertyName; + if (pos != std::string::npos) { + eventName[pos + 1] = std::toupper(eventName[pos + 1]); + eventName = string(eventName.substr(0, pos + 1) + "on" + eventName.substr(pos + 1) + "Changed"); + } + return eventName; + } + }; +} diff --git a/languages/cpp/src/shared/src/Transport/Transport.cpp b/languages/cpp/src/shared/src/Transport/Transport.cpp new file mode 100644 index 00000000..280944c6 --- /dev/null +++ b/languages/cpp/src/shared/src/Transport/Transport.cpp @@ -0,0 +1,24 @@ +/* + * 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 "Transport.h" + +namespace FireboltSDK { + +} + diff --git a/languages/cpp/src/shared/src/Transport/Transport.h b/languages/cpp/src/shared/src/Transport/Transport.h new file mode 100644 index 00000000..6b80cd25 --- /dev/null +++ b/languages/cpp/src/shared/src/Transport/Transport.h @@ -0,0 +1,897 @@ +/* + * 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 "Module.h" +#include "error.h" + +namespace FireboltSDK { + + using namespace WPEFramework::Core::TypeTraits; + + template + class CommunicationChannel { + public: + typedef std::function Callback; + class Entry { + private: + Entry(const Entry&) = delete; + Entry& operator=(const Entry& rhs) = delete; + struct Synchronous { + Synchronous() + : _signal(false, true) + , _response() + { + } + WPEFramework::Core::Event _signal; + std::list> _response; + }; + struct ASynchronous { + ASynchronous(const uint32_t waitTime, const Callback& completed) + : _waitTime(WPEFramework::Core::Time::Now().Add(waitTime).Ticks()) + , _completed(completed) + { + } + uint64_t _waitTime; + Callback _completed; + }; + + public: + Entry() + : _synchronous(true) + , _info() + { + } + Entry(const uint32_t waitTime, const Callback& completed) + : _synchronous(false) + , _info(waitTime, completed) + { + } + ~Entry() + { + if (_synchronous == true) { + _info.sync.~Synchronous(); + } + else { + _info.async.~ASynchronous(); + } + } + + public: + const WPEFramework::Core::ProxyType& Response() const + { + return (*(_info.sync._response.begin())); + } + bool Signal(const WPEFramework::Core::ProxyType& response) + { + if (_synchronous == true) { + _info.sync._response.push_back(response); + _info.sync._signal.SetEvent(); + } + else { + _info.async._completed(*response); + } + + return (_synchronous == false); + } + const uint64_t& Expiry() const + { + return (_info.async._waitTime); + } + void Abort(const uint32_t id) + { + if (_synchronous == true) { + _info.sync._signal.SetEvent(); + } + else { + MESSAGETYPE message; + ToMessage(id, message, WPEFramework::Core::ERROR_ASYNC_ABORTED); + _info.async._completed(message); + } + } + bool Expired(const uint32_t id, const uint64_t& currentTime, uint64_t& nextTime) + { + bool expired = false; + + if (_synchronous == false) { + if (_info.async._waitTime > currentTime) { + if (_info.async._waitTime < nextTime) { + nextTime = _info.async._waitTime; + } + } + else { + MESSAGETYPE message; + ToMessage(id, message, WPEFramework::Core::ERROR_TIMEDOUT); + _info.async._completed(message); + expired = true; + } + } + return (expired); + } + bool WaitForResponse(const uint32_t waitTime) + { + return (_info.sync._signal.Lock(waitTime) == WPEFramework::Core::ERROR_NONE); + } + + private: + void ToMessage(const uint32_t id, WPEFramework::Core::JSONRPC::Message& message, uint32_t error) + { + message.Id = id; + message.Error.Code = error; + switch (error) { + case WPEFramework::Core::ERROR_ASYNC_ABORTED: { + message.Error.Text = _T("Pending a-sync call has been aborted"); + break; + } + case WPEFramework::Core::ERROR_TIMEDOUT: { + message.Error.Text = _T("Pending a-sync call has timed out"); + break; + } + } + } + + bool _synchronous; + union Info { + public: + Info() + : sync() + { + } + Info(const uint32_t waitTime, const Callback& completed) + : async(waitTime, completed) + { + } + ~Info() + { + } + Synchronous sync; + ASynchronous async; + } _info; + }; + + + + private: + class FactoryImpl { + private: + FactoryImpl(const FactoryImpl&) = delete; + FactoryImpl& operator=(const FactoryImpl&) = delete; + + class WatchDog { + private: + WatchDog() = delete; + WatchDog& operator=(const WatchDog&) = delete; + + public: + WatchDog(CLIENT* client) + : _client(client) + { + } + WatchDog(const WatchDog& copy) + : _client(copy._client) + { + } + ~WatchDog() + { + } + + bool operator==(const WatchDog& rhs) const + { + return (rhs._client == _client); + } + bool operator!=(const WatchDog& rhs) const + { + return (!operator==(rhs)); + } + + public: + uint64_t Timed(const uint64_t scheduledTime) { + return (_client->Timed()); + } + + private: + CLIENT* _client; + }; + + friend WPEFramework::Core::SingletonType; + + FactoryImpl() + : _messageFactory(2) + , _watchDog(WPEFramework::Core::Thread::DefaultStackSize(), _T("TransportCleaner")) + { + } + + public: + static FactoryImpl& Instance() + { + return (WPEFramework::Core::SingletonType::Instance()); + } + + ~FactoryImpl() + { + } + + public: + WPEFramework::Core::ProxyType Element(const string&) + { + return (_messageFactory.Element()); + } + void Trigger(const uint64_t& time, CLIENT* client) + { + _watchDog.Trigger(time, client); + } + void Revoke(CLIENT* client) + { + _watchDog.Revoke(client); + } + private: + WPEFramework::Core::ProxyPoolType _messageFactory; + WPEFramework::Core::TimerType _watchDog; + }; + + class ChannelImpl : public WPEFramework::Core::StreamJSONType, FactoryImpl&, INTERFACE> { + private: + ChannelImpl(const ChannelImpl&) = delete; + ChannelImpl& operator=(const ChannelImpl&) = delete; + + typedef WPEFramework::Core::StreamJSONType, FactoryImpl&, INTERFACE> BaseClass; + + public: + ChannelImpl(CommunicationChannel* parent, const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask) + : BaseClass(5, FactoryImpl::Instance(), path, _T("JSON"), query, "", false, mask, false, remoteNode.AnyInterface(), remoteNode, 512, 512) + , _parent(*parent) + { + } + ~ChannelImpl() override = default; + + public: + void Received(WPEFramework::Core::ProxyType& response) override + { + WPEFramework::Core::ProxyType inbound(response); + + ASSERT(inbound.IsValid() == true); + if (inbound.IsValid() == true) { + _parent.Inbound(inbound); + } + } + void Send(WPEFramework::Core::ProxyType& msg) override + { +#ifdef __DEBUG__ + string message; + ToMessage(msg, message); + TRACE_L1("Message: %s send", message.c_str()); +#endif + } + void StateChange() override + { + _parent.StateChange(); + } + bool IsIdle() const override + { + return (true); + } + + private: + void ToMessage(const WPEFramework::Core::ProxyType& jsonObject, string& message) const + { + WPEFramework::Core::ProxyType inbound(jsonObject); + + ASSERT(inbound.IsValid() == true); + if (inbound.IsValid() == true) { + inbound->ToString(message); + } + } + void ToMessage(const WPEFramework::Core::ProxyType& jsonObject, string& message) const + { + WPEFramework::Core::ProxyType inbound(jsonObject); + + ASSERT(inbound.IsValid() == true); + if (inbound.IsValid() == true) { + std::vector values; + inbound->ToBuffer(values); + if (values.empty() != true) { + WPEFramework::Core::ToString(values.data(), static_cast(values.size()), false, message); + } + } + } + + private: + CommunicationChannel& _parent; + }; + + protected: + CommunicationChannel(const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask) + : _channel(this, remoteNode, path, query, mask) + , _sequence(0) + { + } + + public: + ~CommunicationChannel() = default; + static WPEFramework::Core::ProxyType Instance(const WPEFramework::Core::NodeId& remoteNode, const string& path, const string& query, const bool mask = true) + { + static WPEFramework::Core::ProxyMapType channelMap; + + string searchLine = remoteNode.HostAddress() + '@' + path; + + return (channelMap.template Instance(searchLine, remoteNode, path, query, mask)); + } + + public: + static void Trigger(const uint64_t& time, CLIENT* client) + { + FactoryImpl::Instance().Trigger(time, client); + } + static WPEFramework::Core::ProxyType Message() + { + return (FactoryImpl::Instance().Element(string())); + } + uint32_t Sequence() const + { + return (++_sequence); + } + void Register(CLIENT& client) + { + _adminLock.Lock(); + ASSERT(std::find(_observers.begin(), _observers.end(), &client) == _observers.end()); + _observers.push_back(&client); + if (_channel.IsOpen() == true) { + client.Opened(); + } + _adminLock.Unlock(); + } + void Unregister(CLIENT& client) + { + _adminLock.Lock(); + typename std::list::iterator index(std::find(_observers.begin(), _observers.end(), &client)); + if (index != _observers.end()) { + _observers.erase(index); + } + FactoryImpl::Instance().Revoke(&client); + _adminLock.Unlock(); + } + + void Submit(const WPEFramework::Core::ProxyType& message) + { + _channel.Submit(message); + } + bool IsSuspended() const + { + return (_channel.IsSuspended()); + } + uint32_t Initialize() + { + return (Open(0)); + } + void Deinitialize() + { + Close(); + } + bool IsOpen() + { + return (_channel.IsOpen() == true); + } + + protected: + void StateChange() + { + _adminLock.Lock(); + typename std::list::iterator index(_observers.begin()); + while (index != _observers.end()) { + if (_channel.IsOpen() == true) { + (*index)->Opened(); + } + else { + (*index)->Closed(); + } + index++; + } + _adminLock.Unlock(); + } + bool Open(const uint32_t waitTime) + { + bool result = true; + if (_channel.IsClosed() == true) { + result = (_channel.Open(waitTime) == WPEFramework::Core::ERROR_NONE); + } + return (result); + } + void Close() + { + _channel.Close(WPEFramework::Core::infinite); + } + + private: + int32_t Inbound(const WPEFramework::Core::ProxyType& inbound) + { + int32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + _adminLock.Lock(); + typename std::list::iterator index(_observers.begin()); + while ((result != WPEFramework::Core::ERROR_NONE) && (index != _observers.end())) { + result = (*index)->Submit(inbound); + index++; + } + _adminLock.Unlock(); + + return (result); + } + + private: + WPEFramework::Core::CriticalSection _adminLock; + ChannelImpl _channel; + mutable std::atomic _sequence; + std::list _observers; + }; + + class IEventHandler { + public: + virtual int32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) = 0; + virtual int32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) = 0; + virtual ~IEventHandler() = default; + }; + + template + class Transport { + private: + using Channel = CommunicationChannel; + using Entry = typename CommunicationChannel::Entry; + using PendingMap = std::unordered_map; + using EventMap = std::map; + typedef std::function& jsonResponse, bool& enabled)> EventResponseValidatioionFunction; + + class Job : public WPEFramework::Core::IDispatch { + protected: + Job(const WPEFramework::Core::ProxyType& inbound, class Transport* parent) + : _inbound(inbound) + , _parent(parent) + { + } + + public: + Job() = delete; + Job(const Job&) = delete; + Job& operator=(const Job&) = delete; + + ~Job() = default; + + public: + static WPEFramework::Core::ProxyType Create(const WPEFramework::Core::ProxyType& inbound, class Transport* parent); + + void Dispatch() override + { + _parent->Inbound(_inbound); + } + + private: + const WPEFramework::Core::ProxyType _inbound; + class Transport* _parent; + }; + + protected: + static constexpr uint32_t DefaultWaitTime = 10000; + + inline void Announce() { + _channel->Register(*this); + } + + private: + static constexpr const TCHAR* PathPrefix = _T("/"); + public: + Transport() = delete; + Transport(const Transport&) = delete; + Transport& operator=(Transport&) = delete; + Transport(const WPEFramework::Core::URL& url, const uint32_t waitTime) + : _adminLock() + , _connectId(WPEFramework::Core::NodeId(url.Host().Value().c_str(), url.Port().Value())) + , _channel(Channel::Instance(_connectId, ((url.Path().Value().rfind(PathPrefix, 0) == 0) ? url.Path().Value() : string(PathPrefix + url.Path().Value())), url.Query().Value(), true)) + , _eventHandler(nullptr) + , _pendingQueue() + , _scheduledTime(0) + , _waitTime(waitTime) + { + _channel->Register(*this); + } + + virtual ~Transport() + { + _channel->Unregister(*this); + + for (auto& element : _pendingQueue) { + element.second.Abort(element.first); + } + } + + public: + inline bool IsOpen() + { + return _channel->IsOpen(); + } + + void Revoke(const string& eventName) + { + _adminLock.Lock(); + _eventMap.erase(eventName); + _adminLock.Unlock(); + } + + void SetEventHandler(IEventHandler* eventHandler) + { + _eventHandler = eventHandler; + } + + template + int32_t Invoke(const string& method, const PARAMETERS& parameters, RESPONSE& response) + { + Entry slot; + uint32_t id = _channel->Sequence(); + int32_t result = Send(method, parameters, id); + if (result == WPEFramework::Core::ERROR_NONE) { + result = WaitForResponse(id, response, _waitTime); + } + + return (FireboltErrorValue(result)); + } + + template + int32_t Subscribe(const string& eventName, const string& parameters, RESPONSE& response) + { + Entry slot; + uint32_t id = _channel->Sequence(); + int32_t result = Send(eventName, parameters, id); + if (result == WPEFramework::Core::ERROR_NONE) { + _adminLock.Lock(); + _eventMap.emplace(std::piecewise_construct, + std::forward_as_tuple(eventName), + std::forward_as_tuple(~0)); + _adminLock.Unlock(); + + result = WaitForEventResponse(id, eventName, response, _waitTime); + } + + return (FireboltErrorValue(result)); + } + + int32_t Unsubscribe(const string& eventName, const string& parameters) + { + Revoke(eventName); + Entry slot; + uint32_t id = _channel->Sequence(); + int32_t result = Send(eventName, parameters, id); + + return (FireboltErrorValue(result)); + } + + private: + friend Channel; + inline bool IsEvent(const uint32_t id, string& eventName) + { + _adminLock.Lock(); + for (auto& event : _eventMap) { + if (event.second == id) { + eventName = event.first; + break; + } + } + _adminLock.Unlock(); + return (eventName.empty() != true); + } + uint64_t Timed() + { + uint64_t result = ~0; + uint64_t currentTime = WPEFramework::Core::Time::Now().Ticks(); + + // Lets see if some callback are expire. If so trigger and remove... + _adminLock.Lock(); + + typename PendingMap::iterator index = _pendingQueue.begin(); + + while (index != _pendingQueue.end()) { + + if (index->second.Expired(index->first, currentTime, result) == true) { + index = _pendingQueue.erase(index); + } + else { + index++; + } + } + _scheduledTime = (result != static_cast(~0) ? result : 0); + + _adminLock.Unlock(); + + return (_scheduledTime); + } + + virtual void Opened() + { + // Nice to know :-) + } + + void Closed() + { + // Abort any in progress RPC command: + _adminLock.Lock(); + + // See if we issued anything, if so abort it.. + while (_pendingQueue.size() != 0) { + + _pendingQueue.begin()->second.Abort(_pendingQueue.begin()->first); + _pendingQueue.erase(_pendingQueue.begin()); + } + + _adminLock.Unlock(); + } + + int32_t Submit(const WPEFramework::Core::ProxyType& inbound) + { + int32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(inbound, this)); + WPEFramework::Core::IWorkerPool::Instance().Submit(job); + return result; + } + + int32_t Inbound(const WPEFramework::Core::ProxyType& inbound) + { + int32_t result = WPEFramework::Core::ERROR_INVALID_SIGNATURE; + + ASSERT(inbound.IsValid() == true); + + if ((inbound->Id.IsSet() == true) && (inbound->Result.IsSet() || inbound->Error.IsSet())) { + // Looks like this is a response.. + ASSERT(inbound->Parameters.IsSet() == false); + ASSERT(inbound->Designator.IsSet() == false); + + _adminLock.Lock(); + + // See if we issued this.. + typename PendingMap::iterator index = _pendingQueue.find(inbound->Id.Value()); + + if (index != _pendingQueue.end()) { + + if (index->second.Signal(inbound) == true) { + _pendingQueue.erase(index); + } + + result = WPEFramework::Core::ERROR_NONE; + _adminLock.Unlock(); + } else { + _adminLock.Unlock(); + string eventName; + if (IsEvent(inbound->Id.Value(), eventName)) { + _eventHandler->Dispatch(eventName, inbound); + } + + } + } + + return (result); + } + + + template + int32_t Send(const string& method, const PARAMETERS& parameters, const uint32_t& id) + { + int32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; + + if ((_channel.IsValid() == true) && (_channel->IsSuspended() == true)) { + result = WPEFramework::Core::ERROR_ASYNC_FAILED; + } + else if (_channel.IsValid() == true) { + + result = WPEFramework::Core::ERROR_ASYNC_FAILED; + + WPEFramework::Core::ProxyType message(Channel::Message()); + message->Id = id; + message->Designator = method; + ToMessage(parameters, message); + + _adminLock.Lock(); + + typename std::pair< typename PendingMap::iterator, bool> newElement = + _pendingQueue.emplace(std::piecewise_construct, + std::forward_as_tuple(id), + std::forward_as_tuple()); + ASSERT(newElement.second == true); + + if (newElement.second == true) { + + _adminLock.Unlock(); + + _channel->Submit(WPEFramework::Core::ProxyType(message)); + + message.Release(); + result = WPEFramework::Core::ERROR_NONE; + } + } + return result; + } + + template + int32_t WaitForResponse(const uint32_t& id, RESPONSE& response, const uint32_t waitTime) + { + int32_t result = WPEFramework::Core::ERROR_TIMEDOUT; + _adminLock.Lock(); + typename PendingMap::iterator index = _pendingQueue.find(id); + Entry& slot(index->second); + _adminLock.Unlock(); + + if (slot.WaitForResponse(waitTime) == true) { + WPEFramework::Core::ProxyType jsonResponse = slot.Response(); + + // See if we have a jsonResponse, maybe it was just the connection + // that closed? + if (jsonResponse.IsValid() == true) { + if (jsonResponse->Error.IsSet() == true) { + result = jsonResponse->Error.Code.Value(); + } + else { + result = WPEFramework::Core::ERROR_NONE; + if ((jsonResponse->Result.IsSet() == true) + && (jsonResponse->Result.Value().empty() == false)) { + FromMessage((INTERFACE*)&response, *jsonResponse); + } + } + } + } else { + result = WPEFramework::Core::ERROR_TIMEDOUT; + } + _adminLock.Lock(); + _pendingQueue.erase(id); + _adminLock.Unlock(); + return result; + } + + static constexpr uint32_t WAITSLOT_TIME = 100; + template + int32_t WaitForEventResponse(const uint32_t& id, const string& eventName, RESPONSE& response, const uint32_t waitTime) + { + int32_t result = WPEFramework::Core::ERROR_TIMEDOUT; + _adminLock.Lock(); + typename PendingMap::iterator index = _pendingQueue.find(id); + Entry& slot(index->second); + _adminLock.Unlock(); + + uint8_t waiting = waitTime; + do { + uint32_t waitSlot = (waiting > WAITSLOT_TIME ? WAITSLOT_TIME : waiting); + if (slot.WaitForResponse(waitSlot) == true) { + WPEFramework::Core::ProxyType jsonResponse = slot.Response(); + + // See if we have a jsonResponse, maybe it was just the connection + // that closed? + if (jsonResponse.IsValid() == true) { + if (jsonResponse->Error.IsSet() == true) { + result = jsonResponse->Error.Code.Value(); + } else { + if ((jsonResponse->Result.IsSet() == true) + && (jsonResponse->Result.Value().empty() == false)) { + result = WPEFramework::Core::ERROR_NONE; + bool enabled; + result = _eventHandler->ValidateResponse(jsonResponse, enabled); + if (result == WPEFramework::Core::ERROR_NONE) { + FromMessage((INTERFACE*)&response, *jsonResponse); + if (enabled) { + _adminLock.Lock(); + typename EventMap::iterator index = _eventMap.find(eventName); + if (index != _eventMap.end()) { + index->second = id; + } + _adminLock.Unlock(); + } + } + } + } + } + } else { + result = WPEFramework::Core::ERROR_TIMEDOUT; + } + waiting -= (waiting == WPEFramework::Core::infinite ? 0 : waitSlot); + } while ((result != WPEFramework::Core::ERROR_NONE) && (waiting > 0 )); + _adminLock.Lock(); + _pendingQueue.erase(id); + _adminLock.Unlock(); + + return result; + } + + public: + void FromMessage(WPEFramework::Core::JSON::IElement* response, const WPEFramework::Core::JSONRPC::Message& message) const + { + response->FromString(message.Result.Value()); + } + + void FromMessage(WPEFramework::Core::JSON::IMessagePack* response, const WPEFramework::Core::JSONRPC::Message& message) const + { + string value = message.Result.Value(); + std::vector result(value.begin(), value.end()); + response->FromBuffer(result); + } + + + private: + + void ToMessage(const string& parameters, WPEFramework::Core::ProxyType& message) const + { + if (parameters.empty() != true) { + message->Parameters = parameters; + } + } + + template + void ToMessage(PARAMETERS& parameters, WPEFramework::Core::ProxyType& message) const + { + ToMessage((INTERFACE*)(¶meters), message); + return; + } + + void ToMessage(WPEFramework::Core::JSON::IMessagePack* parameters, WPEFramework::Core::ProxyType& message) const + { + std::vector values; + parameters->ToBuffer(values); + if (values.empty() != true) { + string strValues(values.begin(), values.end()); + message->Parameters = strValues; + } + return; + } + + void ToMessage(WPEFramework::Core::JSON::IElement* parameters, WPEFramework::Core::ProxyType& message) const + { + string values; + parameters->ToString(values); + if (values.empty() != true) { + message->Parameters = values; + } + return; + } + + int32_t FireboltErrorValue(const uint32_t error) + { + + int32_t fireboltError = error; + switch (error) { + case WPEFramework::Core::ERROR_NONE: + fireboltError = FireboltSDKErrorNone; + break; + case WPEFramework::Core::ERROR_GENERAL: + fireboltError = FireboltSDKErrorGeneral; + break; + case WPEFramework::Core::ERROR_UNAVAILABLE: + fireboltError = FireboltSDKErrorUnavailable; + break; + case WPEFramework::Core::ERROR_TIMEDOUT: + fireboltError = FireboltSDKErrorTimedout; + break; + default: + break; + } + + return fireboltError; + } + + private: + WPEFramework::Core::CriticalSection _adminLock; + WPEFramework::Core::NodeId _connectId; + WPEFramework::Core::ProxyType _channel; + IEventHandler* _eventHandler; + PendingMap _pendingQueue; + EventMap _eventMap; + uint64_t _scheduledTime; + uint32_t _waitTime; + }; +} diff --git a/languages/cpp/src/shared/src/Types.cpp b/languages/cpp/src/shared/src/Types.cpp new file mode 100644 index 00000000..93f6a8d8 --- /dev/null +++ b/languages/cpp/src/shared/src/Types.cpp @@ -0,0 +1,40 @@ +/* + * 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 "Module.h" +#include "types.h" +#include "TypesPriv.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// String Type Handler Interfaces +const char* Firebolt_String(Firebolt_String_t handle) +{ + return ((reinterpret_cast(handle))->Value().c_str()); +} + +void Firebolt_String_Release(Firebolt_String_t handle) +{ + delete reinterpret_cast(handle); +} + +#ifdef __cplusplus +} +#endif diff --git a/languages/cpp/src/shared/src/TypesPriv.h b/languages/cpp/src/shared/src/TypesPriv.h new file mode 100644 index 00000000..6e365ec7 --- /dev/null +++ b/languages/cpp/src/shared/src/TypesPriv.h @@ -0,0 +1,56 @@ +/* + * 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 + +namespace FireboltSDK { +namespace JSON { +class String : public WPEFramework::Core::JSON::String { + using Base = WPEFramework::Core::JSON::String; + public: + String() + : Base() + , _value() + { + } + String(const char value[]) + : Base(value) + , _value(value) + { + } + String& operator=(const char RHS[]) + { + Base::operator = (RHS); + _value = RHS; + return (*this); + } + + public: + const string& Value() const + { + _value = Base::Value(); + return _value; + } + + private: + mutable std::string _value; + }; +} +} diff --git a/languages/cpp/src/shared/src/firebolt.cpp b/languages/cpp/src/shared/src/firebolt.cpp new file mode 100644 index 00000000..90c54c5c --- /dev/null +++ b/languages/cpp/src/shared/src/firebolt.cpp @@ -0,0 +1,39 @@ +/* + * 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" + + +#ifdef __cplusplus +extern "C" { +#endif + + +int32_t FireboltSDK_Initialize(char* configLine) { + FireboltSDK::Accessor::Instance(configLine); + return FireboltSDKErrorNone; +} + +int32_t FireboltSDK_Deinitialize(void) { + FireboltSDK::Accessor::Dispose(); + return FireboltSDKErrorNone; +} + +#ifdef __cplusplus +} +#endif diff --git a/languages/cpp/src/shared/test/CMakeLists.txt b/languages/cpp/src/shared/test/CMakeLists.txt new file mode 100644 index 00000000..21ee1f55 --- /dev/null +++ b/languages/cpp/src/shared/test/CMakeLists.txt @@ -0,0 +1,86 @@ +# 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 + +cmake_minimum_required(VERSION 3.3) + +project(FireboltSDKTests) +project_version(1.0.0) + +set(TESTLIB ${PROJECT_NAME}) + +message("Setup ${TESTLIB} v${PROJECT_VERSION}") + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +find_package(${NAMESPACE}Core CONFIG REQUIRED) + +add_library(${TESTLIB} STATIC OpenRPCTests.cpp) + +target_link_libraries(${TESTLIB} + PUBLIC + ${NAMESPACE}Core::${NAMESPACE}Core + ${FIREBOLT_NAMESPACE}SDK +) + +target_include_directories(${TESTLIB} + PRIVATE + $ + $ +) + +set_target_properties(${TESTLIB} PROPERTIES + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED YES + LINK_WHAT_YOU_USE TRUE + FRAMEWORK FALSE +) + +install( + TARGETS ${TESTLIB} EXPORT ${TESTLIB}Targets + LIBRARY DESTINATION lib COMPONENT libs + PUBLIC_HEADER DESTINATION include/${FIREBOLT_NAMESPACE}Test COMPONENT devel # headers for mac (note the different component -> different package) + INCLUDES DESTINATION include/${FIREBOLT_NAMESPACE}Test # headers +) + +InstallCMakeConfig(TARGETS ${TESTLIB}) +InstallCMakeConfigs(TARGET ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) +InstallHeaders(TARGET ${TESTLIB} HEADERS . NAMESPACE ${FIREBOLT_NAMESPACE} DESTINATION FireboltTest) +InstallLibraries(TARGET ${TESTLIB} STATIC LIBRARIES ${TESTLIB} DESTINATION ${FIREBOLT_NAMESPACE}) + +set(TESTAPP "FireboltSDKTestApp") + +message("Setup ${TESTAPP}") + +add_executable(${TESTAPP} Main.c) + +target_link_libraries(${TESTAPP} + PRIVATE + ${TESTLIB} +) + +target_include_directories(${TESTAPP} + PRIVATE + $ + $ +) + +add_custom_command( + TARGET ${TESTAPP} + POST_BUILD + COMMENT "=================== Installing TestApp ======================" + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/bin + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/${TESTAPP} ${CMAKE_BINARY_DIR}/${FIREBOLT_NAMESPACE}/usr/bin +) + diff --git a/languages/cpp/src/shared/test/Main.c b/languages/cpp/src/shared/test/Main.c new file mode 100644 index 00000000..6161792e --- /dev/null +++ b/languages/cpp/src/shared/test/Main.c @@ -0,0 +1,45 @@ +/* + * 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 "OpenRPCCTests.h" + +int __cnt = 0; +int __pass = 0; + +int TotalTests = 0; +int TotalTestsPassed = 0; + +int main() +{ + test_firebolt_create_instance(); + test_firebolt_main(); + + // Calling C function sequences + printf("%s:%s:%d Calling C function tests\n", __FILE__, __func__, __LINE__); + EXECUTE("test_properties_get_device_id", test_properties_get_device_id); + EXECUTE("test_properties_set", test_properties_set); + EXECUTE("test_eventregister_by_providing_callback", test_eventregister_by_providing_callback); + EXECUTE("test_eventregister", test_eventregister); + EXECUTE("test_eventregister_with_same_callback", test_eventregister_with_same_callback); + EXECUTE("test_string_set_get_value", test_string_set_get_value); + + test_firebolt_dispose_instance(); + + printf("TOTAL: %i tests; %i PASSED, %i FAILED\n", TotalTests, TotalTestsPassed, (TotalTests - TotalTestsPassed)); +} + diff --git a/languages/cpp/src/shared/test/Module.cpp b/languages/cpp/src/shared/test/Module.cpp new file mode 100644 index 00000000..d63badc4 --- /dev/null +++ b/languages/cpp/src/shared/test/Module.cpp @@ -0,0 +1,21 @@ +/* + * 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 "Module.h" + +MODULE_NAME_DECLARATION(BUILD_REFERENCE) diff --git a/languages/cpp/src/shared/test/Module.h b/languages/cpp/src/shared/test/Module.h new file mode 100644 index 00000000..a147ff75 --- /dev/null +++ b/languages/cpp/src/shared/test/Module.h @@ -0,0 +1,28 @@ +/* + * 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 + +#ifndef MODULE_NAME +#define MODULE_NAME OpenRPCTestApp +#endif + +#include + +#undef EXTERNAL +#define EXTERNAL diff --git a/languages/cpp/src/shared/test/OpenRPCCTests.h b/languages/cpp/src/shared/test/OpenRPCCTests.h new file mode 100644 index 00000000..936a1ff9 --- /dev/null +++ b/languages/cpp/src/shared/test/OpenRPCCTests.h @@ -0,0 +1,43 @@ +/* + * 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 + */ + +#ifndef OPENRPC_C_TESTS_H +#define OPENRPC_C_TESTS_H + +#include "TestUtils.h" + +#ifdef __cplusplus +extern "C" { +#endif + +void test_firebolt_create_instance(); +void test_firebolt_dispose_instance(); + +int32_t test_firebolt_main(); +int32_t test_properties_get_device_id(); +int32_t test_properties_set(); +int32_t test_eventregister(); +int32_t test_eventregister_with_same_callback(); +int32_t test_eventregister_by_providing_callback(); +int32_t test_string_set_get_value(); + +#ifdef __cplusplus +} +#endif + +#endif // OPENRPC_C_TESTS_H diff --git a/languages/cpp/src/shared/test/OpenRPCTests.cpp b/languages/cpp/src/shared/test/OpenRPCTests.cpp new file mode 100644 index 00000000..03fd2645 --- /dev/null +++ b/languages/cpp/src/shared/test/OpenRPCTests.cpp @@ -0,0 +1,504 @@ +/* + * 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 "Module.h" +#include "OpenRPCTests.h" +#include "OpenRPCCTests.h" + +namespace WPEFramework { + +ENUM_CONVERSION_BEGIN(::JsonValue::type) + + { JsonValue::type::EMPTY, _TXT("empty") }, + { JsonValue::type::BOOLEAN, _TXT("boolean") }, + { JsonValue::type::NUMBER, _TXT("number") }, + { JsonValue::type::STRING, _TXT("string") }, + +ENUM_CONVERSION_END(::JsonValue::type) + +ENUM_CONVERSION_BEGIN(TestEnum) + { TestEnum::Test1, _TXT("Test1ValueCheck") }, + { TestEnum::Test2, _TXT("Test2ValueCheck") }, + { TestEnum::Test3, _TXT("Test3ValueCheck") }, + { TestEnum::Test4, _TXT("Test4ValueCheck") }, +ENUM_CONVERSION_END(TestEnum) +} + +typedef void (*OnNotifyDeviceNameChanged)(const void* userData, const char* data); +static void NotifyEvent(const void* userData, const char* data) +{ + printf("NotifyEvent data : %s\n", data); +} + +namespace FireboltSDK { + Tests::Tests() + { + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEventWithMultipleCallback"), + std::forward_as_tuple(&SubscribeEventWithMultipleCallback)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEventwithSameCallback"), + std::forward_as_tuple(&SubscribeEventwithSameCallback)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("SubscribeEvent"), + std::forward_as_tuple(&SubscribeEvent)); + + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Set UnKnown Method"), + std::forward_as_tuple(&SetUnKnownMethod)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Set LifeCycle Close"), + std::forward_as_tuple(&SetLifeCycleClose)); + + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Get UnKnown Method"), + std::forward_as_tuple(&GetUnKnownMethod)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Get Device Version"), + std::forward_as_tuple(&GetDeviceVersion)); + _functionMap.emplace(std::piecewise_construct, std::forward_as_tuple("Get Device Id"), + std::forward_as_tuple(&GetDeviceId)); + } + + /* static */ void Tests::PrintJsonObject(const JsonObject::Iterator& iterator) + { + JsonObject::Iterator index = iterator; + while (index.Next() == true) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "Element [%s]: <%s> = \"%s\"\n", + index.Label(), + WPEFramework::Core::EnumerateType(index.Current().Content()).Data(), + index.Current().Value().c_str()); + } + } + + /* static */ int32_t Tests::GetDeviceId() + { + const string method = _T("device.id"); + WPEFramework::Core::ProxyType response; + int32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "DeviceId : %s", response->Value().c_str()); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d\n", method.c_str(), status); + } + + return status; + } + + /*static */ int32_t Tests::GetDeviceVersion() + { + const string method = _T("device.version"); + WPEFramework::Core::ProxyType response; + int32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "DeviceVersion"); + PrintJsonObject(response->Variants()); + } else { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d", method.c_str(), status); + } + + return status; + } + + /* static */ int32_t Tests::GetUnKnownMethod() + { + const string method = _T("get.unknownMethod"); + WPEFramework::Core::ProxyType response; + int32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_NE(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d\n", method.c_str(), status); + } + + return status; + } + + /* static */ int32_t Tests::SetLifeCycleClose() + { + const string method = _T("lifecycle.close"); + JsonObject parameters; + parameters["reason"] = "remoteButton"; + int32_t status = FireboltSDK::Properties::Set(method, parameters); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d\n", method.c_str(), status); + } + + return status; + } + + /* static */ int32_t Tests::SetUnKnownMethod() + { + const string method = _T("set.unknownMethod"); + JsonObject parameters; + int32_t status = FireboltSDK::Properties::Set(method, parameters); + + EXPECT_NE(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", method.c_str(), status); + } + + return status; + } + + static void deviceNameChangeCallback(void* userCB, const void* userData, void* response) + { + WPEFramework::Core::ProxyType& jsonResponse = *(reinterpret_cast*>(response)); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Received a new event: %s", jsonResponse->Value().c_str()); + FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + OnNotifyDeviceNameChanged notifyDeviceNameChanged = reinterpret_cast(userCB); + notifyDeviceNameChanged(userData, jsonResponse->Value().c_str()); + eventControl->NotifyEvent(); + jsonResponse.Release(); + } + + /* static */ int32_t Tests::SubscribeEvent() + { + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl("EventControl"); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + + eventControl->ResetEvent(); + + JsonObject jsonParameters; + int32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), + "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered successfully, Waiting for event...", __func__); + + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + delete eventControl; + + return status; + } + + /* static */ int32_t Tests::SubscribeEventwithSameCallback() + { + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl("EventControl"); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + + eventControl->ResetEvent(); + + JsonObject jsonParameters; + int32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), + "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered successfully", __func__); + + status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback, reinterpret_cast(NotifyEvent), userdata); + EXPECT_EQ(status, FireboltSDKErrorInUse); + if (status == FireboltSDKErrorInUse) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes this device.name event is already registered with same callback", __func__); + } + status = ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone : status); + } + + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + delete eventControl; + + return status; + } + + + static void NotifyEvent1(const void* userData, const char* data) + { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent1 data : %s", data); + if (userData) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent1 userData : %s\n", reinterpret_cast(userData)->Name().c_str()); + } + } + static void NotifyEvent2(const void* userData, const char* data) + { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent2 data : %s", data); + if (userData) { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "NotifyEvent2 userData : %s\n", reinterpret_cast(userData)->Name().c_str()); + } + } + + template + /* static */ int32_t Tests::SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata) + { + return Properties::Subscribe(eventName, jsonParameters, callbackFunc, usercb, userdata); + } + + static void deviceNameChangeMultipleCallback(void* userCB, const void* userData, void* response) + { + WPEFramework::Core::ProxyType& jsonResponse = *(reinterpret_cast*>(response)); + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "Received a new event from deviceNameChangeMultipleCallback: %s", jsonResponse->Value().c_str()); + FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + OnNotifyDeviceNameChanged notifyDeviceNameChanged = reinterpret_cast(userCB); + notifyDeviceNameChanged(userData, jsonResponse->Value().c_str()); + + eventControl->NotifyEvent(); + jsonResponse.Release(); + } + + /* static */ int32_t Tests::SubscribeEventWithMultipleCallback() + { + FireboltSDK::Tests::EventControl* eventControl1 = new FireboltSDK::Tests::EventControl("EventControl1"); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl1); + + eventControl1->ResetEvent(); + + JsonObject jsonParameters; + int32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent1), userdata); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), + "Set %s status = %d", eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered successfully, Waiting for event...", __func__); + } + + if (status == FireboltSDKErrorNone) { + FireboltSDK::Tests::EventControl* eventControl2 = new FireboltSDK::Tests::EventControl("EventControl2"); + userdata = static_cast(eventControl2); + + status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent2), userdata); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", eventName.c_str(), status); + } else { + status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent2), userdata); + EXPECT_EQ(status, FireboltSDKErrorInUse); + status = ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone : status); + + FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), + "%s Yes registered second callback also successfully, waiting for events...\n", __func__); + + eventControl1->WaitForEvent(WPEFramework::Core::infinite); + eventControl2->WaitForEvent(WPEFramework::Core::infinite); + } + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent2)), FireboltSDKErrorNone); + delete eventControl2; + } + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent1)), FireboltSDKErrorNone); + + delete eventControl1; + return status; + } + +} + +#ifdef __cplusplus +extern "C" { +#endif + +void test_firebolt_create_instance() +{ + 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); +} + +void test_firebolt_dispose_instance() +{ + FireboltSDK::Accessor::Dispose(); +} + +int32_t test_firebolt_main() +{ + return FireboltSDK::Tests::Main(); +} + +int32_t test_properties_get_device_id() +{ + const string method = _T("device.id"); + WPEFramework::Core::ProxyType response; + int32_t status = FireboltSDK::Properties::Get(method, response); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "DeviceId : %s", response->Value().c_str()); + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "Get %s status = %d", method.c_str(), status); + } + + return status; +} + +int32_t test_properties_set() +{ + const string method = _T("lifecycle.close"); + JsonObject parameters; + parameters["reason"] = "remoteButton"; + int32_t status = FireboltSDK::Properties::Set(method, parameters); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "Set %s status = %d", method.c_str(), status); + } + + return status; +} + +static void deviceNameChangeCallbackForC(void* userCB, const void* userData, void* response) +{ + WPEFramework::Core::ProxyType& jsonResponse = *(reinterpret_cast*>(response)); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "Received a new event--->: %s", jsonResponse->Value().c_str()); + + FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); + eventControl->NotifyEvent(); + jsonResponse.Release(); +} + +int32_t test_eventregister() +{ + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + + eventControl->ResetEvent(); + + JsonObject jsonParameters; + int32_t status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Set %s status = %d", __func__, eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes registered successfully, Waiting for event...", __func__); + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + delete eventControl; + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + + return status; +} + +int32_t test_eventregister_with_same_callback() +{ + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + + eventControl->ResetEvent(); + + JsonObject jsonParameters; + int32_t status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Set %s status = %d", __func__, eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes registered successfully", __func__); + + status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); + EXPECT_EQ(status, FireboltSDKErrorInUse); + if (status == FireboltSDKErrorInUse) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes this device.name event is already registered with same callback", __func__); + } + status = ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone : status); + } + + delete eventControl; + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + + return status; +} +int32_t test_eventregister_by_providing_callback() +{ + FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); + + const string eventName = _T("device.Name"); + const void* userdata = static_cast(eventControl); + + eventControl->ResetEvent(); + + JsonObject jsonParameters; + int32_t status = FireboltSDK::Tests::SubscribeEventForC(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); + + EXPECT_EQ(status, FireboltSDKErrorNone); + if (status != FireboltSDKErrorNone) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Set %s status = %d", __func__, eventName.c_str(), status); + } else { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + "%s Yes registered successfully, Waiting for event...", __func__); + eventControl->WaitForEvent(WPEFramework::Core::infinite); + } + + delete eventControl; + EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + return status; +} + +#include "TypesPriv.h" +int32_t test_string_set_get_value() +{ + int32_t status = FireboltSDKErrorNone; + FireboltSDK::JSON::String* str = new FireboltSDK::JSON::String(); + WPEFramework::Core::JSON::String wpeJsonStr("TestString"); + Firebolt_String_t handle = reinterpret_cast(str); + + const char* value = Firebolt_String(handle); + EXPECT_EQ(strncmp(value, str->Value().c_str(), str->Value().length()), 0); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + " ---> type name = %s %s", str->Value().c_str(), value); + + WPEFramework::Core::JSON::EnumType<::TestEnum> testEnum = Test4; + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", + " EnumTest = %d %s", testEnum.Value(), testEnum.Data()); + Firebolt_String_Release(handle); + return status; +} + +#ifdef __cplusplus +} +#endif diff --git a/languages/cpp/src/shared/test/OpenRPCTests.h b/languages/cpp/src/shared/test/OpenRPCTests.h new file mode 100644 index 00000000..8eb7fd30 --- /dev/null +++ b/languages/cpp/src/shared/test/OpenRPCTests.h @@ -0,0 +1,118 @@ +/* + * 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 "FireboltSDK.h" +#include "TestUtils.h" + +typedef enum { + Test1, + Test2, + Test3, + Test4 +} TestEnum; + +namespace FireboltSDK { + typedef int32_t (*Func)(); + + class Tests { + public: + class EventControl { + public: + EventControl() + : _event(false, true) + , _name("EventControl") + { + } + EventControl(string name) + : _event(false, true) + , _name(name) + { + } + ~EventControl() = default; + + public: + void NotifyEvent() + { + _event.SetEvent(); + } + uint32_t WaitForEvent(uint32_t waitTime) + { + return _event.Lock(waitTime); + } + void ResetEvent() + { + _event.ResetEvent(); + } + string Name() const + { + return _name; + } + private: + WPEFramework::Core::Event _event; + string _name; + }; + + private: + typedef std::unordered_map TestFunctionMap; + + public: + Tests(); + virtual ~Tests() = default; + + inline TestFunctionMap& TestList() + { + return _functionMap; + } + + template + static int32_t Main() + { + TESTS fireboltTest; + for (auto i = fireboltTest.TestList().begin(); i != fireboltTest.TestList().end(); i++) { + EXECUTE(i->first.c_str(), i->second); + } + + printf("TOTAL: %i tests; %i PASSED, %i FAILED\n", TotalTests, TotalTestsPassed, (TotalTests - TotalTestsPassed)); + + return 0; + } + + static int32_t GetDeviceId(); + static int32_t GetDeviceVersion(); + static int32_t GetUnKnownMethod(); + + static int32_t SetLifeCycleClose(); + static int32_t SetUnKnownMethod(); + + static int32_t SubscribeEvent(); + static int32_t SubscribeEventwithSameCallback(); + static int32_t SubscribeEventWithMultipleCallback(); + + template + static int32_t SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata); + + protected: + static void PrintJsonObject(const JsonObject::Iterator& iterator); + + protected: + std::list menu; + TestFunctionMap _functionMap; + }; +} diff --git a/languages/cpp/src/shared/test/TestUtils.h b/languages/cpp/src/shared/test/TestUtils.h new file mode 100644 index 00000000..c54db9f0 --- /dev/null +++ b/languages/cpp/src/shared/test/TestUtils.h @@ -0,0 +1,38 @@ +#ifndef TEST_UTILS_H +#define TEST_UTILS_H + +#include +#include +#include + +#define MAX(x, y) (((x) > (y)) ? (x) : (y)) +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) + +#define _RESULT(expr, exprorig, result) if (expr) { printf("TestStatus: SUCCESS: %s\n", #exprorig); __pass++; } else printf("TestStatus: FAILED: %s, actual: %lu\n", #exprorig, result) +#define _EVAL(result, expected, op) do { __cnt++; long resval = ((long)(result)); long expval = ((long)(expected)); _RESULT(resval op expval, result op expected, resval); } while(0) +#define _HEAD(name) printf("\n======== %s\n", name); __cnt = 0; __pass = 0 +#define _FOOT(name) printf("\n======== %s - %i PASSED, %i FAILED\n", name, __pass, (__cnt - __pass)); TotalTests += __cnt; TotalTestsPassed += __pass; + +#define EXECUTE(name, test) do { _HEAD(name); test(); _FOOT(name); printf("\n"); } while(0) +#define EXPECT_EQ(result, expected) _EVAL(result, expected, ==) +#define EXPECT_NE(result, expected) _EVAL(result, expected, !=) +#define EXPECT_LT(result, expected) _EVAL(result, expected, <) +#define EXPECT_LE(result, expected) _EVAL(result, expected, <=) +#define EXPECT_GT(result, expected) _EVAL(result, expected, >) +#define EXPECT_GE(result, expected) _EVAL(result, expected, >=) + +#ifdef __cplusplus +extern "C" { +#endif + +extern int __cnt; +extern int __pass; + +extern int TotalTests ; +extern int TotalTestsPassed; + +#ifdef __cplusplus +} +#endif + +#endif // TEST_UTILS_H diff --git a/languages/cpp/templates/codeblocks/export.c b/languages/cpp/templates/codeblocks/export.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/codeblocks/mock-import.c b/languages/cpp/templates/codeblocks/mock-import.c new file mode 100644 index 00000000..5d22512a --- /dev/null +++ b/languages/cpp/templates/codeblocks/mock-import.c @@ -0,0 +1 @@ +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 new file mode 100644 index 00000000..63e63902 --- /dev/null +++ b/languages/cpp/templates/codeblocks/mock-parameter.c @@ -0,0 +1 @@ + ${info.title}: _${info.title}, \ No newline at end of file diff --git a/languages/cpp/templates/codeblocks/module.c b/languages/cpp/templates/codeblocks/module.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/codeblocks/setter.c b/languages/cpp/templates/codeblocks/setter.c new file mode 100644 index 00000000..c66068bc --- /dev/null +++ b/languages/cpp/templates/codeblocks/setter.c @@ -0,0 +1,7 @@ +/* ${method.rpc.name} - ${method.description} */ +int32_t ${method.Name}( ${method.signature.params} ) +{ + const string method = _T("${info.title.lowercase}.${method.rpc.name}"); +${if.params}${method.params.serialization}${end.if.params} + return FireboltSDK::Properties::Set(method, jsonParameters); +} diff --git a/languages/cpp/templates/declarations/clear.c b/languages/cpp/templates/declarations/clear.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/declarations/default.c b/languages/cpp/templates/declarations/default.c new file mode 100644 index 00000000..4366becf --- /dev/null +++ b/languages/cpp/templates/declarations/default.c @@ -0,0 +1,6 @@ + /* + ${method.name} + ${method.description} + ${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation}${end.if.deprecated} + */ + virtual int32_t ${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}${method.result.type}& ${method.result.name}${end.if.result} ) = 0; \ No newline at end of file diff --git a/languages/cpp/templates/declarations/event.c b/languages/cpp/templates/declarations/event.c new file mode 100644 index 00000000..d20578c9 --- /dev/null +++ b/languages/cpp/templates/declarations/event.c @@ -0,0 +1,10 @@ + /* ${method.name} - ${method.description} */ + struct I${method.Name}Notification { + virtual void ${method.Name} ( ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${method.result.properties} ) = 0; + }; + + virtual int32_t subscribe ( ${event.signature.params}${if.event.params}, ${end.if.event.params}I${method.Name}Notification& notification ) = 0; + virtual int32_t unsubscribe ( I${method.Name}Notification& notification ) = 0; + + // signature callback params: ${event.signature.callback.params} + // method result properties : ${method.result.properties} diff --git a/languages/cpp/templates/declarations/listen.c b/languages/cpp/templates/declarations/listen.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/declarations/once.c b/languages/cpp/templates/declarations/once.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/declarations/polymorphic-pull-event.c b/languages/cpp/templates/declarations/polymorphic-pull-event.c new file mode 100644 index 00000000..755f7f54 --- /dev/null +++ b/languages/cpp/templates/declarations/polymorphic-pull-event.c @@ -0,0 +1,8 @@ +/* ${method.name} - ${method.description} */ +struct I{method.Name}Notification { + virtual void ${method.Name} ( ${method.pulls.param.type}& value ) = 0; +}; + +virtual int32_t subscribe ( I{method.Name}Notification& notification ) = 0; +virtual int32_t unsubscribe ( I{method.Name}Notification& notification ) = 0; + diff --git a/languages/cpp/templates/declarations/polymorphic-pull.c b/languages/cpp/templates/declarations/polymorphic-pull.c new file mode 100644 index 00000000..74f23cc4 --- /dev/null +++ b/languages/cpp/templates/declarations/polymorphic-pull.c @@ -0,0 +1,2 @@ +/* ${method.name} - ${method.description} */ +virtual int32_t ${method.Name}( ${method.signature.params} ) = 0; diff --git a/languages/cpp/templates/declarations/polymorphic-reducer.c b/languages/cpp/templates/declarations/polymorphic-reducer.c new file mode 100644 index 00000000..46f633b8 --- /dev/null +++ b/languages/cpp/templates/declarations/polymorphic-reducer.c @@ -0,0 +1,5 @@ +/* + * ${method.summary} + * ${method.params} + */ +virtual int32_t ${method.Name}(${method.signature.params}${if.result.properties}${if.params}, ${end.if.params}${end.if.result.properties}${method.result.properties}) = 0; diff --git a/languages/cpp/templates/declarations/property.h b/languages/cpp/templates/declarations/property.h new file mode 100644 index 00000000..884fd2f0 --- /dev/null +++ b/languages/cpp/templates/declarations/property.h @@ -0,0 +1,5 @@ + /* + * ${method.description} + * ${method.params} + */ + virtual int32_t ${method.Name} (${method.signature.params}${if.params}, ${end.if.params}${method.result.properties}) = 0; diff --git a/languages/cpp/templates/declarations/provide.c b/languages/cpp/templates/declarations/provide.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/declarations/setter.h b/languages/cpp/templates/declarations/setter.h new file mode 100644 index 00000000..75d3b5a6 --- /dev/null +++ b/languages/cpp/templates/declarations/setter.h @@ -0,0 +1,5 @@ + /* + ${method.rpc.name} + ${method.description} + */ + virtual int32_t ${method.Name}( ${method.signature.params} ) = 0; diff --git a/languages/cpp/templates/defaults/default.c b/languages/cpp/templates/defaults/default.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/defaults/property.c b/languages/cpp/templates/defaults/property.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/imports/calls-metrics.cpp b/languages/cpp/templates/imports/calls-metrics.cpp new file mode 100644 index 00000000..4ba289b3 --- /dev/null +++ b/languages/cpp/templates/imports/calls-metrics.cpp @@ -0,0 +1 @@ +#include "metrics.h" diff --git a/languages/cpp/templates/imports/default.cpp b/languages/cpp/templates/imports/default.cpp new file mode 100644 index 00000000..caf84bc9 --- /dev/null +++ b/languages/cpp/templates/imports/default.cpp @@ -0,0 +1 @@ +#include "jsondata_${info.title.lowercase}.h" diff --git a/languages/cpp/templates/imports/default.h b/languages/cpp/templates/imports/default.h new file mode 100644 index 00000000..56a97a40 --- /dev/null +++ b/languages/cpp/templates/imports/default.h @@ -0,0 +1 @@ +#include "common/${info.title.lowercase}.h" diff --git a/languages/cpp/templates/imports/default.jsondata b/languages/cpp/templates/imports/default.jsondata new file mode 100644 index 00000000..caf84bc9 --- /dev/null +++ b/languages/cpp/templates/imports/default.jsondata @@ -0,0 +1 @@ +#include "jsondata_${info.title.lowercase}.h" diff --git a/languages/cpp/templates/json-types/additionalProperties.c b/languages/cpp/templates/json-types/additionalProperties.c new file mode 100644 index 00000000..b814e5fb --- /dev/null +++ b/languages/cpp/templates/json-types/additionalProperties.c @@ -0,0 +1 @@ +// need cpp code to init, get, set, clear additional properties... \ No newline at end of file diff --git a/languages/cpp/templates/json-types/anyOf.c b/languages/cpp/templates/json-types/anyOf.c new file mode 100644 index 00000000..a2682179 --- /dev/null +++ b/languages/cpp/templates/json-types/anyOf.c @@ -0,0 +1 @@ +/* AnyOf is not supported in C: ${title} */ \ No newline at end of file diff --git a/languages/cpp/templates/json-types/array.c b/languages/cpp/templates/json-types/array.c new file mode 100644 index 00000000..508a9eac --- /dev/null +++ b/languages/cpp/templates/json-types/array.c @@ -0,0 +1,4 @@ +uint32_t ${info.Title}_${Title}Array_Size(${type} handle); +${type} ${title}Array_Get(${type} handle, uint32_t index); +void ${info.Title}_${Title}Array_Add(${propertyType} handle, ${valueType} value); +void ${info.Title}_${Title}Array_Clear(${propertyType} handle); diff --git a/languages/cpp/templates/json-types/boolean.c b/languages/cpp/templates/json-types/boolean.c new file mode 100644 index 00000000..18bbeec2 --- /dev/null +++ b/languages/cpp/templates/json-types/boolean.c @@ -0,0 +1 @@ +WPEFramework::Core::JSON::Boolean \ No newline at end of file diff --git a/languages/cpp/templates/json-types/const.c b/languages/cpp/templates/json-types/const.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/json-types/default.cpp b/languages/cpp/templates/json-types/default.cpp new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/json-types/default.cpp @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/json-types/enum.cpp b/languages/cpp/templates/json-types/enum.cpp new file mode 100644 index 00000000..6776b41a --- /dev/null +++ b/languages/cpp/templates/json-types/enum.cpp @@ -0,0 +1,4 @@ + /* ${title} ${description} */ + ENUM_CONVERSION_BEGIN(${name}) + { ${NAME}_${key}, _T("${value}") }, + ENUM_CONVERSION_END(${name}) diff --git a/languages/cpp/templates/json-types/enum.h b/languages/cpp/templates/json-types/enum.h new file mode 100644 index 00000000..92108c75 --- /dev/null +++ b/languages/cpp/templates/json-types/enum.h @@ -0,0 +1,4 @@ +/* ${title} ${description} */ +typedef enum { + ${NAME}_${key}, +} ${name}; diff --git a/languages/cpp/templates/json-types/float.c b/languages/cpp/templates/json-types/float.c new file mode 100644 index 00000000..c38bca91 --- /dev/null +++ b/languages/cpp/templates/json-types/float.c @@ -0,0 +1 @@ +WPEFramework::Core::JSON::Float \ No newline at end of file diff --git a/languages/cpp/templates/json-types/integer.c b/languages/cpp/templates/json-types/integer.c new file mode 100644 index 00000000..b57fe26e --- /dev/null +++ b/languages/cpp/templates/json-types/integer.c @@ -0,0 +1 @@ +WPEFramework::Core::JSON::DecSInt32 \ No newline at end of file diff --git a/languages/cpp/templates/json-types/namespace.c b/languages/cpp/templates/json-types/namespace.c new file mode 100644 index 00000000..8ea9d7de --- /dev/null +++ b/languages/cpp/templates/json-types/namespace.c @@ -0,0 +1 @@ +FireboltSDK::${info.Title}:: \ No newline at end of file diff --git a/languages/cpp/templates/json-types/object.cpp b/languages/cpp/templates/json-types/object.cpp new file mode 100644 index 00000000..db24d12c --- /dev/null +++ b/languages/cpp/templates/json-types/object.cpp @@ -0,0 +1,25 @@ + class ${title}: public WPEFramework::Core::JSON::Container { + public: + ~${title}() override = default; + + public: + ${title}() + : WPEFramework::Core::JSON::Container() + { + ${properties.register} + } + + ${title}(const ${title}& other) + { + ${properties.assign} + } + + ${title}& operator=(const ${title}& other) + { + ${properties.assign} + return (*this); + } + + public: + ${properties} + }; diff --git a/languages/cpp/templates/json-types/primitive.c b/languages/cpp/templates/json-types/primitive.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/json-types/property-assign.cpp b/languages/cpp/templates/json-types/property-assign.cpp new file mode 100644 index 00000000..88795136 --- /dev/null +++ b/languages/cpp/templates/json-types/property-assign.cpp @@ -0,0 +1,2 @@ + Add(_T("${property}"), &${Property}); + ${Property} = other.${Property} diff --git a/languages/cpp/templates/json-types/property-register.cpp b/languages/cpp/templates/json-types/property-register.cpp new file mode 100644 index 00000000..400b4fd5 --- /dev/null +++ b/languages/cpp/templates/json-types/property-register.cpp @@ -0,0 +1,2 @@ + Add(_T("${property}"), &${Property}); + \ No newline at end of file diff --git a/languages/cpp/templates/json-types/property.cpp b/languages/cpp/templates/json-types/property.cpp new file mode 100644 index 00000000..49f79c0e --- /dev/null +++ b/languages/cpp/templates/json-types/property.cpp @@ -0,0 +1 @@ + ${title} ${Property}; \ No newline at end of file diff --git a/languages/cpp/templates/json-types/ref.c b/languages/cpp/templates/json-types/ref.c new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/json-types/ref.c @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/json-types/string.c b/languages/cpp/templates/json-types/string.c new file mode 100644 index 00000000..2d60a3c8 --- /dev/null +++ b/languages/cpp/templates/json-types/string.c @@ -0,0 +1 @@ +FireboltSDK::JSON::String \ No newline at end of file diff --git a/languages/cpp/templates/json-types/title.c b/languages/cpp/templates/json-types/title.c new file mode 100644 index 00000000..ae1512e5 --- /dev/null +++ b/languages/cpp/templates/json-types/title.c @@ -0,0 +1 @@ +JsonData_${Title} \ No newline at end of file diff --git a/languages/cpp/templates/json-types/tuple.c b/languages/cpp/templates/json-types/tuple.c new file mode 100644 index 00000000..db24d12c --- /dev/null +++ b/languages/cpp/templates/json-types/tuple.c @@ -0,0 +1,25 @@ + class ${title}: public WPEFramework::Core::JSON::Container { + public: + ~${title}() override = default; + + public: + ${title}() + : WPEFramework::Core::JSON::Container() + { + ${properties.register} + } + + ${title}(const ${title}& other) + { + ${properties.assign} + } + + ${title}& operator=(const ${title}& other) + { + ${properties.assign} + return (*this); + } + + public: + ${properties} + }; diff --git a/languages/cpp/templates/json-types/types/object.c b/languages/cpp/templates/json-types/types/object.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/json-types/x-method.c b/languages/cpp/templates/json-types/x-method.c new file mode 100644 index 00000000..573c9f8e --- /dev/null +++ b/languages/cpp/templates/json-types/x-method.c @@ -0,0 +1 @@ +void* \ No newline at end of file diff --git a/languages/cpp/templates/language/enum-item.c b/languages/cpp/templates/language/enum-item.c new file mode 100644 index 00000000..79aabbeb --- /dev/null +++ b/languages/cpp/templates/language/enum-item.c @@ -0,0 +1 @@ + ${key} diff --git a/languages/cpp/templates/language/enum.c b/languages/cpp/templates/language/enum.c new file mode 100644 index 00000000..5056ec3f --- /dev/null +++ b/languages/cpp/templates/language/enum.c @@ -0,0 +1,3 @@ +enum class ${title} { + ${items} +}; diff --git a/languages/cpp/templates/language/parameter.c b/languages/cpp/templates/language/parameter.c new file mode 100644 index 00000000..2ff7a678 --- /dev/null +++ b/languages/cpp/templates/language/parameter.c @@ -0,0 +1 @@ +${type} ${name} \ No newline at end of file diff --git a/languages/cpp/templates/language/schema-item.c b/languages/cpp/templates/language/schema-item.c new file mode 100644 index 00000000..ecded7d5 --- /dev/null +++ b/languages/cpp/templates/language/schema-item.c @@ -0,0 +1 @@ + ${type} ${property}; diff --git a/languages/cpp/templates/language/schema.c b/languages/cpp/templates/language/schema.c new file mode 100644 index 00000000..2e4c66d6 --- /dev/null +++ b/languages/cpp/templates/language/schema.c @@ -0,0 +1,3 @@ +struct ${title} { + ${properties} +}; diff --git a/languages/cpp/templates/methods/calls-metrics.c b/languages/cpp/templates/methods/calls-metrics.c new file mode 100644 index 00000000..d38c499f --- /dev/null +++ b/languages/cpp/templates/methods/calls-metrics.c @@ -0,0 +1,29 @@ +/* ${method.rpc.name} - ${method.description} */ +void Metrics_${method.Name}Dispatcher(const void*${if.result} result${end.if.result}) { + Metrics_${method.Name}(${if.result}(static_cast<${method.result.json.type}>(const_cast(result)))${end.if.result}); +} +int32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name}${end.if.result}${if.signature.empty}void${end.if.signature.empty} ) { + + int32_t status = FireboltSDKErrorUnavailable; + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + + ${method.params.serialization.with.indent} + ${method.result.json.type} jsonResult; + status = transport->Invoke("${info.title}.${method.rpc.name}", jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); + ${method.result.instantiation.with.indent} + + void* result = nullptr; + ${if.result}result = static_cast(new ${method.result.json.type});${end.if.result} + WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(Metrics_${method.Name}Dispatcher, result)); + WPEFramework::Core::IWorkerPool::Instance().Submit(job); + } + + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; +} diff --git a/languages/cpp/templates/methods/clear.c b/languages/cpp/templates/methods/clear.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/methods/default.c b/languages/cpp/templates/methods/default.c new file mode 100644 index 00000000..c375d30f --- /dev/null +++ b/languages/cpp/templates/methods/default.c @@ -0,0 +1,21 @@ +/* ${method.rpc.name} - ${method.description} */ +int32_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} ) { + + int32_t status = FireboltSDKErrorUnavailable; + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + + ${method.params.serialization.with.indent} + ${method.result.json.type} jsonResult; + status = transport->Invoke("${info.title.lowercase}.${method.rpc.name}", jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); + ${method.result.instantiation.with.indent} + } + + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return status; +} diff --git a/languages/cpp/templates/methods/event.c b/languages/cpp/templates/methods/event.c new file mode 100644 index 00000000..85ae3b48 --- /dev/null +++ b/languages/cpp/templates/methods/event.c @@ -0,0 +1,27 @@ +/* ${method.rpc.name} - ${method.description} */ +static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) +{ +${event.callback.params.serialization} + ASSERT(jsonResponse->IsValid() == true); + if (jsonResponse->IsValid() == true) { +${event.callback.result.instantiation} + ${info.Title}${method.Name}Callback callback = reinterpret_cast<${info.Title}${method.Name}Callback>(userCB); + callback(userData, ${event.callback.response.instantiation}); + } +} +int32_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.lowercase}.${method.rpc.name}"); + int32_t status = FireboltSDKErrorNone; + + if (userCB != nullptr) { + ${event.params.serialization} + status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${info.Title}${method.Name}InnerCallback, reinterpret_cast(userCB), userData); + } + return status; +} +int32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB) +{ + return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); +} + diff --git a/languages/cpp/templates/methods/listen.c b/languages/cpp/templates/methods/listen.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/methods/once.c b/languages/cpp/templates/methods/once.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/methods/polymorphic-pull-event.c b/languages/cpp/templates/methods/polymorphic-pull-event.c new file mode 100644 index 00000000..49aa1dba --- /dev/null +++ b/languages/cpp/templates/methods/polymorphic-pull-event.c @@ -0,0 +1,54 @@ +/* ${method.rpc.name} - ${method.description} */ +static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) +{ +${event.callback.params.serialization} + ASSERT(jsonResponse->IsValid() == true); + if (jsonResponse->IsValid() == true) { + + ${info.Title}${method.Name}Callback callback = reinterpret_cast<${info.Title}${method.Name}Callback>(userCB); + + WPEFramework::Core::ProxyType<${method.pulls.param.json.type}>* requestParam = new WPEFramework::Core::ProxyType<${method.pulls.param.json.type}>(); + *requestParam = WPEFramework::Core::ProxyType<${method.pulls.param.json.type}>::Create(); + *(*requestParam) = (*jsonResponse)->${event.pulls.param.name}Parameters; + + ${method.pulls.type} result = reinterpret_cast<${method.pulls.type}>(callback(userData, reinterpret_cast<${method.pulls.param.type}>(requestParam))); + + JsonObject jsonParameters; + WPEFramework::Core::JSON::Variant CorrelationId = (*jsonResponse)->CorrelationId.Value(); + jsonParameters.Set(_T("correlationId"), CorrelationId); + + ${method.pulls.json.type}& resultObj = *(*(reinterpret_cast*>(result))); + string resultStr; + resultObj.ToString(resultStr); + WPEFramework::Core::JSON::VariantContainer resultContainer(resultStr); + WPEFramework::Core::JSON::Variant Result = resultContainer; + jsonParameters.Set(_T("result"), Result); + + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + WPEFramework::Core::JSON::Boolean jsonResult; + int32_t status = transport->Invoke(_T("${info.title.lowercase}.${method.pulls.for}"), jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully pushed with status as %d", jsonResult.Value()); + } + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport"); + } + } +} +int32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callback userCB, const void* userData ) +{ + const string eventName = _T("${info.title.lowercase}.${method.rpc.name}"); + int32_t status = FireboltSDKErrorNone; + + if (userCB != nullptr) { + ${event.params.serialization} + status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${info.Title}${method.Name}InnerCallback, reinterpret_cast(userCB), userData); + } + return status; +} +int32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB) +{ + return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); +} + diff --git a/languages/cpp/templates/methods/polymorphic-pull.c b/languages/cpp/templates/methods/polymorphic-pull.c new file mode 100644 index 00000000..840566e2 --- /dev/null +++ b/languages/cpp/templates/methods/polymorphic-pull.c @@ -0,0 +1,22 @@ +/* ${method.rpc.name} - ${method.description} */ +int32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ) +{ + int32_t status = FireboltSDKErrorUnavailable; + + FireboltSDK::Transport* 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.lowercase}.${method.rpc.name}"), jsonParameters, jsonResult); + if (status == FireboltSDKErrorNone) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully pushed with status as %d", jsonResult.Value()); + status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; + } + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport"); + } + + return status; +} diff --git a/languages/cpp/templates/methods/polymorphic-reducer.c b/languages/cpp/templates/methods/polymorphic-reducer.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/methods/property.c b/languages/cpp/templates/methods/property.c new file mode 100644 index 00000000..7f375d81 --- /dev/null +++ b/languages/cpp/templates/methods/property.c @@ -0,0 +1,14 @@ +/* ${method.rpc.name} - ${method.description} */ +int32_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.lowercase}.${method.rpc.name}"); +${if.params}${method.params.serialization}${end.if.params} + ${method.result.json} jsonResult; + ${if.params}int32_t status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult);${end.if.params} + ${if.params.empty}int32_t status = FireboltSDK::Properties::Get(method, jsonResult);${end.if.params.empty} + if (status == FireboltSDKErrorNone) { +${method.result.instantiation} + } + return status; +} +${method.setter} diff --git a/languages/cpp/templates/methods/provide.c b/languages/cpp/templates/methods/provide.c new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/methods/setter.c b/languages/cpp/templates/methods/setter.c 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 new file mode 100644 index 00000000..f6d5128d --- /dev/null +++ b/languages/cpp/templates/modules/include/module.h @@ -0,0 +1,43 @@ +/* + * 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 +/* ${IMPORTS} */ + +${if.declarations}namespace Firebolt { +namespace ${info.Title} { + +// Enums +/* ${ENUMS} */ + +// Types +/* ${TYPES} */ + + struct I${info.Title} { + + virtual ~I${info.Title} = default; + + // Methods & Events + /* ${DECLARATIONS} */ + + }; + +} //namespace ${info.Title} +}${end.if.declarations} diff --git a/languages/cpp/templates/modules/src/module.cpp b/languages/cpp/templates/modules/src/module.cpp new file mode 100644 index 00000000..8cef2390 --- /dev/null +++ b/languages/cpp/templates/modules/src/module.cpp @@ -0,0 +1,41 @@ +/* + * 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.types}namespace Firebolt { + +/* ${ENUMS:json-types} */ + +${if.definitions}namespace ${info.Title} { + + +// Types + /* ${TYPES:json-types} */ + +// Methods +/* ${METHODS} */ + +// Events +/* ${EVENTS} */ + + +}${end.if.definitions} +}${end.if.types} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/boolean.cpp b/languages/cpp/templates/parameter-serialization/boolean.cpp new file mode 100644 index 00000000..f924ac94 --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/boolean.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/cpp/templates/parameter-serialization/default.cpp b/languages/cpp/templates/parameter-serialization/default.cpp new file mode 100644 index 00000000..f924ac94 --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/default.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/cpp/templates/parameter-serialization/object.cpp b/languages/cpp/templates/parameter-serialization/object.cpp new file mode 100644 index 00000000..f924ac94 --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/object.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/cpp/templates/parameter-serialization/primitive.cpp b/languages/cpp/templates/parameter-serialization/primitive.cpp new file mode 100644 index 00000000..f924ac94 --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/primitive.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/cpp/templates/parameter-serialization/string.cpp b/languages/cpp/templates/parameter-serialization/string.cpp new file mode 100644 index 00000000..f924ac94 --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/string.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/cpp/templates/parameters/default.c b/languages/cpp/templates/parameters/default.c new file mode 100644 index 00000000..f4fc002f --- /dev/null +++ b/languages/cpp/templates/parameters/default.c @@ -0,0 +1 @@ +const ${method.param.type} ${method.param.name} \ No newline at end of file diff --git a/languages/cpp/templates/parameters/json.c b/languages/cpp/templates/parameters/json.c new file mode 100644 index 00000000..5ee36bec --- /dev/null +++ b/languages/cpp/templates/parameters/json.c @@ -0,0 +1,3 @@ + ${json.param.type} ${method.param.Name} = ${method.param.name}; + jsonParameters.Add("_T(${method.param.name})", &${method.param.Name}); + diff --git a/languages/cpp/templates/parameters/object.c b/languages/cpp/templates/parameters/object.c new file mode 100644 index 00000000..5f48625c --- /dev/null +++ b/languages/cpp/templates/parameters/object.c @@ -0,0 +1 @@ +const ${method.param.type}& ${method.param.name} \ No newline at end of file diff --git a/languages/cpp/templates/parameters/optional.c b/languages/cpp/templates/parameters/optional.c new file mode 100644 index 00000000..69cb4659 --- /dev/null +++ b/languages/cpp/templates/parameters/optional.c @@ -0,0 +1 @@ +std::optional<${method.param.type}> ${method.param.name} \ No newline at end of file diff --git a/languages/cpp/templates/parameters/result.c b/languages/cpp/templates/parameters/result.c new file mode 100644 index 00000000..3c96807b --- /dev/null +++ b/languages/cpp/templates/parameters/result.c @@ -0,0 +1 @@ +${method.param.type}& ${method.param.name} \ No newline at end of file diff --git a/languages/cpp/templates/parameters/string.c b/languages/cpp/templates/parameters/string.c new file mode 100644 index 00000000..5f48625c --- /dev/null +++ b/languages/cpp/templates/parameters/string.c @@ -0,0 +1 @@ +const ${method.param.type}& ${method.param.name} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/boolean.cpp b/languages/cpp/templates/result-instantiation/boolean.cpp new file mode 100644 index 00000000..036b4a7d --- /dev/null +++ b/languages/cpp/templates/result-instantiation/boolean.cpp @@ -0,0 +1,2 @@ + *${property} = jsonResult.Value(); + \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/default.cpp b/languages/cpp/templates/result-instantiation/default.cpp new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/result-instantiation/default.cpp @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/object.cpp b/languages/cpp/templates/result-instantiation/object.cpp new file mode 100644 index 00000000..dcf0b333 --- /dev/null +++ b/languages/cpp/templates/result-instantiation/object.cpp @@ -0,0 +1,4 @@ + WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); + *resultPtr = WPEFramework::Core::ProxyType::Create(); + *(*resultPtr) = jsonResult; + *${property} = static_cast<${info.Title}_${title}>(resultPtr); diff --git a/languages/cpp/templates/result-instantiation/primitive.cpp b/languages/cpp/templates/result-instantiation/primitive.cpp new file mode 100644 index 00000000..23bbace7 --- /dev/null +++ b/languages/cpp/templates/result-instantiation/primitive.cpp @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/string.cpp b/languages/cpp/templates/result-instantiation/string.cpp new file mode 100644 index 00000000..b6c9dcb5 --- /dev/null +++ b/languages/cpp/templates/result-instantiation/string.cpp @@ -0,0 +1,2 @@ + FireboltSDK::JSON::String* strResult = new FireboltSDK::JSON::String(jsonResult); + *value = static_cast(strResult); diff --git a/languages/cpp/templates/schemas/default.cpp b/languages/cpp/templates/schemas/default.cpp new file mode 100644 index 00000000..9a52cff7 --- /dev/null +++ b/languages/cpp/templates/schemas/default.cpp @@ -0,0 +1 @@ +${schema.shape} diff --git a/languages/cpp/templates/schemas/include/common/module.h b/languages/cpp/templates/schemas/include/common/module.h new file mode 100644 index 00000000..5628e5b3 --- /dev/null +++ b/languages/cpp/templates/schemas/include/common/module.h @@ -0,0 +1,36 @@ +/* + * 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 +/* ${IMPORTS} */ + +namespace Firebolt { +namespace ${info.Title} { + + +// Enums +/* ${ENUMS} */ + +// Types +/* ${TYPES} */ + + +} //namespace ${info.Title} +} diff --git a/languages/cpp/templates/schemas/src/jsondata_module.h b/languages/cpp/templates/schemas/src/jsondata_module.h new file mode 100644 index 00000000..6e220163 --- /dev/null +++ b/languages/cpp/templates/schemas/src/jsondata_module.h @@ -0,0 +1,30 @@ +/* + * 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 + +/* ${IMPORTS} */ +#include "common/${info.title.lowercase}.h" + +${if.schemas}namespace Firebolt { +namespace ${info.Title} { + // Types + + /* ${SCHEMAS:json-types} */ + } +}${end.if.schemas} diff --git a/languages/cpp/templates/schemas/src/module_common.cpp b/languages/cpp/templates/schemas/src/module_common.cpp new file mode 100644 index 00000000..5570982c --- /dev/null +++ b/languages/cpp/templates/schemas/src/module_common.cpp @@ -0,0 +1,41 @@ +/* + * 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 "jsondata_${info.title.lowercase}.h" + +namespace Firebolt { + + +/* ${ENUMS} */ + +namespace ${info.Title} { + + +// Methods +/* ${METHODS} */ + +// Events +/* ${EVENTS} */ + + +} //namespace ${info.Title} + +} + diff --git a/languages/cpp/templates/sdk/scripts/build.sh b/languages/cpp/templates/sdk/scripts/build.sh new file mode 100755 index 00000000..149cd1ae --- /dev/null +++ b/languages/cpp/templates/sdk/scripts/build.sh @@ -0,0 +1,40 @@ +#!/bin/bash +usage() +{ + echo "options:" + echo " -p sdk path" + echo " -s sysroot path" + echo " -c clear build" + echo " -l enable static build" + echo " -t enable test" + echo " -h : help" + echo + echo "usage: " + echo " ./build.sh -p path -tc" +} + +SdkPath="." +EnableTest="OFF" +SysrootPath=${SYSROOT_PATH} +ClearBuild="N" +EnableStaticLib="OFF" +while getopts p:s:clth flag +do + case "${flag}" in + p) SdkPath="${OPTARG}";; + s) SysrootPath="${OPTARG}";; + c) ClearBuild="Y";; + l) EnableStaticLib="ON";; + t) EnableTest="ON";; + h) usage && exit 1;; + esac +done + +if [ "${ClearBuild}" == "Y" ]; +then + rm -rf ${SdkPath}/build +fi + +cmake -B${SdkPath}/build -S${SdkPath} -DSYSROOT_PATH=${SysrootPath} -DENABLE_TESTS=${EnableTest} -DHIDE_NON_EXTERNAL_SYMBOLS=OFF -DFIREBOLT_ENABLE_STATIC_LIB=${EnableStaticLib} +cmake --build ${SdkPath}/build +cmake --install ${SdkPath}/build --prefix=${SdkPath}/build/Firebolt/usr diff --git a/languages/cpp/templates/sdk/scripts/install.sh b/languages/cpp/templates/sdk/scripts/install.sh new file mode 100755 index 00000000..24bd1c4c --- /dev/null +++ b/languages/cpp/templates/sdk/scripts/install.sh @@ -0,0 +1,58 @@ +#!/bin/bash +usage() +{ + echo "options:" + echo " -i install path" + echo " -s sdk path" + echo " -m module name. i.e, core/manage" + echo + echo "usage: " + echo " ./install.sh -i path -s sdk path -m core" +} + +SdkPath=".." +InstallPath=".." +ModuleName="core" +while getopts i:s:m:h flag +do + case "${flag}" in + i) InstallPath="${OPTARG}";; + s) SdkPath="${OPTARG}";; + m) ModuleName="${OPTARG}";; + h) usage && exit 1;; + esac +done + +GetVersion() +{ + PackagePath=${SdkPath}/../../../../../../package-lock.json + InputKey="name\": \"@firebolt-js/openrpc" + LineNo="$(grep -n "${InputKey}" ${PackagePath} | head -n 1 | cut -d: -f1)" + VersionLine=$((LineNo++)) + eval "array=(`sed -n "${LineNo}p" < ${PackagePath} | sed 's/\"/\n/g'`)" + Version=${array[2]} +} + +Version=0.0 +GetVersion +ReleaseName=firebolt-${ModuleName}-native-sdk-${Version} +ReleasePath=${InstallPath}/${ReleaseName} + +rm -rf ${ReleasePath} +mkdir -p ${ReleasePath} +cp -ar ${SdkPath}/src ${ReleasePath} +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 + +sed -i '/EnableTest="ON";;/d' ${ReleasePath}/build.sh +sed -i 's/getopts p:s:tch/getopts p:s:ch/g' ${ReleasePath}/build.sh +sed -i '/enable test/d' ${ReleasePath}/build.sh +sed -i '/EnableTest="OFF"/d' ${ReleasePath}/build.sh +sed -i 's/ -DENABLE_TESTS=${EnableTest}//g' ${ReleasePath}/build.sh + +cd ${ReleasePath}/../ +tar -cvzf ${ReleaseName}.tgz ${ReleaseName}/* +cd - diff --git a/languages/cpp/templates/sections/declarations.h b/languages/cpp/templates/sections/declarations.h new file mode 100644 index 00000000..b3ef974d --- /dev/null +++ b/languages/cpp/templates/sections/declarations.h @@ -0,0 +1 @@ +${declaration.list} diff --git a/languages/cpp/templates/sections/enum.cpp b/languages/cpp/templates/sections/enum.cpp new file mode 100644 index 00000000..e5165c61 --- /dev/null +++ b/languages/cpp/templates/sections/enum.cpp @@ -0,0 +1,5 @@ +namespace WPEFramework { + +${schema.list} + +} diff --git a/languages/cpp/templates/sections/enums.h b/languages/cpp/templates/sections/enums.h new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/cpp/templates/sections/enums.h @@ -0,0 +1 @@ +${schema.list} diff --git a/languages/cpp/templates/sections/events.h b/languages/cpp/templates/sections/events.h new file mode 100644 index 00000000..5be10409 --- /dev/null +++ b/languages/cpp/templates/sections/events.h @@ -0,0 +1 @@ +${event.list} diff --git a/languages/cpp/templates/sections/methods.h b/languages/cpp/templates/sections/methods.h new file mode 100644 index 00000000..3ab606c0 --- /dev/null +++ b/languages/cpp/templates/sections/methods.h @@ -0,0 +1,4 @@ + +// Methods + +${method.list} diff --git a/languages/cpp/templates/sections/methods_types.h b/languages/cpp/templates/sections/methods_types.h new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/cpp/templates/sections/methods_types.h @@ -0,0 +1 @@ +${schema.list} diff --git a/languages/cpp/templates/sections/provider-interfaces.h b/languages/cpp/templates/sections/provider-interfaces.h new file mode 100644 index 00000000..418d7abf --- /dev/null +++ b/languages/cpp/templates/sections/provider-interfaces.h @@ -0,0 +1,11 @@ + // Provider Interfaces + + interface ProviderSession { + correlationId(): string // Returns the correlation id of the current provider session + } + + interface FocusableProviderSession extends ProviderSession { + focus(): Promise // Requests that the provider app be moved into focus to prevent a user experience + } + + ${providers.list} \ No newline at end of file diff --git a/languages/cpp/templates/sections/schemas.h b/languages/cpp/templates/sections/schemas.h new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/cpp/templates/sections/schemas.h @@ -0,0 +1 @@ +${schema.list} diff --git a/languages/cpp/templates/sections/types.h b/languages/cpp/templates/sections/types.h new file mode 100644 index 00000000..9295133c --- /dev/null +++ b/languages/cpp/templates/sections/types.h @@ -0,0 +1 @@ +${schema.list} diff --git a/languages/cpp/templates/types/additionalProperties.h b/languages/cpp/templates/types/additionalProperties.h new file mode 100644 index 00000000..52882d43 --- /dev/null +++ b/languages/cpp/templates/types/additionalProperties.h @@ -0,0 +1 @@ +std::unordered_map title; \ No newline at end of file diff --git a/languages/cpp/templates/types/anyOf.c b/languages/cpp/templates/types/anyOf.c new file mode 100644 index 00000000..bd2ba3e5 --- /dev/null +++ b/languages/cpp/templates/types/anyOf.c @@ -0,0 +1 @@ +/* AnyOf is not supported in CPP: ${title} */ \ No newline at end of file diff --git a/languages/cpp/templates/types/array.h b/languages/cpp/templates/types/array.h new file mode 100644 index 00000000..2c1e61d4 --- /dev/null +++ b/languages/cpp/templates/types/array.h @@ -0,0 +1 @@ +std::vector<${type}> ${title}; \ No newline at end of file diff --git a/languages/cpp/templates/types/const.h b/languages/cpp/templates/types/const.h new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/types/default.cpp b/languages/cpp/templates/types/default.cpp new file mode 100644 index 00000000..1f1fe89d --- /dev/null +++ b/languages/cpp/templates/types/default.cpp @@ -0,0 +1,4 @@ +/* + * ${title} - ${description} + */ +${shape} diff --git a/languages/cpp/templates/types/enum.cpp b/languages/cpp/templates/types/enum.cpp new file mode 100644 index 00000000..9c98f888 --- /dev/null +++ b/languages/cpp/templates/types/enum.cpp @@ -0,0 +1,4 @@ + /* ${title} ${description} */ + ENUM_CONVERSION_BEGIN(${info.Title}_${name}) + { ${info.TITLE}_${NAME}_${key}, _T("${value}") }, + ENUM_CONVERSION_END(${info.Title}_${name}) diff --git a/languages/cpp/templates/types/enum.h b/languages/cpp/templates/types/enum.h new file mode 100644 index 00000000..166fb231 --- /dev/null +++ b/languages/cpp/templates/types/enum.h @@ -0,0 +1,4 @@ +/* ${title} ${description} */ +enum class ${name} { + ${key}, +}; diff --git a/languages/cpp/templates/types/namespace.h b/languages/cpp/templates/types/namespace.h new file mode 100644 index 00000000..626de353 --- /dev/null +++ b/languages/cpp/templates/types/namespace.h @@ -0,0 +1 @@ +${parent.Title}:: \ No newline at end of file diff --git a/languages/cpp/templates/types/null.h b/languages/cpp/templates/types/null.h new file mode 100644 index 00000000..79c36400 --- /dev/null +++ b/languages/cpp/templates/types/null.h @@ -0,0 +1 @@ +nullptr \ No newline at end of file diff --git a/languages/cpp/templates/types/object.h b/languages/cpp/templates/types/object.h new file mode 100644 index 00000000..c7877332 --- /dev/null +++ b/languages/cpp/templates/types/object.h @@ -0,0 +1,5 @@ +struct ${title} { + + ${properties} + +}; \ No newline at end of file diff --git a/languages/cpp/templates/types/primitive.h b/languages/cpp/templates/types/primitive.h new file mode 100644 index 00000000..23bbace7 --- /dev/null +++ b/languages/cpp/templates/types/primitive.h @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/cpp/templates/types/property.h b/languages/cpp/templates/types/property.h new file mode 100644 index 00000000..39c3b6b8 --- /dev/null +++ b/languages/cpp/templates/types/property.h @@ -0,0 +1 @@ +${if.optional}std::optional<${end.if.optional}${title}${if.optional}>${end.if.optional} ${property}; // ${summary} \ No newline at end of file diff --git a/languages/cpp/templates/types/ref.h b/languages/cpp/templates/types/ref.h new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/types/ref.h @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/types/title.h b/languages/cpp/templates/types/title.h new file mode 100644 index 00000000..2a420b4b --- /dev/null +++ b/languages/cpp/templates/types/title.h @@ -0,0 +1 @@ +${Title} \ No newline at end of file diff --git a/languages/cpp/templates/types/tuple.h b/languages/cpp/templates/types/tuple.h new file mode 100644 index 00000000..0e042b9c --- /dev/null +++ b/languages/cpp/templates/types/tuple.h @@ -0,0 +1,6 @@ +/* ${title} */ +struct ${title} { + + ${properties} + +}; diff --git a/languages/cpp/templates/types/x-method.h b/languages/cpp/templates/types/x-method.h new file mode 100644 index 00000000..573c9f8e --- /dev/null +++ b/languages/cpp/templates/types/x-method.h @@ -0,0 +1 @@ +void* \ No newline at end of file diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index f8dad4bb..8506161e 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -120,6 +120,8 @@ const insertConstMacros = (content, schema, module, name) => { return content } + + const insertEnumMacros = (content, schema, module, name) => { const template = content.split('\n') @@ -469,14 +471,16 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin const suffix = destination && ('.' + destination.split('.').pop()) || '' const namespaceStr = namespace ? getTemplate(path.join(templateDir, 'namespace' + suffix)) : '' - const theTitle = insertSchemaMacros(namespaceStr + getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, schema.title || '', '', '', false) + const theTitle = insertSchemaMacros(namespaceStr + getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, schema.title || '', getXSchemaGroup(schema, module), '', false) const allocatedProxy = event || result const title = schema.type === "object" || schema.enum ? true : false if (schema['$ref']) { if (schema['$ref'][0] === '#') { - return getSchemaType(getPath(schema['$ref'], module), module, {destination, templateDir, link, title, code, asPath, event, result, expandEnums, baseUrl, namespace })// { link: link, code: code, destination }) + const refSchema = getPath(schema['$ref'], module) + const includeNamespace = (module.info.title !== getXSchemaGroup(refSchema, module)) + return getSchemaType(refSchema, module, {destination, templateDir, link, title, code, asPath, event, result, expandEnums, baseUrl, namespace:includeNamespace })// { link: link, code: code, destination }) } else { // TODO: This never happens... but might be worth keeping in case we link to an opaque external schema at some point? From fd66f378246be7575d24d885ee7cdca40a289339 Mon Sep 17 00:00:00 2001 From: Santhosh Ramani Date: Wed, 6 Sep 2023 13:20:43 +0530 Subject: [PATCH 102/137] feat: Fix issues in generated headers --- languages/cpp/templates/declarations/default.c | 12 ++++++------ languages/cpp/templates/declarations/event.c | 18 ++++++++---------- .../declarations/polymorphic-pull-event.c | 14 +++++++------- .../templates/declarations/polymorphic-pull.c | 4 ++-- .../declarations/polymorphic-reducer.c | 10 +++++----- .../cpp/templates/declarations/property.h | 10 +++++----- languages/cpp/templates/declarations/setter.h | 10 +++++----- .../cpp/templates/modules/include/module.h | 12 ++++++------ .../parameters/{default.c => default.h} | 0 .../templates/parameters/{json.c => json.cpp} | 0 .../parameters/{object.c => object.h} | 0 .../parameters/{optional.c => optional.h} | 0 .../cpp/templates/parameters/result-null.h | 0 .../parameters/{result.c => result.h} | 0 .../parameters/{string.c => string.h} | 0 .../cpp/templates/types/additionalProperties.h | 2 +- languages/cpp/templates/types/array.h | 2 +- languages/cpp/templates/types/null.h | 1 - languages/cpp/templates/types/property.h | 2 +- languages/cpp/templates/types/tuple.h | 6 +----- src/macrofier/engine.mjs | 12 ++++++------ 21 files changed, 54 insertions(+), 61 deletions(-) rename languages/cpp/templates/parameters/{default.c => default.h} (100%) rename languages/cpp/templates/parameters/{json.c => json.cpp} (100%) rename languages/cpp/templates/parameters/{object.c => object.h} (100%) rename languages/cpp/templates/parameters/{optional.c => optional.h} (100%) create mode 100644 languages/cpp/templates/parameters/result-null.h rename languages/cpp/templates/parameters/{result.c => result.h} (100%) rename languages/cpp/templates/parameters/{string.c => string.h} (100%) diff --git a/languages/cpp/templates/declarations/default.c b/languages/cpp/templates/declarations/default.c index 4366becf..2c19a1ef 100644 --- a/languages/cpp/templates/declarations/default.c +++ b/languages/cpp/templates/declarations/default.c @@ -1,6 +1,6 @@ - /* - ${method.name} - ${method.description} - ${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation}${end.if.deprecated} - */ - virtual int32_t ${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}${method.result.type}& ${method.result.name}${end.if.result} ) = 0; \ No newline at end of file + /* + ${method.name} + ${method.description} + ${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation}${end.if.deprecated} + */ + virtual int32_t ${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}${method.result.type}& ${method.result.name}${end.if.result} ) = 0; \ No newline at end of file diff --git a/languages/cpp/templates/declarations/event.c b/languages/cpp/templates/declarations/event.c index d20578c9..d2df4f12 100644 --- a/languages/cpp/templates/declarations/event.c +++ b/languages/cpp/templates/declarations/event.c @@ -1,10 +1,8 @@ - /* ${method.name} - ${method.description} */ - struct I${method.Name}Notification { - virtual void ${method.Name} ( ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${method.result.properties} ) = 0; - }; - - virtual int32_t subscribe ( ${event.signature.params}${if.event.params}, ${end.if.event.params}I${method.Name}Notification& notification ) = 0; - virtual int32_t unsubscribe ( I${method.Name}Notification& notification ) = 0; - - // signature callback params: ${event.signature.callback.params} - // method result properties : ${method.result.properties} + /* ${method.name} - ${method.description} */ + struct I${method.Name}Notification { + virtual void ${method.Name} ( ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${method.result.properties} ) = 0; + }; + // signature callback params: ${event.signature.callback.params} + // method result properties : ${method.result.properties} + virtual int32_t subscribe ( ${event.signature.params}${if.event.params}, ${end.if.event.params}I${method.Name}Notification& notification ) = 0; + virtual int32_t unsubscribe ( I${method.Name}Notification& notification ) = 0; \ No newline at end of file diff --git a/languages/cpp/templates/declarations/polymorphic-pull-event.c b/languages/cpp/templates/declarations/polymorphic-pull-event.c index 755f7f54..178678ad 100644 --- a/languages/cpp/templates/declarations/polymorphic-pull-event.c +++ b/languages/cpp/templates/declarations/polymorphic-pull-event.c @@ -1,8 +1,8 @@ -/* ${method.name} - ${method.description} */ -struct I{method.Name}Notification { - virtual void ${method.Name} ( ${method.pulls.param.type}& value ) = 0; -}; - -virtual int32_t subscribe ( I{method.Name}Notification& notification ) = 0; -virtual int32_t unsubscribe ( I{method.Name}Notification& notification ) = 0; + /* ${method.name} - ${method.description} */ + struct I{method.Name}Notification { + virtual void ${method.Name} ( ${method.pulls.param.type}& value ) = 0; + }; + + virtual int32_t subscribe ( I{method.Name}Notification& notification ) = 0; + virtual int32_t unsubscribe ( I{method.Name}Notification& notification ) = 0; diff --git a/languages/cpp/templates/declarations/polymorphic-pull.c b/languages/cpp/templates/declarations/polymorphic-pull.c index 74f23cc4..6588a635 100644 --- a/languages/cpp/templates/declarations/polymorphic-pull.c +++ b/languages/cpp/templates/declarations/polymorphic-pull.c @@ -1,2 +1,2 @@ -/* ${method.name} - ${method.description} */ -virtual int32_t ${method.Name}( ${method.signature.params} ) = 0; + /* ${method.name} - ${method.description} */ + virtual int32_t ${method.Name}( ${method.signature.params} ) = 0; diff --git a/languages/cpp/templates/declarations/polymorphic-reducer.c b/languages/cpp/templates/declarations/polymorphic-reducer.c index 46f633b8..a6f50d1b 100644 --- a/languages/cpp/templates/declarations/polymorphic-reducer.c +++ b/languages/cpp/templates/declarations/polymorphic-reducer.c @@ -1,5 +1,5 @@ -/* - * ${method.summary} - * ${method.params} - */ -virtual int32_t ${method.Name}(${method.signature.params}${if.result.properties}${if.params}, ${end.if.params}${end.if.result.properties}${method.result.properties}) = 0; + /* + * ${method.summary} + * ${method.params} + */ + virtual int32_t ${method.Name}(${method.signature.params}${if.result.properties}${if.params}, ${end.if.params}${end.if.result.properties}${method.result.properties}) = 0; diff --git a/languages/cpp/templates/declarations/property.h b/languages/cpp/templates/declarations/property.h index 884fd2f0..09cc5d7d 100644 --- a/languages/cpp/templates/declarations/property.h +++ b/languages/cpp/templates/declarations/property.h @@ -1,5 +1,5 @@ - /* - * ${method.description} - * ${method.params} - */ - virtual int32_t ${method.Name} (${method.signature.params}${if.params}, ${end.if.params}${method.result.properties}) = 0; + /* + * ${method.description} + * ${method.params} + */ +virtual int32_t ${method.Name} (${method.signature.params}${if.params}, ${end.if.params}${method.result.properties}) = 0; diff --git a/languages/cpp/templates/declarations/setter.h b/languages/cpp/templates/declarations/setter.h index 75d3b5a6..64e4d19e 100644 --- a/languages/cpp/templates/declarations/setter.h +++ b/languages/cpp/templates/declarations/setter.h @@ -1,5 +1,5 @@ - /* - ${method.rpc.name} - ${method.description} - */ - virtual int32_t ${method.Name}( ${method.signature.params} ) = 0; + /* + ${method.rpc.name} + ${method.description} + */ + virtual int32_t ${method.Name}( ${method.signature.params} ) = 0; diff --git a/languages/cpp/templates/modules/include/module.h b/languages/cpp/templates/modules/include/module.h index f6d5128d..462c9a30 100644 --- a/languages/cpp/templates/modules/include/module.h +++ b/languages/cpp/templates/modules/include/module.h @@ -25,19 +25,19 @@ namespace ${info.Title} { // Enums -/* ${ENUMS} */ + /* ${ENUMS} */ // Types /* ${TYPES} */ - struct I${info.Title} { +struct I${info.Title} { - virtual ~I${info.Title} = default; + virtual ~I${info.Title} = default; - // Methods & Events - /* ${DECLARATIONS} */ +// Methods & Events +/* ${DECLARATIONS} */ - }; +}; } //namespace ${info.Title} }${end.if.declarations} diff --git a/languages/cpp/templates/parameters/default.c b/languages/cpp/templates/parameters/default.h similarity index 100% rename from languages/cpp/templates/parameters/default.c rename to languages/cpp/templates/parameters/default.h diff --git a/languages/cpp/templates/parameters/json.c b/languages/cpp/templates/parameters/json.cpp similarity index 100% rename from languages/cpp/templates/parameters/json.c rename to languages/cpp/templates/parameters/json.cpp diff --git a/languages/cpp/templates/parameters/object.c b/languages/cpp/templates/parameters/object.h similarity index 100% rename from languages/cpp/templates/parameters/object.c rename to languages/cpp/templates/parameters/object.h diff --git a/languages/cpp/templates/parameters/optional.c b/languages/cpp/templates/parameters/optional.h similarity index 100% rename from languages/cpp/templates/parameters/optional.c rename to languages/cpp/templates/parameters/optional.h diff --git a/languages/cpp/templates/parameters/result-null.h b/languages/cpp/templates/parameters/result-null.h new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/parameters/result.c b/languages/cpp/templates/parameters/result.h similarity index 100% rename from languages/cpp/templates/parameters/result.c rename to languages/cpp/templates/parameters/result.h diff --git a/languages/cpp/templates/parameters/string.c b/languages/cpp/templates/parameters/string.h similarity index 100% rename from languages/cpp/templates/parameters/string.c rename to languages/cpp/templates/parameters/string.h diff --git a/languages/cpp/templates/types/additionalProperties.h b/languages/cpp/templates/types/additionalProperties.h index 52882d43..baa50800 100644 --- a/languages/cpp/templates/types/additionalProperties.h +++ b/languages/cpp/templates/types/additionalProperties.h @@ -1 +1 @@ -std::unordered_map title; \ No newline at end of file +${title} value; \ No newline at end of file diff --git a/languages/cpp/templates/types/array.h b/languages/cpp/templates/types/array.h index 2c1e61d4..ed5a1d2b 100644 --- a/languages/cpp/templates/types/array.h +++ b/languages/cpp/templates/types/array.h @@ -1 +1 @@ -std::vector<${type}> ${title}; \ No newline at end of file +std::vector<${type}> \ No newline at end of file diff --git a/languages/cpp/templates/types/null.h b/languages/cpp/templates/types/null.h index 79c36400..e69de29b 100644 --- a/languages/cpp/templates/types/null.h +++ b/languages/cpp/templates/types/null.h @@ -1 +0,0 @@ -nullptr \ No newline at end of file diff --git a/languages/cpp/templates/types/property.h b/languages/cpp/templates/types/property.h index 39c3b6b8..eb813df6 100644 --- a/languages/cpp/templates/types/property.h +++ b/languages/cpp/templates/types/property.h @@ -1 +1 @@ -${if.optional}std::optional<${end.if.optional}${title}${if.optional}>${end.if.optional} ${property}; // ${summary} \ No newline at end of file +${if.optional}std::optional<${end.if.optional}${title}${if.optional}>${end.if.optional} ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/types/tuple.h b/languages/cpp/templates/types/tuple.h index 0e042b9c..ce217a83 100644 --- a/languages/cpp/templates/types/tuple.h +++ b/languages/cpp/templates/types/tuple.h @@ -1,6 +1,2 @@ /* ${title} */ -struct ${title} { - - ${properties} - -}; +std::pair<${type},${type}> ${title}; diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index c5055b91..500bc3b1 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -376,7 +376,7 @@ const promoteSchema = (location, property, title, document, destinationPath) => } // only consider sub-objects and sub enums to be sub-schemas -const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) || (schema.type === 'array' && schema.items) +const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) // || (schema.type === 'array' && schema.items) const promoteAndNameSubSchemas = (obj) => { // make a copy so we don't polute our inputs @@ -506,7 +506,7 @@ 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)) @@ -1483,7 +1483,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})) + .replace(/\$\{method\.param\.type\}/g, types.getSchemaType(type, json, {name: name, moduleTitle: moduleTitle, result: true, namespace: true})) ).join(', ') // most languages separate params w/ a comma, so leaving this here for now } // tuples get unwrapped @@ -1492,14 +1492,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})) + .replace(/\$\{method\.param\.type\}/g, types.getSchemaType(type, json, {name: name, 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}) + const template = getTemplate('/parameters/result', templates) + const type = types.getSchemaType(result, json, {name: name, moduleTitle: moduleTitle, result: true, namespace: true}) if (type === 'undefined') { console.log(`Warning: undefined type for ${name}`) } From c952047668f992711ae63a42fe9b4fab70cde778 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 9 Oct 2023 13:03:50 +0530 Subject: [PATCH 103/137] CPPSDK: static code + template changes (#137) * CPPSDK: static code + template changes * CPPSDK: static code updates * CPPSDK: updates in error handling --- languages/cpp/src/shared/include/error.h | 36 ++- languages/cpp/src/shared/include/types.h | 20 +- .../cpp/src/shared/src/Accessor/Accessor.cpp | 46 +-- .../cpp/src/shared/src/Accessor/Accessor.h | 29 +- languages/cpp/src/shared/src/CMakeLists.txt | 2 +- languages/cpp/src/shared/src/Event/Event.cpp | 26 +- languages/cpp/src/shared/src/Event/Event.h | 37 ++- .../{test/OpenRPCCTests.h => src/IModule.h} | 28 +- .../cpp/src/shared/src/Logger/Logger.cpp | 8 +- languages/cpp/src/shared/src/Logger/Logger.h | 4 +- .../src/shared/src/Properties/Properties.h | 28 +- .../cpp/src/shared/src/Transport/Transport.h | 141 ++++++--- languages/cpp/src/shared/src/TypesPriv.h | 6 + languages/cpp/src/shared/test/CMakeLists.txt | 2 +- languages/cpp/src/shared/test/Main.c | 45 --- .../cpp/src/shared/test/OpenRPCTests.cpp | 275 +++--------------- languages/cpp/src/shared/test/OpenRPCTests.h | 20 +- languages/cpp/templates/codeblocks/setter.c | 21 +- .../cpp/templates/declarations/default.c | 6 - languages/cpp/templates/declarations/event.c | 6 +- .../declarations/polymorphic-pull-event.c | 8 - .../templates/declarations/polymorphic-pull.c | 2 - .../declarations/polymorphic-reducer.c | 5 - .../cpp/templates/declarations/property.h | 8 +- languages/cpp/templates/declarations/setter.h | 8 +- .../cpp/templates/methods/calls-metrics.c | 28 -- languages/cpp/templates/methods/default.c | 21 -- languages/cpp/templates/methods/event.c | 52 ++-- .../methods/polymorphic-pull-event.c | 54 ---- .../cpp/templates/methods/polymorphic-pull.c | 22 -- languages/cpp/templates/methods/property.c | 29 +- .../cpp/templates/modules/include/module.h | 18 +- .../cpp/templates/modules/src/module.cpp | 70 ++++- .../templates/schemas/include/common/module.h | 15 +- .../templates/schemas/src/jsondata_module.h | 4 +- .../templates/schemas/src/module_common.cpp | 18 +- languages/cpp/templates/sections/methods.h | 3 - languages/cpp/templates/types/enum.cpp | 6 +- 38 files changed, 434 insertions(+), 723 deletions(-) rename languages/cpp/src/shared/{test/OpenRPCCTests.h => src/IModule.h} (56%) delete mode 100644 languages/cpp/src/shared/test/Main.c diff --git a/languages/cpp/src/shared/include/error.h b/languages/cpp/src/shared/include/error.h index 07d6268a..b02859b3 100644 --- a/languages/cpp/src/shared/include/error.h +++ b/languages/cpp/src/shared/include/error.h @@ -16,26 +16,24 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef FIREBOLT_ERROR_H -#define FIREBOLT_ERROR_H +#pragma once -#ifdef __cplusplus -extern "C" { -#endif +namespace Firebolt { -typedef enum FireboltSDKError { - FireboltSDKErrorNone = 0, - FireboltSDKErrorGeneral = 1, - FireboltSDKErrorUnavailable = 2, - FireboltSDKErrorTimedout = 3, - FireboltSDKErrorNotSubscribed = 4, - FireboltSDKErrorUnknown = 5, - FireboltSDKErrorInUse = 6, - FireboltSDKErrorNotSupported = 7 -} FireboltSDKError_t; + enum class Error : int32_t { + None = 0, + General = 1, + Timedout = 2, + NotConnected = 3, + AlreadyConnected = 4, + //AuthenticationError, ? + InvalidRequest = -32600, + MethodNotFound = -32601, + InvalidParams = -32602, + CapabilityNotAvaialbale = -50300, + CapabilityNotSupported = -50100, + CapabilityGet = -50200, + CapabilityNotPermitted = -40300, + }; -#ifdef __cplusplus } -#endif - -#endif // FIREBOLT_ERROR_H diff --git a/languages/cpp/src/shared/include/types.h b/languages/cpp/src/shared/include/types.h index 8333f0eb..841bda7a 100644 --- a/languages/cpp/src/shared/include/types.h +++ b/languages/cpp/src/shared/include/types.h @@ -16,22 +16,12 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef FIREBOLT_TYPES_H -#define FIREBOLT_TYPES_H +#pragma once #include #include +#include +#include +#include +#include -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct Firebolt_String_s* Firebolt_String_t; -const char* Firebolt_String(Firebolt_String_t handle); -void Firebolt_String_Release(Firebolt_String_t handle); - -#ifdef __cplusplus -} -#endif - -#endif // FIREBOLT_TYPES_H diff --git a/languages/cpp/src/shared/src/Accessor/Accessor.cpp b/languages/cpp/src/shared/src/Accessor/Accessor.cpp index 6d4aceae..e34630ed 100644 --- a/languages/cpp/src/shared/src/Accessor/Accessor.cpp +++ b/languages/cpp/src/shared/src/Accessor/Accessor.cpp @@ -27,15 +27,13 @@ namespace FireboltSDK { , _transport(nullptr) , _config() { + ASSERT(_singleton == nullptr); _singleton = this; _config.FromString(configLine); Logger::SetLogLevel(WPEFramework::Core::EnumerateType(_config.LogLevel.Value().c_str()).Value()); FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "Url = %s", _config.WsUrl.Value().c_str()); - CreateTransport(_config.WsUrl.Value().c_str(), _config.WaitTime.Value()); - CreateEventHandler(); - _workerPool = WPEFramework::Core::ProxyType::Create(_config.WorkerPool.ThreadCount.Value(), _config.WorkerPool.StackSize.Value(), _config.WorkerPool.QueueSize.Value()); WPEFramework::Core::WorkerPool::Assign(&(*_workerPool)); _workerPool->Run(); @@ -43,23 +41,23 @@ namespace FireboltSDK { Accessor::~Accessor() { - DestroyTransport(); - DestroyEventHandler(); WPEFramework::Core::IWorkerPool::Assign(nullptr); _workerPool->Stop(); + + ASSERT(_singleton != nullptr); _singleton = nullptr; } - int32_t Accessor::CreateEventHandler() + Firebolt::Error Accessor::CreateEventHandler() { Event::Instance().Configure(_transport); - return FireboltSDKErrorNone; + return Firebolt::Error::None; } - int32_t Accessor::DestroyEventHandler() + Firebolt::Error Accessor::DestroyEventHandler() { Event::Dispose(); - return FireboltSDKErrorNone; + return Firebolt::Error::None; } Event& Accessor::GetEventManager() @@ -67,29 +65,25 @@ namespace FireboltSDK { return Event::Instance(); } - int32_t Accessor::CreateTransport(const string& url, const uint32_t waitTime = DefaultWaitTime) + Firebolt::Error Accessor::CreateTransport(const string& url, const Transport::Listener& listener, const uint32_t waitTime = DefaultWaitTime) { if (_transport != nullptr) { delete _transport; } - _transport = new Transport(static_cast(url), waitTime); - if (WaitForLinkReady(_transport, waitTime) != FireboltSDKErrorNone) { - delete _transport; - _transport = nullptr; - } + _transport = new Transport(static_cast(url), waitTime, listener); ASSERT(_transport != nullptr); - return ((_transport != nullptr) ? FireboltSDKErrorNone : FireboltSDKErrorUnavailable); + return ((_transport != nullptr) ? Firebolt::Error::None : Firebolt::Error::Timedout); } - int32_t Accessor::DestroyTransport() + Firebolt::Error Accessor::DestroyTransport() { if (_transport != nullptr) { delete _transport; _transport = nullptr; } - return FireboltSDKErrorNone; + return Firebolt::Error::None; } Transport* Accessor::GetTransport() @@ -98,20 +92,4 @@ namespace FireboltSDK { return _transport; } - int32_t Accessor::WaitForLinkReady(Transport* transport, const uint32_t waitTime = DefaultWaitTime) { - uint32_t waiting = (waitTime == WPEFramework::Core::infinite ? WPEFramework::Core::infinite : waitTime); - static constexpr uint32_t SLEEPSLOT_TIME = 100; - - // Right, a wait till connection is closed is requested.. - while ((waiting > 0) && (transport->IsOpen() == false)) { - - uint32_t sleepSlot = (waiting > SLEEPSLOT_TIME ? SLEEPSLOT_TIME : waiting); - - // Right, lets sleep in slices of 100 ms - SleepMs(sleepSlot); - - waiting -= (waiting == WPEFramework::Core::infinite ? 0 : sleepSlot); - } - return (((waiting == 0) || (transport->IsOpen() == true)) ? FireboltSDKErrorNone : FireboltSDKErrorTimedout); - } } diff --git a/languages/cpp/src/shared/src/Accessor/Accessor.h b/languages/cpp/src/shared/src/Accessor/Accessor.h index e247df98..29dd7dda 100644 --- a/languages/cpp/src/shared/src/Accessor/Accessor.h +++ b/languages/cpp/src/shared/src/Accessor/Accessor.h @@ -103,15 +103,34 @@ namespace FireboltSDK { delete _singleton; } } + + Firebolt::Error Connect(const Transport::Listener& listener) + { + Firebolt::Error status = CreateTransport(_config.WsUrl.Value().c_str(), listener, _config.WaitTime.Value()); + if (status == Firebolt::Error::None) { + status = CreateEventHandler(); + } + return status; + } + + Firebolt::Error Disconnect() + { + Firebolt::Error status = Firebolt::Error::None; + status = DestroyTransport(); + if (status == Firebolt::Error::None) { + status = DestroyEventHandler(); + } + return status; + } + Event& GetEventManager(); Transport* GetTransport(); private: - int32_t CreateEventHandler(); - int32_t DestroyEventHandler(); - int32_t CreateTransport(const string& url, const uint32_t waitTime); - int32_t DestroyTransport(); - int32_t WaitForLinkReady(Transport* transport, const uint32_t waitTime); + Firebolt::Error CreateEventHandler(); + Firebolt::Error DestroyEventHandler(); + Firebolt::Error CreateTransport(const string& url, const Transport::Listener& listener, const uint32_t waitTime); + Firebolt::Error DestroyTransport(); private: WPEFramework::Core::ProxyType _workerPool; diff --git a/languages/cpp/src/shared/src/CMakeLists.txt b/languages/cpp/src/shared/src/CMakeLists.txt index ecaf4efb..960af8de 100644 --- a/languages/cpp/src/shared/src/CMakeLists.txt +++ b/languages/cpp/src/shared/src/CMakeLists.txt @@ -45,7 +45,7 @@ target_include_directories(${TARGET} ) set_target_properties(${TARGET} PROPERTIES - CXX_STANDARD 11 + CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES FRAMEWORK FALSE LINK_WHAT_YOU_USE TRUE diff --git a/languages/cpp/src/shared/src/Event/Event.cpp b/languages/cpp/src/shared/src/Event/Event.cpp index c1fdff6f..2438e3c4 100644 --- a/languages/cpp/src/shared/src/Event/Event.cpp +++ b/languages/cpp/src/shared/src/Event/Event.cpp @@ -60,33 +60,35 @@ namespace FireboltSDK { _transport->SetEventHandler(this); } - int32_t Event::Unsubscribe(const string& eventName, void* usercb) + Firebolt::Error Event::Unsubscribe(const string& eventName, void* usercb) { - int32_t status = Revoke(eventName, usercb); + Firebolt::Error status = Revoke(eventName, usercb); - if (status == FireboltSDKErrorNone) { + if (status == Firebolt::Error::None) { if (_transport != nullptr) { const string parameters("{\"listen\":false}"); status = _transport->Unsubscribe(eventName, parameters); } + } else { + status = Firebolt::Error::None; } - return ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone: status); + return status; } - int32_t Event::ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) /* override */ + Firebolt::Error Event::ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) /* override */ { - int32_t result = FireboltSDKErrorGeneral; + Firebolt::Error result = Firebolt::Error::General; Response response; _transport->FromMessage((WPEFramework::Core::JSON::IElement*)&response, *jsonResponse); if (response.Listening.IsSet() == true) { - result = FireboltSDKErrorNone; + result = Firebolt::Error::None; enabled = response.Listening.Value(); } return result; } - int32_t Event::Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) /* override */ + Firebolt::Error Event::Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) /* override */ { string response = jsonResponse->Result.Value(); _adminLock.Lock(); @@ -117,12 +119,12 @@ namespace FireboltSDK { } _adminLock.Unlock(); - return FireboltSDKErrorNone;; + return Firebolt::Error::None;; } - int32_t Event::Revoke(const string& eventName, void* usercb) + Firebolt::Error Event::Revoke(const string& eventName, void* usercb) { - int32_t status = FireboltSDKErrorNone; + Firebolt::Error status = Firebolt::Error::None; _adminLock.Lock(); EventMap::iterator eventIndex = _eventMap.find(eventName); if (eventIndex != _eventMap.end()) { @@ -137,7 +139,7 @@ namespace FireboltSDK { if (eventIndex->second.size() == 0) { _eventMap.erase(eventIndex); } else { - status = FireboltSDKErrorInUse; + status = Firebolt::Error::General; } } _adminLock.Unlock(); diff --git a/languages/cpp/src/shared/src/Event/Event.h b/languages/cpp/src/shared/src/Event/Event.h index dd65cb53..cf2fdced 100644 --- a/languages/cpp/src/shared/src/Event/Event.h +++ b/languages/cpp/src/shared/src/Event/Event.h @@ -26,7 +26,7 @@ namespace FireboltSDK { class Event : public IEventHandler { public: - typedef std::function DispatchFunction; + typedef std::function DispatchFunction; private: enum State : uint8_t { IDLE, @@ -73,20 +73,20 @@ namespace FireboltSDK { public: template - int32_t Subscribe(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) + Firebolt::Error Subscribe(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) { JsonObject jsonParameters; return Subscribe(eventName, jsonParameters, callback, usercb, userdata); } template - int32_t Subscribe(const string& eventName, JsonObject& jsonParameters, const CALLBACK& callback, void* usercb, const void* userdata) + Firebolt::Error Subscribe(const string& eventName, JsonObject& jsonParameters, const CALLBACK& callback, void* usercb, const void* userdata) { - int32_t status = FireboltSDKErrorUnavailable; + Firebolt::Error status = Firebolt::Error::General; if (_transport != nullptr) { status = Assign(eventName, callback, usercb, userdata); - if (status == FireboltSDKErrorNone) { + if (status == Firebolt::Error::None) { Response response; WPEFramework::Core::JSON::Variant Listen = true; @@ -96,13 +96,11 @@ namespace FireboltSDK { status = _transport->Subscribe(eventName, parameters, response); - if (status != FireboltSDKErrorNone) { + if (status != Firebolt::Error::None) { Revoke(eventName, usercb); } else if ((response.Listening.IsSet() == true) && (response.Listening.Value() == true)) { - status = FireboltSDKErrorNone; - } else { - status = FireboltSDKErrorNotSubscribed; + status = Firebolt::Error::None; } } } @@ -110,21 +108,21 @@ namespace FireboltSDK { return status; } - int32_t Unsubscribe(const string& eventName, void* usercb); + Firebolt::Error Unsubscribe(const string& eventName, void* usercb); private: template - int32_t Assign(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) + Firebolt::Error Assign(const string& eventName, const CALLBACK& callback, void* usercb, const void* userdata) { - int32_t status = FireboltSDKErrorNone; + Firebolt::Error status = Firebolt::Error::General; std::function actualCallback = callback; - DispatchFunction implementation = [actualCallback](void* usercb, const void* userdata, const string& parameters) -> int32_t { + DispatchFunction implementation = [actualCallback](void* usercb, const void* userdata, const string& parameters) -> Firebolt::Error { WPEFramework::Core::ProxyType* inbound = new WPEFramework::Core::ProxyType(); *inbound = WPEFramework::Core::ProxyType::Create(); (*inbound)->FromString(parameters); actualCallback(usercb, userdata, static_cast(inbound)); - return (FireboltSDKErrorNone); + return (Firebolt::Error::None); }; CallbackData callbackData = {implementation, userdata, State::IDLE}; @@ -134,26 +132,25 @@ namespace FireboltSDK { CallbackMap::iterator callbackIndex = eventIndex->second.find(usercb); if (callbackIndex == eventIndex->second.end()) { eventIndex->second.emplace(std::piecewise_construct, std::forward_as_tuple(usercb), std::forward_as_tuple(callbackData)); - } else { - // Already registered, no need to register again; - status = FireboltSDKErrorInUse; + status = Firebolt::Error::None; } } else { CallbackMap callbackMap; callbackMap.emplace(std::piecewise_construct, std::forward_as_tuple(usercb), std::forward_as_tuple(callbackData)); _eventMap.emplace(std::piecewise_construct, std::forward_as_tuple(eventName), std::forward_as_tuple(callbackMap)); + status = Firebolt::Error::None; } _adminLock.Unlock(); return status; } - int32_t Revoke(const string& eventName, void* usercb); + Firebolt::Error Revoke(const string& eventName, void* usercb); private: - int32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) override; - int32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) override; + Firebolt::Error ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) override; + Firebolt::Error Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) override; private: EventMap _eventMap; diff --git a/languages/cpp/src/shared/test/OpenRPCCTests.h b/languages/cpp/src/shared/src/IModule.h similarity index 56% rename from languages/cpp/src/shared/test/OpenRPCCTests.h rename to languages/cpp/src/shared/src/IModule.h index 936a1ff9..1349e78a 100644 --- a/languages/cpp/src/shared/test/OpenRPCCTests.h +++ b/languages/cpp/src/shared/src/IModule.h @@ -16,28 +16,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifndef OPENRPC_C_TESTS_H -#define OPENRPC_C_TESTS_H +#pragma once -#include "TestUtils.h" - -#ifdef __cplusplus -extern "C" { -#endif - -void test_firebolt_create_instance(); -void test_firebolt_dispose_instance(); - -int32_t test_firebolt_main(); -int32_t test_properties_get_device_id(); -int32_t test_properties_set(); -int32_t test_eventregister(); -int32_t test_eventregister_with_same_callback(); -int32_t test_eventregister_by_providing_callback(); -int32_t test_string_set_get_value(); - -#ifdef __cplusplus +namespace Firebolt { + struct IModule { + virtual ~IModule() = default; + }; } -#endif - -#endif // OPENRPC_C_TESTS_H diff --git a/languages/cpp/src/shared/src/Logger/Logger.cpp b/languages/cpp/src/shared/src/Logger/Logger.cpp index 44ebaba8..c66c6b68 100644 --- a/languages/cpp/src/shared/src/Logger/Logger.cpp +++ b/languages/cpp/src/shared/src/Logger/Logger.cpp @@ -35,7 +35,7 @@ ENUM_CONVERSION_BEGIN(FireboltSDK::Logger::Category) { FireboltSDK::Logger::Category::OpenRPC, _TXT("FireboltSDK::OpenRPC") }, { FireboltSDK::Logger::Category::Core, _TXT("FireboltSDK::Core") }, - { FireboltSDK::Logger::Category::Management, _TXT("FireboltSDK::Management") }, + { FireboltSDK::Logger::Category::Manage, _TXT("FireboltSDK::Manage") }, { FireboltSDK::Logger::Category::Discovery, _TXT("FireboltSDK::Discovery") }, ENUM_CONVERSION_END(FireboltSDK::Logger::Category) @@ -45,13 +45,13 @@ ENUM_CONVERSION_END(FireboltSDK::Logger::Category) namespace FireboltSDK { /* static */ Logger::LogLevel Logger::_logLevel = Logger::LogLevel::Error; - int32_t Logger::SetLogLevel(Logger::LogLevel logLevel) + Firebolt::Error Logger::SetLogLevel(Logger::LogLevel logLevel) { ASSERT(logLevel < Logger::LogLevel::MaxLevel); - int32_t status = FireboltSDKErrorNotSupported; + Firebolt::Error status = Firebolt::Error::General; if (logLevel < Logger::LogLevel::MaxLevel) { _logLevel = logLevel; - status = FireboltSDKErrorNone; + status = Firebolt::Error::None; } return status; } diff --git a/languages/cpp/src/shared/src/Logger/Logger.h b/languages/cpp/src/shared/src/Logger/Logger.h index b8e42031..ffe5a455 100644 --- a/languages/cpp/src/shared/src/Logger/Logger.h +++ b/languages/cpp/src/shared/src/Logger/Logger.h @@ -38,7 +38,7 @@ namespace FireboltSDK { enum class Category : uint8_t { OpenRPC, Core, - Management, + Manage, Discovery }; @@ -49,7 +49,7 @@ namespace FireboltSDK { ~Logger() = default; public: - static int32_t SetLogLevel(LogLevel logLevel); + static Firebolt::Error SetLogLevel(LogLevel logLevel); static void Log(LogLevel logLevel, Category category, const std::string& module, const std::string file, const std::string function, const uint16_t line, const std::string& format, ...); public: diff --git a/languages/cpp/src/shared/src/Properties/Properties.h b/languages/cpp/src/shared/src/Properties/Properties.h index eaf6c1a4..52051397 100644 --- a/languages/cpp/src/shared/src/Properties/Properties.h +++ b/languages/cpp/src/shared/src/Properties/Properties.h @@ -33,15 +33,15 @@ namespace FireboltSDK { public: template - static int32_t Get(const string& propertyName, WPEFramework::Core::ProxyType& response) + static Firebolt::Error Get(const string& propertyName, WPEFramework::Core::ProxyType& response) { - int32_t status = FireboltSDKErrorUnavailable; + Firebolt::Error status = Firebolt::Error::General; Transport* transport = Accessor::Instance().GetTransport(); if (transport != nullptr) { JsonObject parameters; RESPONSETYPE responseType; status = transport->Invoke(propertyName, parameters, responseType); - if (status == FireboltSDKErrorNone) { + if (status == Firebolt::Error::None) { ASSERT(response.IsValid() == false); if (response.IsValid() == true) { response.Release(); @@ -57,14 +57,14 @@ namespace FireboltSDK { } template - static int32_t Get(const string& propertyName, const PARAMETERS& parameters, WPEFramework::Core::ProxyType& response) + static Firebolt::Error Get(const string& propertyName, const PARAMETERS& parameters, WPEFramework::Core::ProxyType& response) { - int32_t status = FireboltSDKErrorUnavailable; + Firebolt::Error status = Firebolt::Error::General; Transport* transport = Accessor::Instance().GetTransport(); if (transport != nullptr) { RESPONSETYPE responseType; status = transport->Invoke(propertyName, parameters, responseType); - if (status == FireboltSDKErrorNone) { + if (status == Firebolt::Error::None) { ASSERT(response.IsValid() == false); if (response.IsValid() == true) { response.Release(); @@ -81,9 +81,9 @@ namespace FireboltSDK { template - static int32_t Get(const string& propertyName, RESPONSETYPE& response) + static Firebolt::Error Get(const string& propertyName, RESPONSETYPE& response) { - int32_t status = FireboltSDKErrorUnavailable; + Firebolt::Error status = Firebolt::Error::General; Transport* transport = Accessor::Instance().GetTransport(); if (transport != nullptr) { JsonObject parameters; @@ -96,9 +96,9 @@ namespace FireboltSDK { } template - static int32_t Get(const string& propertyName, const PARAMETERS& parameters, RESPONSETYPE& response) + static Firebolt::Error Get(const string& propertyName, const PARAMETERS& parameters, RESPONSETYPE& response) { - int32_t status = FireboltSDKErrorUnavailable; + Firebolt::Error status = Firebolt::Error::General; Transport* transport = Accessor::Instance().GetTransport(); if (transport != nullptr) { status = transport->Invoke(propertyName, parameters, response); @@ -110,9 +110,9 @@ namespace FireboltSDK { } template - static int32_t Set(const string& propertyName, const PARAMETERS& parameters) + static Firebolt::Error Set(const string& propertyName, const PARAMETERS& parameters) { - int32_t status = FireboltSDKErrorUnavailable; + Firebolt::Error status = Firebolt::Error::General; Transport* transport = Accessor::Instance().GetTransport(); if (transport != nullptr) { JsonObject responseType; @@ -125,12 +125,12 @@ namespace FireboltSDK { } template - static int32_t Subscribe(const string& propertyName, JsonObject& paramsters, const CALLBACK& callback, void* usercb, const void* userdata) + static Firebolt::Error Subscribe(const string& propertyName, JsonObject& paramsters, const CALLBACK& callback, void* usercb, const void* userdata) { return Event::Instance().Subscribe(EventName(propertyName), paramsters, callback, usercb, userdata); } - static int32_t Unsubscribe(const string& propertyName, void* usercb) + static Firebolt::Error Unsubscribe(const string& propertyName, void* usercb) { return Event::Instance().Unsubscribe(EventName(propertyName), usercb); } diff --git a/languages/cpp/src/shared/src/Transport/Transport.h b/languages/cpp/src/shared/src/Transport/Transport.h index 6b80cd25..87632dc1 100644 --- a/languages/cpp/src/shared/src/Transport/Transport.h +++ b/languages/cpp/src/shared/src/Transport/Transport.h @@ -441,8 +441,8 @@ namespace FireboltSDK { class IEventHandler { public: - virtual int32_t ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) = 0; - virtual int32_t Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) = 0; + virtual Firebolt::Error ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) = 0; + virtual Firebolt::Error Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) = 0; virtual ~IEventHandler() = default; }; @@ -455,20 +455,20 @@ namespace FireboltSDK { using EventMap = std::map; typedef std::function& jsonResponse, bool& enabled)> EventResponseValidatioionFunction; - class Job : public WPEFramework::Core::IDispatch { + class CommunicationJob : public WPEFramework::Core::IDispatch { protected: - Job(const WPEFramework::Core::ProxyType& inbound, class Transport* parent) + CommunicationJob(const WPEFramework::Core::ProxyType& inbound, class Transport* parent) : _inbound(inbound) , _parent(parent) { } public: - Job() = delete; - Job(const Job&) = delete; - Job& operator=(const Job&) = delete; + CommunicationJob() = delete; + CommunicationJob(const CommunicationJob&) = delete; + CommunicationJob& operator=(const CommunicationJob&) = delete; - ~Job() = default; + ~CommunicationJob() = default; public: static WPEFramework::Core::ProxyType Create(const WPEFramework::Core::ProxyType& inbound, class Transport* parent); @@ -483,6 +483,36 @@ namespace FireboltSDK { class Transport* _parent; }; + class ConnectionJob : public WPEFramework::Core::IDispatch { + protected: + ConnectionJob(class Transport* parent) + : _parent(parent) + { + } + + public: + ConnectionJob() = delete; + ConnectionJob(const ConnectionJob&) = delete; + ConnectionJob& operator=(const ConnectionJob&) = delete; + + ~ConnectionJob() = default; + + public: + static WPEFramework::Core::ProxyType Create(class Transport* parent); + + void Dispatch() override + { + if (Firebolt::Error::None != _parent->WaitForLinkReady()) { + _parent->NotifyStatus(Firebolt::Error::Timedout); + } + } + + private: + const WPEFramework::Core::ProxyType _inbound; + class Transport* _parent; + }; + + protected: static constexpr uint32_t DefaultWaitTime = 10000; @@ -492,11 +522,15 @@ namespace FireboltSDK { private: static constexpr const TCHAR* PathPrefix = _T("/"); + + public: + typedef std::function Listener; + public: Transport() = delete; Transport(const Transport&) = delete; Transport& operator=(Transport&) = delete; - Transport(const WPEFramework::Core::URL& url, const uint32_t waitTime) + Transport(const WPEFramework::Core::URL& url, const uint32_t waitTime, const Listener listener) : _adminLock() , _connectId(WPEFramework::Core::NodeId(url.Host().Value().c_str(), url.Port().Value())) , _channel(Channel::Instance(_connectId, ((url.Path().Value().rfind(PathPrefix, 0) == 0) ? url.Path().Value() : string(PathPrefix + url.Path().Value())), url.Query().Value(), true)) @@ -504,8 +538,12 @@ namespace FireboltSDK { , _pendingQueue() , _scheduledTime(0) , _waitTime(waitTime) + , _listener(listener) + , _status(Firebolt::Error::NotConnected) { _channel->Register(*this); + WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(this)); + WPEFramework::Core::IWorkerPool::Instance().Submit(job); } virtual ~Transport() @@ -536,25 +574,25 @@ namespace FireboltSDK { } template - int32_t Invoke(const string& method, const PARAMETERS& parameters, RESPONSE& response) + Firebolt::Error Invoke(const string& method, const PARAMETERS& parameters, RESPONSE& response) { Entry slot; uint32_t id = _channel->Sequence(); - int32_t result = Send(method, parameters, id); - if (result == WPEFramework::Core::ERROR_NONE) { + Firebolt::Error result = Send(method, parameters, id); + if (result == Firebolt::Error::None) { result = WaitForResponse(id, response, _waitTime); } - return (FireboltErrorValue(result)); + return (result); } template - int32_t Subscribe(const string& eventName, const string& parameters, RESPONSE& response) + Firebolt::Error Subscribe(const string& eventName, const string& parameters, RESPONSE& response) { Entry slot; uint32_t id = _channel->Sequence(); - int32_t result = Send(eventName, parameters, id); - if (result == WPEFramework::Core::ERROR_NONE) { + Firebolt::Error result = Send(eventName, parameters, id); + if (result == Firebolt::Error::None) { _adminLock.Lock(); _eventMap.emplace(std::piecewise_construct, std::forward_as_tuple(eventName), @@ -564,17 +602,39 @@ namespace FireboltSDK { result = WaitForEventResponse(id, eventName, response, _waitTime); } - return (FireboltErrorValue(result)); + return (result); } - int32_t Unsubscribe(const string& eventName, const string& parameters) + Firebolt::Error Unsubscribe(const string& eventName, const string& parameters) { Revoke(eventName); Entry slot; uint32_t id = _channel->Sequence(); - int32_t result = Send(eventName, parameters, id); - return (FireboltErrorValue(result)); + return Send(eventName, parameters, id); + } + + void NotifyStatus(Firebolt::Error status) + { + _listener(false, status); + } + + Firebolt::Error WaitForLinkReady() + { + uint32_t waiting = _waitTime; + static constexpr uint32_t SLEEPSLOT_TIME = 100; + + // Right, a wait till connection is closed is requested.. + while ((waiting > 0) && (IsOpen() == false) && (_status == Firebolt::Error::NotConnected)) { + + uint32_t sleepSlot = (waiting > SLEEPSLOT_TIME ? SLEEPSLOT_TIME : waiting); + + // Right, lets sleep in slices of 100 ms + SleepMs(sleepSlot); + + waiting -= (waiting == WPEFramework::Core::infinite ? 0 : sleepSlot); + } + return (((waiting == 0) || (IsOpen() == true)) ? Firebolt::Error::None : Firebolt::Error::Timedout); } private: @@ -619,7 +679,8 @@ namespace FireboltSDK { virtual void Opened() { - // Nice to know :-) + _status = Firebolt::Error::None; + _listener(true, _status); } void Closed() @@ -635,12 +696,13 @@ namespace FireboltSDK { } _adminLock.Unlock(); + _listener(false, _status); } int32_t Submit(const WPEFramework::Core::ProxyType& inbound) { int32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; - WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(inbound, this)); + WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(inbound, this)); WPEFramework::Core::IWorkerPool::Instance().Submit(job); return result; } @@ -684,7 +746,7 @@ namespace FireboltSDK { template - int32_t Send(const string& method, const PARAMETERS& parameters, const uint32_t& id) + Firebolt::Error Send(const string& method, const PARAMETERS& parameters, const uint32_t& id) { int32_t result = WPEFramework::Core::ERROR_UNAVAILABLE; @@ -718,11 +780,11 @@ namespace FireboltSDK { result = WPEFramework::Core::ERROR_NONE; } } - return result; + return FireboltErrorValue(result); } template - int32_t WaitForResponse(const uint32_t& id, RESPONSE& response, const uint32_t waitTime) + Firebolt::Error WaitForResponse(const uint32_t& id, RESPONSE& response, const uint32_t waitTime) { int32_t result = WPEFramework::Core::ERROR_TIMEDOUT; _adminLock.Lock(); @@ -753,14 +815,14 @@ namespace FireboltSDK { _adminLock.Lock(); _pendingQueue.erase(id); _adminLock.Unlock(); - return result; + return FireboltErrorValue(result); } static constexpr uint32_t WAITSLOT_TIME = 100; template - int32_t WaitForEventResponse(const uint32_t& id, const string& eventName, RESPONSE& response, const uint32_t waitTime) + Firebolt::Error WaitForEventResponse(const uint32_t& id, const string& eventName, RESPONSE& response, const uint32_t waitTime) { - int32_t result = WPEFramework::Core::ERROR_TIMEDOUT; + Firebolt::Error result = Firebolt::Error::Timedout; _adminLock.Lock(); typename PendingMap::iterator index = _pendingQueue.find(id); Entry& slot(index->second); @@ -776,14 +838,13 @@ namespace FireboltSDK { // that closed? if (jsonResponse.IsValid() == true) { if (jsonResponse->Error.IsSet() == true) { - result = jsonResponse->Error.Code.Value(); + result = FireboltErrorValue(jsonResponse->Error.Code.Value()); } else { if ((jsonResponse->Result.IsSet() == true) && (jsonResponse->Result.Value().empty() == false)) { - result = WPEFramework::Core::ERROR_NONE; bool enabled; result = _eventHandler->ValidateResponse(jsonResponse, enabled); - if (result == WPEFramework::Core::ERROR_NONE) { + if (result == Firebolt::Error::None) { FromMessage((INTERFACE*)&response, *jsonResponse); if (enabled) { _adminLock.Lock(); @@ -798,10 +859,10 @@ namespace FireboltSDK { } } } else { - result = WPEFramework::Core::ERROR_TIMEDOUT; + result = Firebolt::Error::Timedout; } waiting -= (waiting == WPEFramework::Core::infinite ? 0 : waitSlot); - } while ((result != WPEFramework::Core::ERROR_NONE) && (waiting > 0 )); + } while ((result != Firebolt::Error::None) && (waiting > 0 )); _adminLock.Lock(); _pendingQueue.erase(id); _adminLock.Unlock(); @@ -860,22 +921,20 @@ namespace FireboltSDK { return; } - int32_t FireboltErrorValue(const uint32_t error) + Firebolt::Error FireboltErrorValue(const uint32_t error) { - int32_t fireboltError = error; + Firebolt::Error fireboltError = static_cast(error); switch (error) { case WPEFramework::Core::ERROR_NONE: - fireboltError = FireboltSDKErrorNone; + fireboltError = Firebolt::Error::None; break; case WPEFramework::Core::ERROR_GENERAL: - fireboltError = FireboltSDKErrorGeneral; - break; case WPEFramework::Core::ERROR_UNAVAILABLE: - fireboltError = FireboltSDKErrorUnavailable; + fireboltError = Firebolt::Error::General; break; case WPEFramework::Core::ERROR_TIMEDOUT: - fireboltError = FireboltSDKErrorTimedout; + fireboltError = Firebolt::Error::Timedout; break; default: break; @@ -893,5 +952,7 @@ namespace FireboltSDK { EventMap _eventMap; uint64_t _scheduledTime; uint32_t _waitTime; + Listener _listener; + Firebolt::Error _status; }; } diff --git a/languages/cpp/src/shared/src/TypesPriv.h b/languages/cpp/src/shared/src/TypesPriv.h index 6e365ec7..224f0552 100644 --- a/languages/cpp/src/shared/src/TypesPriv.h +++ b/languages/cpp/src/shared/src/TypesPriv.h @@ -41,6 +41,12 @@ class String : public WPEFramework::Core::JSON::String { _value = RHS; return (*this); } + String& operator=(const string RHS) + { + Base::operator = (RHS); + _value = RHS; + return (*this); + } public: const string& Value() const diff --git a/languages/cpp/src/shared/test/CMakeLists.txt b/languages/cpp/src/shared/test/CMakeLists.txt index 21ee1f55..012f1a6d 100644 --- a/languages/cpp/src/shared/test/CMakeLists.txt +++ b/languages/cpp/src/shared/test/CMakeLists.txt @@ -63,7 +63,7 @@ set(TESTAPP "FireboltSDKTestApp") message("Setup ${TESTAPP}") -add_executable(${TESTAPP} Main.c) +add_executable(${TESTAPP} Main.cpp) target_link_libraries(${TESTAPP} PRIVATE diff --git a/languages/cpp/src/shared/test/Main.c b/languages/cpp/src/shared/test/Main.c deleted file mode 100644 index 6161792e..00000000 --- a/languages/cpp/src/shared/test/Main.c +++ /dev/null @@ -1,45 +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 "OpenRPCCTests.h" - -int __cnt = 0; -int __pass = 0; - -int TotalTests = 0; -int TotalTestsPassed = 0; - -int main() -{ - test_firebolt_create_instance(); - test_firebolt_main(); - - // Calling C function sequences - printf("%s:%s:%d Calling C function tests\n", __FILE__, __func__, __LINE__); - EXECUTE("test_properties_get_device_id", test_properties_get_device_id); - EXECUTE("test_properties_set", test_properties_set); - EXECUTE("test_eventregister_by_providing_callback", test_eventregister_by_providing_callback); - EXECUTE("test_eventregister", test_eventregister); - EXECUTE("test_eventregister_with_same_callback", test_eventregister_with_same_callback); - EXECUTE("test_string_set_get_value", test_string_set_get_value); - - test_firebolt_dispose_instance(); - - printf("TOTAL: %i tests; %i PASSED, %i FAILED\n", TotalTests, TotalTestsPassed, (TotalTests - TotalTestsPassed)); -} - diff --git a/languages/cpp/src/shared/test/OpenRPCTests.cpp b/languages/cpp/src/shared/test/OpenRPCTests.cpp index 03fd2645..8fc4f4fb 100644 --- a/languages/cpp/src/shared/test/OpenRPCTests.cpp +++ b/languages/cpp/src/shared/test/OpenRPCTests.cpp @@ -18,7 +18,6 @@ #include "Module.h" #include "OpenRPCTests.h" -#include "OpenRPCCTests.h" namespace WPEFramework { @@ -80,14 +79,14 @@ namespace FireboltSDK { } } - /* static */ int32_t Tests::GetDeviceId() + /* static */ Firebolt::Error Tests::GetDeviceId() { const string method = _T("device.id"); WPEFramework::Core::ProxyType response; - int32_t status = FireboltSDK::Properties::Get(method, response); + Firebolt::Error status = FireboltSDK::Properties::Get(method, response); - EXPECT_EQ(status, FireboltSDKErrorNone); - if (status == FireboltSDKErrorNone) { + EXPECT_EQ(status, Firebolt::Error::None); + if (status == Firebolt::Error::None) { FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "DeviceId : %s", response->Value().c_str()); } else { FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d\n", method.c_str(), status); @@ -96,14 +95,14 @@ namespace FireboltSDK { return status; } - /*static */ int32_t Tests::GetDeviceVersion() + /*static */ Firebolt::Error Tests::GetDeviceVersion() { const string method = _T("device.version"); WPEFramework::Core::ProxyType response; - int32_t status = FireboltSDK::Properties::Get(method, response); + Firebolt::Error status = FireboltSDK::Properties::Get(method, response); - EXPECT_EQ(status, FireboltSDKErrorNone); - if (status == FireboltSDKErrorNone) { + EXPECT_EQ(status, Firebolt::Error::None); + if (status == Firebolt::Error::None) { FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "DeviceVersion"); PrintJsonObject(response->Variants()); } else { @@ -113,43 +112,43 @@ namespace FireboltSDK { return status; } - /* static */ int32_t Tests::GetUnKnownMethod() + /* static */ Firebolt::Error Tests::GetUnKnownMethod() { const string method = _T("get.unknownMethod"); WPEFramework::Core::ProxyType response; - int32_t status = FireboltSDK::Properties::Get(method, response); + Firebolt::Error status = FireboltSDK::Properties::Get(method, response); - EXPECT_NE(status, FireboltSDKErrorNone); - if (status != FireboltSDKErrorNone) { + EXPECT_NE(status, Firebolt::Error::None); + if (status != Firebolt::Error::None) { FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Get %s status = %d\n", method.c_str(), status); } return status; } - /* static */ int32_t Tests::SetLifeCycleClose() + /* static */ Firebolt::Error Tests::SetLifeCycleClose() { const string method = _T("lifecycle.close"); JsonObject parameters; parameters["reason"] = "remoteButton"; - int32_t status = FireboltSDK::Properties::Set(method, parameters); + Firebolt::Error status = FireboltSDK::Properties::Set(method, parameters); - EXPECT_EQ(status, FireboltSDKErrorNone); - if (status != FireboltSDKErrorNone) { + EXPECT_EQ(status, Firebolt::Error::None); + if (status != Firebolt::Error::None) { FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d\n", method.c_str(), status); } return status; } - /* static */ int32_t Tests::SetUnKnownMethod() + /* static */ Firebolt::Error Tests::SetUnKnownMethod() { const string method = _T("set.unknownMethod"); JsonObject parameters; - int32_t status = FireboltSDK::Properties::Set(method, parameters); + Firebolt::Error status = FireboltSDK::Properties::Set(method, parameters); - EXPECT_NE(status, FireboltSDKErrorNone); - if (status != FireboltSDKErrorNone) { + EXPECT_NE(status, Firebolt::Error::None); + if (status != Firebolt::Error::None) { FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", method.c_str(), status); } @@ -167,7 +166,7 @@ namespace FireboltSDK { jsonResponse.Release(); } - /* static */ int32_t Tests::SubscribeEvent() + /* static */ Firebolt::Error Tests::SubscribeEvent() { FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl("EventControl"); const string eventName = _T("device.Name"); @@ -176,10 +175,10 @@ namespace FireboltSDK { eventControl->ResetEvent(); JsonObject jsonParameters; - int32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); + Firebolt::Error status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); - EXPECT_EQ(status, FireboltSDKErrorNone); - if (status != FireboltSDKErrorNone) { + EXPECT_EQ(status, Firebolt::Error::None); + if (status != Firebolt::Error::None) { FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", eventName.c_str(), status); } else { @@ -189,13 +188,13 @@ namespace FireboltSDK { eventControl->WaitForEvent(WPEFramework::Core::infinite); } - EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), Firebolt::Error::None); delete eventControl; return status; } - /* static */ int32_t Tests::SubscribeEventwithSameCallback() + /* static */ Firebolt::Error Tests::SubscribeEventwithSameCallback() { FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl("EventControl"); const string eventName = _T("device.Name"); @@ -204,10 +203,10 @@ namespace FireboltSDK { eventControl->ResetEvent(); JsonObject jsonParameters; - int32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); + Firebolt::Error status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback,reinterpret_cast(NotifyEvent), userdata); - EXPECT_EQ(status, FireboltSDKErrorNone); - if (status != FireboltSDKErrorNone) { + EXPECT_EQ(status, Firebolt::Error::None); + if (status != Firebolt::Error::None) { FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", eventName.c_str(), status); } else { @@ -215,15 +214,15 @@ namespace FireboltSDK { "%s Yes registered successfully", __func__); status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallback, reinterpret_cast(NotifyEvent), userdata); - EXPECT_EQ(status, FireboltSDKErrorInUse); - if (status == FireboltSDKErrorInUse) { + EXPECT_EQ(status, Firebolt::Error::General); + if (status == Firebolt::Error::General) { FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "%s Yes this device.name event is already registered with same callback", __func__); } - status = ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone : status); + status = ((status == Firebolt::Error::General) ? Firebolt::Error::None : status); } - EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), Firebolt::Error::None); delete eventControl; return status; @@ -250,7 +249,7 @@ namespace FireboltSDK { } template - /* static */ int32_t Tests::SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata) + /* static */ Firebolt::Error Tests::SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata) { return Properties::Subscribe(eventName, jsonParameters, callbackFunc, usercb, userdata); } @@ -268,7 +267,7 @@ namespace FireboltSDK { jsonResponse.Release(); } - /* static */ int32_t Tests::SubscribeEventWithMultipleCallback() + /* static */ Firebolt::Error Tests::SubscribeEventWithMultipleCallback() { FireboltSDK::Tests::EventControl* eventControl1 = new FireboltSDK::Tests::EventControl("EventControl1"); const string eventName = _T("device.Name"); @@ -277,10 +276,10 @@ namespace FireboltSDK { eventControl1->ResetEvent(); JsonObject jsonParameters; - int32_t status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent1), userdata); + Firebolt::Error status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent1), userdata); - EXPECT_EQ(status, FireboltSDKErrorNone); - if (status != FireboltSDKErrorNone) { + EXPECT_EQ(status, Firebolt::Error::None); + if (status != Firebolt::Error::None) { FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", eventName.c_str(), status); } else { @@ -288,19 +287,19 @@ namespace FireboltSDK { "%s Yes registered successfully, Waiting for event...", __func__); } - if (status == FireboltSDKErrorNone) { + if (status == Firebolt::Error::None) { FireboltSDK::Tests::EventControl* eventControl2 = new FireboltSDK::Tests::EventControl("EventControl2"); userdata = static_cast(eventControl2); status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent2), userdata); - EXPECT_EQ(status, FireboltSDKErrorNone); - if (status != FireboltSDKErrorNone) { + EXPECT_EQ(status, Firebolt::Error::None); + if (status != Firebolt::Error::None) { FIREBOLT_LOG_ERROR(Logger::Category::OpenRPC, Logger::Module(), "Set %s status = %d", eventName.c_str(), status); } else { status = Properties::Subscribe(eventName, jsonParameters, deviceNameChangeMultipleCallback, reinterpret_cast(NotifyEvent2), userdata); - EXPECT_EQ(status, FireboltSDKErrorInUse); - status = ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone : status); + EXPECT_EQ(status, Firebolt::Error::General); + status = ((status == Firebolt::Error::General) ? Firebolt::Error::None : status); FIREBOLT_LOG_INFO(Logger::Category::OpenRPC, Logger::Module(), "%s Yes registered second callback also successfully, waiting for events...\n", __func__); @@ -308,197 +307,13 @@ namespace FireboltSDK { eventControl1->WaitForEvent(WPEFramework::Core::infinite); eventControl2->WaitForEvent(WPEFramework::Core::infinite); } - EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent2)), FireboltSDKErrorNone); + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent2)), Firebolt::Error::None); delete eventControl2; } - EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent1)), FireboltSDKErrorNone); + EXPECT_EQ(Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent1)), Firebolt::Error::None); delete eventControl1; return status; } } - -#ifdef __cplusplus -extern "C" { -#endif - -void test_firebolt_create_instance() -{ - 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); -} - -void test_firebolt_dispose_instance() -{ - FireboltSDK::Accessor::Dispose(); -} - -int32_t test_firebolt_main() -{ - return FireboltSDK::Tests::Main(); -} - -int32_t test_properties_get_device_id() -{ - const string method = _T("device.id"); - WPEFramework::Core::ProxyType response; - int32_t status = FireboltSDK::Properties::Get(method, response); - - EXPECT_EQ(status, FireboltSDKErrorNone); - if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "DeviceId : %s", response->Value().c_str()); - } else { - FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "Get %s status = %d", method.c_str(), status); - } - - return status; -} - -int32_t test_properties_set() -{ - const string method = _T("lifecycle.close"); - JsonObject parameters; - parameters["reason"] = "remoteButton"; - int32_t status = FireboltSDK::Properties::Set(method, parameters); - - EXPECT_EQ(status, FireboltSDKErrorNone); - if (status != FireboltSDKErrorNone) { - FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "Set %s status = %d", method.c_str(), status); - } - - return status; -} - -static void deviceNameChangeCallbackForC(void* userCB, const void* userData, void* response) -{ - WPEFramework::Core::ProxyType& jsonResponse = *(reinterpret_cast*>(response)); - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "Received a new event--->: %s", jsonResponse->Value().c_str()); - - FireboltSDK::Tests::EventControl* eventControl = reinterpret_cast(const_cast(userData)); - eventControl->NotifyEvent(); - jsonResponse.Release(); -} - -int32_t test_eventregister() -{ - FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); - const string eventName = _T("device.Name"); - const void* userdata = static_cast(eventControl); - - eventControl->ResetEvent(); - - JsonObject jsonParameters; - int32_t status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); - - EXPECT_EQ(status, FireboltSDKErrorNone); - if (status != FireboltSDKErrorNone) { - FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "%s Set %s status = %d", __func__, eventName.c_str(), status); - } else { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "%s Yes registered successfully, Waiting for event...", __func__); - eventControl->WaitForEvent(WPEFramework::Core::infinite); - } - - delete eventControl; - EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); - - return status; -} - -int32_t test_eventregister_with_same_callback() -{ - FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); - const string eventName = _T("device.Name"); - const void* userdata = static_cast(eventControl); - - eventControl->ResetEvent(); - - JsonObject jsonParameters; - int32_t status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); - - EXPECT_EQ(status, FireboltSDKErrorNone); - if (status != FireboltSDKErrorNone) { - FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "%s Set %s status = %d", __func__, eventName.c_str(), status); - } else { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "%s Yes registered successfully", __func__); - - status = FireboltSDK::Properties::Subscribe(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); - EXPECT_EQ(status, FireboltSDKErrorInUse); - if (status == FireboltSDKErrorInUse) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "%s Yes this device.name event is already registered with same callback", __func__); - } - status = ((status == FireboltSDKErrorInUse) ? FireboltSDKErrorNone : status); - } - - delete eventControl; - EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); - - return status; -} -int32_t test_eventregister_by_providing_callback() -{ - FireboltSDK::Tests::EventControl* eventControl = new FireboltSDK::Tests::EventControl(); - - const string eventName = _T("device.Name"); - const void* userdata = static_cast(eventControl); - - eventControl->ResetEvent(); - - JsonObject jsonParameters; - int32_t status = FireboltSDK::Tests::SubscribeEventForC(eventName, jsonParameters, deviceNameChangeCallbackForC, reinterpret_cast(NotifyEvent), userdata); - - EXPECT_EQ(status, FireboltSDKErrorNone); - if (status != FireboltSDKErrorNone) { - FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "%s Set %s status = %d", __func__, eventName.c_str(), status); - } else { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", - "%s Yes registered successfully, Waiting for event...", __func__); - eventControl->WaitForEvent(WPEFramework::Core::infinite); - } - - delete eventControl; - EXPECT_EQ(FireboltSDK::Properties::Unsubscribe(eventName, reinterpret_cast(NotifyEvent)), FireboltSDKErrorNone); - return status; -} - -#include "TypesPriv.h" -int32_t test_string_set_get_value() -{ - int32_t status = FireboltSDKErrorNone; - FireboltSDK::JSON::String* str = new FireboltSDK::JSON::String(); - WPEFramework::Core::JSON::String wpeJsonStr("TestString"); - Firebolt_String_t handle = reinterpret_cast(str); - - const char* value = Firebolt_String(handle); - EXPECT_EQ(strncmp(value, str->Value().c_str(), str->Value().length()), 0); - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", - " ---> type name = %s %s", str->Value().c_str(), value); - - WPEFramework::Core::JSON::EnumType<::TestEnum> testEnum = Test4; - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, "ctest", - " EnumTest = %d %s", testEnum.Value(), testEnum.Data()); - Firebolt_String_Release(handle); - return status; -} - -#ifdef __cplusplus -} -#endif diff --git a/languages/cpp/src/shared/test/OpenRPCTests.h b/languages/cpp/src/shared/test/OpenRPCTests.h index 8eb7fd30..9c84bcf4 100644 --- a/languages/cpp/src/shared/test/OpenRPCTests.h +++ b/languages/cpp/src/shared/test/OpenRPCTests.h @@ -29,7 +29,7 @@ typedef enum { } TestEnum; namespace FireboltSDK { - typedef int32_t (*Func)(); + typedef Firebolt::Error (*Func)(); class Tests { public: @@ -94,19 +94,19 @@ namespace FireboltSDK { return 0; } - static int32_t GetDeviceId(); - static int32_t GetDeviceVersion(); - static int32_t GetUnKnownMethod(); + static Firebolt::Error GetDeviceId(); + static Firebolt::Error GetDeviceVersion(); + static Firebolt::Error GetUnKnownMethod(); - static int32_t SetLifeCycleClose(); - static int32_t SetUnKnownMethod(); + static Firebolt::Error SetLifeCycleClose(); + static Firebolt::Error SetUnKnownMethod(); - static int32_t SubscribeEvent(); - static int32_t SubscribeEventwithSameCallback(); - static int32_t SubscribeEventWithMultipleCallback(); + static Firebolt::Error SubscribeEvent(); + static Firebolt::Error SubscribeEventwithSameCallback(); + static Firebolt::Error SubscribeEventWithMultipleCallback(); template - static int32_t SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata); + static Firebolt::Error SubscribeEventForC(const string& eventName, JsonObject& jsonParameters, CALLBACK& callbackFunc, void* usercb, const void* userdata); protected: static void PrintJsonObject(const JsonObject::Iterator& iterator); diff --git a/languages/cpp/templates/codeblocks/setter.c b/languages/cpp/templates/codeblocks/setter.c index c66068bc..ffe24fc6 100644 --- a/languages/cpp/templates/codeblocks/setter.c +++ b/languages/cpp/templates/codeblocks/setter.c @@ -1,7 +1,16 @@ -/* ${method.rpc.name} - ${method.description} */ -int32_t ${method.Name}( ${method.signature.params} ) -{ - const string method = _T("${info.title.lowercase}.${method.rpc.name}"); + + /* ${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} - return FireboltSDK::Properties::Set(method, jsonParameters); -} + + 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/declarations/default.c b/languages/cpp/templates/declarations/default.c index 2c19a1ef..e69de29b 100644 --- a/languages/cpp/templates/declarations/default.c +++ b/languages/cpp/templates/declarations/default.c @@ -1,6 +0,0 @@ - /* - ${method.name} - ${method.description} - ${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation}${end.if.deprecated} - */ - virtual int32_t ${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}${method.result.type}& ${method.result.name}${end.if.result} ) = 0; \ No newline at end of file diff --git a/languages/cpp/templates/declarations/event.c b/languages/cpp/templates/declarations/event.c index d2df4f12..8939efc8 100644 --- a/languages/cpp/templates/declarations/event.c +++ b/languages/cpp/templates/declarations/event.c @@ -1,8 +1,8 @@ /* ${method.name} - ${method.description} */ struct I${method.Name}Notification { - virtual void ${method.Name} ( ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${method.result.properties} ) = 0; + virtual void ${method.Name}( ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${event.result.type} ) = 0; }; // signature callback params: ${event.signature.callback.params} // method result properties : ${method.result.properties} - virtual int32_t subscribe ( ${event.signature.params}${if.event.params}, ${end.if.event.params}I${method.Name}Notification& notification ) = 0; - virtual int32_t unsubscribe ( I${method.Name}Notification& notification ) = 0; \ No newline at end of file + virtual void Subscribe( ${event.signature.params}${if.event.params}, ${end.if.event.params}I${method.Name}Notification& notification, Firebolt::Error *err = nullptr ) = 0; + virtual void Unsubscribe( I${method.Name}Notification& notification, Firebolt::Error *err = nullptr ) = 0; diff --git a/languages/cpp/templates/declarations/polymorphic-pull-event.c b/languages/cpp/templates/declarations/polymorphic-pull-event.c index 178678ad..e69de29b 100644 --- a/languages/cpp/templates/declarations/polymorphic-pull-event.c +++ b/languages/cpp/templates/declarations/polymorphic-pull-event.c @@ -1,8 +0,0 @@ - /* ${method.name} - ${method.description} */ - struct I{method.Name}Notification { - virtual void ${method.Name} ( ${method.pulls.param.type}& value ) = 0; - }; - - virtual int32_t subscribe ( I{method.Name}Notification& notification ) = 0; - virtual int32_t unsubscribe ( I{method.Name}Notification& notification ) = 0; - diff --git a/languages/cpp/templates/declarations/polymorphic-pull.c b/languages/cpp/templates/declarations/polymorphic-pull.c index 6588a635..e69de29b 100644 --- a/languages/cpp/templates/declarations/polymorphic-pull.c +++ b/languages/cpp/templates/declarations/polymorphic-pull.c @@ -1,2 +0,0 @@ - /* ${method.name} - ${method.description} */ - virtual int32_t ${method.Name}( ${method.signature.params} ) = 0; diff --git a/languages/cpp/templates/declarations/polymorphic-reducer.c b/languages/cpp/templates/declarations/polymorphic-reducer.c index a6f50d1b..e69de29b 100644 --- a/languages/cpp/templates/declarations/polymorphic-reducer.c +++ b/languages/cpp/templates/declarations/polymorphic-reducer.c @@ -1,5 +0,0 @@ - /* - * ${method.summary} - * ${method.params} - */ - virtual int32_t ${method.Name}(${method.signature.params}${if.result.properties}${if.params}, ${end.if.params}${end.if.result.properties}${method.result.properties}) = 0; diff --git a/languages/cpp/templates/declarations/property.h b/languages/cpp/templates/declarations/property.h index 09cc5d7d..6d8890e4 100644 --- a/languages/cpp/templates/declarations/property.h +++ b/languages/cpp/templates/declarations/property.h @@ -1,5 +1,5 @@ /* - * ${method.description} - * ${method.params} - */ -virtual int32_t ${method.Name} (${method.signature.params}${if.params}, ${end.if.params}${method.result.properties}) = 0; + * ${method.description} + * ${method.params} + */ + virtual ${method.signature.result} ${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr ) const = 0; diff --git a/languages/cpp/templates/declarations/setter.h b/languages/cpp/templates/declarations/setter.h index 64e4d19e..b1035bc4 100644 --- a/languages/cpp/templates/declarations/setter.h +++ b/languages/cpp/templates/declarations/setter.h @@ -1,5 +1,5 @@ /* - ${method.rpc.name} - ${method.description} - */ - virtual int32_t ${method.Name}( ${method.signature.params} ) = 0; + ${method.rpc.name} + ${method.description} + */ + virtual void ${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr ) = 0; diff --git a/languages/cpp/templates/methods/calls-metrics.c b/languages/cpp/templates/methods/calls-metrics.c index d38c499f..8b137891 100644 --- a/languages/cpp/templates/methods/calls-metrics.c +++ b/languages/cpp/templates/methods/calls-metrics.c @@ -1,29 +1 @@ -/* ${method.rpc.name} - ${method.description} */ -void Metrics_${method.Name}Dispatcher(const void*${if.result} result${end.if.result}) { - Metrics_${method.Name}(${if.result}(static_cast<${method.result.json.type}>(const_cast(result)))${end.if.result}); -} -int32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}OUT ${method.result.type}* ${method.result.name}${end.if.result}${if.signature.empty}void${end.if.signature.empty} ) { - int32_t status = FireboltSDKErrorUnavailable; - FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); - if (transport != nullptr) { - - ${method.params.serialization.with.indent} - ${method.result.json.type} jsonResult; - status = transport->Invoke("${info.title}.${method.rpc.name}", jsonParameters, jsonResult); - if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); - ${method.result.instantiation.with.indent} - - void* result = nullptr; - ${if.result}result = static_cast(new ${method.result.json.type});${end.if.result} - WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(Metrics_${method.Name}Dispatcher, result)); - WPEFramework::Core::IWorkerPool::Instance().Submit(job); - } - - } else { - FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); - } - - return status; -} diff --git a/languages/cpp/templates/methods/default.c b/languages/cpp/templates/methods/default.c index c375d30f..e69de29b 100644 --- a/languages/cpp/templates/methods/default.c +++ b/languages/cpp/templates/methods/default.c @@ -1,21 +0,0 @@ -/* ${method.rpc.name} - ${method.description} */ -int32_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} ) { - - int32_t status = FireboltSDKErrorUnavailable; - FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); - if (transport != nullptr) { - - ${method.params.serialization.with.indent} - ${method.result.json.type} jsonResult; - status = transport->Invoke("${info.title.lowercase}.${method.rpc.name}", jsonParameters, jsonResult); - if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); - ${method.result.instantiation.with.indent} - } - - } else { - FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); - } - - return status; -} diff --git a/languages/cpp/templates/methods/event.c b/languages/cpp/templates/methods/event.c index 85ae3b48..8745c653 100644 --- a/languages/cpp/templates/methods/event.c +++ b/languages/cpp/templates/methods/event.c @@ -1,27 +1,33 @@ -/* ${method.rpc.name} - ${method.description} */ -static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) -{ + /* ${method.rpc.name} - ${method.description} */ + static void ${info.Title}${method.Name}InnerCallback( void* notification, const void* userData, void* jsonResponse ) + { ${event.callback.params.serialization} - ASSERT(jsonResponse->IsValid() == true); - if (jsonResponse->IsValid() == true) { + ASSERT(proxyResponse->IsValid() == true); + + if (proxyResponse->IsValid() == true) { ${event.callback.result.instantiation} - ${info.Title}${method.Name}Callback callback = reinterpret_cast<${info.Title}${method.Name}Callback>(userCB); - callback(userData, ${event.callback.response.instantiation}); - } -} -int32_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.lowercase}.${method.rpc.name}"); - int32_t status = FireboltSDKErrorNone; + proxyResponse->Release(); - if (userCB != nullptr) { - ${event.params.serialization} - status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${info.Title}${method.Name}InnerCallback, reinterpret_cast(userCB), userData); - } - return status; -} -int32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB) -{ - return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); -} + 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/polymorphic-pull-event.c b/languages/cpp/templates/methods/polymorphic-pull-event.c index 49aa1dba..e69de29b 100644 --- a/languages/cpp/templates/methods/polymorphic-pull-event.c +++ b/languages/cpp/templates/methods/polymorphic-pull-event.c @@ -1,54 +0,0 @@ -/* ${method.rpc.name} - ${method.description} */ -static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response ) -{ -${event.callback.params.serialization} - ASSERT(jsonResponse->IsValid() == true); - if (jsonResponse->IsValid() == true) { - - ${info.Title}${method.Name}Callback callback = reinterpret_cast<${info.Title}${method.Name}Callback>(userCB); - - WPEFramework::Core::ProxyType<${method.pulls.param.json.type}>* requestParam = new WPEFramework::Core::ProxyType<${method.pulls.param.json.type}>(); - *requestParam = WPEFramework::Core::ProxyType<${method.pulls.param.json.type}>::Create(); - *(*requestParam) = (*jsonResponse)->${event.pulls.param.name}Parameters; - - ${method.pulls.type} result = reinterpret_cast<${method.pulls.type}>(callback(userData, reinterpret_cast<${method.pulls.param.type}>(requestParam))); - - JsonObject jsonParameters; - WPEFramework::Core::JSON::Variant CorrelationId = (*jsonResponse)->CorrelationId.Value(); - jsonParameters.Set(_T("correlationId"), CorrelationId); - - ${method.pulls.json.type}& resultObj = *(*(reinterpret_cast*>(result))); - string resultStr; - resultObj.ToString(resultStr); - WPEFramework::Core::JSON::VariantContainer resultContainer(resultStr); - WPEFramework::Core::JSON::Variant Result = resultContainer; - jsonParameters.Set(_T("result"), Result); - - FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); - if (transport != nullptr) { - WPEFramework::Core::JSON::Boolean jsonResult; - int32_t status = transport->Invoke(_T("${info.title.lowercase}.${method.pulls.for}"), jsonParameters, jsonResult); - if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully pushed with status as %d", jsonResult.Value()); - } - } else { - FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport"); - } - } -} -int32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callback userCB, const void* userData ) -{ - const string eventName = _T("${info.title.lowercase}.${method.rpc.name}"); - int32_t status = FireboltSDKErrorNone; - - if (userCB != nullptr) { - ${event.params.serialization} - status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${info.Title}${method.Name}InnerCallback, reinterpret_cast(userCB), userData); - } - return status; -} -int32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB) -{ - return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(userCB)); -} - diff --git a/languages/cpp/templates/methods/polymorphic-pull.c b/languages/cpp/templates/methods/polymorphic-pull.c index 840566e2..e69de29b 100644 --- a/languages/cpp/templates/methods/polymorphic-pull.c +++ b/languages/cpp/templates/methods/polymorphic-pull.c @@ -1,22 +0,0 @@ -/* ${method.rpc.name} - ${method.description} */ -int32_t ${info.Title}_Push${method.Name}( ${method.signature.params} ) -{ - int32_t status = FireboltSDKErrorUnavailable; - - FireboltSDK::Transport* 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.lowercase}.${method.rpc.name}"), jsonParameters, jsonResult); - if (status == FireboltSDKErrorNone) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully pushed with status as %d", jsonResult.Value()); - status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported; - } - } else { - FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport"); - } - - return status; -} diff --git a/languages/cpp/templates/methods/property.c b/languages/cpp/templates/methods/property.c index 7f375d81..f3d91141 100644 --- a/languages/cpp/templates/methods/property.c +++ b/languages/cpp/templates/methods/property.c @@ -1,14 +1,17 @@ -/* ${method.rpc.name} - ${method.description} */ -int32_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.lowercase}.${method.rpc.name}"); -${if.params}${method.params.serialization}${end.if.params} - ${method.result.json} jsonResult; - ${if.params}int32_t status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult);${end.if.params} - ${if.params.empty}int32_t status = FireboltSDK::Properties::Get(method, jsonResult);${end.if.params.empty} - if (status == FireboltSDKErrorNone) { + /* ${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} - } - return status; -} -${method.setter} + } + if (err != nullptr) { + *err = status; + } + return ${method.result.name}; + }${method.setter} \ No newline at end of file diff --git a/languages/cpp/templates/modules/include/module.h b/languages/cpp/templates/modules/include/module.h index 462c9a30..6080265e 100644 --- a/languages/cpp/templates/modules/include/module.h +++ b/languages/cpp/templates/modules/include/module.h @@ -18,24 +18,28 @@ #pragma once -#include +#include "error.h" /* ${IMPORTS} */ ${if.declarations}namespace Firebolt { namespace ${info.Title} { +${if.enums} // Enums - /* ${ENUMS} */ - +/* ${ENUMS} */${end.if.enums} +${if.types} // Types /* ${TYPES} */ - +${end.if.types} struct I${info.Title} { - virtual ~I${info.Title} = default; + static I${info.Title}& Instance(); + static void Dispose(); + + virtual ~I${info.Title}() = default; -// Methods & Events -/* ${DECLARATIONS} */ + // Methods & Events + /* ${DECLARATIONS} */ }; diff --git a/languages/cpp/templates/modules/src/module.cpp b/languages/cpp/templates/modules/src/module.cpp index 8cef2390..ebdbb0b7 100644 --- a/languages/cpp/templates/modules/src/module.cpp +++ b/languages/cpp/templates/modules/src/module.cpp @@ -20,22 +20,70 @@ /* ${IMPORTS} */ #include "${info.title.lowercase}.h" -${if.types}namespace Firebolt { +${if.implementations} +namespace Firebolt { +namespace ${info.Title} { +${if.enums} -/* ${ENUMS:json-types} */ +/* ${ENUMS:json-types} */${end.if.enums} +${if.types} + // Types +/* ${TYPES:json-types} */${end.if.types} -${if.definitions}namespace ${info.Title} { + ${if.definitions}class ${info.Title}Impl : public I${info.Title} { + private: + ${info.Title}Impl() + { + ASSERT(_singleton == nullptr); + _singleton = this; + } -// Types - /* ${TYPES:json-types} */ + public: + ${info.Title}Impl(const ${info.Title}Impl&) = delete; + ${info.Title}Impl& operator=(const ${info.Title}Impl&) = delete; -// Methods -/* ${METHODS} */ + ~${info.Title}Impl() + { + ASSERT(_singleton != nullptr); + _singleton = nullptr; + } -// Events -/* ${EVENTS} */ + 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; + } + } -}${end.if.definitions} -}${end.if.types} \ No newline at end of file + + // 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/templates/schemas/include/common/module.h b/languages/cpp/templates/schemas/include/common/module.h index 5628e5b3..87ba7425 100644 --- a/languages/cpp/templates/schemas/include/common/module.h +++ b/languages/cpp/templates/schemas/include/common/module.h @@ -18,19 +18,18 @@ #pragma once -#include +#include "error.h" /* ${IMPORTS} */ -namespace Firebolt { +${if.declarations}namespace Firebolt { namespace ${info.Title} { - +${if.enums} // Enums -/* ${ENUMS} */ - +/* ${ENUMS} */${end.if.enums} +${if.types} // Types -/* ${TYPES} */ - +/* ${TYPES} */${end.if.types} } //namespace ${info.Title} -} +}${end.if.declarations} diff --git a/languages/cpp/templates/schemas/src/jsondata_module.h b/languages/cpp/templates/schemas/src/jsondata_module.h index 6e220163..916b8698 100644 --- a/languages/cpp/templates/schemas/src/jsondata_module.h +++ b/languages/cpp/templates/schemas/src/jsondata_module.h @@ -23,8 +23,8 @@ ${if.schemas}namespace Firebolt { namespace ${info.Title} { - // Types + // Types /* ${SCHEMAS:json-types} */ - } +} }${end.if.schemas} diff --git a/languages/cpp/templates/schemas/src/module_common.cpp b/languages/cpp/templates/schemas/src/module_common.cpp index 5570982c..87498ab8 100644 --- a/languages/cpp/templates/schemas/src/module_common.cpp +++ b/languages/cpp/templates/schemas/src/module_common.cpp @@ -19,23 +19,11 @@ #include "FireboltSDK.h" /* ${IMPORTS} */ #include "jsondata_${info.title.lowercase}.h" +${if.enums} -namespace Firebolt { +namespace WPEFramework { /* ${ENUMS} */ -namespace ${info.Title} { - - -// Methods -/* ${METHODS} */ - -// Events -/* ${EVENTS} */ - - -} //namespace ${info.Title} - -} - +}${end.if.enums} diff --git a/languages/cpp/templates/sections/methods.h b/languages/cpp/templates/sections/methods.h index 3ab606c0..e8200eb0 100644 --- a/languages/cpp/templates/sections/methods.h +++ b/languages/cpp/templates/sections/methods.h @@ -1,4 +1 @@ - -// Methods - ${method.list} diff --git a/languages/cpp/templates/types/enum.cpp b/languages/cpp/templates/types/enum.cpp index 9c98f888..e162ef43 100644 --- a/languages/cpp/templates/types/enum.cpp +++ b/languages/cpp/templates/types/enum.cpp @@ -1,4 +1,4 @@ /* ${title} ${description} */ - ENUM_CONVERSION_BEGIN(${info.Title}_${name}) - { ${info.TITLE}_${NAME}_${key}, _T("${value}") }, - ENUM_CONVERSION_END(${info.Title}_${name}) + ENUM_CONVERSION_BEGIN(Firebolt::${info.Title}::${name}) + { Firebolt::${info.Title}::${name}::${key}, _T("${value}") }, + ENUM_CONVERSION_END(Firebolt::${info.Title}::${name}) From b7a27f09b2999affc5b594ca60d8282866e322a5 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Tue, 10 Oct 2023 09:19:31 +0530 Subject: [PATCH 104/137] CPPSDK: namespace settings changes (#135) --- languages/cpp/templates/types/namespace.h | 2 +- src/macrofier/types.mjs | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/languages/cpp/templates/types/namespace.h b/languages/cpp/templates/types/namespace.h index 626de353..b3afde8a 100644 --- a/languages/cpp/templates/types/namespace.h +++ b/languages/cpp/templates/types/namespace.h @@ -1 +1 @@ -${parent.Title}:: \ No newline at end of file +${if.namespace.notsame}${parent.Title}::${end.if.namespace.notsame} \ No newline at end of file diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index 8506161e..d6e53788 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -56,7 +56,7 @@ function getMethodSignatureParams(method, module, { destination, callback }) { const paramRequired = getTemplate('/parameters/default') const paramOptional = getTemplate('/parameters/optional') return method.params.map(param => { - let type = getSchemaType(param.schema, module, { destination }) + let type = getSchemaType(param.schema, module, { destination, namespace : true }) if (callback && allocatedPrimitiveProxies[type]) { type = allocatedPrimitiveProxies[type] } @@ -97,6 +97,7 @@ function insertSchemaMacros(content, schema, module, name, parent, property, rec .replace(/\$\{TITLE\}/g, title.toUpperCase()) .replace(/\$\{property\}/g, property) .replace(/\$\{Property\}/g, capitalize(property)) + .replace(/\$\{if\.namespace\.notsame}(.*?)\$\{end\.if\.namespace\.notsame\}/g, (module.info.title !== parent) ? '$1' : '') .replace(/\$\{parent\.title\}/g, parent) .replace(/\$\{parent\.Title\}/g, capitalize(parent)) .replace(/\$\{description\}/g, schema.description ? schema.description : '') @@ -106,10 +107,9 @@ function insertSchemaMacros(content, schema, module, name, parent, property, rec .replace(/\$\{info.title\}/g, moduleTitle) .replace(/\$\{info.Title\}/g, capitalize(moduleTitle)) .replace(/\$\{info.TITLE\}/g, moduleTitle.toUpperCase()) - // .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module, { name: title })) if (recursive) { - content = content.replace(/\$\{type\}/g, getSchemaType(schema, module, { name: title, destination: state.destination, section: state.section, code: false })) + content = content.replace(/\$\{type\}/g, getSchemaType(schema, module, { name: title, destination: state.destination, section: state.section, code: false, namespace: true })) } return content } @@ -203,7 +203,7 @@ const insertObjectMacros = (content, schema, module, title, property, options) = if (schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { type = schema.additionalProperties } - + if (schema.patternProperties) { Object.entries(schema.patternProperties).forEach(([pattern, schema]) => { let regex = new RegExp(pattern) @@ -591,7 +591,7 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin if (schema.title) { union.title = schema.title } - return getSchemaType(union, module, { destination, link, title, code, asPath, baseUrl }) + return getSchemaType(union, module, { destination, link, title, code, asPath, baseUrl, namespace }) } else if (schema.oneOf || schema.anyOf) { if (!schema.anyOf) { From 5695efe54635faf910e719c46d2969afd4ae0976 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Wed, 18 Oct 2023 09:09:23 +0530 Subject: [PATCH 105/137] CPP SDK : changes to handle additional Properties (#134) CPP SDK : changes to handle additional Properties --- .../templates/types/additionalProperties.h | 2 +- .../templates/types/additionalPropertiesKey.h | 1 + src/macrofier/types.mjs | 101 ++++++++++++------ 3 files changed, 72 insertions(+), 32 deletions(-) create mode 100644 languages/cpp/templates/types/additionalPropertiesKey.h diff --git a/languages/cpp/templates/types/additionalProperties.h b/languages/cpp/templates/types/additionalProperties.h index baa50800..05581106 100644 --- a/languages/cpp/templates/types/additionalProperties.h +++ b/languages/cpp/templates/types/additionalProperties.h @@ -1 +1 @@ -${title} value; \ No newline at end of file +std::unordered_map<${key}, ${type}> ${title}; diff --git a/languages/cpp/templates/types/additionalPropertiesKey.h b/languages/cpp/templates/types/additionalPropertiesKey.h new file mode 100644 index 00000000..9c1a95b6 --- /dev/null +++ b/languages/cpp/templates/types/additionalPropertiesKey.h @@ -0,0 +1 @@ +std::string diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index d6e53788..7c627fce 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -30,6 +30,7 @@ const primitives = { "string": "string" } +const isPrimitiveType = type => primitives[type] ? true : false const allocatedPrimitiveProxies = {} function setTemplates(t) { @@ -109,7 +110,7 @@ function insertSchemaMacros(content, schema, module, name, parent, property, rec .replace(/\$\{info.TITLE\}/g, moduleTitle.toUpperCase()) if (recursive) { - content = content.replace(/\$\{type\}/g, getSchemaType(schema, module, { name: title, destination: state.destination, section: state.section, code: false, namespace: true })) + content = content.replace(/\$\{type\}/g, getSchemaType(schema, module, { destination: state.destination, section: state.section, code: false, namespace: true })) } return content } @@ -137,13 +138,40 @@ const insertEnumMacros = (content, schema, module, name) => { return template.join('\n') } -const insertObjectMacros = (content, schema, module, title, property, options) => { - options = options ? JSON.parse(JSON.stringify(options)) : {} +const insertObjectAdditionalPropertiesMacros = (content, schema, module, title, options) => { + const options2 = options ? JSON.parse(JSON.stringify(options)) : {} + options2.parent = title + options2.level = options.level + 1 + + const shape = getSchemaShape(schema.additionalProperties, module, options2) + let type = getSchemaType(schema.additionalProperties, module, options2).trimEnd() + const propertyNames = localizeDependencies(schema, module).propertyNames + + let jsonType = getJsonType(schema.additionalProperties, module) + if (!isPrimitiveType(jsonType)) { + jsonType = 'string' + } + + const additionalType = getPrimitiveType(jsonType, 'additional-types') + let key = (propertyNames && propertyNames.title) ? propertyNames.title : getTemplate(path.join(options.templateDir, 'additionalPropertiesKey')).trimEnd() + + content = content + .replace(/\$\{shape\}/g, shape) + .replace(/\$\{parent\.title\}/g, title) + .replace(/\$\{title\}/g, title) + .replace(/\$\{type\}/g, type) + .replace(/\$\{additional\.type\}/g, additionalType) + .replace(/\$\{key\}/g, key) + .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, '') + .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/g, '') - const options2 = JSON.parse(JSON.stringify(options)) + return content +} + +const insertObjectMacros = (content, schema, module, title, property, options) => { + const options2 = options ? JSON.parse(JSON.stringify(options)) : {} options2.parent = title options2.level = options.level + 1 - options2.name = '' ;(['properties', 'properties.register', 'properties.assign']).forEach(macro => { const indent = (content.split('\n').find(line => line.includes("${" + macro + "}")) || '').match(/^\s+/) || [''][0] @@ -151,21 +179,7 @@ const insertObjectMacros = (content, schema, module, title, property, options) = const template = getTemplate(path.join(options.templateDir, 'property' + (templateType ? `-${templateType}` : ''))).replace(/\n/gms, indent + '\n') const properties = [] - - if (schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { - const template = getTemplate(path.join(options.templateDir, 'additionalProperties')) - let type = getSchemaType(schema.additionalProperties, module, options2) - const shape = getSchemaShape(schema.additionalProperties, module, options2) - properties.push(template - .replace(/\$\{property\}/g, '') - .replace(/\$\{Property\}/g, '') - .replace(/\$\{shape\}/g, shape) - .replace(/\$\{parent\.title\}/g, title) - .replace(/\$\{title\}/g, type) - .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, '') - .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/g, '')) - } - + if (schema.properties) { Object.entries(schema.properties).forEach(([name, prop], i) => { options2.property = name @@ -319,7 +333,7 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', name if (level === 0 && !schema.title) { return '' } - + const suffix = destination && ('.' + destination.split('.').pop()) || '' const theTitle = insertSchemaMacros(getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, schema.title || name, parent, property, false) @@ -353,8 +367,14 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', name return insertSchemaMacros(result, schema, module, theTitle, parent, property) } else if (schema.type === 'object') { - const shape = insertObjectMacros(getTemplate(path.join(templateDir, 'object' + suffix)), schema, module, theTitle, property, { level, parent, property, templateDir, descriptions, destination, section, enums }) - + let shape + const additionalPropertiesTemplate = getTemplate(path.join(templateDir, 'additionalProperties')) + if (additionalPropertiesTemplate && schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { + shape = insertObjectAdditionalPropertiesMacros(additionalPropertiesTemplate, schema, module, theTitle, { level, parent, templateDir, namespace: true }) + } + else { + shape = insertObjectMacros(getTemplate(path.join(templateDir, 'object' + suffix)), schema, module, theTitle, property, { level, parent, property, templateDir, descriptions, destination, section, enums, namespace: true }) + } result = result.replace(/\$\{shape\}/g, shape) return insertSchemaMacros(result, schema, module, theTitle, parent, property) } @@ -614,11 +634,17 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin // } } else if (schema.type) { - // TODO: this assumes that when type is an array of types, that it's one other primative & 'null', which isn't necessarily true. - const schemaType = !Array.isArray(schema.type) ? schema.type : schema.type.find(t => t !== 'null') - const primitive = getPrimitiveType(schemaType, templateDir) - const type = allocatedProxy ? allocatedPrimitiveProxies[schemaType] || primitive : primitive - return wrap(type, code ? '`' : '') + const template = getTemplate(path.join(templateDir, 'additionalProperties')) + if (schema.additionalProperties && template ) { + return insertSchemaMacros(getTemplate(path.join(templateDir, 'Title')), schema, module, theTitle, '', '', false) + } + else { + // TODO: this assumes that when type is an array of types, that it's one other primative & 'null', which isn't necessarily true. + const schemaType = !Array.isArray(schema.type) ? schema.type : schema.type.find(t => t !== 'null') + const primitive = getPrimitiveType(schemaType, templateDir) + const type = allocatedProxy ? allocatedPrimitiveProxies[schemaType] || primitive : primitive + return wrap(type, code ? '`' : '') + } } else { // TODO this is TypeScript specific @@ -627,7 +653,21 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin } function getJsonType(schema, module, { destination, link = false, title = false, code = false, asPath = false, event = false, expandEnums = true, baseUrl = '' } = {}) { - return '' + + schema = sanitize(schema) + let type + if (schema['$ref']) { + if (schema['$ref'][0] === '#') { + //Ref points to local schema + //Get Path to ref in this module and getSchemaType + let definition = getPath(schema['$ref'], module) + type = getJsonType(definition, schema, {destination}) + } + } + else { + type = !Array.isArray(schema.type) ? schema.type : schema.type.find(t => t !== 'null') + } + return type } function getSchemaInstantiation(schema, module, { instantiationType }) { @@ -642,6 +682,5 @@ export default { getMethodSignatureParams, getSchemaShape, getSchemaType, - getJsonType, getSchemaInstantiation -} \ No newline at end of file +} From 1f2854bea633b01ac554367bac22ad0ba6f92f31 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Wed, 18 Oct 2023 09:12:02 +0530 Subject: [PATCH 106/137] CPPSDK: parameter and result handling changes (#136) CPPSDK: 1. parameter and result handling changes 2. anyOf type handling 3. reference schema handling --- languages/cpp/templates/json-types/anyOf.c | 1 - languages/cpp/templates/json-types/anyOf.h | 1 + .../templates/json-types/anyOfSchemaShape.h | 1 + .../parameter-serialization/generic.cpp | 2 + .../parameters/{object.h => nonprimitive.h} | 0 .../cpp/templates/parameters/result-null.h | 0 languages/cpp/templates/parameters/result.h | 1 - .../cpp/templates/result-callback/default.h | 1 + .../templates/result-callback/nonprimitive.h | 1 + .../cpp/templates/result-callback/string.h | 1 + languages/cpp/templates/result/default.h | 1 + languages/cpp/templates/types/anyOf.c | 1 - languages/cpp/templates/types/anyOf.h | 1 + .../cpp/templates/types/anyOfSchemaShape.h | 1 + languages/cpp/templates/types/tuple.h | 2 +- .../templates/types/tuple-delimiter.mjs | 1 + src/macrofier/engine.mjs | 10 ++- src/macrofier/types.mjs | 88 +++++++++++++++---- 18 files changed, 87 insertions(+), 27 deletions(-) delete mode 100644 languages/cpp/templates/json-types/anyOf.c create mode 100644 languages/cpp/templates/json-types/anyOf.h create mode 100644 languages/cpp/templates/json-types/anyOfSchemaShape.h create mode 100644 languages/cpp/templates/parameter-serialization/generic.cpp rename languages/cpp/templates/parameters/{object.h => nonprimitive.h} (100%) delete mode 100644 languages/cpp/templates/parameters/result-null.h delete mode 100644 languages/cpp/templates/parameters/result.h create mode 100644 languages/cpp/templates/result-callback/default.h create mode 100644 languages/cpp/templates/result-callback/nonprimitive.h create mode 100644 languages/cpp/templates/result-callback/string.h create mode 100644 languages/cpp/templates/result/default.h delete mode 100644 languages/cpp/templates/types/anyOf.c create mode 100644 languages/cpp/templates/types/anyOf.h create mode 100644 languages/cpp/templates/types/anyOfSchemaShape.h create mode 100644 languages/javascript/templates/types/tuple-delimiter.mjs diff --git a/languages/cpp/templates/json-types/anyOf.c b/languages/cpp/templates/json-types/anyOf.c deleted file mode 100644 index a2682179..00000000 --- a/languages/cpp/templates/json-types/anyOf.c +++ /dev/null @@ -1 +0,0 @@ -/* AnyOf is not supported in C: ${title} */ \ No newline at end of file diff --git a/languages/cpp/templates/json-types/anyOf.h b/languages/cpp/templates/json-types/anyOf.h new file mode 100644 index 00000000..fc121f63 --- /dev/null +++ b/languages/cpp/templates/json-types/anyOf.h @@ -0,0 +1 @@ +WPEFramework::Core::JSON::VariantContainer \ No newline at end of file diff --git a/languages/cpp/templates/json-types/anyOfSchemaShape.h b/languages/cpp/templates/json-types/anyOfSchemaShape.h new file mode 100644 index 00000000..9a53ff94 --- /dev/null +++ b/languages/cpp/templates/json-types/anyOfSchemaShape.h @@ -0,0 +1 @@ + /* anyOf schema shape is supported right now */ diff --git a/languages/cpp/templates/parameter-serialization/generic.cpp b/languages/cpp/templates/parameter-serialization/generic.cpp new file mode 100644 index 00000000..8ccb8295 --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/generic.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property} = ${property}; + jsonParameters.Set(_T("${property}"), ${Property}); \ No newline at end of file diff --git a/languages/cpp/templates/parameters/object.h b/languages/cpp/templates/parameters/nonprimitive.h similarity index 100% rename from languages/cpp/templates/parameters/object.h rename to languages/cpp/templates/parameters/nonprimitive.h diff --git a/languages/cpp/templates/parameters/result-null.h b/languages/cpp/templates/parameters/result-null.h deleted file mode 100644 index e69de29b..00000000 diff --git a/languages/cpp/templates/parameters/result.h b/languages/cpp/templates/parameters/result.h deleted file mode 100644 index 3c96807b..00000000 --- a/languages/cpp/templates/parameters/result.h +++ /dev/null @@ -1 +0,0 @@ -${method.param.type}& ${method.param.name} \ No newline at end of file diff --git a/languages/cpp/templates/result-callback/default.h b/languages/cpp/templates/result-callback/default.h new file mode 100644 index 00000000..d66fdb8a --- /dev/null +++ b/languages/cpp/templates/result-callback/default.h @@ -0,0 +1 @@ +const ${method.result.type} \ No newline at end of file diff --git a/languages/cpp/templates/result-callback/nonprimitive.h b/languages/cpp/templates/result-callback/nonprimitive.h new file mode 100644 index 00000000..84b86816 --- /dev/null +++ b/languages/cpp/templates/result-callback/nonprimitive.h @@ -0,0 +1 @@ +const ${method.result.type}& \ No newline at end of file diff --git a/languages/cpp/templates/result-callback/string.h b/languages/cpp/templates/result-callback/string.h new file mode 100644 index 00000000..84b86816 --- /dev/null +++ b/languages/cpp/templates/result-callback/string.h @@ -0,0 +1 @@ +const ${method.result.type}& \ No newline at end of file diff --git a/languages/cpp/templates/result/default.h b/languages/cpp/templates/result/default.h new file mode 100644 index 00000000..d66fdb8a --- /dev/null +++ b/languages/cpp/templates/result/default.h @@ -0,0 +1 @@ +const ${method.result.type} \ No newline at end of file diff --git a/languages/cpp/templates/types/anyOf.c b/languages/cpp/templates/types/anyOf.c deleted file mode 100644 index bd2ba3e5..00000000 --- a/languages/cpp/templates/types/anyOf.c +++ /dev/null @@ -1 +0,0 @@ -/* AnyOf is not supported in CPP: ${title} */ \ No newline at end of file diff --git a/languages/cpp/templates/types/anyOf.h b/languages/cpp/templates/types/anyOf.h new file mode 100644 index 00000000..c6d1c815 --- /dev/null +++ b/languages/cpp/templates/types/anyOf.h @@ -0,0 +1 @@ +std::string \ No newline at end of file diff --git a/languages/cpp/templates/types/anyOfSchemaShape.h b/languages/cpp/templates/types/anyOfSchemaShape.h new file mode 100644 index 00000000..9a53ff94 --- /dev/null +++ b/languages/cpp/templates/types/anyOfSchemaShape.h @@ -0,0 +1 @@ + /* anyOf schema shape is supported right now */ diff --git a/languages/cpp/templates/types/tuple.h b/languages/cpp/templates/types/tuple.h index ce217a83..b00d2610 100644 --- a/languages/cpp/templates/types/tuple.h +++ b/languages/cpp/templates/types/tuple.h @@ -1,2 +1,2 @@ /* ${title} */ -std::pair<${type},${type}> ${title}; +std::pair<${items}> ${title}; diff --git a/languages/javascript/templates/types/tuple-delimiter.mjs b/languages/javascript/templates/types/tuple-delimiter.mjs new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/languages/javascript/templates/types/tuple-delimiter.mjs @@ -0,0 +1 @@ + diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 500bc3b1..b5527ac6 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -120,7 +120,7 @@ const getLinkForSchema = (schema, json, { name = '' } = {}) => { 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]) { @@ -844,7 +844,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 @@ -1207,7 +1207,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) // 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 pullsForParamType = pullsParams ? types.getSchemaType(pullsParams, json, { destination: state.destination, section: state.section }) : '' + 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' }) : '' @@ -1245,6 +1245,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' : '') @@ -1253,6 +1254,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) @@ -1287,7 +1289,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .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 })) // 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.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) diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index 7c627fce..6ee24f2a 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -30,6 +30,7 @@ const primitives = { "string": "string" } +const isVoid = type => (type === 'void') ? true : false const isPrimitiveType = type => primitives[type] ? true : false const allocatedPrimitiveProxies = {} @@ -54,17 +55,52 @@ const safeName = value => value.split(':').pop().replace(/[\.\-]/g, '_').replace // TODO: This is what's left of getMethodSignatureParams. We need to figure out / handle C's `FireboltTypes_StringHandle` function getMethodSignatureParams(method, module, { destination, callback }) { - const paramRequired = getTemplate('/parameters/default') const paramOptional = getTemplate('/parameters/optional') return method.params.map(param => { let type = getSchemaType(param.schema, module, { destination, namespace : true }) if (callback && allocatedPrimitiveProxies[type]) { type = allocatedPrimitiveProxies[type] } + + let paramRequired = '' + let jsonType = getJsonType(param.schema, module, { destination }) + if (!isPrimitiveType(jsonType) && getTemplate('/parameters/nonprimitive')) { + paramRequired = getTemplate('/parameters/nonprimitive') + } + else if ((jsonType === 'string') && getTemplate('/parameters/string')) { + paramRequired = getTemplate('/parameters/string') + } + else { + paramRequired = getTemplate('/parameters/default') + } + return (param.required ? paramRequired : paramOptional).replace(/\$\{method\.param\.name\}/g, param.name).replace(/\$\{method\.param\.type\}/g, type) }).join(', ') } +function getMethodSignatureResult(method, module, { destination, callback, overrideRule = false }) { + let type = getSchemaType(method.result.schema, module, { destination, namespace : true }) + let result = '' + + if (callback) { + let jsonType = getJsonType(method.result.schema, module, { destination }) + + if (!isVoid(type) && !isPrimitiveType(jsonType) && getTemplate('/result-callback/nonprimitive')) { + result = getTemplate('/result-callback/nonprimitive') + } + else if ((jsonType === 'string') && getTemplate('/result-callback/string')) { + result = getTemplate('/result-callback/string') + } + else { + result = getTemplate('/result-callback/default') + } + } + else { + result = getTemplate('/result/default') + } + return result.replace(/\$\{method\.result\.type\}/g, type) +} + const getTemplate = (name) => { if (name[0] !== '/') { name = '/' + name @@ -121,8 +157,6 @@ const insertConstMacros = (content, schema, module, name) => { return content } - - const insertEnumMacros = (content, schema, module, name) => { const template = content.split('\n') @@ -213,7 +247,7 @@ const insertObjectMacros = (content, schema, module, title, property, options) = } // TODO: add language config feature for 'unknown' type let type; // = { type: "null" } - + if (schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { type = schema.additionalProperties } @@ -226,7 +260,7 @@ const insertObjectMacros = (content, schema, module, title, property, options) = } }) } - + if (type) { options2.property = prop const schemaShape = getSchemaShape(type, module, options2) @@ -265,6 +299,7 @@ const insertTupleMacros = (content, schema, module, title, options) => { const itemsTemplate = getTemplate(path.join(options.templateDir, 'items')) const propIndent = (content.split('\n').find(line => line.includes("${properties}")) || '').match(/^\s+/) || [''][0] const itemsIndent = (content.split('\n').find(line => line.includes("${items}")) || '').match(/^\s+/) || [''][0] + const tupleDelimiter = getTemplate(path.join(options.templateDir, 'tuple-delimiter')) const doMacroWork = (str, prop, i, indent) => { const schemaShape = getSchemaShape(prop, module, options) @@ -281,8 +316,8 @@ const insertTupleMacros = (content, schema, module, title, options) => { .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, '') } - content = content.replace(/\$\{properties\}/g, schema.items.map((prop, i) => doMacroWork(propTemplate, prop, i, propIndent)).join('\n')) - content = content.replace(/\$\{items\}/g, schema.items.map((prop, i) => doMacroWork(itemsTemplate, prop, i, itemsIndent)).join('\n')) + content = content.replace(/\$\{properties\}/g, schema.items.map((prop, i) => doMacroWork(propTemplate, prop, i, propIndent)).join(tupleDelimiter)) + content = content.replace(/\$\{items\}/g, schema.items.map((prop, i) => doMacroWork(itemsTemplate, prop, i, itemsIndent)).join(tupleDelimiter)) return content } @@ -301,10 +336,13 @@ const insertPrimitiveMacros = (content, schema, module, name, templateDir) => { const insertAnyOfMacros = (content, schema, module, name) => { const itemTemplate = content - content = schema.anyOf.map((item, i) => itemTemplate - .replace(/\$\{type\}/g, getSchemaType(item, module)) - .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, i === schema.anyOf.length - 1 ? '' : '$1') - ).join('') + if (content.split('\n').find(line => line.includes("${type}"))) { + content = schema.anyOf.map((item, i) => itemTemplate + .replace(/\$\{type\}/g, getSchemaType(item, module)) + .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, i === schema.anyOf.length - 1 ? '' : '$1') + ).join('') + } + return content } @@ -379,14 +417,25 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', name return insertSchemaMacros(result, schema, module, theTitle, parent, property) } else if (schema.anyOf || schema.oneOf) { - // borrow anyOf logic, note that schema is a copy, so we're not breaking it. - if (!schema.anyOf) { - schema.anyOf = schema.oneOf + const template = getTemplate(path.join(templateDir, 'anyOfSchemaShape' + suffix)) + let shape + if (template) { + shape = insertAnyOfMacros(template, schema, module, theTitle) + } + else { + // borrow anyOf logic, note that schema is a copy, so we're not breaking it. + if (!schema.anyOf) { + schema.anyOf = schema.oneOf + } + shape = insertAnyOfMacros(getTemplate(path.join(templateDir, 'anyOf' + suffix)), schema, module, theTitle) + } + if (shape) { + result = result.replace(/\$\{shape\}/g, shape) + return insertSchemaMacros(result, schema, module, theTitle, parent, property) + } + else { + return '' } - const shape = insertAnyOfMacros(getTemplate(path.join(templateDir, 'anyOf' + suffix)), schema, module, theTitle) - - result = result.replace(/\$\{shape\}/g, shape) - return insertSchemaMacros(result, schema, module, theTitle, parent, property) } else if (schema.allOf) { const merger = (key) => function (a, b) { @@ -500,7 +549,7 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin if (schema['$ref'][0] === '#') { const refSchema = getPath(schema['$ref'], module) const includeNamespace = (module.info.title !== getXSchemaGroup(refSchema, module)) - return getSchemaType(refSchema, module, {destination, templateDir, link, title, code, asPath, event, result, expandEnums, baseUrl, namespace:includeNamespace })// { link: link, code: code, destination }) + return getSchemaType(refSchema, module, {destination, templateDir, link, code, asPath, event, result, expandEnums, baseUrl, namespace:includeNamespace })// { link: link, code: code, destination }) } else { // TODO: This never happens... but might be worth keeping in case we link to an opaque external schema at some point? @@ -680,6 +729,7 @@ export default { setConvertTuples, setAllocatedPrimitiveProxies, getMethodSignatureParams, + getMethodSignatureResult, getSchemaShape, getSchemaType, getSchemaInstantiation From 7031fc227141ff1ce872fd92ceb27611d8c4cd42 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Tue, 24 Oct 2023 09:45:32 +0530 Subject: [PATCH 107/137] CPPSDK: aggregate files based on suffix type handling added, module and override module generation also handled (#139) CPPSDK: aggregate files based on suffix type handling added, module and override module generation also handled --- languages/cpp/language.config.json | 10 +- .../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 .../rpc-only.h} | 0 .../templates/declarations-override/setter.h | 5 + .../declarations/{provide.c => clear.h} | 0 .../default.c => declarations/default.h} | 0 .../declarations/{event.c => event.h} | 0 .../property.c => declarations/listen.h} | 0 .../{methods/clear.c => declarations/once.h} | 0 .../polymorphic-pull-event.h} | 0 .../polymorphic-pull.h} | 0 .../polymorphic-reducer.h} | 0 .../provide.h} | 0 languages/cpp/templates/imports/default.impl | 1 + .../{calls-metrics.c => calls-metrics.cpp} | 0 .../methods/{polymorphic-pull.c => clear.cpp} | 0 .../{polymorphic-reducer.c => default.cpp} | 0 languages/cpp/templates/methods/event.c | 33 --- languages/cpp/templates/methods/event.cpp | 35 +++ .../methods/{provide.c => listen.cpp} | 0 .../templates/methods/{setter.c => once.cpp} | 0 .../methods/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 | 9 +- .../cpp/templates/modules/src/module.cpp | 89 ------- .../modules/src/module_impl.cpp} | 31 +-- .../cpp/templates/modules/src/module_impl.h | 47 ++++ .../cpp/templates/sdk/include/firebolt.h | 133 ++++++++++ .../cpp/templates/sdk/scripts/install.sh | 2 +- languages/cpp/templates/sdk/src/firebolt.cpp | 116 ++++++++ languages/javascript/language.config.json | 6 +- .../templates/codeblocks/module.mjs | 4 +- src/macrofier/engine.mjs | 251 +++++++++++------- src/macrofier/index.mjs | 26 +- src/sdk/index.mjs | 3 +- src/shared/json-schema.mjs | 1 - 60 files changed, 635 insertions(+), 315 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%) rename languages/cpp/templates/{declarations/polymorphic-reducer.c => declarations-override/rpc-only.h} (100%) create mode 100644 languages/cpp/templates/declarations-override/setter.h rename languages/cpp/templates/declarations/{provide.c => clear.h} (100%) rename languages/cpp/templates/{defaults/default.c => declarations/default.h} (100%) rename languages/cpp/templates/declarations/{event.c => event.h} (100%) rename languages/cpp/templates/{defaults/property.c => declarations/listen.h} (100%) rename languages/cpp/templates/{methods/clear.c => declarations/once.h} (100%) rename languages/cpp/templates/{methods/default.c => declarations/polymorphic-pull-event.h} (100%) rename languages/cpp/templates/{methods/listen.c => declarations/polymorphic-pull.h} (100%) rename languages/cpp/templates/{methods/once.c => declarations/polymorphic-reducer.h} (100%) rename languages/cpp/templates/{methods/polymorphic-pull-event.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.c => clear.cpp} (100%) rename languages/cpp/templates/methods/{polymorphic-reducer.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/{provide.c => listen.cpp} (100%) rename languages/cpp/templates/methods/{setter.c => once.cpp} (100%) create mode 100644 languages/cpp/templates/methods/polymorphic-pull-event.cpp 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 diff --git a/languages/cpp/language.config.json b/languages/cpp/language.config.json index 491e9559..debc539d 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", @@ -23,5 +28,6 @@ "string": "std::string" }, "langVersion" : "c++17", - "additionalSchemaTemplates": [ "json-types" ] + "additionalSchemaTemplates": [ "json-types" ], + "additionalMethodTemplates": [ "declarations", "declarations-override" ] } 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/polymorphic-reducer.c b/languages/cpp/templates/declarations-override/rpc-only.h similarity index 100% rename from languages/cpp/templates/declarations/polymorphic-reducer.c rename to languages/cpp/templates/declarations-override/rpc-only.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/provide.c b/languages/cpp/templates/declarations/clear.h similarity index 100% rename from languages/cpp/templates/declarations/provide.c rename to languages/cpp/templates/declarations/clear.h diff --git a/languages/cpp/templates/defaults/default.c b/languages/cpp/templates/declarations/default.h similarity index 100% rename from languages/cpp/templates/defaults/default.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/property.c b/languages/cpp/templates/declarations/listen.h similarity index 100% rename from languages/cpp/templates/defaults/property.c rename to languages/cpp/templates/declarations/listen.h diff --git a/languages/cpp/templates/methods/clear.c b/languages/cpp/templates/declarations/once.h similarity index 100% rename from languages/cpp/templates/methods/clear.c rename to languages/cpp/templates/declarations/once.h diff --git a/languages/cpp/templates/methods/default.c b/languages/cpp/templates/declarations/polymorphic-pull-event.h similarity index 100% rename from languages/cpp/templates/methods/default.c rename to languages/cpp/templates/declarations/polymorphic-pull-event.h diff --git a/languages/cpp/templates/methods/listen.c b/languages/cpp/templates/declarations/polymorphic-pull.h similarity index 100% rename from languages/cpp/templates/methods/listen.c rename to languages/cpp/templates/declarations/polymorphic-pull.h diff --git a/languages/cpp/templates/methods/once.c b/languages/cpp/templates/declarations/polymorphic-reducer.h similarity index 100% rename from languages/cpp/templates/methods/once.c rename to languages/cpp/templates/declarations/polymorphic-reducer.h diff --git a/languages/cpp/templates/methods/polymorphic-pull-event.c b/languages/cpp/templates/declarations/provide.h similarity index 100% rename from languages/cpp/templates/methods/polymorphic-pull-event.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.c b/languages/cpp/templates/methods/clear.cpp similarity index 100% rename from languages/cpp/templates/methods/polymorphic-pull.c rename to languages/cpp/templates/methods/clear.cpp diff --git a/languages/cpp/templates/methods/polymorphic-reducer.c b/languages/cpp/templates/methods/default.cpp similarity index 100% rename from languages/cpp/templates/methods/polymorphic-reducer.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/provide.c b/languages/cpp/templates/methods/listen.cpp similarity index 100% rename from languages/cpp/templates/methods/provide.c rename to languages/cpp/templates/methods/listen.cpp diff --git a/languages/cpp/templates/methods/setter.c b/languages/cpp/templates/methods/once.cpp similarity index 100% rename from languages/cpp/templates/methods/setter.c rename to languages/cpp/templates/methods/once.cpp diff --git a/languages/cpp/templates/methods/polymorphic-pull-event.cpp b/languages/cpp/templates/methods/polymorphic-pull-event.cpp new file mode 100644 index 00000000..e69de29b 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..de58e77a 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} */ + /* ${METHODS: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..33e6e005 --- /dev/null +++ b/languages/cpp/templates/modules/src/module_impl.h @@ -0,0 +1,47 @@ +/* + * 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 + /* ${METHODS: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/javascript/language.config.json b/languages/javascript/language.config.json index 540e6375..529ac99a 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": { @@ -20,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 b5527ac6..b1d2dd89 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 } @@ -99,12 +98,12 @@ 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) => { - return getTemplateTypeForMethod(method, 'declarations', templates) +const getTemplateForDeclaration = (method, templates, templateDir) => { + return getTemplateTypeForMethod(method, templateDir, templates) } const getTemplateForExample = (method, templates) => { @@ -116,7 +115,7 @@ 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 @@ -459,7 +458,6 @@ const mergeAnyOfs = (obj) => { obj = JSON.parse(JSON.stringify(obj)) findAll('anyOf', obj, anyOf => mergeAnyOf(anyOf)) -// findAll('onyOf', obj, onyOf => mergeOnyOf(onyOf)) return obj } @@ -496,46 +494,62 @@ const generateMacros = (obj, templates, languages, options = {}) => { const macros = { schemas: {}, types: {}, - enums: {} + enums: {}, + 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')) 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))) + state.typeTemplateDir = 'types' 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 examples = generateExamples(obj, templates, languages) + const allMethodsArray = generateMethods(obj, examples, templates) + + Array.from(new Set(['methods'].concat(config.additionalMethodTemplates))).filter(dir => dir).forEach(dir => { + + 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)) + } + } + }) 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, initialization, - events, - eventList, eventsEnum, - methods, - methodList, - declarations, defaults, examples, providerInterfaces, @@ -543,12 +557,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 +585,7 @@ const insertAggregateMacros = (fContents = '', aggregateMacros = {}) => { } const insertMacros = (fContents = '', macros = {}) => { - if (macros.append) { + if (macros.append && macros.module) { fContents += '\n' + macros.module } @@ -569,17 +594,33 @@ 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.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\.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(/[ \t]*\/\* \$\{METHODS\} \*\/[ \t]*\n/, macros.methods) - fContents = fContents.replace(/[ \t]*\/\* \$\{DECLARATIONS\} \*\/[ \t]*\n/, macros.declarations) + 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.methods.trim() || macros.events.methods.trim()) ? '$1' : '') + + // 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 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') + 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) @@ -587,12 +628,12 @@ const insertMacros = (fContents = '', macros = {}) => { 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]) }) - }) + }) fContents = fContents.replace(/[ \t]*\/\* \$\{PROVIDERS\} \*\/[ \t]*\n/, macros.providerInterfaces) fContents = fContents.replace(/[ \t]*\/\* \$\{IMPORTS\} \*\/[ \t]*\n/, macros.imports) @@ -826,7 +867,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)) @@ -890,7 +931,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') @@ -927,16 +968,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']) { @@ -1044,6 +1089,27 @@ function generateExamples(json = {}, mainTemplates = {}, languages = {}) { return examples } +function generateMethodResult(type, templates) { + const result = { + name: type, + body: {}, + declaration: {}, + } + + Array.from(new Set(['methods'].concat(config.additionalMethodTemplates))).filter(dir => dir).forEach(dir => { + const template = getTemplate(('/' + dir + '/' + type), templates) + if (template) { + if (dir.includes('declarations')) { + result.declaration[dir] = template + } + else if (dir.includes('methods')) { + result.body[dir] = template + } + } + }) + return result +} + function generateMethods(json = {}, examples = {}, templates = {}) { const methods = compose( option([]), @@ -1054,25 +1120,27 @@ function generateMethods(json = {}, examples = {}, templates = {}) { const results = reduce((acc, methodObj, i, arr) => { const result = { name: methodObj.name, - body: '', - declaration: '', + 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 - } - - template = getTemplateForDeclaration(methodObj, templates) - - if (template && template.length) { - let javascript = insertMethodMacros(template, methodObj, json, templates, examples) - result.declaration = 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 => { + 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) + } + } + }) acc.push(result) @@ -1081,36 +1149,17 @@ 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)) }) } results.sort((a, b) => a.name.localeCompare(b.name)) - return results } @@ -1196,20 +1245,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 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' }) : '' @@ -1285,9 +1334,9 @@ 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\}/, 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.getMethodSignatureResult(event, json, { destination: state.destination, section: state.section, callback: true }) : '') .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) @@ -1308,7 +1357,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!! @@ -1431,7 +1480,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') @@ -1448,7 +1497,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 !== '#') { @@ -1458,7 +1507,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 { @@ -1466,7 +1515,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) { @@ -1485,7 +1534,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 @@ -1494,14 +1543,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}`) } @@ -1514,8 +1563,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 || '') } @@ -1525,9 +1574,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 @@ -1540,7 +1589,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)) } @@ -1710,6 +1759,7 @@ function insertProviderParameterMacros(data = '', parameters, module = {}, optio export { generateMacros, + clearMacros, insertMacros, generateAggregateMacros, insertAggregateMacros @@ -1717,6 +1767,7 @@ export { export default { generateMacros, + clearMacros, insertMacros, generateAggregateMacros, insertAggregateMacros, diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 1899f310..04cdd9fb 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -52,8 +52,9 @@ const macrofy = async ( allocatedPrimitiveProxies, convertTuplesToArraysOrObjects, additionalSchemaTemplates, + additionalMethodTemplates, excludeDeclarations, - aggregateFile, + aggregateFiles, operators, primitives, hidePrivate = true, @@ -94,6 +95,7 @@ const macrofy = async ( primitives, allocatedPrimitiveProxies, additionalSchemaTemplates, + additionalMethodTemplates, excludeDeclarations, operators }) @@ -144,22 +146,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 +194,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..763b6c9e 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -68,10 +68,11 @@ const run = async ({ unwrapResultObjects: config.unwrapResultObjects, allocatedPrimitiveProxies: config.allocatedPrimitiveProxies, additionalSchemaTemplates: config.additionalSchemaTemplates, + additionalMethodTemplates: config.additionalMethodTemplates, 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 6d1339bf50da11c106b74a0b28533854bcc1635f Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Wed, 25 Oct 2023 09:23:30 +0530 Subject: [PATCH 108/137] CPPSDK: changes to handle enum and x-schema enum without title (#138) --- languages/cpp/templates/types/enum.h | 2 +- src/macrofier/engine.mjs | 50 +++++++++++++++++----------- src/macrofier/types.mjs | 24 ++++++++----- src/shared/modules.mjs | 5 +++ 4 files changed, 53 insertions(+), 28 deletions(-) diff --git a/languages/cpp/templates/types/enum.h b/languages/cpp/templates/types/enum.h index 166fb231..6ec88816 100644 --- a/languages/cpp/templates/types/enum.h +++ b/languages/cpp/templates/types/enum.h @@ -1,4 +1,4 @@ /* ${title} ${description} */ enum class ${name} { - ${key}, + ${key}${delimiter},${end.delimiter} }; diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index b1d2dd89..c853e324 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -375,7 +375,10 @@ const promoteSchema = (location, property, title, document, destinationPath) => } // only consider sub-objects and sub enums to be sub-schemas -const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) // || (schema.type === 'array' && schema.items) +const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) + +// check schema is sub enum of array +const isSubEnumOfArraySchema = (schema) => (schema.type === 'array' && schema.items.enum) const promoteAndNameSubSchemas = (obj) => { // make a copy so we don't polute our inputs @@ -402,19 +405,30 @@ const promoteAndNameSubSchemas = (obj) => { while (more) { more = false Object.entries(obj.components.schemas).forEach(([key, schema]) => { - if ((schema.type === "object") && schema.properties) { - Object.entries(schema.properties).forEach(([name, propSchema]) => { - if (isSubSchema(propSchema)) { - more = true - const descriptor = { - name: name, - schema: propSchema + let componentSchemaProperties = schema.allOf ? schema.allOf : [schema] + componentSchemaProperties.forEach((componentSchema) => { + if ((componentSchema.type === "object") && componentSchema.properties) { + Object.entries(componentSchema.properties).forEach(([name, propSchema]) => { + if (isSubSchema(propSchema)) { + more = true + const descriptor = { + name: name, + schema: propSchema + } + addContentDescriptorSubSchema(descriptor, key, obj) + componentSchema.properties[name] = descriptor.schema } - addContentDescriptorSubSchema(descriptor, key, obj) - schema.properties[name] = descriptor.schema - } - }) - } + if (isSubEnumOfArraySchema(propSchema)) { + const descriptor = { + name: name, + schema: propSchema.items + } + addContentDescriptorSubSchema(descriptor, key, obj) + componentSchema.properties[name].items = descriptor.schema + } + }) + } + }) if (!schema.title) { schema.title = capitalize(key) @@ -727,14 +741,12 @@ const convertEnumTemplate = (schema, templateName, templates) => { const template = getTemplate(templateName, templates).split('\n') for (var i = 0; i < template.length; i++) { if (template[i].indexOf('${key}') >= 0) { - template[i] = enumSchema.enum.map(value => { + template[i] = enumSchema.enum.map((value, id) => { const safeName = value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() return template[i].replace(/\$\{key\}/g, safeName) .replace(/\$\{value\}/g, value) + .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, id === enumSchema.enum.length - 1 ? '' : '$1') }).join('\n') - if (!templateName.includes(".cpp")) { - template[i] = template[i].replace(/,*$/, ''); - } } } return template.join('\n') @@ -867,7 +879,7 @@ function generateSchemas(json, templates, options) { else { content = content.replace(/\$\{if\.description\}(.*?)\{end\.if\.description\}/gms, '$1') } - const schemaShape = types.getSchemaShape(schema, json, { 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)) @@ -887,7 +899,7 @@ function generateSchemas(json, templates, options) { } content = content.trim().length ? content : content.trim() - const isEnum = x => x.type === 'string' && Array.isArray(x.enum) && x.title + const isEnum = x => x.type && Array.isArray(x.enum) && x.title && ((x.type === 'string') || (x.type[0] === 'string')) const result = uri ? { uri: uri, diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index 6ee24f2a..f25a9689 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -157,14 +157,21 @@ const insertConstMacros = (content, schema, module, name) => { return content } -const insertEnumMacros = (content, schema, module, name) => { +const insertEnumMacros = (content, schema, module, name, suffix, templateDir = "types") => { const template = content.split('\n') for (var i = 0; i < template.length; i++) { if (template[i].indexOf('${key}') >= 0) { - template[i] = schema.enum.map(value => { - return template[i].replace(/\$\{key\}/g, safeName(value)) - .replace(/\$\{value\}/g, value) + let values = [] + schema.enum.map(value => { + if (!value) { + value = getTemplate(path.join(templateDir, 'unset' + suffix)) + } + value ? values.push(template[i].replace(/\$\{key\}/g, safeName(value)) + .replace(/\$\{value\}/g, value)) : '' + }) + template[i] = values.map((value, id) => { + return value.replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, id === values.length - 1 ? '' : '$1') }).join('\n') } } @@ -377,15 +384,15 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', name let result = level === 0 ? getTemplate(path.join(templateDir, 'default' + suffix)) : '${shape}' - if (enums && level === 0 && schema.type === "string" && Array.isArray(schema.enum)) { + if (enums && level === 0 && Array.isArray(schema.enum) && ((schema.type === "string") || (schema.type[0] === "string"))) { result = getTemplate(path.join(templateDir, 'enum' + suffix)) - return insertSchemaMacros(insertEnumMacros(result, schema, module, theTitle), schema, module, theTitle, parent, property) + return insertSchemaMacros(insertEnumMacros(result, schema, module, theTitle, suffix, templateDir), schema, module, theTitle, parent, property) } if (schema['$ref']) { const someJson = getPath(schema['$ref'], module) if (someJson) { - return getSchemaShape(someJson, module, { templateDir, name, parent, property, level, summary, descriptions, destination, enums: false }) + return getSchemaShape(someJson, module, { templateDir, name, parent, property, level, summary, descriptions, destination, enums }) } throw "Unresolvable $ref: " + schema['ref'] + ", in " + module.info.title } @@ -395,8 +402,9 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', name return result } else if (!skipTitleOnce && (level > 0) && schema.title) { + let enumType = (schema.type === 'string' && Array.isArray(schema.enum)) // TODO: allow the 'ref' template to actually insert the shape using getSchemaShape - const innerShape = getSchemaShape(schema, module, { skipTitleOnce: true, templateDir, name, parent, property, level, summary, descriptions, destination, enums: false }) + const innerShape = getSchemaShape(schema, module, { skipTitleOnce: true, templateDir, name, parent, property, level, summary, descriptions, destination, enums: enumType }) const shape = getTemplate(path.join(templateDir, 'ref' + suffix)) .replace(/\$\{shape\}/g, innerShape) diff --git a/src/shared/modules.mjs b/src/shared/modules.mjs index ed0f474a..9f85bb1d 100644 --- a/src/shared/modules.mjs +++ b/src/shared/modules.mjs @@ -1224,6 +1224,11 @@ const getModule = (name, json, copySchemas) => { ...(openrpc[destination[0]][destination[1]][destination[2]] || {}) } } + const capitalize = str => str[0].toUpperCase() + str.substr(1) + if (!schema.title) { + schema.title = capitalize(parts.pop()) + } + openrpc = setPath(destination, schema, openrpc) } }) From 24eedc4968a54f09bc84e0e859817e3e9db9d125 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Wed, 25 Oct 2023 10:06:43 +0530 Subject: [PATCH 109/137] CPPSDK: parameter/result handling for method and events + inner object handling (#140) --- .../templates/additional-types/boolean.cpp | 1 + .../templates/additional-types/integer.cpp | 1 + .../cpp/templates/additional-types/number.cpp | 1 + .../cpp/templates/additional-types/string.cpp | 1 + .../generic.cpp | 1 + .../primitive.cpp | 1 + .../ref.h} | 0 .../generic.cpp | 1 + .../primitive.cpp | 1 + .../ref.h} | 0 .../additionalProperties.cpp | 5 + .../callback-result-instantiation/array.cpp | 5 + .../callback-result-instantiation/enum.cpp | 1 + .../callback-result-instantiation/generic.cpp | 1 + .../callback-result-instantiation/object.cpp | 2 + .../primitive.cpp | 1 + .../property.cpp | 1 + .../ref.h} | 0 .../sub-property/object-separator.cpp | 1 + .../sub-property/object.cpp | 1 + .../sub-property/property.cpp | 1 + .../sub-property/ref.h | 1 + .../sub-property/title.cpp | 1 + .../callback-result-instantiation/title.cpp | 1 + .../callback-result-instantiation/tuple.cpp | 4 + .../json-types/additionalProperties.c | 1 - .../json-types/additionalProperties.cpp | 1 + languages/cpp/templates/json-types/array.c | 4 - languages/cpp/templates/json-types/array.h | 1 + .../json-types/{boolean.c => boolean.h} | 0 .../templates/json-types/{const.c => const.h} | 0 languages/cpp/templates/json-types/default.h | 1 + languages/cpp/templates/json-types/enum.cpp | 5 +- languages/cpp/templates/json-types/enum.h | 4 - .../json-types/{integer.c => integer.h} | 0 .../cpp/templates/json-types/namespace.c | 1 - .../cpp/templates/json-types/namespace.h | 1 + languages/cpp/templates/json-types/null.h | 1 + .../json-types/{float.c => number.h} | 0 languages/cpp/templates/json-types/object.cpp | 8 +- .../cpp/templates/json-types/primitive.c | 0 .../cpp/templates/json-types/primitive.h | 1 + .../templates/json-types/property-assign.cpp | 4 +- .../json-types/property-register.cpp | 3 +- languages/cpp/templates/json-types/ref.h | 1 + .../json-types/{string.c => string.h} | 0 .../templates/json-types/{title.c => title.h} | 0 languages/cpp/templates/json-types/tuple.c | 25 --- languages/cpp/templates/json-types/tuple.cpp | 1 + .../cpp/templates/json-types/types/object.c | 0 languages/cpp/templates/json-types/void.cpp | 1 + .../json-types/{x-method.c => x-method.h} | 0 .../language/{enum-item.c => enum-item.h} | 0 .../cpp/templates/language/{enum.c => enum.h} | 0 .../language/{parameter.c => parameter.h} | 0 .../language/{schema-item.c => schema-item.h} | 0 .../templates/language/{schema.c => schema.h} | 0 .../parameter-serialization/array.cpp | 7 + .../parameter-serialization/boolean.cpp | 2 - .../parameter-serialization/default.cpp | 2 - .../parameter-serialization/enum.cpp | 3 + .../parameter-serialization/generic.cpp | 4 +- .../parameter-serialization/object-array.cpp | 7 + .../parameter-serialization/object.cpp | 8 +- .../parameter-serialization/primitive.cpp | 3 +- .../parameter-serialization/property.cpp | 1 + .../templates/parameter-serialization/ref.h | 1 + .../parameter-serialization/string.cpp | 2 - .../sub-property/object-separator.cpp | 1 + .../sub-property/object.cpp | 1 + .../sub-property/property.cpp | 1 + .../sub-property/ref.h | 1 + .../sub-property/title.cpp | 1 + languages/cpp/templates/parameters/optional.h | 2 +- .../additionalProperties.cpp | 1 + .../templates/result-initialization/array.cpp | 1 + .../result-initialization/boolean.cpp | 1 + .../result-initialization/generic.cpp | 1 + .../result-initialization/namespace.cpp | 1 + .../result-initialization/number.cpp | 1 + .../result-initialization/primitive.cpp | 1 + .../result-initialization/string.cpp | 1 + .../templates/result-initialization/title.cpp | 1 + .../additionalProperties.cpp | 6 + .../templates/result-instantiation/array.cpp | 4 + .../result-instantiation/boolean.cpp | 2 - .../result-instantiation/generic.cpp | 1 + .../result-instantiation/object-array.cpp | 4 + .../templates/result-instantiation/object.cpp | 7 +- .../result-instantiation/property.cpp | 1 + .../cpp/templates/result-instantiation/ref.h | 1 + .../templates/result-instantiation/string.cpp | 3 +- .../sub-property/array.cpp | 4 + .../sub-property/object-array.cpp | 4 + .../sub-property/object-separator.cpp | 1 + .../sub-property/object.cpp | 1 + .../sub-property/property.cpp | 1 + .../result-instantiation/sub-property/ref.h | 1 + .../sub-property/title.cpp | 1 + .../templates/result-instantiation/title.cpp | 1 + .../templates/result-instantiation/tuple.cpp | 3 + .../templates/types/additionalProperties.h | 2 +- languages/cpp/templates/types/const.h | 1 + languages/cpp/templates/types/default.cpp | 4 - languages/cpp/templates/types/default.h | 1 + languages/cpp/templates/types/items.h | 1 + languages/cpp/templates/types/null.h | 1 + languages/cpp/templates/types/object.h | 2 - src/macrofier/engine.mjs | 13 +- src/macrofier/types.mjs | 150 +++++++++++++----- 110 files changed, 251 insertions(+), 124 deletions(-) create mode 100644 languages/cpp/templates/additional-types/boolean.cpp create mode 100644 languages/cpp/templates/additional-types/integer.cpp create mode 100644 languages/cpp/templates/additional-types/number.cpp create mode 100644 languages/cpp/templates/additional-types/string.cpp create mode 100644 languages/cpp/templates/callback-parameter-serialization/generic.cpp create mode 100644 languages/cpp/templates/callback-parameter-serialization/primitive.cpp rename languages/cpp/templates/{json-types/default.cpp => callback-parameter-serialization/ref.h} (100%) create mode 100644 languages/cpp/templates/callback-response-instantiation/generic.cpp create mode 100644 languages/cpp/templates/callback-response-instantiation/primitive.cpp rename languages/cpp/templates/{json-types/ref.c => callback-response-instantiation/ref.h} (100%) create mode 100644 languages/cpp/templates/callback-result-instantiation/additionalProperties.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/array.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/enum.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/generic.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/object.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/primitive.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/property.cpp rename languages/cpp/templates/{result-instantiation/default.cpp => callback-result-instantiation/ref.h} (100%) create mode 100644 languages/cpp/templates/callback-result-instantiation/sub-property/object-separator.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/sub-property/ref.h create mode 100644 languages/cpp/templates/callback-result-instantiation/sub-property/title.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/title.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/tuple.cpp delete mode 100644 languages/cpp/templates/json-types/additionalProperties.c create mode 100644 languages/cpp/templates/json-types/additionalProperties.cpp delete mode 100644 languages/cpp/templates/json-types/array.c create mode 100644 languages/cpp/templates/json-types/array.h rename languages/cpp/templates/json-types/{boolean.c => boolean.h} (100%) rename languages/cpp/templates/json-types/{const.c => const.h} (100%) create mode 100644 languages/cpp/templates/json-types/default.h delete mode 100644 languages/cpp/templates/json-types/enum.h rename languages/cpp/templates/json-types/{integer.c => integer.h} (100%) delete mode 100644 languages/cpp/templates/json-types/namespace.c create mode 100644 languages/cpp/templates/json-types/namespace.h create mode 100644 languages/cpp/templates/json-types/null.h rename languages/cpp/templates/json-types/{float.c => number.h} (100%) delete mode 100644 languages/cpp/templates/json-types/primitive.c create mode 100644 languages/cpp/templates/json-types/primitive.h create mode 100644 languages/cpp/templates/json-types/ref.h rename languages/cpp/templates/json-types/{string.c => string.h} (100%) rename languages/cpp/templates/json-types/{title.c => title.h} (100%) delete mode 100644 languages/cpp/templates/json-types/tuple.c create mode 100644 languages/cpp/templates/json-types/tuple.cpp delete mode 100644 languages/cpp/templates/json-types/types/object.c create mode 100644 languages/cpp/templates/json-types/void.cpp rename languages/cpp/templates/json-types/{x-method.c => x-method.h} (100%) rename languages/cpp/templates/language/{enum-item.c => enum-item.h} (100%) rename languages/cpp/templates/language/{enum.c => enum.h} (100%) rename languages/cpp/templates/language/{parameter.c => parameter.h} (100%) rename languages/cpp/templates/language/{schema-item.c => schema-item.h} (100%) rename languages/cpp/templates/language/{schema.c => schema.h} (100%) create mode 100644 languages/cpp/templates/parameter-serialization/array.cpp delete mode 100644 languages/cpp/templates/parameter-serialization/boolean.cpp delete mode 100644 languages/cpp/templates/parameter-serialization/default.cpp create mode 100644 languages/cpp/templates/parameter-serialization/enum.cpp create mode 100644 languages/cpp/templates/parameter-serialization/object-array.cpp create mode 100644 languages/cpp/templates/parameter-serialization/property.cpp create mode 100644 languages/cpp/templates/parameter-serialization/ref.h delete mode 100644 languages/cpp/templates/parameter-serialization/string.cpp create mode 100644 languages/cpp/templates/parameter-serialization/sub-property/object-separator.cpp create mode 100644 languages/cpp/templates/parameter-serialization/sub-property/object.cpp create mode 100644 languages/cpp/templates/parameter-serialization/sub-property/property.cpp create mode 100644 languages/cpp/templates/parameter-serialization/sub-property/ref.h create mode 100644 languages/cpp/templates/parameter-serialization/sub-property/title.cpp create mode 100644 languages/cpp/templates/result-initialization/additionalProperties.cpp create mode 100644 languages/cpp/templates/result-initialization/array.cpp create mode 100644 languages/cpp/templates/result-initialization/boolean.cpp create mode 100644 languages/cpp/templates/result-initialization/generic.cpp create mode 100644 languages/cpp/templates/result-initialization/namespace.cpp create mode 100644 languages/cpp/templates/result-initialization/number.cpp create mode 100644 languages/cpp/templates/result-initialization/primitive.cpp create mode 100644 languages/cpp/templates/result-initialization/string.cpp create mode 100644 languages/cpp/templates/result-initialization/title.cpp create mode 100644 languages/cpp/templates/result-instantiation/additionalProperties.cpp create mode 100644 languages/cpp/templates/result-instantiation/array.cpp delete mode 100644 languages/cpp/templates/result-instantiation/boolean.cpp create mode 100644 languages/cpp/templates/result-instantiation/generic.cpp create mode 100644 languages/cpp/templates/result-instantiation/object-array.cpp create mode 100644 languages/cpp/templates/result-instantiation/property.cpp create mode 100644 languages/cpp/templates/result-instantiation/ref.h create mode 100644 languages/cpp/templates/result-instantiation/sub-property/array.cpp create mode 100644 languages/cpp/templates/result-instantiation/sub-property/object-array.cpp create mode 100644 languages/cpp/templates/result-instantiation/sub-property/object-separator.cpp create mode 100644 languages/cpp/templates/result-instantiation/sub-property/object.cpp create mode 100644 languages/cpp/templates/result-instantiation/sub-property/property.cpp create mode 100644 languages/cpp/templates/result-instantiation/sub-property/ref.h create mode 100644 languages/cpp/templates/result-instantiation/sub-property/title.cpp create mode 100644 languages/cpp/templates/result-instantiation/title.cpp create mode 100644 languages/cpp/templates/result-instantiation/tuple.cpp delete mode 100644 languages/cpp/templates/types/default.cpp create mode 100644 languages/cpp/templates/types/default.h create mode 100644 languages/cpp/templates/types/items.h diff --git a/languages/cpp/templates/additional-types/boolean.cpp b/languages/cpp/templates/additional-types/boolean.cpp new file mode 100644 index 00000000..feef819e --- /dev/null +++ b/languages/cpp/templates/additional-types/boolean.cpp @@ -0,0 +1 @@ +Boolean() \ No newline at end of file diff --git a/languages/cpp/templates/additional-types/integer.cpp b/languages/cpp/templates/additional-types/integer.cpp new file mode 100644 index 00000000..15c659a4 --- /dev/null +++ b/languages/cpp/templates/additional-types/integer.cpp @@ -0,0 +1 @@ +Number() \ No newline at end of file diff --git a/languages/cpp/templates/additional-types/number.cpp b/languages/cpp/templates/additional-types/number.cpp new file mode 100644 index 00000000..a5d368a4 --- /dev/null +++ b/languages/cpp/templates/additional-types/number.cpp @@ -0,0 +1 @@ +Float() \ No newline at end of file diff --git a/languages/cpp/templates/additional-types/string.cpp b/languages/cpp/templates/additional-types/string.cpp new file mode 100644 index 00000000..d2a52c84 --- /dev/null +++ b/languages/cpp/templates/additional-types/string.cpp @@ -0,0 +1 @@ +String() \ No newline at end of file diff --git a/languages/cpp/templates/callback-parameter-serialization/generic.cpp b/languages/cpp/templates/callback-parameter-serialization/generic.cpp new file mode 100644 index 00000000..530005ca --- /dev/null +++ b/languages/cpp/templates/callback-parameter-serialization/generic.cpp @@ -0,0 +1 @@ + WPEFramework::Core::ProxyType<${method.result.json}>* proxyResponse = reinterpret_cast*>(jsonResponse); \ No newline at end of file diff --git a/languages/cpp/templates/callback-parameter-serialization/primitive.cpp b/languages/cpp/templates/callback-parameter-serialization/primitive.cpp new file mode 100644 index 00000000..23bbace7 --- /dev/null +++ b/languages/cpp/templates/callback-parameter-serialization/primitive.cpp @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/cpp/templates/json-types/default.cpp b/languages/cpp/templates/callback-parameter-serialization/ref.h similarity index 100% rename from languages/cpp/templates/json-types/default.cpp rename to languages/cpp/templates/callback-parameter-serialization/ref.h diff --git a/languages/cpp/templates/callback-response-instantiation/generic.cpp b/languages/cpp/templates/callback-response-instantiation/generic.cpp new file mode 100644 index 00000000..c8f3f090 --- /dev/null +++ b/languages/cpp/templates/callback-response-instantiation/generic.cpp @@ -0,0 +1 @@ +response \ No newline at end of file diff --git a/languages/cpp/templates/callback-response-instantiation/primitive.cpp b/languages/cpp/templates/callback-response-instantiation/primitive.cpp new file mode 100644 index 00000000..23bbace7 --- /dev/null +++ b/languages/cpp/templates/callback-response-instantiation/primitive.cpp @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/cpp/templates/json-types/ref.c b/languages/cpp/templates/callback-response-instantiation/ref.h similarity index 100% rename from languages/cpp/templates/json-types/ref.c rename to languages/cpp/templates/callback-response-instantiation/ref.h diff --git a/languages/cpp/templates/callback-result-instantiation/additionalProperties.cpp b/languages/cpp/templates/callback-result-instantiation/additionalProperties.cpp new file mode 100644 index 00000000..a304af7e --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/additionalProperties.cpp @@ -0,0 +1,5 @@ + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} elements = (*proxyResponse)->Variants(); + ${if.namespace.notsame}${info.Title}::${end.if.namespace.notsame}${title} response; + while (elements.Next()) { + response.insert(elements.Label(), elements.Current().${additional.type}.Value()); + } \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/array.cpp b/languages/cpp/templates/callback-result-instantiation/array.cpp new file mode 100644 index 00000000..603644e3 --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/array.cpp @@ -0,0 +1,5 @@ + auto index((*proxyResponse)->Elements()); + ${type} response; + while (index.Next() == true) { + response.push_back(index.Current().Value()); + } diff --git a/languages/cpp/templates/callback-result-instantiation/enum.cpp b/languages/cpp/templates/callback-result-instantiation/enum.cpp new file mode 100644 index 00000000..30fdf717 --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/enum.cpp @@ -0,0 +1 @@ + ${if.namespace.notsame}${info.Title}::${end.if.namespace.notsame}${title} response = (*proxyResponse)->Value(); \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/generic.cpp b/languages/cpp/templates/callback-result-instantiation/generic.cpp new file mode 100644 index 00000000..8c7a2fea --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/generic.cpp @@ -0,0 +1 @@ + ${type} response = (*proxyResponse)->Value(); \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/object.cpp b/languages/cpp/templates/callback-result-instantiation/object.cpp new file mode 100644 index 00000000..8722a92e --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/object.cpp @@ -0,0 +1,2 @@ + ${title} response; +${properties} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/primitive.cpp b/languages/cpp/templates/callback-result-instantiation/primitive.cpp new file mode 100644 index 00000000..23bbace7 --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/primitive.cpp @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/property.cpp b/languages/cpp/templates/callback-result-instantiation/property.cpp new file mode 100644 index 00000000..31648b06 --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/property.cpp @@ -0,0 +1 @@ +${shape} ${if.non.object}response.${property} = (*proxyResponse)->${Property};${end.if.non.object} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/default.cpp b/languages/cpp/templates/callback-result-instantiation/ref.h similarity index 100% rename from languages/cpp/templates/result-instantiation/default.cpp rename to languages/cpp/templates/callback-result-instantiation/ref.h diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/object-separator.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/object-separator.cpp new file mode 100644 index 00000000..945c9b46 --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/object-separator.cpp @@ -0,0 +1 @@ +. \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp new file mode 100644 index 00000000..c4569c3e --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp @@ -0,0 +1 @@ +${properties} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp new file mode 100644 index 00000000..1f8541f2 --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp @@ -0,0 +1 @@ +${shape} ${if.non.object}response.${property.dependency}${property} = (*proxyResponse)->${Property.dependency}${Property};${end.if.non.object} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/ref.h b/languages/cpp/templates/callback-result-instantiation/sub-property/ref.h new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/ref.h @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/title.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/title.cpp new file mode 100644 index 00000000..2a420b4b --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/title.cpp @@ -0,0 +1 @@ +${Title} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/title.cpp b/languages/cpp/templates/callback-result-instantiation/title.cpp new file mode 100644 index 00000000..2a420b4b --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/title.cpp @@ -0,0 +1 @@ +${Title} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/tuple.cpp b/languages/cpp/templates/callback-result-instantiation/tuple.cpp new file mode 100644 index 00000000..76dde980 --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/tuple.cpp @@ -0,0 +1,4 @@ + auto index((*proxyResponse)->Elements()); + ${if.namespace.notsame}${info.Title}::${end.if.namespace.notsame}${title} response; + response.first = index.Get(0); + response.second = index.Get(1); \ No newline at end of file diff --git a/languages/cpp/templates/json-types/additionalProperties.c b/languages/cpp/templates/json-types/additionalProperties.c deleted file mode 100644 index b814e5fb..00000000 --- a/languages/cpp/templates/json-types/additionalProperties.c +++ /dev/null @@ -1 +0,0 @@ -// need cpp code to init, get, set, clear additional properties... \ No newline at end of file diff --git a/languages/cpp/templates/json-types/additionalProperties.cpp b/languages/cpp/templates/json-types/additionalProperties.cpp new file mode 100644 index 00000000..3466cdce --- /dev/null +++ b/languages/cpp/templates/json-types/additionalProperties.cpp @@ -0,0 +1 @@ + using ${title} = WPEFramework::Core::JSON::VariantContainer; \ No newline at end of file diff --git a/languages/cpp/templates/json-types/array.c b/languages/cpp/templates/json-types/array.c deleted file mode 100644 index 508a9eac..00000000 --- a/languages/cpp/templates/json-types/array.c +++ /dev/null @@ -1,4 +0,0 @@ -uint32_t ${info.Title}_${Title}Array_Size(${type} handle); -${type} ${title}Array_Get(${type} handle, uint32_t index); -void ${info.Title}_${Title}Array_Add(${propertyType} handle, ${valueType} value); -void ${info.Title}_${Title}Array_Clear(${propertyType} handle); diff --git a/languages/cpp/templates/json-types/array.h b/languages/cpp/templates/json-types/array.h new file mode 100644 index 00000000..4ab0d5ac --- /dev/null +++ b/languages/cpp/templates/json-types/array.h @@ -0,0 +1 @@ +WPEFramework::Core::JSON::ArrayType<${json.type}> \ No newline at end of file diff --git a/languages/cpp/templates/json-types/boolean.c b/languages/cpp/templates/json-types/boolean.h similarity index 100% rename from languages/cpp/templates/json-types/boolean.c rename to languages/cpp/templates/json-types/boolean.h diff --git a/languages/cpp/templates/json-types/const.c b/languages/cpp/templates/json-types/const.h similarity index 100% rename from languages/cpp/templates/json-types/const.c rename to languages/cpp/templates/json-types/const.h diff --git a/languages/cpp/templates/json-types/default.h b/languages/cpp/templates/json-types/default.h new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/json-types/default.h @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/json-types/enum.cpp b/languages/cpp/templates/json-types/enum.cpp index 6776b41a..9acb1ea5 100644 --- a/languages/cpp/templates/json-types/enum.cpp +++ b/languages/cpp/templates/json-types/enum.cpp @@ -1,4 +1 @@ - /* ${title} ${description} */ - ENUM_CONVERSION_BEGIN(${name}) - { ${NAME}_${key}, _T("${value}") }, - ENUM_CONVERSION_END(${name}) + using JsonData_${type} = WPEFramework::Core::JSON::EnumType<${type}>; diff --git a/languages/cpp/templates/json-types/enum.h b/languages/cpp/templates/json-types/enum.h deleted file mode 100644 index 92108c75..00000000 --- a/languages/cpp/templates/json-types/enum.h +++ /dev/null @@ -1,4 +0,0 @@ -/* ${title} ${description} */ -typedef enum { - ${NAME}_${key}, -} ${name}; diff --git a/languages/cpp/templates/json-types/integer.c b/languages/cpp/templates/json-types/integer.h similarity index 100% rename from languages/cpp/templates/json-types/integer.c rename to languages/cpp/templates/json-types/integer.h diff --git a/languages/cpp/templates/json-types/namespace.c b/languages/cpp/templates/json-types/namespace.c deleted file mode 100644 index 8ea9d7de..00000000 --- a/languages/cpp/templates/json-types/namespace.c +++ /dev/null @@ -1 +0,0 @@ -FireboltSDK::${info.Title}:: \ No newline at end of file diff --git a/languages/cpp/templates/json-types/namespace.h b/languages/cpp/templates/json-types/namespace.h new file mode 100644 index 00000000..c63c1089 --- /dev/null +++ b/languages/cpp/templates/json-types/namespace.h @@ -0,0 +1 @@ +Firebolt::${info.Title}:: \ No newline at end of file diff --git a/languages/cpp/templates/json-types/null.h b/languages/cpp/templates/json-types/null.h new file mode 100644 index 00000000..fc121f63 --- /dev/null +++ b/languages/cpp/templates/json-types/null.h @@ -0,0 +1 @@ +WPEFramework::Core::JSON::VariantContainer \ No newline at end of file diff --git a/languages/cpp/templates/json-types/float.c b/languages/cpp/templates/json-types/number.h similarity index 100% rename from languages/cpp/templates/json-types/float.c rename to languages/cpp/templates/json-types/number.h diff --git a/languages/cpp/templates/json-types/object.cpp b/languages/cpp/templates/json-types/object.cpp index db24d12c..43c667d3 100644 --- a/languages/cpp/templates/json-types/object.cpp +++ b/languages/cpp/templates/json-types/object.cpp @@ -6,20 +6,20 @@ ${title}() : WPEFramework::Core::JSON::Container() { - ${properties.register} +${properties.register} } ${title}(const ${title}& other) { - ${properties.assign} +${properties.assign} } ${title}& operator=(const ${title}& other) { - ${properties.assign} +${properties.assign} return (*this); } public: - ${properties} +${properties} }; diff --git a/languages/cpp/templates/json-types/primitive.c b/languages/cpp/templates/json-types/primitive.c deleted file mode 100644 index e69de29b..00000000 diff --git a/languages/cpp/templates/json-types/primitive.h b/languages/cpp/templates/json-types/primitive.h new file mode 100644 index 00000000..23bbace7 --- /dev/null +++ b/languages/cpp/templates/json-types/primitive.h @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/cpp/templates/json-types/property-assign.cpp b/languages/cpp/templates/json-types/property-assign.cpp index 88795136..36bdbf83 100644 --- a/languages/cpp/templates/json-types/property-assign.cpp +++ b/languages/cpp/templates/json-types/property-assign.cpp @@ -1,2 +1,2 @@ - Add(_T("${property}"), &${Property}); - ${Property} = other.${Property} + Add(_T("${property}"), &${Property}); + ${Property} = other.${Property}; diff --git a/languages/cpp/templates/json-types/property-register.cpp b/languages/cpp/templates/json-types/property-register.cpp index 400b4fd5..01e2a7e0 100644 --- a/languages/cpp/templates/json-types/property-register.cpp +++ b/languages/cpp/templates/json-types/property-register.cpp @@ -1,2 +1 @@ - Add(_T("${property}"), &${Property}); - \ No newline at end of file + Add(_T("${property}"), &${Property}); \ No newline at end of file diff --git a/languages/cpp/templates/json-types/ref.h b/languages/cpp/templates/json-types/ref.h new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/json-types/ref.h @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/json-types/string.c b/languages/cpp/templates/json-types/string.h similarity index 100% rename from languages/cpp/templates/json-types/string.c rename to languages/cpp/templates/json-types/string.h diff --git a/languages/cpp/templates/json-types/title.c b/languages/cpp/templates/json-types/title.h similarity index 100% rename from languages/cpp/templates/json-types/title.c rename to languages/cpp/templates/json-types/title.h diff --git a/languages/cpp/templates/json-types/tuple.c b/languages/cpp/templates/json-types/tuple.c deleted file mode 100644 index db24d12c..00000000 --- a/languages/cpp/templates/json-types/tuple.c +++ /dev/null @@ -1,25 +0,0 @@ - class ${title}: public WPEFramework::Core::JSON::Container { - public: - ~${title}() override = default; - - public: - ${title}() - : WPEFramework::Core::JSON::Container() - { - ${properties.register} - } - - ${title}(const ${title}& other) - { - ${properties.assign} - } - - ${title}& operator=(const ${title}& other) - { - ${properties.assign} - return (*this); - } - - public: - ${properties} - }; diff --git a/languages/cpp/templates/json-types/tuple.cpp b/languages/cpp/templates/json-types/tuple.cpp new file mode 100644 index 00000000..f734872b --- /dev/null +++ b/languages/cpp/templates/json-types/tuple.cpp @@ -0,0 +1 @@ + using ${title} = WPEFramework::Core::JSON::ArrayType<${json.type}>; \ No newline at end of file diff --git a/languages/cpp/templates/json-types/types/object.c b/languages/cpp/templates/json-types/types/object.c deleted file mode 100644 index e69de29b..00000000 diff --git a/languages/cpp/templates/json-types/void.cpp b/languages/cpp/templates/json-types/void.cpp new file mode 100644 index 00000000..fc121f63 --- /dev/null +++ b/languages/cpp/templates/json-types/void.cpp @@ -0,0 +1 @@ +WPEFramework::Core::JSON::VariantContainer \ No newline at end of file diff --git a/languages/cpp/templates/json-types/x-method.c b/languages/cpp/templates/json-types/x-method.h similarity index 100% rename from languages/cpp/templates/json-types/x-method.c rename to languages/cpp/templates/json-types/x-method.h diff --git a/languages/cpp/templates/language/enum-item.c b/languages/cpp/templates/language/enum-item.h similarity index 100% rename from languages/cpp/templates/language/enum-item.c rename to languages/cpp/templates/language/enum-item.h diff --git a/languages/cpp/templates/language/enum.c b/languages/cpp/templates/language/enum.h similarity index 100% rename from languages/cpp/templates/language/enum.c rename to languages/cpp/templates/language/enum.h diff --git a/languages/cpp/templates/language/parameter.c b/languages/cpp/templates/language/parameter.h similarity index 100% rename from languages/cpp/templates/language/parameter.c rename to languages/cpp/templates/language/parameter.h diff --git a/languages/cpp/templates/language/schema-item.c b/languages/cpp/templates/language/schema-item.h similarity index 100% rename from languages/cpp/templates/language/schema-item.c rename to languages/cpp/templates/language/schema-item.h diff --git a/languages/cpp/templates/language/schema.c b/languages/cpp/templates/language/schema.h similarity index 100% rename from languages/cpp/templates/language/schema.c rename to languages/cpp/templates/language/schema.h diff --git a/languages/cpp/templates/parameter-serialization/array.cpp b/languages/cpp/templates/parameter-serialization/array.cpp new file mode 100644 index 00000000..d45916ab --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/array.cpp @@ -0,0 +1,7 @@ + WPEFramework::Core::JSON::ArrayType ${Property}; + for (auto& element : ${property}) { +${if.object}${items.with.indent}${end.if.object}${if.non.object}${Property}.Add() = element;${end.if.non.object} + } + WPEFramework::Core::JSON::Variant ${Property}Variant; + ${Property}Variant.Array(${Property}); + jsonParameters.Set(_T("${property}"), ${Property}Variant); diff --git a/languages/cpp/templates/parameter-serialization/boolean.cpp b/languages/cpp/templates/parameter-serialization/boolean.cpp deleted file mode 100644 index f924ac94..00000000 --- a/languages/cpp/templates/parameter-serialization/boolean.cpp +++ /dev/null @@ -1,2 +0,0 @@ - WPEFramework::Core::JSON::Variant ${Property} = ${property}; - jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/cpp/templates/parameter-serialization/default.cpp b/languages/cpp/templates/parameter-serialization/default.cpp deleted file mode 100644 index f924ac94..00000000 --- a/languages/cpp/templates/parameter-serialization/default.cpp +++ /dev/null @@ -1,2 +0,0 @@ - WPEFramework::Core::JSON::Variant ${Property} = ${property}; - jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/cpp/templates/parameter-serialization/enum.cpp b/languages/cpp/templates/parameter-serialization/enum.cpp new file mode 100644 index 00000000..2367c118 --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/enum.cpp @@ -0,0 +1,3 @@ + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonValue = ${property}${if.optional}.value()${end.if.optional}; + WPEFramework::Core::JSON::Variant ${Property}(jsonValue.Data()); + jsonParameters.Set(_T("${property}"), ${Property}); \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/generic.cpp b/languages/cpp/templates/parameter-serialization/generic.cpp index 8ccb8295..566c7354 100644 --- a/languages/cpp/templates/parameter-serialization/generic.cpp +++ b/languages/cpp/templates/parameter-serialization/generic.cpp @@ -1,2 +1,2 @@ - WPEFramework::Core::JSON::Variant ${Property} = ${property}; - jsonParameters.Set(_T("${property}"), ${Property}); \ No newline at end of file + WPEFramework::Core::JSON::Variant ${Property}(${property}${if.optional}.value()${end.if.optional}); + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/cpp/templates/parameter-serialization/object-array.cpp b/languages/cpp/templates/parameter-serialization/object-array.cpp new file mode 100644 index 00000000..0965afae --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/object-array.cpp @@ -0,0 +1,7 @@ + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${Property}Container; +${properties} + string ${Property}Str; + ${Property}Container.ToString(${Property}Str); + WPEFramework::Core::JSON::VariantContainer ${Property}VariantContainer(${Property}Str); + WPEFramework::Core::JSON::Variant ${Property}Variant = ${Property}VariantContainer; + ${Property}.Add() = ${Property}Variant; diff --git a/languages/cpp/templates/parameter-serialization/object.cpp b/languages/cpp/templates/parameter-serialization/object.cpp index f924ac94..42226921 100644 --- a/languages/cpp/templates/parameter-serialization/object.cpp +++ b/languages/cpp/templates/parameter-serialization/object.cpp @@ -1,2 +1,8 @@ - WPEFramework::Core::JSON::Variant ${Property} = ${property}; + auto element = ${property}; + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${Property}Container; +${properties} + string ${Property}Str; + ${Property}Container.ToString(${Property}Str); + WPEFramework::Core::JSON::VariantContainer ${Property}VariantContainer(${Property}Str); + WPEFramework::Core::JSON::Variant ${Property} = ${Property}VariantContainer; jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/cpp/templates/parameter-serialization/primitive.cpp b/languages/cpp/templates/parameter-serialization/primitive.cpp index f924ac94..23bbace7 100644 --- a/languages/cpp/templates/parameter-serialization/primitive.cpp +++ b/languages/cpp/templates/parameter-serialization/primitive.cpp @@ -1,2 +1 @@ - WPEFramework::Core::JSON::Variant ${Property} = ${property}; - jsonParameters.Set(_T("${property}"), ${Property}); +${type} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/property.cpp b/languages/cpp/templates/parameter-serialization/property.cpp new file mode 100644 index 00000000..7036ea07 --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/property.cpp @@ -0,0 +1 @@ +${shape} ${if.non.object}${base.Title}Container.${Property} = element${if.base.optional}.value()${end.if.base.optional}.${property}${if.optional}.value()${end.if.optional};${end.if.non.object} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/ref.h b/languages/cpp/templates/parameter-serialization/ref.h new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/ref.h @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/string.cpp b/languages/cpp/templates/parameter-serialization/string.cpp deleted file mode 100644 index f924ac94..00000000 --- a/languages/cpp/templates/parameter-serialization/string.cpp +++ /dev/null @@ -1,2 +0,0 @@ - WPEFramework::Core::JSON::Variant ${Property} = ${property}; - jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/cpp/templates/parameter-serialization/sub-property/object-separator.cpp b/languages/cpp/templates/parameter-serialization/sub-property/object-separator.cpp new file mode 100644 index 00000000..945c9b46 --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/sub-property/object-separator.cpp @@ -0,0 +1 @@ +. \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/object.cpp b/languages/cpp/templates/parameter-serialization/sub-property/object.cpp new file mode 100644 index 00000000..c4569c3e --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/sub-property/object.cpp @@ -0,0 +1 @@ +${properties} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/property.cpp b/languages/cpp/templates/parameter-serialization/sub-property/property.cpp new file mode 100644 index 00000000..58aa5943 --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/sub-property/property.cpp @@ -0,0 +1 @@ +${shape} ${if.non.object}${title}.${Property.dependency}${Property} = element${if.base.optional}.value()${end.if.base.optional}.${property.dependency}${property}${if.optional}.value()${end.if.optional};${end.if.non.object} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/ref.h b/languages/cpp/templates/parameter-serialization/sub-property/ref.h new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/sub-property/ref.h @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/title.cpp b/languages/cpp/templates/parameter-serialization/sub-property/title.cpp new file mode 100644 index 00000000..e2e80c7c --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/sub-property/title.cpp @@ -0,0 +1 @@ +${Title} diff --git a/languages/cpp/templates/parameters/optional.h b/languages/cpp/templates/parameters/optional.h index 69cb4659..d21cf868 100644 --- a/languages/cpp/templates/parameters/optional.h +++ b/languages/cpp/templates/parameters/optional.h @@ -1 +1 @@ -std::optional<${method.param.type}> ${method.param.name} \ No newline at end of file +const std::optional<${method.param.type}>& ${method.param.name} \ No newline at end of file diff --git a/languages/cpp/templates/result-initialization/additionalProperties.cpp b/languages/cpp/templates/result-initialization/additionalProperties.cpp new file mode 100644 index 00000000..c33c2ea0 --- /dev/null +++ b/languages/cpp/templates/result-initialization/additionalProperties.cpp @@ -0,0 +1 @@ + ${Title} ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/result-initialization/array.cpp b/languages/cpp/templates/result-initialization/array.cpp new file mode 100644 index 00000000..2f0629ac --- /dev/null +++ b/languages/cpp/templates/result-initialization/array.cpp @@ -0,0 +1 @@ + ${type} ${property}; diff --git a/languages/cpp/templates/result-initialization/boolean.cpp b/languages/cpp/templates/result-initialization/boolean.cpp new file mode 100644 index 00000000..23bbf1be --- /dev/null +++ b/languages/cpp/templates/result-initialization/boolean.cpp @@ -0,0 +1 @@ + ${type} ${property} = false; \ No newline at end of file diff --git a/languages/cpp/templates/result-initialization/generic.cpp b/languages/cpp/templates/result-initialization/generic.cpp new file mode 100644 index 00000000..1bcce663 --- /dev/null +++ b/languages/cpp/templates/result-initialization/generic.cpp @@ -0,0 +1 @@ + ${type} ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/result-initialization/namespace.cpp b/languages/cpp/templates/result-initialization/namespace.cpp new file mode 100644 index 00000000..b3afde8a --- /dev/null +++ b/languages/cpp/templates/result-initialization/namespace.cpp @@ -0,0 +1 @@ +${if.namespace.notsame}${parent.Title}::${end.if.namespace.notsame} \ No newline at end of file diff --git a/languages/cpp/templates/result-initialization/number.cpp b/languages/cpp/templates/result-initialization/number.cpp new file mode 100644 index 00000000..6e34ae51 --- /dev/null +++ b/languages/cpp/templates/result-initialization/number.cpp @@ -0,0 +1 @@ + ${type} ${property} = 0; \ No newline at end of file diff --git a/languages/cpp/templates/result-initialization/primitive.cpp b/languages/cpp/templates/result-initialization/primitive.cpp new file mode 100644 index 00000000..23bbace7 --- /dev/null +++ b/languages/cpp/templates/result-initialization/primitive.cpp @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/cpp/templates/result-initialization/string.cpp b/languages/cpp/templates/result-initialization/string.cpp new file mode 100644 index 00000000..2f0629ac --- /dev/null +++ b/languages/cpp/templates/result-initialization/string.cpp @@ -0,0 +1 @@ + ${type} ${property}; diff --git a/languages/cpp/templates/result-initialization/title.cpp b/languages/cpp/templates/result-initialization/title.cpp new file mode 100644 index 00000000..2a420b4b --- /dev/null +++ b/languages/cpp/templates/result-initialization/title.cpp @@ -0,0 +1 @@ +${Title} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/additionalProperties.cpp b/languages/cpp/templates/result-instantiation/additionalProperties.cpp new file mode 100644 index 00000000..e5d7b116 --- /dev/null +++ b/languages/cpp/templates/result-instantiation/additionalProperties.cpp @@ -0,0 +1,6 @@ + while (jsonResult.Variants().Next()) { + std::string label = jsonResult.Variants().Label(); + ${property}.emplace(std::piecewise_construct, + std::forward_as_tuple(label), + std::forward_as_tuple(jsonResult.Variants().Current().${additional.type})); + } \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/array.cpp b/languages/cpp/templates/result-instantiation/array.cpp new file mode 100644 index 00000000..2fab5f07 --- /dev/null +++ b/languages/cpp/templates/result-instantiation/array.cpp @@ -0,0 +1,4 @@ + auto index(jsonResult.Elements()); + while (index.Next() == true) { +${if.object}${items.with.indent}${end.if.object}${if.non.object} ${property}.push_back(index.Current().Value());${end.if.non.object} + } \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/boolean.cpp b/languages/cpp/templates/result-instantiation/boolean.cpp deleted file mode 100644 index 036b4a7d..00000000 --- a/languages/cpp/templates/result-instantiation/boolean.cpp +++ /dev/null @@ -1,2 +0,0 @@ - *${property} = jsonResult.Value(); - \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/generic.cpp b/languages/cpp/templates/result-instantiation/generic.cpp new file mode 100644 index 00000000..8949a5fb --- /dev/null +++ b/languages/cpp/templates/result-instantiation/generic.cpp @@ -0,0 +1 @@ + ${property} = jsonResult.Value(); \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/object-array.cpp b/languages/cpp/templates/result-instantiation/object-array.cpp new file mode 100644 index 00000000..0c396b43 --- /dev/null +++ b/languages/cpp/templates/result-instantiation/object-array.cpp @@ -0,0 +1,4 @@ + ${type} ${property}Result${level}; + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonResult = index.Current(); +${properties} + ${property}.push_back(${property}Result${level}); \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/object.cpp b/languages/cpp/templates/result-instantiation/object.cpp index dcf0b333..5119c58b 100644 --- a/languages/cpp/templates/result-instantiation/object.cpp +++ b/languages/cpp/templates/result-instantiation/object.cpp @@ -1,4 +1,3 @@ - WPEFramework::Core::ProxyType* resultPtr = new WPEFramework::Core::ProxyType(); - *resultPtr = WPEFramework::Core::ProxyType::Create(); - *(*resultPtr) = jsonResult; - *${property} = static_cast<${info.Title}_${title}>(resultPtr); + ${type} ${property}Result${level}; +${properties} + ${property} = ${property}Result${level}; \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/property.cpp b/languages/cpp/templates/result-instantiation/property.cpp new file mode 100644 index 00000000..fe19dab1 --- /dev/null +++ b/languages/cpp/templates/result-instantiation/property.cpp @@ -0,0 +1 @@ +${shape} ${if.non.array}${if.non.object}${base.title}Result${level}.${property} = jsonResult.${Property}.Value();${end.if.non.object}${end.if.non.array} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/ref.h b/languages/cpp/templates/result-instantiation/ref.h new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/result-instantiation/ref.h @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/string.cpp b/languages/cpp/templates/result-instantiation/string.cpp index b6c9dcb5..886728a4 100644 --- a/languages/cpp/templates/result-instantiation/string.cpp +++ b/languages/cpp/templates/result-instantiation/string.cpp @@ -1,2 +1 @@ - FireboltSDK::JSON::String* strResult = new FireboltSDK::JSON::String(jsonResult); - *value = static_cast(strResult); + ${property} = jsonResult.Value().c_str(); \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/sub-property/array.cpp b/languages/cpp/templates/result-instantiation/sub-property/array.cpp new file mode 100644 index 00000000..efa1adeb --- /dev/null +++ b/languages/cpp/templates/result-instantiation/sub-property/array.cpp @@ -0,0 +1,4 @@ + auto index(jsonResult.${Property}.Elements()); + while (index.Next() == true) { +${if.object}${items.with.indent}${end.if.object}${if.non.object} ${property}.push_back(index.Current().Value());${end.if.non.object} + } \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/sub-property/object-array.cpp b/languages/cpp/templates/result-instantiation/sub-property/object-array.cpp new file mode 100644 index 00000000..06a4d04d --- /dev/null +++ b/languages/cpp/templates/result-instantiation/sub-property/object-array.cpp @@ -0,0 +1,4 @@ + ${type} ${property}Result${level}; + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonResult = index.Current(); +${properties} + ${property}Result.${property}${if.impl.optional}.value()${end.if.impl.optional}.push_back(${property}Result${level}); \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/sub-property/object-separator.cpp b/languages/cpp/templates/result-instantiation/sub-property/object-separator.cpp new file mode 100644 index 00000000..945c9b46 --- /dev/null +++ b/languages/cpp/templates/result-instantiation/sub-property/object-separator.cpp @@ -0,0 +1 @@ +. \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/sub-property/object.cpp b/languages/cpp/templates/result-instantiation/sub-property/object.cpp new file mode 100644 index 00000000..c04d0a50 --- /dev/null +++ b/languages/cpp/templates/result-instantiation/sub-property/object.cpp @@ -0,0 +1 @@ +${properties} diff --git a/languages/cpp/templates/result-instantiation/sub-property/property.cpp b/languages/cpp/templates/result-instantiation/sub-property/property.cpp new file mode 100644 index 00000000..97e0dc0f --- /dev/null +++ b/languages/cpp/templates/result-instantiation/sub-property/property.cpp @@ -0,0 +1 @@ +${shape} ${if.non.object}${base.title}Result${level}.${property.dependency}${if.impl.optional}value().${end.if.impl.optional}${property} = jsonResult.${Property.dependency}${Property};${end.if.non.object} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/sub-property/ref.h b/languages/cpp/templates/result-instantiation/sub-property/ref.h new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/result-instantiation/sub-property/ref.h @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/sub-property/title.cpp b/languages/cpp/templates/result-instantiation/sub-property/title.cpp new file mode 100644 index 00000000..2a420b4b --- /dev/null +++ b/languages/cpp/templates/result-instantiation/sub-property/title.cpp @@ -0,0 +1 @@ +${Title} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/title.cpp b/languages/cpp/templates/result-instantiation/title.cpp new file mode 100644 index 00000000..2a420b4b --- /dev/null +++ b/languages/cpp/templates/result-instantiation/title.cpp @@ -0,0 +1 @@ +${Title} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/tuple.cpp b/languages/cpp/templates/result-instantiation/tuple.cpp new file mode 100644 index 00000000..58f79f1d --- /dev/null +++ b/languages/cpp/templates/result-instantiation/tuple.cpp @@ -0,0 +1,3 @@ + auto index(jsonResult.Elements()); + ${property}.first = index.Get(0); + ${property}.second = index.Get(1); \ No newline at end of file diff --git a/languages/cpp/templates/types/additionalProperties.h b/languages/cpp/templates/types/additionalProperties.h index 05581106..eced27fe 100644 --- a/languages/cpp/templates/types/additionalProperties.h +++ b/languages/cpp/templates/types/additionalProperties.h @@ -1 +1 @@ -std::unordered_map<${key}, ${type}> ${title}; +using ${title} = std::unordered_map<${key}, ${type}>; diff --git a/languages/cpp/templates/types/const.h b/languages/cpp/templates/types/const.h index e69de29b..c6d1c815 100644 --- a/languages/cpp/templates/types/const.h +++ b/languages/cpp/templates/types/const.h @@ -0,0 +1 @@ +std::string \ No newline at end of file diff --git a/languages/cpp/templates/types/default.cpp b/languages/cpp/templates/types/default.cpp deleted file mode 100644 index 1f1fe89d..00000000 --- a/languages/cpp/templates/types/default.cpp +++ /dev/null @@ -1,4 +0,0 @@ -/* - * ${title} - ${description} - */ -${shape} diff --git a/languages/cpp/templates/types/default.h b/languages/cpp/templates/types/default.h new file mode 100644 index 00000000..a034b220 --- /dev/null +++ b/languages/cpp/templates/types/default.h @@ -0,0 +1 @@ +${shape} diff --git a/languages/cpp/templates/types/items.h b/languages/cpp/templates/types/items.h new file mode 100644 index 00000000..52268157 --- /dev/null +++ b/languages/cpp/templates/types/items.h @@ -0,0 +1 @@ +${title}${delimiter}, ${end.delimiter} \ No newline at end of file diff --git a/languages/cpp/templates/types/null.h b/languages/cpp/templates/types/null.h index e69de29b..ab6cc8f6 100644 --- a/languages/cpp/templates/types/null.h +++ b/languages/cpp/templates/types/null.h @@ -0,0 +1 @@ +void \ No newline at end of file diff --git a/languages/cpp/templates/types/object.h b/languages/cpp/templates/types/object.h index c7877332..88d35c97 100644 --- a/languages/cpp/templates/types/object.h +++ b/languages/cpp/templates/types/object.h @@ -1,5 +1,3 @@ struct ${title} { - ${properties} - }; \ No newline at end of file diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index c853e324..4def4f6e 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -1252,15 +1252,16 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) : '' - const serializedParams = flattenedMethod.params.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') + const serializedParams = flattenedMethod.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'parameter-serialization', property: param.name, required: param.required || false, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true })).join('\n') const resultInst = types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-instantiation', property: flattenedMethod.result.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) // w/out level: 1, getSchemaShape skips anonymous types, like primitives - 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') : '' + const resultInit = types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-initialization', property: flattenedMethod.result.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) // w/out level: 1, getSchemaShape skips anonymous types, like primitives + const serializedEventParams = event ? flattenedMethod.params.filter(p => p.name !== 'listen').map(param => types.getSchemaShape(param.schema, json, {templateDir: 'parameter-serialization', property: param.name, required: param.required || false, 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, { templateDir: 'result-instantiation' }) : '' -// const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.response' }) : '' + const callbackSerializedParams = event ? types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-parameter-serialization', property: result.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) : '' + + const callbackResultInst = event ? types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-result-instantiation', property: result.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) : '' // 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 callbackResponseInst = event ? types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-response-instantiation', property: result.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) : '' 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}) diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index f25a9689..e7bd5e71 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -51,6 +51,21 @@ function setAllocatedPrimitiveProxies(m) { } const capitalize = str => str ? str[0].toUpperCase() + str.substr(1) : str +const indent = (str, padding) => { + let first = true + if (str) { + return str.split('\n').map(line => { + if (first) { + first = false + return line + } + else { + return padding + line + } + }).join('\n') + } +} + const safeName = value => value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() // TODO: This is what's left of getMethodSignatureParams. We need to figure out / handle C's `FireboltTypes_StringHandle` @@ -78,7 +93,7 @@ function getMethodSignatureParams(method, module, { destination, callback }) { }).join(', ') } -function getMethodSignatureResult(method, module, { destination, callback, overrideRule = false }) { +function getMethodSignatureResult(method, module, { destination, callback }) { let type = getSchemaType(method.result.schema, module, { destination, namespace : true }) let result = '' @@ -124,7 +139,7 @@ const getXSchemaGroup = (schema, module) => { return group } -function insertSchemaMacros(content, schema, module, name, parent, property, recursive = true) { +function insertSchemaMacros(content, schema, module, { name = '', parent = '', property = '', required = true, recursive = true, templateDir = 'types'}) { const title = name || schema.title || '' let moduleTitle = getXSchemaGroup(schema, module) @@ -134,9 +149,11 @@ function insertSchemaMacros(content, schema, module, name, parent, property, rec .replace(/\$\{TITLE\}/g, title.toUpperCase()) .replace(/\$\{property\}/g, property) .replace(/\$\{Property\}/g, capitalize(property)) - .replace(/\$\{if\.namespace\.notsame}(.*?)\$\{end\.if\.namespace\.notsame\}/g, (module.info.title !== parent) ? '$1' : '') + .replace(/\$\{if\.namespace\.notsame}(.*?)\$\{end\.if\.namespace\.notsame\}/g, (module.info.title !== (parent || moduleTitle)) ? '$1' : '') .replace(/\$\{parent\.title\}/g, parent) .replace(/\$\{parent\.Title\}/g, capitalize(parent)) + .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, required ? '' : '$1') + .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, required ? '' : '$1') .replace(/\$\{description\}/g, schema.description ? schema.description : '') .replace(/\$\{summary\}/g, schema.description ? schema.description.split('\n')[0] : '') .replace(/\$\{name\}/g, title) @@ -146,14 +163,14 @@ function insertSchemaMacros(content, schema, module, name, parent, property, rec .replace(/\$\{info.TITLE\}/g, moduleTitle.toUpperCase()) if (recursive) { - content = content.replace(/\$\{type\}/g, getSchemaType(schema, module, { destination: state.destination, section: state.section, code: false, namespace: true })) + content = content.replace(/\$\{type\}/g, getSchemaType(schema, module, { templateDir: templateDir, destination: state.destination, section: state.section, code: false, namespace: true })) } return content } // TODO using JSON.stringify probably won't work for many languages... const insertConstMacros = (content, schema, module, name) => { - content = content.replace(/\$\{value\}/g, JSON.stringify(schema.const)) + content = content.replace(/\$\{value\}/g, (typeof schema.const === 'string' ? `'${schema.const}'` : schema.const)) return content } @@ -205,6 +222,7 @@ const insertObjectAdditionalPropertiesMacros = (content, schema, module, title, .replace(/\$\{key\}/g, key) .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, '') .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/g, '') + .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/g, '') return content } @@ -212,7 +230,9 @@ const insertObjectAdditionalPropertiesMacros = (content, schema, module, title, const insertObjectMacros = (content, schema, module, title, property, options) => { const options2 = options ? JSON.parse(JSON.stringify(options)) : {} options2.parent = title + options2.parentLevel = options.parentLevel options2.level = options.level + 1 + options2.templateDir = options.templateDir ;(['properties', 'properties.register', 'properties.assign']).forEach(macro => { const indent = (content.split('\n').find(line => line.includes("${" + macro + "}")) || '').match(/^\s+/) || [''][0] @@ -223,13 +243,19 @@ const insertObjectMacros = (content, schema, module, title, property, options) = if (schema.properties) { Object.entries(schema.properties).forEach(([name, prop], i) => { - options2.property = name + let localizedProp = localizeDependencies(prop, module) + const subProperty = getTemplate(path.join(options2.templateDir, 'sub-property/object')) + options2.templateDir += subProperty ? '/sub-property' : '' + const objSeparator = getTemplate(path.join(options2.templateDir, 'object-separator')) + + options2.required = prop.required ? prop.required : false const schemaShape = getSchemaShape(prop, module, options2) + const type = getSchemaType(prop, module, options2) // don't push properties w/ unsupported types if (type) { - properties.push((i !== 0 ? indent : '') + template + let replacedTemplate = template .replace(/(^\s+)/g, '$1'.repeat(options2.level)) .replace(/\$\{property\}/g, name) .replace(/\$\{Property\}/g, capitalize(name)) @@ -239,7 +265,30 @@ const insertObjectMacros = (content, schema, module, title, property, options) = .replace(/\$\{description\}/g, prop.description || '') .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/gms, i === schema.properties.length - 1 ? '' : '$1') - .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, schema.required && schema.required.includes(name) ? '' : '$1')) + .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, schema.required && schema.required.includes(name) ? '' : '$1') + .replace(/\$\{if\.base\.optional\}(.*?)\$\{end\.if\.base\.optional\}/gms, options.required ? '' : '$1') + .replace(/\$\{if\.non\.object\}(.*?)\$\{end\.if\.non\.object\}/gms, (localizedProp.type === 'object') ? '' : '$1') + .replace(/\$\{if\.non\.array\}(.*?)\$\{end\.if\.non\.array\}/gms, (localizedProp.type === 'array') ? '' : '$1') + let baseTitle = options.property + if (localizedProp.type === 'object') { + replacedTemplate = replacedTemplate + .replace(/\$\{property.dependency\}/g, ((options.level > 1) ? '${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}' : '') + name + objSeparator) + .replace(/\$\{Property.dependency\}/g, ((options.level > 1) ? '${Property.dependency}' : '') + capitalize(name) + (objSeparator)) + } + else { + if (options2.level <= 1) { + replacedTemplate = replacedTemplate + .replace(/\$\{property.dependency\}/g, '') + .replace(/\$\{Property.dependency\}/g, '') + .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, '') + } + } + replacedTemplate = replacedTemplate + .replace(/\$\{obj\.separator}/g, objSeparator) + .replace(/\$\{base.title\}/g, (baseTitle ? (baseTitle)[0].toLowerCase() + (baseTitle).substr(1) : '')).trimEnd() + .replace(/\$\{base.Title\}/g, (baseTitle ? (baseTitle)[0].toUpperCase() + (baseTitle).substr(1) : '')).trimEnd() + .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, prop.required ? '' : '$1') + properties.push((i !== 0 ? indent : '') + replacedTemplate) } }) } @@ -289,12 +338,17 @@ const insertObjectMacros = (content, schema, module, title, property, options) = const regex = new RegExp("\\$\\{" + macro + "\\}", "g") content = content.replace(regex, properties.join('\n')) + .replace(/\$\{level}/g, options.parentLevel > 0 ? options.parentLevel : '') }) return content } -const insertArrayMacros = (content, schema, module, name) => { +const insertArrayMacros = (content, schema, module, level = 0, items) => { + content = content + .replace(/\$\{json\.type\}/g, getSchemaType(schema.items, module, { templateDir: 'json-types', destination: state.destination, section: state.section, code: false, namespace: true })) + .replace(/\$\{items\}/g, items) + .replace(/\$\{items\.with\.indent\}/g, indent(items, ' ')) return content } @@ -321,16 +375,17 @@ const insertTupleMacros = (content, schema, module, title, options) => { .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, i === schema.items.length - 1 ? '' : '$1') .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, '') + .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, '') } content = content.replace(/\$\{properties\}/g, schema.items.map((prop, i) => doMacroWork(propTemplate, prop, i, propIndent)).join(tupleDelimiter)) content = content.replace(/\$\{items\}/g, schema.items.map((prop, i) => doMacroWork(itemsTemplate, prop, i, itemsIndent)).join(tupleDelimiter)) - + content = content.replace(/\$\{json\.type\}/g, getSchemaType(schema.items[0], module, { templateDir: 'json-types', destination: state.destination, section: state.section, code: false, namespace: true })) return content } -const getPrimitiveType = (type, templateDir) => { - const template = getTemplate(path.join(templateDir, type)) +const getPrimitiveType = (type, templateDir = 'types') => { + const template = getTemplate(path.join(templateDir, type)) || getTemplate(path.join(templateDir, 'generic')) return primitives[type] || template } @@ -369,7 +424,7 @@ const sanitize = (schema) => { return result } -function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', name = '', parent = '', property = '', level = 0, summary, descriptions = true, destination, section, enums = true, skipTitleOnce = false } = {}) { +function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', parent = '', property = '', required = true, parentLevel = 0, level = 0, summary, descriptions = true, destination, section, enums = true, skipTitleOnce = false, array = false } = {}) { schema = sanitize(schema) state.destination = destination @@ -380,37 +435,38 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', name } const suffix = destination && ('.' + destination.split('.').pop()) || '' - const theTitle = insertSchemaMacros(getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, schema.title || name, parent, property, false) + const theTitle = insertSchemaMacros(getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, { name: schema.title, parent, property, required, recursive: false}) let result = level === 0 ? getTemplate(path.join(templateDir, 'default' + suffix)) : '${shape}' + let genericTemplate = getTemplate(path.join(templateDir, 'generic' + suffix)) if (enums && level === 0 && Array.isArray(schema.enum) && ((schema.type === "string") || (schema.type[0] === "string"))) { - result = getTemplate(path.join(templateDir, 'enum' + suffix)) - return insertSchemaMacros(insertEnumMacros(result, schema, module, theTitle, suffix, templateDir), schema, module, theTitle, parent, property) + result = getTemplate(path.join(templateDir, 'enum' + suffix)) || genericTemplate + return insertSchemaMacros(insertEnumMacros(result, schema, module, theTitle, suffix, templateDir), schema, module, { name: theTitle, parent, property, required }) } if (schema['$ref']) { const someJson = getPath(schema['$ref'], module) if (someJson) { - return getSchemaShape(someJson, module, { templateDir, name, parent, property, level, summary, descriptions, destination, enums }) + return getSchemaShape(someJson, module, { templateDir, parent, property, required, parentLevel, level, summary, descriptions, destination, enums, array }) } throw "Unresolvable $ref: " + schema['ref'] + ", in " + module.info.title } else if (schema.hasOwnProperty('const')) { const shape = insertConstMacros(getTemplate(path.join(templateDir, 'const' + suffix)), schema, module, theTitle) - result = insertSchemaMacros(result.replace(/\$\{shape\}/g, shape), schema, module, theTitle, parent, property) + result = insertSchemaMacros(result.replace(/\$\{shape\}/g, shape), schema, module, { name: theTitle, parent, property, required }) return result } else if (!skipTitleOnce && (level > 0) && schema.title) { let enumType = (schema.type === 'string' && Array.isArray(schema.enum)) // TODO: allow the 'ref' template to actually insert the shape using getSchemaShape - const innerShape = getSchemaShape(schema, module, { skipTitleOnce: true, templateDir, name, parent, property, level, summary, descriptions, destination, enums: enumType }) + const innerShape = getSchemaShape(schema, module, { skipTitleOnce: true, templateDir, parent, property, required, parentLevel, level, summary, descriptions, destination, enums: enumType, array }) const shape = getTemplate(path.join(templateDir, 'ref' + suffix)) .replace(/\$\{shape\}/g, innerShape) result = result.replace(/\$\{shape\}/g, shape) - return insertSchemaMacros(result, schema, module, theTitle, parent, property) + return insertSchemaMacros(result, schema, module, { name: theTitle, parent, property, required }) } else if (schema.type === 'object') { let shape @@ -419,16 +475,17 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', name shape = insertObjectAdditionalPropertiesMacros(additionalPropertiesTemplate, schema, module, theTitle, { level, parent, templateDir, namespace: true }) } else { - shape = insertObjectMacros(getTemplate(path.join(templateDir, 'object' + suffix)), schema, module, theTitle, property, { level, parent, property, templateDir, descriptions, destination, section, enums, namespace: true }) + let objectLevel = array ? 0 : level + shape = insertObjectMacros(getTemplate(path.join(templateDir, 'object' + (array ? '-array' : '') + suffix)) || genericTemplate, schema, module, theTitle, property, { parentLevel, level: objectLevel, parent, property, required, templateDir, descriptions, destination, section, enums, namespace: true }) } result = result.replace(/\$\{shape\}/g, shape) - return insertSchemaMacros(result, schema, module, theTitle, parent, property) + return insertSchemaMacros(result, schema, module, { name: theTitle, parent, property, required, templateDir }) } else if (schema.anyOf || schema.oneOf) { const template = getTemplate(path.join(templateDir, 'anyOfSchemaShape' + suffix)) let shape if (template) { - shape = insertAnyOfMacros(template, schema, module, theTitle) + shape = insertAnyOfMacros(template, schema, module, theTitle) } else { // borrow anyOf logic, note that schema is a copy, so we're not breaking it. @@ -439,7 +496,7 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', name } if (shape) { result = result.replace(/\$\{shape\}/g, shape) - return insertSchemaMacros(result, schema, module, theTitle, parent, property) + return insertSchemaMacros(result, schema, module, { name: theTitle, parent, property, required }) } else { return '' @@ -467,26 +524,28 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', name } delete union['$ref'] - return getSchemaShape(union, module, { templateDir, name, parent, property, level, summary, descriptions, destination, enums: false }) + return getSchemaShape(union, module, { templateDir, parent, property, required, parentLevel, level, summary, descriptions, destination, enums: false, array }) } else if (schema.type === "array" && schema.items && isSupportedTuple(schema)) { // tuple - const shape = insertTupleMacros(getTemplate(path.join(templateDir, 'tuple' + suffix)), schema, module, theTitle, { level, templateDir, descriptions, destination, section, enums }) + const shape = insertTupleMacros(getTemplate(path.join(templateDir, 'tuple' + suffix)) || genericTemplate, schema, module, theTitle, { level, templateDir, descriptions, destination, section, enums }) result = result.replace(/\$\{shape\}/g, shape) - return insertSchemaMacros(result, schema, module, theTitle, parent, property) + return insertSchemaMacros(result, schema, module, { name: theTitle, parent, property, required, templateDir }) } else if (schema.type === "array" && schema.items && !Array.isArray(schema.items)) { // array - const items = getSchemaShape(schema.items, module, { templateDir, name, parent, property, level, summary, descriptions, destination, enums: false }) - const shape = insertArrayMacros(getTemplate(path.join(templateDir, 'array' + suffix)), schema, module, items) + const items = getSchemaShape(schema.items, module, { templateDir, parent, property, required, parentLevel: parentLevel + 1, level, summary, descriptions, destination, enums: false , array: true}) + const shape = insertArrayMacros(getTemplate(path.join(templateDir, 'array' + suffix)) || genericTemplate, schema, module, level, items) result = result.replace(/\$\{shape\}/g, shape) - return insertSchemaMacros(result, schema, module, items, parent, property) + .replace(/\$\{if\.object\}(.*?)\$\{end\.if\.object\}/gms, (schema.items.type === 'object') ? '$1' : '') + .replace(/\$\{if\.non\.object\}(.*?)\$\{end\.if\.non\.object\}/gms, (schema.items.type !== 'object') ? '$1' : '') + return insertSchemaMacros(result, schema, module, { name: items, parent, property, required, templateDir }) } else if (schema.type) { - const shape = insertPrimitiveMacros(getTemplate(path.join(templateDir, 'primitive' + suffix)), schema, module, theTitle, templateDir) + const shape = insertPrimitiveMacros(getTemplate(path.join(templateDir, 'primitive' + suffix) || genericTemplate), schema, module, theTitle, templateDir) result = result.replace(/\$\{shape\}/g, shape) if (level > 0) { - return insertSchemaMacros(result, schema, module, theTitle, parent, property) + return insertSchemaMacros(result, schema, module, { name: theTitle, parent, property, required, templateDir}) } } @@ -548,7 +607,7 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin const suffix = destination && ('.' + destination.split('.').pop()) || '' const namespaceStr = namespace ? getTemplate(path.join(templateDir, 'namespace' + suffix)) : '' - const theTitle = insertSchemaMacros(namespaceStr + getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, schema.title || '', getXSchemaGroup(schema, module), '', false) + const theTitle = insertSchemaMacros(namespaceStr + getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, { name: schema.title, parent: getXSchemaGroup(schema, module), recursive: false}) const allocatedProxy = event || result const title = schema.type === "object" || schema.enum ? true : false @@ -579,7 +638,7 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin } } else if (schema.const) { - return (typeof schema.const === 'string' ? `'${schema.const}'` : schema.const) + return insertConstMacros(getTemplate(path.join(templateDir, 'const' + suffix)), schema, module) } else if (schema['x-method']) { const target = JSON.parse(JSON.stringify(module.methods.find(m => m.name === schema['x-method'].split('.').pop()))) @@ -598,7 +657,7 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin const params = getMethodSignatureParams(target, module, { destination }) const template = getTemplate(path.join(templateDir, 'x-method')) - return insertSchemaMacros(template.replace(/\$\{params\}/g, params), target.result.schema, module, theTitle, '', '', false) + return insertSchemaMacros(template.replace(/\$\{params\}/g, params), target.result.schema, module, { name: theTitle, recursive: false }) } else if (schema.type === 'string' && schema.enum) { let type = expandEnums ? schema.enum.map(e => wrap(e, '\'')).join(' | ') : schema.type @@ -645,16 +704,17 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin // Tuple -> Array if (convertTuplesToArraysOrObjects && isTuple(schema) && isHomogenous(schema)) { template = insertArrayMacros(getTemplate(path.join(templateDir, 'array')), schema, module) - template = insertSchemaMacros(template, firstItem, module, getSchemaType(firstItem, module, {destination, templateDir, link, title, code, asPath, event, result, expandEnums, baseUrl, namespace }), '', '', false) + template = insertSchemaMacros(template, firstItem, module, { name: getSchemaType(firstItem, module, {destination, templateDir, link, title, code, asPath, event, result, expandEnums, baseUrl, namespace }), recursive: false }) } // Normal Array else if (!isTuple(schema)) { - template = insertArrayMacros(getTemplate(path.join(templateDir, 'array')), schema, module) - template = insertSchemaMacros(template, schema.items, module, getSchemaType(schema.items, module, {destination, templateDir, link, title, code, asPath, event, result, expandEnums, baseUrl, namespace }), '', '', true) + const baseDir = (templateDir !== 'json-types' ? 'types': templateDir) + template = insertArrayMacros(getTemplate(path.join(baseDir, 'array')), schema, module) + template = insertSchemaMacros(template, schema.items, module, { name: getSchemaType(schema.items, module, {destination, templateDir, link, title, code, asPath, event, result, expandEnums, baseUrl, namespace }) }) } else { template = insertTupleMacros(getTemplate(path.join(templateDir, 'tuple')), schema, module, '', { templateDir }) - template = insertSchemaMacros(template, firstItem, module, '', '', '', false) + template = insertSchemaMacros(template, firstItem, module, { recursive: false }) } if (code) { @@ -668,7 +728,7 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin if (schema.title) { union.title = schema.title } - return getSchemaType(union, module, { destination, link, title, code, asPath, baseUrl, namespace }) + return getSchemaType(union, module, { templateDir, destination, link, title, code, asPath, baseUrl, namespace }) } else if (schema.oneOf || schema.anyOf) { if (!schema.anyOf) { @@ -676,7 +736,7 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin } // todo... we probably shouldn't allow untitled anyOfs, at least not w/out a feature flag const shape = insertAnyOfMacros(getTemplate(path.join(templateDir, 'anyOf' + suffix)), schema, module, theTitle) - return insertSchemaMacros(shape, schema, module, theTitle, '', '', false) + return insertSchemaMacros(shape, schema, module, { name: theTitle, recursive: false }) // if (event) { @@ -693,19 +753,21 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin else if (schema.type) { const template = getTemplate(path.join(templateDir, 'additionalProperties')) if (schema.additionalProperties && template ) { - return insertSchemaMacros(getTemplate(path.join(templateDir, 'Title')), schema, module, theTitle, '', '', false) + return insertSchemaMacros(getTemplate(path.join(templateDir, 'Title')), schema, module, { name: theTitle, recursive: false}) } else { // TODO: this assumes that when type is an array of types, that it's one other primative & 'null', which isn't necessarily true. const schemaType = !Array.isArray(schema.type) ? schema.type : schema.type.find(t => t !== 'null') - const primitive = getPrimitiveType(schemaType, templateDir) + const baseDir = (templateDir !== 'json-types' ? 'types': templateDir) + const primitive = getPrimitiveType(schemaType, baseDir) const type = allocatedProxy ? allocatedPrimitiveProxies[schemaType] || primitive : primitive return wrap(type, code ? '`' : '') } } else { + const template = getTemplate(path.join(templateDir, 'void')) || 'void' // TODO this is TypeScript specific - return wrap('void', code ? '`' : '') + return wrap(template, code ? '`' : '') } } From ebe1439d70a6b233348895c2135bb2d08ee04cbe Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Tue, 31 Oct 2023 09:56:55 +0530 Subject: [PATCH 110/137] CPPSDK: template added for capabilties-method (#142) --- languages/cpp/src/shared/include/firebolt.h | 68 ------------------- .../templates/declarations-override/default.h | 5 ++ .../cpp/templates/declarations/default.h | 6 ++ .../cpp/templates/declarations/rpc-only.h | 0 languages/cpp/templates/methods/default.cpp | 23 +++++++ languages/cpp/templates/methods/rpc-only.cpp | 0 .../parameter-serialization/array.cpp | 2 +- .../parameter-serialization/generic.cpp | 2 +- .../templates/result-initialization/array.cpp | 2 +- .../result-initialization/string.cpp | 2 +- 10 files changed, 38 insertions(+), 72 deletions(-) delete mode 100644 languages/cpp/src/shared/include/firebolt.h create mode 100644 languages/cpp/templates/declarations/rpc-only.h create mode 100644 languages/cpp/templates/methods/rpc-only.cpp diff --git a/languages/cpp/src/shared/include/firebolt.h b/languages/cpp/src/shared/include/firebolt.h deleted file mode 100644 index 565b363c..00000000 --- a/languages/cpp/src/shared/include/firebolt.h +++ /dev/null @@ -1,68 +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 - */ - -#ifndef FIREBOLT_H -#define FIREBOLT_H - -#include "error.h" -#include "types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define IN -#define OUT - -/** - * @brief Intitialize the Firebolt SDK - * - * @param configLine JSON String with configuration options - * - * CONFIG Format: - * { - * "waitTime": 1000, - * "logLevel": "Info", - * "workerPool":{ - * "queueSize": 8, - * "threadCount": 3 - * }, - * "wsUrl": "ws://127.0.0.1:9998" - * } - * - * - * @return FireboltSDKErrorNone if success, appropriate error otherwise. - * - */ -uint32_t FireboltSDK_Initialize(char* configLine); - - -/** - * @brief Deintitialize the Firebolt SDK - * - * @return FireboltSDKErrorNone if success, appropriate error otherwise. - * - */ -uint32_t FireboltSDK_Deinitialize(void); - -#ifdef __cplusplus -} -#endif - - -#endif // FIREBOLT_H diff --git a/languages/cpp/templates/declarations-override/default.h b/languages/cpp/templates/declarations-override/default.h index e69de29b..cc0c3a2a 100644 --- a/languages/cpp/templates/declarations-override/default.h +++ b/languages/cpp/templates/declarations-override/default.h @@ -0,0 +1,5 @@ + /* + ${method.name} + ${method.description} + */ + ${method.signature.result} ${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr )${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} override; diff --git a/languages/cpp/templates/declarations/default.h b/languages/cpp/templates/declarations/default.h index e69de29b..5e7f8e3f 100644 --- a/languages/cpp/templates/declarations/default.h +++ b/languages/cpp/templates/declarations/default.h @@ -0,0 +1,6 @@ + /* + ${method.name} + ${method.description} + ${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation}${end.if.deprecated} + */ + virtual ${method.signature.result} ${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr )${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} = 0; \ No newline at end of file diff --git a/languages/cpp/templates/declarations/rpc-only.h b/languages/cpp/templates/declarations/rpc-only.h new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/methods/default.cpp b/languages/cpp/templates/methods/default.cpp index e69de29b..dde99ffc 100644 --- a/languages/cpp/templates/methods/default.cpp +++ b/languages/cpp/templates/methods/default.cpp @@ -0,0 +1,23 @@ + /* ${method.rpc.name} - ${method.description} */ + ${method.signature.result} ${info.Title}Impl::${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err ) ${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} + { + Firebolt::Error status = Firebolt::Error::NotConnected; +${if.result.nonvoid}${method.result.initialization}${end.if.result.nonvoid} + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + + JsonObject jsonParameters; + ${method.params.serialization.with.indent} + ${method.result.json.type} jsonResult; + status = transport->Invoke("${info.title.lowercase}.${method.rpc.name}", jsonParameters, jsonResult); + if (status == Firebolt::Error::None) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); + ${if.result.nonvoid}${method.result.instantiation.with.indent}${end.if.result.nonvoid} + } + + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return${if.result.nonvoid} ${method.result.name}${end.if.result.nonvoid}; + } diff --git a/languages/cpp/templates/methods/rpc-only.cpp b/languages/cpp/templates/methods/rpc-only.cpp new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/parameter-serialization/array.cpp b/languages/cpp/templates/parameter-serialization/array.cpp index d45916ab..5768dfc5 100644 --- a/languages/cpp/templates/parameter-serialization/array.cpp +++ b/languages/cpp/templates/parameter-serialization/array.cpp @@ -4,4 +4,4 @@ } WPEFramework::Core::JSON::Variant ${Property}Variant; ${Property}Variant.Array(${Property}); - jsonParameters.Set(_T("${property}"), ${Property}Variant); + jsonParameters.Set(_T("${property}"), ${Property}Variant); \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/generic.cpp b/languages/cpp/templates/parameter-serialization/generic.cpp index 566c7354..d38bcfca 100644 --- a/languages/cpp/templates/parameter-serialization/generic.cpp +++ b/languages/cpp/templates/parameter-serialization/generic.cpp @@ -1,2 +1,2 @@ WPEFramework::Core::JSON::Variant ${Property}(${property}${if.optional}.value()${end.if.optional}); - jsonParameters.Set(_T("${property}"), ${Property}); + jsonParameters.Set(_T("${property}"), ${Property}); \ No newline at end of file diff --git a/languages/cpp/templates/result-initialization/array.cpp b/languages/cpp/templates/result-initialization/array.cpp index 2f0629ac..1bcce663 100644 --- a/languages/cpp/templates/result-initialization/array.cpp +++ b/languages/cpp/templates/result-initialization/array.cpp @@ -1 +1 @@ - ${type} ${property}; + ${type} ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/result-initialization/string.cpp b/languages/cpp/templates/result-initialization/string.cpp index 2f0629ac..1bcce663 100644 --- a/languages/cpp/templates/result-initialization/string.cpp +++ b/languages/cpp/templates/result-initialization/string.cpp @@ -1 +1 @@ - ${type} ${property}; + ${type} ${property}; \ No newline at end of file From 3e45884c8389e315634738933c31ed0af3587b5f Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Fri, 3 Nov 2023 14:40:40 +0530 Subject: [PATCH 111/137] CPPSDK: method name changed to camel case (#144) --- languages/cpp/templates/codeblocks/setter.cpp | 2 +- languages/cpp/templates/declarations-override/default.h | 2 +- languages/cpp/templates/declarations-override/property.h | 2 +- languages/cpp/templates/declarations-override/setter.h | 2 +- languages/cpp/templates/declarations/default.h | 2 +- languages/cpp/templates/declarations/property.h | 2 +- languages/cpp/templates/declarations/setter.h | 2 +- languages/cpp/templates/methods/default.cpp | 2 +- languages/cpp/templates/methods/property.cpp | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/languages/cpp/templates/codeblocks/setter.cpp b/languages/cpp/templates/codeblocks/setter.cpp index 6861be7f..fa0e0901 100644 --- a/languages/cpp/templates/codeblocks/setter.cpp +++ b/languages/cpp/templates/codeblocks/setter.cpp @@ -1,6 +1,6 @@ /* ${method.rpc.name} - ${method.description} */ - void ${info.Title}Impl::${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err ) + 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}"); diff --git a/languages/cpp/templates/declarations-override/default.h b/languages/cpp/templates/declarations-override/default.h index cc0c3a2a..47554196 100644 --- a/languages/cpp/templates/declarations-override/default.h +++ b/languages/cpp/templates/declarations-override/default.h @@ -2,4 +2,4 @@ ${method.name} ${method.description} */ - ${method.signature.result} ${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr )${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} override; + ${method.signature.result} ${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr )${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} override; diff --git a/languages/cpp/templates/declarations-override/property.h b/languages/cpp/templates/declarations-override/property.h index c7d6ac13..d62e1bd9 100644 --- a/languages/cpp/templates/declarations-override/property.h +++ b/languages/cpp/templates/declarations-override/property.h @@ -2,4 +2,4 @@ * ${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 + ${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-override/setter.h b/languages/cpp/templates/declarations-override/setter.h index 7b8e11d9..8a843dc9 100644 --- a/languages/cpp/templates/declarations-override/setter.h +++ b/languages/cpp/templates/declarations-override/setter.h @@ -2,4 +2,4 @@ * ${method.rpc.name} * ${method.description} */ - void ${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr ) override; + void ${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr ) override; diff --git a/languages/cpp/templates/declarations/default.h b/languages/cpp/templates/declarations/default.h index 5e7f8e3f..ba37cb9d 100644 --- a/languages/cpp/templates/declarations/default.h +++ b/languages/cpp/templates/declarations/default.h @@ -3,4 +3,4 @@ ${method.description} ${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation}${end.if.deprecated} */ - virtual ${method.signature.result} ${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr )${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} = 0; \ No newline at end of file + virtual ${method.signature.result} ${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr )${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} = 0; \ No newline at end of file diff --git a/languages/cpp/templates/declarations/property.h b/languages/cpp/templates/declarations/property.h index 6d8890e4..503f4698 100644 --- a/languages/cpp/templates/declarations/property.h +++ b/languages/cpp/templates/declarations/property.h @@ -2,4 +2,4 @@ * ${method.description} * ${method.params} */ - virtual ${method.signature.result} ${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr ) const = 0; + virtual ${method.signature.result} ${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr ) const = 0; diff --git a/languages/cpp/templates/declarations/setter.h b/languages/cpp/templates/declarations/setter.h index b1035bc4..77659fcd 100644 --- a/languages/cpp/templates/declarations/setter.h +++ b/languages/cpp/templates/declarations/setter.h @@ -2,4 +2,4 @@ ${method.rpc.name} ${method.description} */ - virtual void ${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr ) = 0; + virtual void ${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr ) = 0; diff --git a/languages/cpp/templates/methods/default.cpp b/languages/cpp/templates/methods/default.cpp index dde99ffc..fbeaf160 100644 --- a/languages/cpp/templates/methods/default.cpp +++ b/languages/cpp/templates/methods/default.cpp @@ -1,5 +1,5 @@ /* ${method.rpc.name} - ${method.description} */ - ${method.signature.result} ${info.Title}Impl::${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err ) ${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} + ${method.signature.result} ${info.Title}Impl::${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err ) ${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} { Firebolt::Error status = Firebolt::Error::NotConnected; ${if.result.nonvoid}${method.result.initialization}${end.if.result.nonvoid} diff --git a/languages/cpp/templates/methods/property.cpp b/languages/cpp/templates/methods/property.cpp index acecc416..ef29221a 100644 --- a/languages/cpp/templates/methods/property.cpp +++ b/languages/cpp/templates/methods/property.cpp @@ -1,5 +1,5 @@ /* ${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 + ${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} From 239636406fe8d8dc7299048b1ed23c12f180b048 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 6 Nov 2023 11:57:27 +0530 Subject: [PATCH 112/137] CPPSDK: event name changed to camelcase (#145) --- languages/cpp/templates/declarations-override/event.h | 4 ++-- languages/cpp/templates/declarations/event.h | 6 +++--- languages/cpp/templates/methods/event.cpp | 10 +++++----- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/languages/cpp/templates/declarations-override/event.h b/languages/cpp/templates/declarations-override/event.h index 025f525a..25fd5887 100644 --- a/languages/cpp/templates/declarations-override/event.h +++ b/languages/cpp/templates/declarations-override/event.h @@ -1,4 +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; + 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/event.h b/languages/cpp/templates/declarations/event.h index 8939efc8..a29c245c 100644 --- a/languages/cpp/templates/declarations/event.h +++ b/languages/cpp/templates/declarations/event.h @@ -1,8 +1,8 @@ /* ${method.name} - ${method.description} */ struct I${method.Name}Notification { - virtual void ${method.Name}( ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${event.result.type} ) = 0; + virtual void ${method.name}( ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${event.result.type} ) = 0; }; // signature callback params: ${event.signature.callback.params} // method result properties : ${method.result.properties} - virtual void Subscribe( ${event.signature.params}${if.event.params}, ${end.if.event.params}I${method.Name}Notification& notification, Firebolt::Error *err = nullptr ) = 0; - virtual void Unsubscribe( I${method.Name}Notification& notification, Firebolt::Error *err = nullptr ) = 0; + virtual void subscribe( ${event.signature.params}${if.event.params}, ${end.if.event.params}I${method.Name}Notification& notification, Firebolt::Error *err = nullptr ) = 0; + virtual void unsubscribe( I${method.Name}Notification& notification, Firebolt::Error *err = nullptr ) = 0; diff --git a/languages/cpp/templates/methods/event.cpp b/languages/cpp/templates/methods/event.cpp index 5cbcbea7..52549399 100644 --- a/languages/cpp/templates/methods/event.cpp +++ b/languages/cpp/templates/methods/event.cpp @@ -1,5 +1,5 @@ /* ${method.rpc.name} - ${method.description} */ - static void ${info.Title}${method.Name}InnerCallback( void* notification, const void* userData, void* jsonResponse ) + static void ${method.name}InnerCallback( void* notification, const void* userData, void* jsonResponse ) { ${event.callback.params.serialization} ASSERT(proxyResponse->IsValid() == true); @@ -9,23 +9,23 @@ proxyResponse->Release(); I${info.Title}::I${method.Name}Notification& notifier = *(reinterpret_cast(notification)); - notifier.${method.Name}(${event.callback.response.instantiation}); + 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 ) + 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); + status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${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 ) + 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)); From fddefeeb3036d0723e47c4c7d7272fdd1f6f8810 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 6 Nov 2023 20:57:09 +0530 Subject: [PATCH 113/137] CPPSDK: add overrideRule to handle template generation + remove enum level checking (#141) 1. Add properties to the template only if object has properties or additionalProperties 2. use primitive types from templates, instead defined variable --- languages/cpp/language.config.json | 9 +-- .../json-types/object-empty-property.h | 1 + languages/cpp/templates/types/boolean.h | 1 + languages/cpp/templates/types/integer.h | 1 + languages/cpp/templates/types/number.h | 1 + .../templates/types/object-empty-property.h | 2 + languages/cpp/templates/types/string.h | 1 + src/macrofier/engine.mjs | 23 ++++--- src/macrofier/types.mjs | 69 +++++++++---------- 9 files changed, 55 insertions(+), 53 deletions(-) create mode 100644 languages/cpp/templates/json-types/object-empty-property.h create mode 100644 languages/cpp/templates/types/boolean.h create mode 100644 languages/cpp/templates/types/integer.h create mode 100644 languages/cpp/templates/types/number.h create mode 100644 languages/cpp/templates/types/object-empty-property.h create mode 100644 languages/cpp/templates/types/string.h diff --git a/languages/cpp/language.config.json b/languages/cpp/language.config.json index debc539d..db9b7ddc 100644 --- a/languages/cpp/language.config.json +++ b/languages/cpp/language.config.json @@ -5,7 +5,7 @@ "extractSubSchemas": true, "unwrapResultObjects": false, "createPolymorphicMethods": true, - "excludeDeclarations":true, + "excludeDeclarations": true, "aggregateFiles": [ "/include/firebolt.h", "/src/firebolt.cpp" @@ -21,12 +21,7 @@ "/src/jsondata_module.h" ], "persistPermission": true, - "primitives": { - "boolean": "bool", - "integer": "int32_t", - "number": "float", - "string": "std::string" - }, + "primitives": {}, "langVersion" : "c++17", "additionalSchemaTemplates": [ "json-types" ], "additionalMethodTemplates": [ "declarations", "declarations-override" ] diff --git a/languages/cpp/templates/json-types/object-empty-property.h b/languages/cpp/templates/json-types/object-empty-property.h new file mode 100644 index 00000000..94be02b1 --- /dev/null +++ b/languages/cpp/templates/json-types/object-empty-property.h @@ -0,0 +1 @@ + using ${title} = WPEFramework::Core::JSON::VariantContainer; diff --git a/languages/cpp/templates/types/boolean.h b/languages/cpp/templates/types/boolean.h new file mode 100644 index 00000000..fc75f206 --- /dev/null +++ b/languages/cpp/templates/types/boolean.h @@ -0,0 +1 @@ +bool \ No newline at end of file diff --git a/languages/cpp/templates/types/integer.h b/languages/cpp/templates/types/integer.h new file mode 100644 index 00000000..33028e0f --- /dev/null +++ b/languages/cpp/templates/types/integer.h @@ -0,0 +1 @@ +int32_t \ No newline at end of file diff --git a/languages/cpp/templates/types/number.h b/languages/cpp/templates/types/number.h new file mode 100644 index 00000000..05eeb48f --- /dev/null +++ b/languages/cpp/templates/types/number.h @@ -0,0 +1 @@ +float \ No newline at end of file diff --git a/languages/cpp/templates/types/object-empty-property.h b/languages/cpp/templates/types/object-empty-property.h new file mode 100644 index 00000000..a5aae7f4 --- /dev/null +++ b/languages/cpp/templates/types/object-empty-property.h @@ -0,0 +1,2 @@ +/* ${title} */ +using ${title} = std::string; \ No newline at end of file diff --git a/languages/cpp/templates/types/string.h b/languages/cpp/templates/types/string.h new file mode 100644 index 00000000..c6d1c815 --- /dev/null +++ b/languages/cpp/templates/types/string.h @@ -0,0 +1 @@ +std::string \ No newline at end of file diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 4def4f6e..031e61ea 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -879,7 +879,7 @@ function generateSchemas(json, templates, options) { else { content = content.replace(/\$\{if\.description\}(.*?)\{end\.if\.description\}/gms, '$1') } - const schemaShape = types.getSchemaShape(schema, json, { 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)) @@ -943,7 +943,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, { 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) + ')') // need full module here, not just the schema .filter(link => link) .join('\n') @@ -1252,16 +1252,16 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) : '' - const serializedParams = flattenedMethod.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'parameter-serialization', property: param.name, required: param.required || false, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true })).join('\n') - const resultInst = types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-instantiation', property: flattenedMethod.result.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) // w/out level: 1, getSchemaShape skips anonymous types, like primitives - const resultInit = types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-initialization', property: flattenedMethod.result.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) // w/out level: 1, getSchemaShape skips anonymous types, like primitives - const serializedEventParams = event ? flattenedMethod.params.filter(p => p.name !== 'listen').map(param => types.getSchemaShape(param.schema, json, {templateDir: 'parameter-serialization', property: param.name, required: param.required || false, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true })).join('\n') : '' + const serializedParams = flattenedMethod.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'parameter-serialization', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n') + const resultInst = types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-instantiation', property: flattenedMethod.result.name, required: flattenedMethod.result.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) // w/out primitive: true, getSchemaShape skips anonymous types, like primitives + const resultInit = types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-initialization', property: flattenedMethod.result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) // w/out primitive: true, getSchemaShape skips anonymous types, like primitives + const serializedEventParams = event ? flattenedMethod.params.filter(p => p.name !== 'listen').map(param => types.getSchemaShape(param.schema, json, {templateDir: 'parameter-serialization', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, 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: 'callback-parameter-serialization', property: result.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) : '' + const callbackSerializedParams = event ? types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-parameter-serialization', property: result.name, required: event.result.schema.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' - const callbackResultInst = event ? types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-result-instantiation', property: result.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) : '' + const callbackResultInst = event ? types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-result-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' // hmm... how is this different from callbackSerializedParams? i guess they get merged? - const callbackResponseInst = event ? types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-response-instantiation', property: result.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) : '' + const callbackResponseInst = event ? types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-response-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' 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}) @@ -1349,7 +1349,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.result\.summary\}/g, result.summary) .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 })) + .replace(/\$\{method\.result\.json\}/g, 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.getMethodSignatureResult(event, json, { destination: state.destination, section: state.section, callback: true }) : '') .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) @@ -1358,6 +1358,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.result\}/g, generateResult(result.schema, json, templates, { name: result.name })) .replace(/\$\{method\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{method\.result\.instantiation\}/g, resultInst) + .replace(/\$\{method\.result\.initialization\}/g, resultInit) .replace(/\$\{method\.result\.properties\}/g, resultParams) .replace(/\$\{method\.result\.instantiation\.with\.indent\}/g, indent(resultInst, ' ')) .replace(/\$\{method\.example\.value\}/g, JSON.stringify(methodObj.examples[0].result.value)) @@ -1603,7 +1604,7 @@ function insertParameterMacros(template, param, method, module) { .replace(/\$\{method.param.type\}/g, type) .replace(/\$\{json.param.type\}/g, jsonType) .replace(/\$\{method.param.link\}/g, getLinkForSchema(param.schema, module)) //getType(param)) - .replace(/\$\{method.param.constraints\}/g, constraints) //getType(param)) + .replace(/\$\{method.param.constraints\}/g, constraints) //getType(param)) } function insertCapabilityMacros(template, capabilities, method, module) { diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index e7bd5e71..280b7192 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -23,15 +23,16 @@ import path from "path" let convertTuplesToArraysOrObjects = false const templates = {} const state = {} -const primitives = { +let primitives = { "integer": "number", "number": "number", "boolean": "boolean", "string": "string" } +const stdPrimitives = [ "integer", "number", "boolean", "string" ] const isVoid = type => (type === 'void') ? true : false -const isPrimitiveType = type => primitives[type] ? true : false +const isPrimitiveType = type => stdPrimitives.includes(type) ? true : false const allocatedPrimitiveProxies = {} function setTemplates(t) { @@ -39,7 +40,9 @@ function setTemplates(t) { } function setPrimitives(p) { - Object.assign(primitives, p) + if (p) { + primitives = p + } } function setConvertTuples(t) { @@ -139,7 +142,7 @@ const getXSchemaGroup = (schema, module) => { return group } -function insertSchemaMacros(content, schema, module, { name = '', parent = '', property = '', required = true, recursive = true, templateDir = 'types'}) { +function insertSchemaMacros(content, schema, module, { name = '', parent = '', property = '', required = false, recursive = true, templateDir = 'types'}) { const title = name || schema.title || '' let moduleTitle = getXSchemaGroup(schema, module) @@ -150,8 +153,8 @@ function insertSchemaMacros(content, schema, module, { name = '', parent = '', p .replace(/\$\{property\}/g, property) .replace(/\$\{Property\}/g, capitalize(property)) .replace(/\$\{if\.namespace\.notsame}(.*?)\$\{end\.if\.namespace\.notsame\}/g, (module.info.title !== (parent || moduleTitle)) ? '$1' : '') - .replace(/\$\{parent\.title\}/g, parent) - .replace(/\$\{parent\.Title\}/g, capitalize(parent)) + .replace(/\$\{parent\.title\}/g, parent || moduleTitle) + .replace(/\$\{parent\.Title\}/g, capitalize(parent || moduleTitle)) .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, required ? '' : '$1') .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, required ? '' : '$1') .replace(/\$\{description\}/g, schema.description ? schema.description : '') @@ -200,7 +203,7 @@ const insertObjectAdditionalPropertiesMacros = (content, schema, module, title, const options2 = options ? JSON.parse(JSON.stringify(options)) : {} options2.parent = title options2.level = options.level + 1 - + options2.required = options.required const shape = getSchemaShape(schema.additionalProperties, module, options2) let type = getSchemaType(schema.additionalProperties, module, options2).trimEnd() const propertyNames = localizeDependencies(schema, module).propertyNames @@ -233,14 +236,11 @@ const insertObjectMacros = (content, schema, module, title, property, options) = options2.parentLevel = options.parentLevel options2.level = options.level + 1 options2.templateDir = options.templateDir - ;(['properties', 'properties.register', 'properties.assign']).forEach(macro => { const indent = (content.split('\n').find(line => line.includes("${" + macro + "}")) || '').match(/^\s+/) || [''][0] const templateType = macro.split('.').slice(1).join('') const template = getTemplate(path.join(options.templateDir, 'property' + (templateType ? `-${templateType}` : ''))).replace(/\n/gms, indent + '\n') - const properties = [] - if (schema.properties) { Object.entries(schema.properties).forEach(([name, prop], i) => { let localizedProp = localizeDependencies(prop, module) @@ -248,11 +248,10 @@ const insertObjectMacros = (content, schema, module, title, property, options) = options2.templateDir += subProperty ? '/sub-property' : '' const objSeparator = getTemplate(path.join(options2.templateDir, 'object-separator')) - options2.required = prop.required ? prop.required : false + options2.required = schema.required && schema.required.includes(name) const schemaShape = getSchemaShape(prop, module, options2) const type = getSchemaType(prop, module, options2) - // don't push properties w/ unsupported types if (type) { let replacedTemplate = template @@ -292,7 +291,7 @@ const insertObjectMacros = (content, schema, module, title, property, options) = } }) } - + if (schema.propertyNames) { const { propertyNames } = localizeDependencies(schema, module) if (propertyNames.enum) { @@ -334,13 +333,15 @@ const insertObjectMacros = (content, schema, module, title, property, options) = }) } } - - const regex = new RegExp("\\$\\{" + macro + "\\}", "g") + const regex = new RegExp("\\$\\{" + macro + "\\}", "g") content = content.replace(regex, properties.join('\n')) .replace(/\$\{level}/g, options.parentLevel > 0 ? options.parentLevel : '') - }) + if (!schema.properties && !schema.propertyNames && !schema.additionalProperties) { + content = !schema.additionalProperties ? getTemplate(path.join(options.templateDir, 'object-empty-property')) : '' + } + }) return content } @@ -386,7 +387,7 @@ const insertTupleMacros = (content, schema, module, title, options) => { const getPrimitiveType = (type, templateDir = 'types') => { const template = getTemplate(path.join(templateDir, type)) || getTemplate(path.join(templateDir, 'generic')) - return primitives[type] || template + return (primitives[type] || template) } const pickBestType = types => Array.isArray(types) ? types.find(t => t !== 'null') : types @@ -424,20 +425,18 @@ const sanitize = (schema) => { return result } -function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', parent = '', property = '', required = true, parentLevel = 0, level = 0, summary, descriptions = true, destination, section, enums = true, skipTitleOnce = false, array = false } = {}) { +function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', parent = '', property = '', required = false, parentLevel = 0, level = 0, summary, descriptions = true, destination, section, enums = true, skipTitleOnce = false, array = false, primitive = false } = {}) { schema = sanitize(schema) - state.destination = destination state.section = section - - if (level === 0 && !schema.title) { + if (level === 0 && !schema.title && !primitive) { return '' } const suffix = destination && ('.' + destination.split('.').pop()) || '' - const theTitle = insertSchemaMacros(getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, { name: schema.title, parent, property, required, recursive: false}) + const theTitle = insertSchemaMacros(getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, { name: schema.title, parent, property, required, recursive: false }) - let result = level === 0 ? getTemplate(path.join(templateDir, 'default' + suffix)) : '${shape}' + let result = level === 0 && !primitive ? getTemplate(path.join(templateDir, 'default' + suffix)) : '${shape}' let genericTemplate = getTemplate(path.join(templateDir, 'generic' + suffix)) if (enums && level === 0 && Array.isArray(schema.enum) && ((schema.type === "string") || (schema.type[0] === "string"))) { @@ -448,7 +447,7 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren if (schema['$ref']) { const someJson = getPath(schema['$ref'], module) if (someJson) { - return getSchemaShape(someJson, module, { templateDir, parent, property, required, parentLevel, level, summary, descriptions, destination, enums, array }) + return getSchemaShape(someJson, module, { templateDir, parent, property, required, parentLevel, level, summary, descriptions, destination, enums, array, primitive }) } throw "Unresolvable $ref: " + schema['ref'] + ", in " + module.info.title } @@ -460,7 +459,7 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren else if (!skipTitleOnce && (level > 0) && schema.title) { let enumType = (schema.type === 'string' && Array.isArray(schema.enum)) // TODO: allow the 'ref' template to actually insert the shape using getSchemaShape - const innerShape = getSchemaShape(schema, module, { skipTitleOnce: true, templateDir, parent, property, required, parentLevel, level, summary, descriptions, destination, enums: enumType, array }) + const innerShape = getSchemaShape(schema, module, { skipTitleOnce: true, templateDir, parent, property, required, parentLevel, level, summary, descriptions, destination, enums: enumType, array, primitive }) const shape = getTemplate(path.join(templateDir, 'ref' + suffix)) .replace(/\$\{shape\}/g, innerShape) @@ -472,11 +471,11 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren let shape const additionalPropertiesTemplate = getTemplate(path.join(templateDir, 'additionalProperties')) if (additionalPropertiesTemplate && schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { - shape = insertObjectAdditionalPropertiesMacros(additionalPropertiesTemplate, schema, module, theTitle, { level, parent, templateDir, namespace: true }) + shape = insertObjectAdditionalPropertiesMacros(additionalPropertiesTemplate, schema, module, theTitle, { level, parent, templateDir, namespace: true, required }) } else { let objectLevel = array ? 0 : level - shape = insertObjectMacros(getTemplate(path.join(templateDir, 'object' + (array ? '-array' : '') + suffix)) || genericTemplate, schema, module, theTitle, property, { parentLevel, level: objectLevel, parent, property, required, templateDir, descriptions, destination, section, enums, namespace: true }) + shape = insertObjectMacros(getTemplate(path.join(templateDir, 'object' + (array ? '-array' : '') + suffix)) || genericTemplate, schema, module, theTitle, property, { parentLevel, level: objectLevel, parent, property, required, templateDir, descriptions, destination, section, enums, namespace: true, primitive }) } result = result.replace(/\$\{shape\}/g, shape) return insertSchemaMacros(result, schema, module, { name: theTitle, parent, property, required, templateDir }) @@ -524,7 +523,7 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren } delete union['$ref'] - return getSchemaShape(union, module, { templateDir, parent, property, required, parentLevel, level, summary, descriptions, destination, enums: false, array }) + return getSchemaShape(union, module, { templateDir, parent, property, required, parentLevel, level, summary, descriptions, destination, enums: false, array, primitive }) } else if (schema.type === "array" && schema.items && isSupportedTuple(schema)) { // tuple @@ -534,8 +533,8 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren } else if (schema.type === "array" && schema.items && !Array.isArray(schema.items)) { // array - const items = getSchemaShape(schema.items, module, { templateDir, parent, property, required, parentLevel: parentLevel + 1, level, summary, descriptions, destination, enums: false , array: true}) - const shape = insertArrayMacros(getTemplate(path.join(templateDir, 'array' + suffix)) || genericTemplate, schema, module, level, items) + const items = getSchemaShape(schema.items, module, { templateDir, parent, property, required, parentLevel: parentLevel + 1, level, summary, descriptions, destination, enums: false, array: true, primitive }) + const shape = insertArrayMacros(getTemplate(path.join(templateDir, 'array' + suffix)) || genericTemplate, schema, module, level, items, schema.required) result = result.replace(/\$\{shape\}/g, shape) .replace(/\$\{if\.object\}(.*?)\$\{end\.if\.object\}/gms, (schema.items.type === 'object') ? '$1' : '') .replace(/\$\{if\.non\.object\}(.*?)\$\{end\.if\.non\.object\}/gms, (schema.items.type !== 'object') ? '$1' : '') @@ -544,8 +543,8 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren else if (schema.type) { const shape = insertPrimitiveMacros(getTemplate(path.join(templateDir, 'primitive' + suffix) || genericTemplate), schema, module, theTitle, templateDir) result = result.replace(/\$\{shape\}/g, shape) - if (level > 0) { - return insertSchemaMacros(result, schema, module, { name: theTitle, parent, property, required, templateDir}) + if (level > 0 || primitive) { + return insertSchemaMacros(result, schema, module, { name: theTitle, parent, property, required, templateDir }) } } @@ -607,7 +606,7 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin const suffix = destination && ('.' + destination.split('.').pop()) || '' const namespaceStr = namespace ? getTemplate(path.join(templateDir, 'namespace' + suffix)) : '' - const theTitle = insertSchemaMacros(namespaceStr + getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, { name: schema.title, parent: getXSchemaGroup(schema, module), recursive: false}) + const theTitle = insertSchemaMacros(namespaceStr + getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, { name: schema.title, parent: getXSchemaGroup(schema, module), recursive: false }) const allocatedProxy = event || result const title = schema.type === "object" || schema.enum ? true : false @@ -710,7 +709,7 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin else if (!isTuple(schema)) { const baseDir = (templateDir !== 'json-types' ? 'types': templateDir) template = insertArrayMacros(getTemplate(path.join(baseDir, 'array')), schema, module) - template = insertSchemaMacros(template, schema.items, module, { name: getSchemaType(schema.items, module, {destination, templateDir, link, title, code, asPath, event, result, expandEnums, baseUrl, namespace }) }) + template = insertSchemaMacros(template, schema.items, module, { name: getSchemaType(schema.items, module, {destination, templateDir, link, title, code, asPath, event, result, expandEnums, baseUrl, namespace })}) } else { template = insertTupleMacros(getTemplate(path.join(templateDir, 'tuple')), schema, module, '', { templateDir }) @@ -753,7 +752,7 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin else if (schema.type) { const template = getTemplate(path.join(templateDir, 'additionalProperties')) if (schema.additionalProperties && template ) { - return insertSchemaMacros(getTemplate(path.join(templateDir, 'Title')), schema, module, { name: theTitle, recursive: false}) + return insertSchemaMacros(getTemplate(path.join(templateDir, 'Title')), schema, module, { name: theTitle, recursive: false }) } else { // TODO: this assumes that when type is an array of types, that it's one other primative & 'null', which isn't necessarily true. From b50d33d8e55132d794fa8eee0ddd158676be2689 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Tue, 7 Nov 2023 13:31:59 +0530 Subject: [PATCH 114/137] CPPSDK: remove const from return type (#149) --- languages/cpp/templates/result/default.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/languages/cpp/templates/result/default.h b/languages/cpp/templates/result/default.h index d66fdb8a..30cba475 100644 --- a/languages/cpp/templates/result/default.h +++ b/languages/cpp/templates/result/default.h @@ -1 +1 @@ -const ${method.result.type} \ No newline at end of file +${method.result.type} \ No newline at end of file From fcae038df820da44bfb5c4fbf9eda81ae78db5f4 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 9 Nov 2023 16:54:57 +0530 Subject: [PATCH 115/137] CPPSDK: typo fix (#150) --- languages/cpp/templates/json-types/anyOfSchemaShape.h | 2 +- languages/cpp/templates/types/anyOfSchemaShape.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/languages/cpp/templates/json-types/anyOfSchemaShape.h b/languages/cpp/templates/json-types/anyOfSchemaShape.h index 9a53ff94..08d72bbd 100644 --- a/languages/cpp/templates/json-types/anyOfSchemaShape.h +++ b/languages/cpp/templates/json-types/anyOfSchemaShape.h @@ -1 +1 @@ - /* anyOf schema shape is supported right now */ + /* anyOf schema shape is not supported right now */ diff --git a/languages/cpp/templates/types/anyOfSchemaShape.h b/languages/cpp/templates/types/anyOfSchemaShape.h index 9a53ff94..08d72bbd 100644 --- a/languages/cpp/templates/types/anyOfSchemaShape.h +++ b/languages/cpp/templates/types/anyOfSchemaShape.h @@ -1 +1 @@ - /* anyOf schema shape is supported right now */ + /* anyOf schema shape is not supported right now */ From 195bce4f3b23af9bb1741dbe390f2daed6c71f59 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Mon, 13 Nov 2023 20:38:52 +0530 Subject: [PATCH 116/137] CPPSDK: handle empty properties and propertyNames with templates (#152) --- .../javascript/templates/types/enum-empty-property.mjs | 3 +++ src/macrofier/types.mjs | 10 +++++++--- 2 files changed, 10 insertions(+), 3 deletions(-) create mode 100644 languages/javascript/templates/types/enum-empty-property.mjs diff --git a/languages/javascript/templates/types/enum-empty-property.mjs b/languages/javascript/templates/types/enum-empty-property.mjs new file mode 100644 index 00000000..0db3279e --- /dev/null +++ b/languages/javascript/templates/types/enum-empty-property.mjs @@ -0,0 +1,3 @@ +{ + +} diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index 280b7192..ba26051c 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -337,9 +337,13 @@ const insertObjectMacros = (content, schema, module, title, property, options) = const regex = new RegExp("\\$\\{" + macro + "\\}", "g") content = content.replace(regex, properties.join('\n')) .replace(/\$\{level}/g, options.parentLevel > 0 ? options.parentLevel : '') - - if (!schema.properties && !schema.propertyNames && !schema.additionalProperties) { - content = !schema.additionalProperties ? getTemplate(path.join(options.templateDir, 'object-empty-property')) : '' + if (!schema.properties && !schema.additionalProperties) { + if (schema.propertyNames && schema.propertyNames.enum) { + content = getTemplate(path.join(options.templateDir, 'enum-empty-property')) + } + else { + content = getTemplate(path.join(options.templateDir, 'object-empty-property')) + } } }) return content From 993c25d3a715e15245daee43deff9e4611cc01fc Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Wed, 15 Nov 2023 21:09:48 +0530 Subject: [PATCH 117/137] CPPSDK: code generation template and engine changes (#151) 1. Callback generation + types: with generation changes + template updates 2.Set title for properties inside x-schemas --- .../additionalProperties.cpp | 6 ++ .../callback-context-instantiation/anyOf.cpp | 1 + .../callback-context-instantiation/array.cpp | 6 ++ .../callback-context-instantiation/enum.cpp | 3 + .../generic.cpp | 3 + .../namespace.cpp | 1 + .../callback-context-instantiation/object.cpp | 8 ++ .../primitive.cpp | 1 + .../property.cpp | 1 + .../callback-context-instantiation/ref.h | 1 + .../callback-context-instantiation/string.cpp | 3 + .../sub-property/anyOf.cpp | 1 + .../sub-property/anyOfSchemaShape.cpp | 3 + .../sub-property/array.cpp | 5 ++ .../sub-property/const.cpp | 1 + .../sub-property/generic.cpp | 1 + .../sub-property/namespace.cpp | 1 + .../sub-property/object-array.cpp | 4 + .../sub-property/object-separator.cpp | 1 + .../sub-property/object.cpp | 3 + .../sub-property/property.cpp | 1 + .../sub-property/ref.h | 1 + .../sub-property/title.cpp | 1 + .../callback-context-instantiation/title.cpp | 1 + .../callback-context-instantiation/tuple.cpp | 4 + .../additionalProperties.cpp | 1 + .../callback-initialization/anyOf.cpp | 1 + .../callback-initialization/array.cpp | 1 + .../callback-initialization/enum.cpp | 1 + .../callback-initialization/generic.cpp | 1 + .../object-empty-property.cpp | 1 + .../callback-initialization/object.cpp | 1 + .../callback-initialization/primitive.cpp | 1 + .../callback-initialization/title.cpp | 1 + .../callback-instantiation/generic.cpp | 12 +++ .../additionalProperties.cpp | 1 + .../generic.cpp | 2 +- .../additionalProperties.cpp | 10 ++- .../callback-result-instantiation/anyOf.cpp | 1 + .../callback-result-instantiation/array.cpp | 7 +- .../callback-result-instantiation/enum.cpp | 2 +- .../callback-result-instantiation/generic.cpp | 2 +- .../namespace.cpp | 1 + .../callback-result-instantiation/object.cpp | 1 - .../property.cpp | 2 +- .../sub-property/anyOf.cpp | 1 + .../sub-property/anyOfSchemaShape.cpp | 3 + .../sub-property/array.cpp | 5 ++ .../sub-property/const.cpp | 1 + .../sub-property/namespace.cpp | 1 + .../sub-property/object-array.cpp | 4 + .../sub-property/object.cpp | 2 + .../sub-property/property.cpp | 2 +- .../callback-result-instantiation/tuple.cpp | 6 +- .../additionalProperties.cpp | 1 + .../callback-result-serialization/generic.cpp | 1 + .../primitive.cpp | 1 + .../callback-result-serialization/ref.h | 1 + .../callback-serialization/generic.cpp | 1 + .../declarations-override/calls-metrics.h | 1 + .../templates/declarations/calls-metrics.h | 1 + .../templates/json-types/anyOfSchemaShape.h | 2 +- languages/cpp/templates/json-types/const.h | 1 + languages/cpp/templates/json-types/integer.h | 2 +- languages/cpp/templates/methods/event.cpp | 14 ++-- languages/cpp/templates/methods/property.cpp | 2 +- .../additionalProperties.cpp | 9 +++ .../parameter-serialization/array.cpp | 2 +- .../parameter-serialization/enum.cpp | 2 +- .../parameter-serialization/generic.cpp | 2 +- .../object-empty-property.cpp | 2 + .../parameter-serialization/object.cpp | 2 +- .../parameter-serialization/property.cpp | 2 +- .../sub-property/anyOf.cpp | 1 + .../sub-property/anyOfSchemaShape.cpp | 1 + .../sub-property/array.cpp | 8 ++ .../sub-property/const.cpp | 1 + .../sub-property/object-array.cpp | 7 ++ .../sub-property/object.cpp | 2 +- .../sub-property/property.cpp | 2 +- .../sub-property/title.cpp | 2 +- .../parameter-serialization/title.cpp | 1 + .../additionalProperties.cpp | 2 +- .../templates/result-initialization/anyOf.cpp | 1 + .../object-empty-property.cpp | 1 + .../cpp/templates/result-initialization/ref.h | 1 + .../additionalProperties.cpp | 11 +-- .../templates/result-instantiation/anyOf.cpp | 3 + .../result-instantiation/namespace.cpp | 1 + .../object-empty-property.cpp | 3 + .../result-instantiation/property.cpp | 2 +- .../sub-property/anyOf.cpp | 1 + .../sub-property/anyOfSchemaShape.cpp | 3 + .../sub-property/array.cpp | 3 +- .../sub-property/namespace.cpp | 1 + .../sub-property/object-array.cpp | 2 +- .../sub-property/object.cpp | 4 +- .../sub-property/property.cpp | 2 +- .../templates/result-instantiation/tuple.cpp | 5 +- languages/cpp/templates/schemas/default.cpp | 2 +- .../templates/types/additionalProperties.h | 2 +- .../cpp/templates/types/anyOfSchemaShape.h | 2 +- languages/cpp/templates/types/property.h | 2 +- languages/cpp/templates/types/tuple.h | 2 +- src/macrofier/engine.mjs | 29 +++++-- src/macrofier/index.mjs | 7 +- src/macrofier/types.mjs | 80 ++++++++++++++----- src/shared/modules.mjs | 48 ++++++++++- 108 files changed, 343 insertions(+), 88 deletions(-) create mode 100644 languages/cpp/templates/callback-context-instantiation/additionalProperties.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/anyOf.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/array.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/enum.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/generic.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/namespace.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/object.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/primitive.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/property.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/ref.h create mode 100644 languages/cpp/templates/callback-context-instantiation/string.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/anyOf.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/anyOfSchemaShape.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/array.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/const.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/generic.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/namespace.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/object-array.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/object-separator.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/object.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/ref.h create mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/title.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/title.cpp create mode 100644 languages/cpp/templates/callback-context-instantiation/tuple.cpp create mode 100644 languages/cpp/templates/callback-initialization/additionalProperties.cpp create mode 100644 languages/cpp/templates/callback-initialization/anyOf.cpp create mode 100644 languages/cpp/templates/callback-initialization/array.cpp create mode 100644 languages/cpp/templates/callback-initialization/enum.cpp create mode 100644 languages/cpp/templates/callback-initialization/generic.cpp create mode 100644 languages/cpp/templates/callback-initialization/object-empty-property.cpp create mode 100644 languages/cpp/templates/callback-initialization/object.cpp create mode 100644 languages/cpp/templates/callback-initialization/primitive.cpp create mode 100644 languages/cpp/templates/callback-initialization/title.cpp create mode 100644 languages/cpp/templates/callback-instantiation/generic.cpp create mode 100644 languages/cpp/templates/callback-response-instantiation/additionalProperties.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/anyOf.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/namespace.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/sub-property/anyOf.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/sub-property/anyOfSchemaShape.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/sub-property/const.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/sub-property/namespace.cpp create mode 100644 languages/cpp/templates/callback-result-instantiation/sub-property/object-array.cpp create mode 100644 languages/cpp/templates/callback-result-serialization/additionalProperties.cpp create mode 100644 languages/cpp/templates/callback-result-serialization/generic.cpp create mode 100644 languages/cpp/templates/callback-result-serialization/primitive.cpp create mode 100644 languages/cpp/templates/callback-result-serialization/ref.h create mode 100644 languages/cpp/templates/callback-serialization/generic.cpp create mode 100644 languages/cpp/templates/declarations-override/calls-metrics.h create mode 100644 languages/cpp/templates/declarations/calls-metrics.h create mode 100644 languages/cpp/templates/parameter-serialization/additionalProperties.cpp create mode 100644 languages/cpp/templates/parameter-serialization/object-empty-property.cpp create mode 100644 languages/cpp/templates/parameter-serialization/sub-property/anyOf.cpp create mode 100644 languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp create mode 100644 languages/cpp/templates/parameter-serialization/sub-property/array.cpp create mode 100644 languages/cpp/templates/parameter-serialization/sub-property/const.cpp create mode 100644 languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp create mode 100644 languages/cpp/templates/parameter-serialization/title.cpp create mode 100644 languages/cpp/templates/result-initialization/anyOf.cpp create mode 100644 languages/cpp/templates/result-initialization/object-empty-property.cpp create mode 100644 languages/cpp/templates/result-initialization/ref.h create mode 100644 languages/cpp/templates/result-instantiation/anyOf.cpp create mode 100644 languages/cpp/templates/result-instantiation/namespace.cpp create mode 100644 languages/cpp/templates/result-instantiation/object-empty-property.cpp create mode 100644 languages/cpp/templates/result-instantiation/sub-property/anyOf.cpp create mode 100644 languages/cpp/templates/result-instantiation/sub-property/anyOfSchemaShape.cpp create mode 100644 languages/cpp/templates/result-instantiation/sub-property/namespace.cpp diff --git a/languages/cpp/templates/callback-context-instantiation/additionalProperties.cpp b/languages/cpp/templates/callback-context-instantiation/additionalProperties.cpp new file mode 100644 index 00000000..cecd2df5 --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/additionalProperties.cpp @@ -0,0 +1,6 @@ + if (strcmp(elements.Label(), "${property}") == 0) { + ${if.namespace.notsame}${info.Title}::${end.if.namespace.notsame}JsonData_${title}::Iterator elements = elements.Current().Variants(); + while (elements.Next()) { + ${property}.insert(elements.Label(), elements.Current().${additional.type}; + } + } diff --git a/languages/cpp/templates/callback-context-instantiation/anyOf.cpp b/languages/cpp/templates/callback-context-instantiation/anyOf.cpp new file mode 100644 index 00000000..120561dd --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/anyOf.cpp @@ -0,0 +1 @@ + ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/array.cpp b/languages/cpp/templates/callback-context-instantiation/array.cpp new file mode 100644 index 00000000..63e7c4fa --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/array.cpp @@ -0,0 +1,6 @@ + if (strcmp(elements.Label(), "${property}") == 0) { + auto index(element.Current().Elements()); + while (index.Next() == true) { + ${property}.push_back(index.Current().Value()); + } + } \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/enum.cpp b/languages/cpp/templates/callback-context-instantiation/enum.cpp new file mode 100644 index 00000000..75545c29 --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/enum.cpp @@ -0,0 +1,3 @@ + if (strcmp(elements.Label(), "${property}") == 0) { + ${property} = WPEFramework::Core::EnumerateType<${if.namespace.notsame}${info.Title}::${end.if.namespace.notsame}${title}>(elements.Current().String().c_str(), false).Value(); + } diff --git a/languages/cpp/templates/callback-context-instantiation/generic.cpp b/languages/cpp/templates/callback-context-instantiation/generic.cpp new file mode 100644 index 00000000..a715e2cc --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/generic.cpp @@ -0,0 +1,3 @@ + if (strcmp(elements.Label(), "${property}") == 0) { + ${property} = elements.Current().Value(); + } \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/namespace.cpp b/languages/cpp/templates/callback-context-instantiation/namespace.cpp new file mode 100644 index 00000000..b3afde8a --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/namespace.cpp @@ -0,0 +1 @@ +${if.namespace.notsame}${parent.Title}::${end.if.namespace.notsame} \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/object.cpp b/languages/cpp/templates/callback-context-instantiation/object.cpp new file mode 100644 index 00000000..53bea7d7 --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/object.cpp @@ -0,0 +1,8 @@ + if (strcmp(elements.Label(), "${property}") == 0) { + WPEFramework::Core::JSON::VariantContainer container = elements.Current().Object(); + std::string strContainer; + container.ToString(strContainer); + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} response; + response.FromString(strContainer); +${properties} + } \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/primitive.cpp b/languages/cpp/templates/callback-context-instantiation/primitive.cpp new file mode 100644 index 00000000..23bbace7 --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/primitive.cpp @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/property.cpp b/languages/cpp/templates/callback-context-instantiation/property.cpp new file mode 100644 index 00000000..a4e489d0 --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/property.cpp @@ -0,0 +1 @@ +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}.${property} = response.${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/ref.h b/languages/cpp/templates/callback-context-instantiation/ref.h new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/ref.h @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/string.cpp b/languages/cpp/templates/callback-context-instantiation/string.cpp new file mode 100644 index 00000000..e0a62ec1 --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/string.cpp @@ -0,0 +1,3 @@ + if (strcmp(elements.Label(), "${property}") == 0) { + ${property} = elements.Current().Value().c_str(); + } \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/anyOf.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/anyOf.cpp new file mode 100644 index 00000000..e2e80c7c --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/anyOf.cpp @@ -0,0 +1 @@ +${Title} diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/anyOfSchemaShape.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/anyOfSchemaShape.cpp new file mode 100644 index 00000000..f8d48279 --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/anyOfSchemaShape.cpp @@ -0,0 +1,3 @@ + string ${property}Str; + response.${Property.dependency}${Property}.ToString(${property}Str); + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = ${property}Str; diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/array.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/array.cpp new file mode 100644 index 00000000..006b4322 --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/array.cpp @@ -0,0 +1,5 @@ + ${if.impl.array.optional}${base.title}.${property} = std::make_optional<${type}>();${end.if.impl.array.optional} + auto index(response.${Property}.Elements()); + while (index.Next() == true) { +${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}.push_back(index.Current().Value());${end.if.non.object} + } \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/const.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/const.cpp new file mode 100644 index 00000000..41bc1feb --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/const.cpp @@ -0,0 +1 @@ + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response.${Property.dependency}${Property}; diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/generic.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/generic.cpp new file mode 100644 index 00000000..41bc1feb --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/generic.cpp @@ -0,0 +1 @@ + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response.${Property.dependency}${Property}; diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/namespace.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/namespace.cpp new file mode 100644 index 00000000..b3afde8a --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/namespace.cpp @@ -0,0 +1 @@ +${if.namespace.notsame}${parent.Title}::${end.if.namespace.notsame} \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/object-array.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/object-array.cpp new file mode 100644 index 00000000..4a4eecb7 --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/object-array.cpp @@ -0,0 +1,4 @@ + ${type} ${property}Result${level}; + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonResult = index.Current(); +${properties} + ${base.title}.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}.push_back(${property}Result${level}); \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/object-separator.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/object-separator.cpp new file mode 100644 index 00000000..945c9b46 --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/object-separator.cpp @@ -0,0 +1 @@ +. \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/object.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/object.cpp new file mode 100644 index 00000000..ddd85ed9 --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/object.cpp @@ -0,0 +1,3 @@ +${if.impl.optional} + ${base.title}${property.dependency} = std::make_optional<${type}>();${end.if.impl.optional} +${properties} \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp new file mode 100644 index 00000000..0d95dcab --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp @@ -0,0 +1 @@ +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response.${Property.dependency}${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/ref.h b/languages/cpp/templates/callback-context-instantiation/sub-property/ref.h new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/ref.h @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/title.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/title.cpp new file mode 100644 index 00000000..2a420b4b --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/title.cpp @@ -0,0 +1 @@ +${Title} \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/title.cpp b/languages/cpp/templates/callback-context-instantiation/title.cpp new file mode 100644 index 00000000..2a420b4b --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/title.cpp @@ -0,0 +1 @@ +${Title} \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/tuple.cpp b/languages/cpp/templates/callback-context-instantiation/tuple.cpp new file mode 100644 index 00000000..c2934799 --- /dev/null +++ b/languages/cpp/templates/callback-context-instantiation/tuple.cpp @@ -0,0 +1,4 @@ + if (strcmp(elements.Label(), "${property}") == 0) { + ${property}.first = elements.Current().Get(0); + ${property}.second = elements.Current().Get(1); + } \ No newline at end of file diff --git a/languages/cpp/templates/callback-initialization/additionalProperties.cpp b/languages/cpp/templates/callback-initialization/additionalProperties.cpp new file mode 100644 index 00000000..754b0fed --- /dev/null +++ b/languages/cpp/templates/callback-initialization/additionalProperties.cpp @@ -0,0 +1 @@ + ${if.namespace.notsame}${parent.Title}::${end.if.namespace.notsame}${title} ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/callback-initialization/anyOf.cpp b/languages/cpp/templates/callback-initialization/anyOf.cpp new file mode 100644 index 00000000..30f233a7 --- /dev/null +++ b/languages/cpp/templates/callback-initialization/anyOf.cpp @@ -0,0 +1 @@ +{property}; diff --git a/languages/cpp/templates/callback-initialization/array.cpp b/languages/cpp/templates/callback-initialization/array.cpp new file mode 100644 index 00000000..7ecdb522 --- /dev/null +++ b/languages/cpp/templates/callback-initialization/array.cpp @@ -0,0 +1 @@ + ${type} ${property}; diff --git a/languages/cpp/templates/callback-initialization/enum.cpp b/languages/cpp/templates/callback-initialization/enum.cpp new file mode 100644 index 00000000..754b0fed --- /dev/null +++ b/languages/cpp/templates/callback-initialization/enum.cpp @@ -0,0 +1 @@ + ${if.namespace.notsame}${parent.Title}::${end.if.namespace.notsame}${title} ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/callback-initialization/generic.cpp b/languages/cpp/templates/callback-initialization/generic.cpp new file mode 100644 index 00000000..b8231bf0 --- /dev/null +++ b/languages/cpp/templates/callback-initialization/generic.cpp @@ -0,0 +1 @@ + ${type} ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/callback-initialization/object-empty-property.cpp b/languages/cpp/templates/callback-initialization/object-empty-property.cpp new file mode 100644 index 00000000..92a17554 --- /dev/null +++ b/languages/cpp/templates/callback-initialization/object-empty-property.cpp @@ -0,0 +1 @@ + std::string ${property}; diff --git a/languages/cpp/templates/callback-initialization/object.cpp b/languages/cpp/templates/callback-initialization/object.cpp new file mode 100644 index 00000000..754b0fed --- /dev/null +++ b/languages/cpp/templates/callback-initialization/object.cpp @@ -0,0 +1 @@ + ${if.namespace.notsame}${parent.Title}::${end.if.namespace.notsame}${title} ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/callback-initialization/primitive.cpp b/languages/cpp/templates/callback-initialization/primitive.cpp new file mode 100644 index 00000000..23bbace7 --- /dev/null +++ b/languages/cpp/templates/callback-initialization/primitive.cpp @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/cpp/templates/callback-initialization/title.cpp b/languages/cpp/templates/callback-initialization/title.cpp new file mode 100644 index 00000000..2a420b4b --- /dev/null +++ b/languages/cpp/templates/callback-initialization/title.cpp @@ -0,0 +1 @@ +${Title} \ No newline at end of file diff --git a/languages/cpp/templates/callback-instantiation/generic.cpp b/languages/cpp/templates/callback-instantiation/generic.cpp new file mode 100644 index 00000000..3b0b6489 --- /dev/null +++ b/languages/cpp/templates/callback-instantiation/generic.cpp @@ -0,0 +1,12 @@ + WPEFramework::Core::JSON::VariantContainer::Iterator elements = proxyResponse->Variants(); + while (elements.Next()) { +${callback.result.instantiation} + else if (strcmp(elements.Label(), "context") == 0) { + WPEFramework::Core::JSON::VariantContainer::Iterator params = elements.Current().Object().Variants(); + while (params.Next()) { + ${callback.param.instantiation.with.indent} + } + } else { + ASSERT(false); + } + } \ No newline at end of file diff --git a/languages/cpp/templates/callback-response-instantiation/additionalProperties.cpp b/languages/cpp/templates/callback-response-instantiation/additionalProperties.cpp new file mode 100644 index 00000000..b39e4545 --- /dev/null +++ b/languages/cpp/templates/callback-response-instantiation/additionalProperties.cpp @@ -0,0 +1 @@ +${property} \ No newline at end of file diff --git a/languages/cpp/templates/callback-response-instantiation/generic.cpp b/languages/cpp/templates/callback-response-instantiation/generic.cpp index c8f3f090..b39e4545 100644 --- a/languages/cpp/templates/callback-response-instantiation/generic.cpp +++ b/languages/cpp/templates/callback-response-instantiation/generic.cpp @@ -1 +1 @@ -response \ No newline at end of file +${property} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/additionalProperties.cpp b/languages/cpp/templates/callback-result-instantiation/additionalProperties.cpp index a304af7e..59e3acf2 100644 --- a/languages/cpp/templates/callback-result-instantiation/additionalProperties.cpp +++ b/languages/cpp/templates/callback-result-instantiation/additionalProperties.cpp @@ -1,5 +1,7 @@ - ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} elements = (*proxyResponse)->Variants(); - ${if.namespace.notsame}${info.Title}::${end.if.namespace.notsame}${title} response; + ${if.namespace.notsame}${info.Title}::${end.if.namespace.notsame}JsonData_${title}::Iterator elements = proxyResponse->Variants(); while (elements.Next()) { - response.insert(elements.Label(), elements.Current().${additional.type}.Value()); - } \ No newline at end of file +${if.not.default} ${namespace}${key} key = WPEFramework::Core::EnumerateType<${namespace}${key}>(elements.Label(), false).Value();${end.if.not.default}${if.default} ${key} key = elements.Label();${end.if.default} + ${property}.emplace(std::piecewise_construct, + std::forward_as_tuple(key), + std::forward_as_tuple(elements.Current().${additional.type})); + } diff --git a/languages/cpp/templates/callback-result-instantiation/anyOf.cpp b/languages/cpp/templates/callback-result-instantiation/anyOf.cpp new file mode 100644 index 00000000..120561dd --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/anyOf.cpp @@ -0,0 +1 @@ + ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/array.cpp b/languages/cpp/templates/callback-result-instantiation/array.cpp index 603644e3..0e48a92b 100644 --- a/languages/cpp/templates/callback-result-instantiation/array.cpp +++ b/languages/cpp/templates/callback-result-instantiation/array.cpp @@ -1,5 +1,4 @@ - auto index((*proxyResponse)->Elements()); - ${type} response; + auto index(proxyResponse->Elements()); while (index.Next() == true) { - response.push_back(index.Current().Value()); - } + ${property}.push_back(index.Current().Value()); + } \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/enum.cpp b/languages/cpp/templates/callback-result-instantiation/enum.cpp index 30fdf717..d5bc4150 100644 --- a/languages/cpp/templates/callback-result-instantiation/enum.cpp +++ b/languages/cpp/templates/callback-result-instantiation/enum.cpp @@ -1 +1 @@ - ${if.namespace.notsame}${info.Title}::${end.if.namespace.notsame}${title} response = (*proxyResponse)->Value(); \ No newline at end of file + ${if.namespace.notsame}${info.Title}::${end.if.namespace.notsame}${title} response = proxyResponse->Value(); \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/generic.cpp b/languages/cpp/templates/callback-result-instantiation/generic.cpp index 8c7a2fea..6d8fa873 100644 --- a/languages/cpp/templates/callback-result-instantiation/generic.cpp +++ b/languages/cpp/templates/callback-result-instantiation/generic.cpp @@ -1 +1 @@ - ${type} response = (*proxyResponse)->Value(); \ No newline at end of file + ${property} = proxyResponse->Value(); \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/namespace.cpp b/languages/cpp/templates/callback-result-instantiation/namespace.cpp new file mode 100644 index 00000000..b3afde8a --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/namespace.cpp @@ -0,0 +1 @@ +${if.namespace.notsame}${parent.Title}::${end.if.namespace.notsame} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/object.cpp b/languages/cpp/templates/callback-result-instantiation/object.cpp index 8722a92e..c4569c3e 100644 --- a/languages/cpp/templates/callback-result-instantiation/object.cpp +++ b/languages/cpp/templates/callback-result-instantiation/object.cpp @@ -1,2 +1 @@ - ${title} response; ${properties} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/property.cpp b/languages/cpp/templates/callback-result-instantiation/property.cpp index 31648b06..db30050c 100644 --- a/languages/cpp/templates/callback-result-instantiation/property.cpp +++ b/languages/cpp/templates/callback-result-instantiation/property.cpp @@ -1 +1 @@ -${shape} ${if.non.object}response.${property} = (*proxyResponse)->${Property};${end.if.non.object} \ No newline at end of file +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}.${property} = proxyResponse->${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/anyOf.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/anyOf.cpp new file mode 100644 index 00000000..e2e80c7c --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/anyOf.cpp @@ -0,0 +1 @@ +${Title} diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/anyOfSchemaShape.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/anyOfSchemaShape.cpp new file mode 100644 index 00000000..56f90f5b --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/anyOfSchemaShape.cpp @@ -0,0 +1,3 @@ + string ${property}Str; + proxyResponse->${Property.dependency}${Property}.ToString(${property}Str); + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = ${property}Str; \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp new file mode 100644 index 00000000..03910b83 --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp @@ -0,0 +1,5 @@ + ${if.impl.array.optional}${base.title}.${property} = std::make_optional<${type}>();${end.if.impl.array.optional} + auto index(proxyResponse->${Property}.Elements()); + while (index.Next() == true) { +${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}.push_back(index.Current().Value());${end.if.non.object} + } \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/const.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/const.cpp new file mode 100644 index 00000000..e84a8c35 --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/const.cpp @@ -0,0 +1 @@ + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = proxyResponse->${Property.dependency}${Property}; \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/namespace.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/namespace.cpp new file mode 100644 index 00000000..b3afde8a --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/namespace.cpp @@ -0,0 +1 @@ +${if.namespace.notsame}${parent.Title}::${end.if.namespace.notsame} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/object-array.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/object-array.cpp new file mode 100644 index 00000000..7bcc042c --- /dev/null +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/object-array.cpp @@ -0,0 +1,4 @@ + ${type} ${property}Result${level}; + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonResult = index.Current(); +${properties} + ${property}response.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}.push_back(${property}Result${level}); \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp index c4569c3e..b134dafe 100644 --- a/languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp @@ -1 +1,3 @@ +${if.impl.optional} + ${base.title}${property.dependency} = std::make_optional<${type}>();${end.if.impl.optional} ${properties} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp index 1f8541f2..beff7b1e 100644 --- a/languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp @@ -1 +1 @@ -${shape} ${if.non.object}response.${property.dependency}${property} = (*proxyResponse)->${Property.dependency}${Property};${end.if.non.object} \ No newline at end of file +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = proxyResponse->${Property.dependency}${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/tuple.cpp b/languages/cpp/templates/callback-result-instantiation/tuple.cpp index 76dde980..09c06ed0 100644 --- a/languages/cpp/templates/callback-result-instantiation/tuple.cpp +++ b/languages/cpp/templates/callback-result-instantiation/tuple.cpp @@ -1,4 +1,2 @@ - auto index((*proxyResponse)->Elements()); - ${if.namespace.notsame}${info.Title}::${end.if.namespace.notsame}${title} response; - response.first = index.Get(0); - response.second = index.Get(1); \ No newline at end of file + ${property}.first = proxyResponse->Get(0); + ${property}.second = proxyResponse->Get(1); \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-serialization/additionalProperties.cpp b/languages/cpp/templates/callback-result-serialization/additionalProperties.cpp new file mode 100644 index 00000000..1ee44075 --- /dev/null +++ b/languages/cpp/templates/callback-result-serialization/additionalProperties.cpp @@ -0,0 +1 @@ + WPEFramework::Core::ProxyType& proxyResponse = *(reinterpret_cast*>(jsonResponse)); diff --git a/languages/cpp/templates/callback-result-serialization/generic.cpp b/languages/cpp/templates/callback-result-serialization/generic.cpp new file mode 100644 index 00000000..c08e747a --- /dev/null +++ b/languages/cpp/templates/callback-result-serialization/generic.cpp @@ -0,0 +1 @@ + WPEFramework::Core::ProxyType<${method.result.json}>& proxyResponse = *(reinterpret_cast*>(jsonResponse)); diff --git a/languages/cpp/templates/callback-result-serialization/primitive.cpp b/languages/cpp/templates/callback-result-serialization/primitive.cpp new file mode 100644 index 00000000..23bbace7 --- /dev/null +++ b/languages/cpp/templates/callback-result-serialization/primitive.cpp @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-serialization/ref.h b/languages/cpp/templates/callback-result-serialization/ref.h new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/callback-result-serialization/ref.h @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/callback-serialization/generic.cpp b/languages/cpp/templates/callback-serialization/generic.cpp new file mode 100644 index 00000000..1ee44075 --- /dev/null +++ b/languages/cpp/templates/callback-serialization/generic.cpp @@ -0,0 +1 @@ + WPEFramework::Core::ProxyType& proxyResponse = *(reinterpret_cast*>(jsonResponse)); diff --git a/languages/cpp/templates/declarations-override/calls-metrics.h b/languages/cpp/templates/declarations-override/calls-metrics.h new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/languages/cpp/templates/declarations-override/calls-metrics.h @@ -0,0 +1 @@ + diff --git a/languages/cpp/templates/declarations/calls-metrics.h b/languages/cpp/templates/declarations/calls-metrics.h new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/languages/cpp/templates/declarations/calls-metrics.h @@ -0,0 +1 @@ + diff --git a/languages/cpp/templates/json-types/anyOfSchemaShape.h b/languages/cpp/templates/json-types/anyOfSchemaShape.h index 08d72bbd..ab257971 100644 --- a/languages/cpp/templates/json-types/anyOfSchemaShape.h +++ b/languages/cpp/templates/json-types/anyOfSchemaShape.h @@ -1 +1 @@ - /* anyOf schema shape is not supported right now */ + /* anyOf schema shape is not supported right now */ \ No newline at end of file diff --git a/languages/cpp/templates/json-types/const.h b/languages/cpp/templates/json-types/const.h index e69de29b..2d60a3c8 100644 --- a/languages/cpp/templates/json-types/const.h +++ b/languages/cpp/templates/json-types/const.h @@ -0,0 +1 @@ +FireboltSDK::JSON::String \ No newline at end of file diff --git a/languages/cpp/templates/json-types/integer.h b/languages/cpp/templates/json-types/integer.h index b57fe26e..4bf0dddb 100644 --- a/languages/cpp/templates/json-types/integer.h +++ b/languages/cpp/templates/json-types/integer.h @@ -1 +1 @@ -WPEFramework::Core::JSON::DecSInt32 \ No newline at end of file +WPEFramework::Core::JSON::DecSInt32 diff --git a/languages/cpp/templates/methods/event.cpp b/languages/cpp/templates/methods/event.cpp index 52549399..b46f2208 100644 --- a/languages/cpp/templates/methods/event.cpp +++ b/languages/cpp/templates/methods/event.cpp @@ -1,12 +1,14 @@ /* ${method.rpc.name} - ${method.description} */ static void ${method.name}InnerCallback( void* notification, const void* userData, void* jsonResponse ) { -${event.callback.params.serialization} - ASSERT(proxyResponse->IsValid() == true); +${event.callback.serialization} + ASSERT(proxyResponse.IsValid() == true); - if (proxyResponse->IsValid() == true) { -${event.callback.result.instantiation} - proxyResponse->Release(); + if (proxyResponse.IsValid() == true) { +${event.callback.initialization} + +${event.callback.instantiation} + proxyResponse.Release(); I${info.Title}::I${method.Name}Notification& notifier = *(reinterpret_cast(notification)); notifier.${method.name}(${event.callback.response.instantiation}); @@ -32,4 +34,4 @@ if (err != nullptr) { *err = status; } - } \ No newline at end of file + } diff --git a/languages/cpp/templates/methods/property.cpp b/languages/cpp/templates/methods/property.cpp index ef29221a..4fbe9fc4 100644 --- a/languages/cpp/templates/methods/property.cpp +++ b/languages/cpp/templates/methods/property.cpp @@ -15,4 +15,4 @@ } return ${method.result.name}; - }${method.setter} \ No newline at end of file + }${method.setter} diff --git a/languages/cpp/templates/parameter-serialization/additionalProperties.cpp b/languages/cpp/templates/parameter-serialization/additionalProperties.cpp new file mode 100644 index 00000000..caa132d9 --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/additionalProperties.cpp @@ -0,0 +1,9 @@ + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}${title} map = ${property}${if.impl.optional}.value()${end.if.impl.optional}; + WPEFramework::Core::JSON::Variant ${property}Variant; + for (auto element: map) { + WPEFramework::Core::JSON::Variant jsonElement = element.second; + WPEFramework::Core::JSON::VariantContainer jsonContainer; + jsonContainer.Set(element.first.c_str(), jsonElement); + ${property}Variant = jsonContainer; + } + jsonParameters.Set(_T("${property}"), ${property}Variant); diff --git a/languages/cpp/templates/parameter-serialization/array.cpp b/languages/cpp/templates/parameter-serialization/array.cpp index 5768dfc5..d45916ab 100644 --- a/languages/cpp/templates/parameter-serialization/array.cpp +++ b/languages/cpp/templates/parameter-serialization/array.cpp @@ -4,4 +4,4 @@ } WPEFramework::Core::JSON::Variant ${Property}Variant; ${Property}Variant.Array(${Property}); - jsonParameters.Set(_T("${property}"), ${Property}Variant); \ No newline at end of file + jsonParameters.Set(_T("${property}"), ${Property}Variant); diff --git a/languages/cpp/templates/parameter-serialization/enum.cpp b/languages/cpp/templates/parameter-serialization/enum.cpp index 2367c118..991ea807 100644 --- a/languages/cpp/templates/parameter-serialization/enum.cpp +++ b/languages/cpp/templates/parameter-serialization/enum.cpp @@ -1,3 +1,3 @@ ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonValue = ${property}${if.optional}.value()${end.if.optional}; WPEFramework::Core::JSON::Variant ${Property}(jsonValue.Data()); - jsonParameters.Set(_T("${property}"), ${Property}); \ No newline at end of file + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/cpp/templates/parameter-serialization/generic.cpp b/languages/cpp/templates/parameter-serialization/generic.cpp index d38bcfca..566c7354 100644 --- a/languages/cpp/templates/parameter-serialization/generic.cpp +++ b/languages/cpp/templates/parameter-serialization/generic.cpp @@ -1,2 +1,2 @@ WPEFramework::Core::JSON::Variant ${Property}(${property}${if.optional}.value()${end.if.optional}); - jsonParameters.Set(_T("${property}"), ${Property}); \ No newline at end of file + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/cpp/templates/parameter-serialization/object-empty-property.cpp b/languages/cpp/templates/parameter-serialization/object-empty-property.cpp new file mode 100644 index 00000000..566c7354 --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/object-empty-property.cpp @@ -0,0 +1,2 @@ + WPEFramework::Core::JSON::Variant ${Property}(${property}${if.optional}.value()${end.if.optional}); + jsonParameters.Set(_T("${property}"), ${Property}); diff --git a/languages/cpp/templates/parameter-serialization/object.cpp b/languages/cpp/templates/parameter-serialization/object.cpp index 42226921..ef2aa794 100644 --- a/languages/cpp/templates/parameter-serialization/object.cpp +++ b/languages/cpp/templates/parameter-serialization/object.cpp @@ -1,4 +1,4 @@ - auto element = ${property}; + auto element = ${property}${if.impl.optional}.value()${end.if.impl.optional}; ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${Property}Container; ${properties} string ${Property}Str; diff --git a/languages/cpp/templates/parameter-serialization/property.cpp b/languages/cpp/templates/parameter-serialization/property.cpp index 7036ea07..fbbe778a 100644 --- a/languages/cpp/templates/parameter-serialization/property.cpp +++ b/languages/cpp/templates/parameter-serialization/property.cpp @@ -1 +1 @@ -${shape} ${if.non.object}${base.Title}Container.${Property} = element${if.base.optional}.value()${end.if.base.optional}.${property}${if.optional}.value()${end.if.optional};${end.if.non.object} \ No newline at end of file +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.Title}Container.${Property} = element.${property}${if.optional}.value()${end.if.optional};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/anyOf.cpp b/languages/cpp/templates/parameter-serialization/sub-property/anyOf.cpp new file mode 100644 index 00000000..e2e80c7c --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/sub-property/anyOf.cpp @@ -0,0 +1 @@ +${Title} diff --git a/languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp b/languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp new file mode 100644 index 00000000..ea65b36f --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp @@ -0,0 +1 @@ + ${base.Title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}${if.optional}.value()${end.if.optional}; diff --git a/languages/cpp/templates/parameter-serialization/sub-property/array.cpp b/languages/cpp/templates/parameter-serialization/sub-property/array.cpp new file mode 100644 index 00000000..50bbc39e --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/sub-property/array.cpp @@ -0,0 +1,8 @@ + WPEFramework::Core::JSON::ArrayType ${Property}; + ${type} ${property} = element.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}; + for (auto& element : ${property}) { +${if.object}${items.with.indent}${end.if.object}${if.non.object}${Property}.Add() = element;${end.if.non.object} + } + WPEFramework::Core::JSON::Variant ${Property}Variant; + ${Property}Variant.Array(${Property}); + jsonParameters.Set(_T("${property}"), ${Property}Variant); diff --git a/languages/cpp/templates/parameter-serialization/sub-property/const.cpp b/languages/cpp/templates/parameter-serialization/sub-property/const.cpp new file mode 100644 index 00000000..498529d8 --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/sub-property/const.cpp @@ -0,0 +1 @@ + ${base.Title}Container.${Property.dependency}${Property} = element${property.dependency}.${property}${if.optional}.value()${end.if.optional}; diff --git a/languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp b/languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp new file mode 100644 index 00000000..f52f229e --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp @@ -0,0 +1,7 @@ + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${Property}Container; +${properties} + string ${Property}Str; + ${Property}Container.ToString(${Property}Str); + WPEFramework::Core::JSON::VariantContainer ${Property}VariantContainer(${Property}Str); + WPEFramework::Core::JSON::Variant ${Property}Variant = ${Property}VariantContainer; + ${Property}.Add() = ${Property}Variant; \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/object.cpp b/languages/cpp/templates/parameter-serialization/sub-property/object.cpp index c4569c3e..c04d0a50 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/object.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/object.cpp @@ -1 +1 @@ -${properties} \ No newline at end of file +${properties} diff --git a/languages/cpp/templates/parameter-serialization/sub-property/property.cpp b/languages/cpp/templates/parameter-serialization/sub-property/property.cpp index 58aa5943..a8ddffe4 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/property.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/property.cpp @@ -1 +1 @@ -${shape} ${if.non.object}${title}.${Property.dependency}${Property} = element${if.base.optional}.value()${end.if.base.optional}.${property.dependency}${property}${if.optional}.value()${end.if.optional};${end.if.non.object} \ No newline at end of file +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.Title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}${if.optional}.value()${end.if.optional};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/title.cpp b/languages/cpp/templates/parameter-serialization/sub-property/title.cpp index e2e80c7c..2a420b4b 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/title.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/title.cpp @@ -1 +1 @@ -${Title} +${Title} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/title.cpp b/languages/cpp/templates/parameter-serialization/title.cpp new file mode 100644 index 00000000..2a420b4b --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/title.cpp @@ -0,0 +1 @@ +${Title} \ No newline at end of file diff --git a/languages/cpp/templates/result-initialization/additionalProperties.cpp b/languages/cpp/templates/result-initialization/additionalProperties.cpp index c33c2ea0..6f7f63f0 100644 --- a/languages/cpp/templates/result-initialization/additionalProperties.cpp +++ b/languages/cpp/templates/result-initialization/additionalProperties.cpp @@ -1 +1 @@ - ${Title} ${property}; \ No newline at end of file + ${if.namespace.notsame}${parent.Title}::${end.if.namespace.notsame}${Title} ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/result-initialization/anyOf.cpp b/languages/cpp/templates/result-initialization/anyOf.cpp new file mode 100644 index 00000000..6a698651 --- /dev/null +++ b/languages/cpp/templates/result-initialization/anyOf.cpp @@ -0,0 +1 @@ + std::string ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/result-initialization/object-empty-property.cpp b/languages/cpp/templates/result-initialization/object-empty-property.cpp new file mode 100644 index 00000000..6f7f63f0 --- /dev/null +++ b/languages/cpp/templates/result-initialization/object-empty-property.cpp @@ -0,0 +1 @@ + ${if.namespace.notsame}${parent.Title}::${end.if.namespace.notsame}${Title} ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/result-initialization/ref.h b/languages/cpp/templates/result-initialization/ref.h new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/result-initialization/ref.h @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/additionalProperties.cpp b/languages/cpp/templates/result-instantiation/additionalProperties.cpp index e5d7b116..7f10732d 100644 --- a/languages/cpp/templates/result-instantiation/additionalProperties.cpp +++ b/languages/cpp/templates/result-instantiation/additionalProperties.cpp @@ -1,6 +1,7 @@ - while (jsonResult.Variants().Next()) { - std::string label = jsonResult.Variants().Label(); + WPEFramework::Core::JSON::VariantContainer::Iterator variants = jsonResult.Variants(); + while (variants.Next()) { +${if.not.default} ${namespace}${key} key = WPEFramework::Core::EnumerateType<${namespace}${key}>(variants.Label(), false).Value();${end.if.not.default}${if.default} ${key} key = variants.Label();${end.if.default} ${property}.emplace(std::piecewise_construct, - std::forward_as_tuple(label), - std::forward_as_tuple(jsonResult.Variants().Current().${additional.type})); - } \ No newline at end of file + std::forward_as_tuple(key), + std::forward_as_tuple(variants.Current().${additional.type})); + } diff --git a/languages/cpp/templates/result-instantiation/anyOf.cpp b/languages/cpp/templates/result-instantiation/anyOf.cpp new file mode 100644 index 00000000..8ca96768 --- /dev/null +++ b/languages/cpp/templates/result-instantiation/anyOf.cpp @@ -0,0 +1,3 @@ + std::string resultStr; + jsonResult.ToString(resultStr); + ${property} = resultStr; \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/namespace.cpp b/languages/cpp/templates/result-instantiation/namespace.cpp new file mode 100644 index 00000000..b3afde8a --- /dev/null +++ b/languages/cpp/templates/result-instantiation/namespace.cpp @@ -0,0 +1 @@ +${if.namespace.notsame}${parent.Title}::${end.if.namespace.notsame} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/object-empty-property.cpp b/languages/cpp/templates/result-instantiation/object-empty-property.cpp new file mode 100644 index 00000000..8ca96768 --- /dev/null +++ b/languages/cpp/templates/result-instantiation/object-empty-property.cpp @@ -0,0 +1,3 @@ + std::string resultStr; + jsonResult.ToString(resultStr); + ${property} = resultStr; \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/property.cpp b/languages/cpp/templates/result-instantiation/property.cpp index fe19dab1..fb6ca4d4 100644 --- a/languages/cpp/templates/result-instantiation/property.cpp +++ b/languages/cpp/templates/result-instantiation/property.cpp @@ -1 +1 @@ -${shape} ${if.non.array}${if.non.object}${base.title}Result${level}.${property} = jsonResult.${Property}.Value();${end.if.non.object}${end.if.non.array} \ No newline at end of file +${shape} ${if.non.anyOf}${if.non.array}${if.non.object}${base.title}Result${level}.${property} = jsonResult.${Property}.Value();${end.if.non.object}${end.if.non.array}${end.if.non.anyOf} diff --git a/languages/cpp/templates/result-instantiation/sub-property/anyOf.cpp b/languages/cpp/templates/result-instantiation/sub-property/anyOf.cpp new file mode 100644 index 00000000..e2e80c7c --- /dev/null +++ b/languages/cpp/templates/result-instantiation/sub-property/anyOf.cpp @@ -0,0 +1 @@ +${Title} diff --git a/languages/cpp/templates/result-instantiation/sub-property/anyOfSchemaShape.cpp b/languages/cpp/templates/result-instantiation/sub-property/anyOfSchemaShape.cpp new file mode 100644 index 00000000..1d5afa9b --- /dev/null +++ b/languages/cpp/templates/result-instantiation/sub-property/anyOfSchemaShape.cpp @@ -0,0 +1,3 @@ + string ${property}Str; + jsonResult.${Property.dependency}${Property}.ToString(${property}Str); + ${base.title}Result${level}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = ${property}Str; diff --git a/languages/cpp/templates/result-instantiation/sub-property/array.cpp b/languages/cpp/templates/result-instantiation/sub-property/array.cpp index efa1adeb..5d401ef3 100644 --- a/languages/cpp/templates/result-instantiation/sub-property/array.cpp +++ b/languages/cpp/templates/result-instantiation/sub-property/array.cpp @@ -1,4 +1,5 @@ + ${if.impl.array.optional}${base.title}Result${level}.${property} = std::make_optional<${type}>();${end.if.impl.array.optional} auto index(jsonResult.${Property}.Elements()); while (index.Next() == true) { -${if.object}${items.with.indent}${end.if.object}${if.non.object} ${property}.push_back(index.Current().Value());${end.if.non.object} +${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}Result${level}.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}.push_back(index.Current().Value());${end.if.non.object} } \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/sub-property/namespace.cpp b/languages/cpp/templates/result-instantiation/sub-property/namespace.cpp new file mode 100644 index 00000000..b3afde8a --- /dev/null +++ b/languages/cpp/templates/result-instantiation/sub-property/namespace.cpp @@ -0,0 +1 @@ +${if.namespace.notsame}${parent.Title}::${end.if.namespace.notsame} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/sub-property/object-array.cpp b/languages/cpp/templates/result-instantiation/sub-property/object-array.cpp index 06a4d04d..87f0971d 100644 --- a/languages/cpp/templates/result-instantiation/sub-property/object-array.cpp +++ b/languages/cpp/templates/result-instantiation/sub-property/object-array.cpp @@ -1,4 +1,4 @@ ${type} ${property}Result${level}; ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonResult = index.Current(); ${properties} - ${property}Result.${property}${if.impl.optional}.value()${end.if.impl.optional}.push_back(${property}Result${level}); \ No newline at end of file + ${property}Result.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}.push_back(${property}Result${level}); \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/sub-property/object.cpp b/languages/cpp/templates/result-instantiation/sub-property/object.cpp index c04d0a50..2f526fef 100644 --- a/languages/cpp/templates/result-instantiation/sub-property/object.cpp +++ b/languages/cpp/templates/result-instantiation/sub-property/object.cpp @@ -1 +1,3 @@ -${properties} +${if.impl.optional} + ${base.title}Result${level}${property.dependency} = std::make_optional<${type}>();${end.if.impl.optional} +${properties} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/sub-property/property.cpp b/languages/cpp/templates/result-instantiation/sub-property/property.cpp index 97e0dc0f..6e938509 100644 --- a/languages/cpp/templates/result-instantiation/sub-property/property.cpp +++ b/languages/cpp/templates/result-instantiation/sub-property/property.cpp @@ -1 +1 @@ -${shape} ${if.non.object}${base.title}Result${level}.${property.dependency}${if.impl.optional}value().${end.if.impl.optional}${property} = jsonResult.${Property.dependency}${Property};${end.if.non.object} \ No newline at end of file +${shape} ${if.non.anyOf}${if.non.array}${if.non.object}${base.title}Result${level}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = jsonResult.${Property.dependency}${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/tuple.cpp b/languages/cpp/templates/result-instantiation/tuple.cpp index 58f79f1d..c94a7054 100644 --- a/languages/cpp/templates/result-instantiation/tuple.cpp +++ b/languages/cpp/templates/result-instantiation/tuple.cpp @@ -1,3 +1,2 @@ - auto index(jsonResult.Elements()); - ${property}.first = index.Get(0); - ${property}.second = index.Get(1); \ No newline at end of file + ${property}.first = jsonResult.Get(0); + ${property}.second = jsonResult.Get(1); \ No newline at end of file diff --git a/languages/cpp/templates/schemas/default.cpp b/languages/cpp/templates/schemas/default.cpp index 9a52cff7..13239ca8 100644 --- a/languages/cpp/templates/schemas/default.cpp +++ b/languages/cpp/templates/schemas/default.cpp @@ -1 +1 @@ -${schema.shape} +${schema.shape} \ No newline at end of file diff --git a/languages/cpp/templates/types/additionalProperties.h b/languages/cpp/templates/types/additionalProperties.h index eced27fe..89a249cc 100644 --- a/languages/cpp/templates/types/additionalProperties.h +++ b/languages/cpp/templates/types/additionalProperties.h @@ -1 +1 @@ -using ${title} = std::unordered_map<${key}, ${type}>; +using ${title} = std::unordered_map<${namespace}${key}, ${type}>; \ No newline at end of file diff --git a/languages/cpp/templates/types/anyOfSchemaShape.h b/languages/cpp/templates/types/anyOfSchemaShape.h index 08d72bbd..c239e142 100644 --- a/languages/cpp/templates/types/anyOfSchemaShape.h +++ b/languages/cpp/templates/types/anyOfSchemaShape.h @@ -1 +1 @@ - /* anyOf schema shape is not supported right now */ +/* anyOf schema shape is not supported right now */ \ No newline at end of file diff --git a/languages/cpp/templates/types/property.h b/languages/cpp/templates/types/property.h index eb813df6..92de9ade 100644 --- a/languages/cpp/templates/types/property.h +++ b/languages/cpp/templates/types/property.h @@ -1 +1 @@ -${if.optional}std::optional<${end.if.optional}${title}${if.optional}>${end.if.optional} ${property}; \ No newline at end of file +${if.optional}std::optional<${end.if.optional}${title}${if.optional}>${end.if.optional} ${property}; diff --git a/languages/cpp/templates/types/tuple.h b/languages/cpp/templates/types/tuple.h index b00d2610..0ba9370f 100644 --- a/languages/cpp/templates/types/tuple.h +++ b/languages/cpp/templates/types/tuple.h @@ -1,2 +1,2 @@ /* ${title} */ -std::pair<${items}> ${title}; +using ${title} = std::pair<${items}>; \ No newline at end of file diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 031e61ea..8af37cdf 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -1257,11 +1257,25 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) const resultInit = types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-initialization', property: flattenedMethod.result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) // w/out primitive: true, getSchemaShape skips anonymous types, like primitives const serializedEventParams = event ? flattenedMethod.params.filter(p => p.name !== 'listen').map(param => types.getSchemaShape(param.schema, json, {templateDir: 'parameter-serialization', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, 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: 'callback-parameter-serialization', property: result.name, required: event.result.schema.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' - - const callbackResultInst = event ? types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-result-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' - // hmm... how is this different from callbackSerializedParams? i guess they get merged? - const callbackResponseInst = event ? types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-response-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' + const callbackSerializedList = event ? types.getSchemaShape(event.result.schema, json, { templateDir: event.params && event.params.length ? 'callback-serialization' : 'callback-result-serialization', property: result.name, required: event.result.schema.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' + const callbackInitialization = event ? ((event.params && event.params.length ? (event.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'callback-initialization', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n')) + '\n' : '' ) + (types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-initialization', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }))) : '' + let callbackInstantiation = '' + if (event) { + if (event.params && event.params.length) { + callbackInstantiation = types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) + let paramInstantiation = event.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'callback-context-instantiation', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n') + let resultInstantiation = types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-context-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) + callbackInstantiation = callbackInstantiation + .replace(/\$\{callback\.param\.instantiation\.with\.indent\}/g, indent(paramInstantiation, ' ')) + .replace(/\$\{callback\.result\.instantiation\}/g, resultInstantiation) + } + else { + callbackInstantiation = types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-result-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) + } + } + // hmm... how is this different from callbackSerializedList? i guess they get merged? + //console.log("event --- ", event) + const callbackResponseInst = event ? (event.params && event.params.length ? (event.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'callback-response-instantiation', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join(', ')) + ', ' : '' ) + (types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-response-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })) : '' 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}) @@ -1329,8 +1343,9 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{event\.signature\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section }) : '') .replace(/\$\{event\.signature\.callback\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section, callback: true }) : '') .replace(/\$\{event\.params\.serialization\}/g, serializedEventParams) - .replace(/\$\{event\.callback\.params\.serialization\}/g, callbackSerializedParams) - .replace(/\$\{event\.callback\.result\.instantiation\}/g, callbackResultInst) + .replace(/\$\{event\.callback\.serialization\}/g, callbackSerializedList) + .replace(/\$\{event\.callback\.initialization\}/g, callbackInitialization) + .replace(/\$\{event\.callback\.instantiation\}/g, callbackInstantiation) .replace(/\$\{event\.callback\.response\.instantiation\}/g, callbackResponseInst) .replace(/\$\{info\.title\.lowercase\}/g, info.title.toLowerCase()) .replace(/\$\{info\.title\}/g, info.title) diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 04cdd9fb..b3ad15db 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -133,12 +133,11 @@ const macrofy = async ( const staticModules = staticModuleNames.map(name => ( { info: { title: name } } )) let modules - if (hidePrivate) { - modules = moduleList.map(name => getModule(name, openrpc, copySchemasIntoModules)).filter(hasPublicAPIs) + modules = moduleList.map(name => getModule(name, openrpc, copySchemasIntoModules, extractSubSchemas)).filter(hasPublicAPIs) } else { - modules = moduleList.map(name => getModule(name, openrpc, copySchemasIntoModules)) + modules = moduleList.map(name => getModule(name, openrpc, copySchemasIntoModules, extractSubSchemas)) } const aggregateMacros = engine.generateAggregateMacros(openrpc, modules.concat(staticModules), templates, libraryName) @@ -160,7 +159,7 @@ const macrofy = async ( if (isPrimary) { primaryOutput.push(path.join(output, outputFile)) - } + } const content = engine.insertAggregateMacros(templates[file], aggregateMacros) outputFiles[path.join(output, outputFile)] = content diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index ba26051c..f2a8089e 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -126,16 +126,34 @@ const getTemplate = (name) => { return templates[Object.keys(templates).find(k => k === name)] || templates[Object.keys(templates).find(k => k.startsWith(name.split('.').shift() + '.'))] || '' } +const getXSchemaGroupFromProperties = (schema, title, properties, group) => { + if (properties) { + Object.entries(properties).forEach(([name, prop]) => { + if (schema.title === prop.title) { + group = title + } else { + group = getXSchemaGroupFromProperties(schema, title, prop.properties, group) + } + }) + } + return group +} + // TODO: this assumes the same title doesn't exist in multiple x-schema groups! const getXSchemaGroup = (schema, module) => { let group = module.info.title if (schema.title && module['x-schemas']) { Object.entries(module['x-schemas']).forEach(([title, module]) => { - Object.values(module).forEach(s => { - if (schema.title === s.title) { - group = title - } + Object.values(module).forEach(moduleSchema => { + let schemas = moduleSchema.allOf ? moduleSchema.allOf : [moduleSchema] + schemas.forEach((s) => { + if (schema.title === s.title || schema.title === moduleSchema.title) { + group = title + } else { + group = getXSchemaGroupFromProperties(schema, title, s.properties, group) + } + }) }) }) } @@ -156,7 +174,6 @@ function insertSchemaMacros(content, schema, module, { name = '', parent = '', p .replace(/\$\{parent\.title\}/g, parent || moduleTitle) .replace(/\$\{parent\.Title\}/g, capitalize(parent || moduleTitle)) .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, required ? '' : '$1') - .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, required ? '' : '$1') .replace(/\$\{description\}/g, schema.description ? schema.description : '') .replace(/\$\{summary\}/g, schema.description ? schema.description.split('\n')[0] : '') .replace(/\$\{name\}/g, title) @@ -214,18 +231,31 @@ const insertObjectAdditionalPropertiesMacros = (content, schema, module, title, } const additionalType = getPrimitiveType(jsonType, 'additional-types') - let key = (propertyNames && propertyNames.title) ? propertyNames.title : getTemplate(path.join(options.templateDir, 'additionalPropertiesKey')).trimEnd() + let namespace = '' + let defaultKey = true + let key = getTemplate(path.join('types', 'additionalPropertiesKey')).trimEnd() + if (propertyNames && propertyNames.title) { + let parent = getXSchemaGroup(propertyNames, module) + key = propertyNames.title + namespace = getTemplate(path.join(options.templateDir, 'namespace')) + .replace(/\$\{if\.namespace\.notsame}(.*?)\$\{end\.if\.namespace\.notsame\}/g, (module.info.title !== (parent || moduleTitle)) ? '$1' : '') + .replace(/\$\{parent\.Title\}/g, (parent && module.info.title !== parent) ? parent : '') + defaultKey = false + } content = content .replace(/\$\{shape\}/g, shape) + .replace(/\$\{if\.default\}(.*?)\$\{end\.if\.default\}/g, defaultKey ? '$1' : '') + .replace(/\$\{if\.not.default\}(.*?)\$\{end\.if\.not.default\}/gms, defaultKey ? '' : '$1') .replace(/\$\{parent\.title\}/g, title) .replace(/\$\{title\}/g, title) .replace(/\$\{type\}/g, type) .replace(/\$\{additional\.type\}/g, additionalType) .replace(/\$\{key\}/g, key) + .replace(/\$\{namespace\}/g, namespace) .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, '') .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/g, '') - .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/g, '') + .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/g, options.required ? '' : '$1') return content } @@ -247,11 +277,14 @@ const insertObjectMacros = (content, schema, module, title, property, options) = const subProperty = getTemplate(path.join(options2.templateDir, 'sub-property/object')) options2.templateDir += subProperty ? '/sub-property' : '' const objSeparator = getTemplate(path.join(options2.templateDir, 'object-separator')) - + if (localizedProp.type === 'array' || localizedProp.anyOf || localizedProp.oneOf || (typeof localizedProp.const === 'string')) { + options2.property = name + } else { + options2.property = options.property + } options2.required = schema.required && schema.required.includes(name) - const schemaShape = getSchemaShape(prop, module, options2) - - const type = getSchemaType(prop, module, options2) + const schemaShape = getSchemaShape(localizedProp, module, options2) + const type = getSchemaType(localizedProp, module, options2) // don't push properties w/ unsupported types if (type) { let replacedTemplate = template @@ -268,11 +301,14 @@ const insertObjectMacros = (content, schema, module, title, property, options) = .replace(/\$\{if\.base\.optional\}(.*?)\$\{end\.if\.base\.optional\}/gms, options.required ? '' : '$1') .replace(/\$\{if\.non\.object\}(.*?)\$\{end\.if\.non\.object\}/gms, (localizedProp.type === 'object') ? '' : '$1') .replace(/\$\{if\.non\.array\}(.*?)\$\{end\.if\.non\.array\}/gms, (localizedProp.type === 'array') ? '' : '$1') + .replace(/\$\{if\.non\.anyOf\}(.*?)\$\{end\.if\.non\.anyOf\}/gms, (localizedProp.anyOf || localizedProp.anyOneOf) ? '' : '$1') + .replace(/\$\{if\.non\.const\}(.*?)\$\{end\.if\.non\.const\}/gms, (typeof localizedProp.const === 'string') ? '' : '$1') let baseTitle = options.property if (localizedProp.type === 'object') { replacedTemplate = replacedTemplate - .replace(/\$\{property.dependency\}/g, ((options.level > 1) ? '${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}' : '') + name + objSeparator) - .replace(/\$\{Property.dependency\}/g, ((options.level > 1) ? '${Property.dependency}' : '') + capitalize(name) + (objSeparator)) + .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, schema.required && schema.required.includes(name) ? '' : '$1') + .replace(/\$\{property.dependency\}/g, ((options.level > 0) ? '${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}' : '') + objSeparator + name) + .replace(/\$\{Property.dependency\}/g, ((options.level > 0) ? '${Property.dependency}' : '') + capitalize(name) + (objSeparator)) } else { if (options2.level <= 1) { @@ -286,7 +322,6 @@ const insertObjectMacros = (content, schema, module, title, property, options) = .replace(/\$\{obj\.separator}/g, objSeparator) .replace(/\$\{base.title\}/g, (baseTitle ? (baseTitle)[0].toLowerCase() + (baseTitle).substr(1) : '')).trimEnd() .replace(/\$\{base.Title\}/g, (baseTitle ? (baseTitle)[0].toUpperCase() + (baseTitle).substr(1) : '')).trimEnd() - .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, prop.required ? '' : '$1') properties.push((i !== 0 ? indent : '') + replacedTemplate) } }) @@ -335,8 +370,7 @@ const insertObjectMacros = (content, schema, module, title, property, options) = } const regex = new RegExp("\\$\\{" + macro + "\\}", "g") - content = content.replace(regex, properties.join('\n')) - .replace(/\$\{level}/g, options.parentLevel > 0 ? options.parentLevel : '') + content = content.replace(regex, properties.join('\n')).replace(/\$\{level}/g, options.parentLevel > 0 ? options.parentLevel : '') if (!schema.properties && !schema.additionalProperties) { if (schema.propertyNames && schema.propertyNames.enum) { content = getTemplate(path.join(options.templateDir, 'enum-empty-property')) @@ -349,11 +383,13 @@ const insertObjectMacros = (content, schema, module, title, property, options) = return content } -const insertArrayMacros = (content, schema, module, level = 0, items) => { +const insertArrayMacros = (content, schema, module, level = 0, items, required = false) => { content = content .replace(/\$\{json\.type\}/g, getSchemaType(schema.items, module, { templateDir: 'json-types', destination: state.destination, section: state.section, code: false, namespace: true })) .replace(/\$\{items\}/g, items) .replace(/\$\{items\.with\.indent\}/g, indent(items, ' ')) + .replace(/\$\{if\.impl.array.optional\}(.*?)\$\{end\.if\.impl.array.optional\}/gms, required ? '' : '$1') + return content } @@ -456,9 +492,8 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren throw "Unresolvable $ref: " + schema['ref'] + ", in " + module.info.title } else if (schema.hasOwnProperty('const')) { - const shape = insertConstMacros(getTemplate(path.join(templateDir, 'const' + suffix)), schema, module, theTitle) - result = insertSchemaMacros(result.replace(/\$\{shape\}/g, shape), schema, module, { name: theTitle, parent, property, required }) - return result + const shape = insertConstMacros(getTemplate(path.join(templateDir, 'const' + suffix)) || genericTemplate, schema, module, theTitle) + return insertSchemaMacros(result.replace(/\$\{shape\}/g, shape), schema, module, { name: theTitle, parent, property, required }) } else if (!skipTitleOnce && (level > 0) && schema.title) { let enumType = (schema.type === 'string' && Array.isArray(schema.enum)) @@ -482,6 +517,7 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren shape = insertObjectMacros(getTemplate(path.join(templateDir, 'object' + (array ? '-array' : '') + suffix)) || genericTemplate, schema, module, theTitle, property, { parentLevel, level: objectLevel, parent, property, required, templateDir, descriptions, destination, section, enums, namespace: true, primitive }) } result = result.replace(/\$\{shape\}/g, shape) + result = result.replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, required ? '' : '$1') return insertSchemaMacros(result, schema, module, { name: theTitle, parent, property, required, templateDir }) } else if (schema.anyOf || schema.oneOf) { @@ -495,7 +531,7 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren if (!schema.anyOf) { schema.anyOf = schema.oneOf } - shape = insertAnyOfMacros(getTemplate(path.join(templateDir, 'anyOf' + suffix)), schema, module, theTitle) + shape = insertAnyOfMacros(getTemplate(path.join(templateDir, 'anyOf' + suffix)) || genericTemplate, schema, module, theTitle) } if (shape) { result = result.replace(/\$\{shape\}/g, shape) @@ -545,7 +581,7 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren return insertSchemaMacros(result, schema, module, { name: items, parent, property, required, templateDir }) } else if (schema.type) { - const shape = insertPrimitiveMacros(getTemplate(path.join(templateDir, 'primitive' + suffix) || genericTemplate), schema, module, theTitle, templateDir) + const shape = insertPrimitiveMacros(getTemplate(path.join(templateDir, 'primitive' + suffix)), schema, module, theTitle, templateDir) result = result.replace(/\$\{shape\}/g, shape) if (level > 0 || primitive) { return insertSchemaMacros(result, schema, module, { name: theTitle, parent, property, required, templateDir }) diff --git a/src/shared/modules.mjs b/src/shared/modules.mjs index 9f85bb1d..105ab8f7 100644 --- a/src/shared/modules.mjs +++ b/src/shared/modules.mjs @@ -986,6 +986,49 @@ const createPolymorphicMethods = (method, json) => { return polymorphicMethodSchemas } +const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) + +const addComponentSubSchemasNameForProperties = (key, schema) => { + if ((schema.type === "object") && schema.properties) { + Object.entries(schema.properties).forEach(([name, propSchema]) => { + if (isSubSchema(propSchema)) { + key = key + name.charAt(0).toUpperCase() + name.substring(1) + if (!propSchema.title) { + propSchema.title = key + } + propSchema = addComponentSubSchemasNameForProperties(key, propSchema) + } + }) + } + + return schema +} + +const addComponentSubSchemasName = (obj, schemas) => { + Object.entries(schemas).forEach(([key, schema]) => { + let componentSchemaProperties = schema.allOf ? schema.allOf : [schema] + componentSchemaProperties.forEach((componentSchema) => { + key = key.charAt(0).toUpperCase() + key.substring(1) + componentSchema = addComponentSubSchemasNameForProperties(key, componentSchema) + }) + if (!schema.title && !key) { + schema.title = capitalize(key) + } + }) + + return schemas +} + +const promoteAndNameXSchemas = (obj) => { + obj = JSON.parse(JSON.stringify(obj)) + if (obj['x-schemas']) { + Object.entries(obj['x-schemas']).forEach(([name, schemas]) => { + schemas = addComponentSubSchemasName(obj, schemas) + }) + } + return obj +} + const getPathFromModule = (module, path) => { console.error("DEPRECATED: getPathFromModule") @@ -1170,7 +1213,7 @@ const removeUnusedSchemas = (json) => { return schema } -const getModule = (name, json, copySchemas) => { +const getModule = (name, json, copySchemas, extractSubSchemas) => { let openrpc = JSON.parse(JSON.stringify(json)) openrpc.methods = openrpc.methods .filter(method => method.name.toLowerCase().startsWith(name.toLowerCase() + '.')) @@ -1230,6 +1273,9 @@ const getModule = (name, json, copySchemas) => { } openrpc = setPath(destination, schema, openrpc) + if (extractSubSchemas) { + openrpc = promoteAndNameXSchemas(openrpc) + } } }) } From 77f2cfc78b0651a2dd2191b16bc16a06a84da87a Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 16 Nov 2023 20:30:03 +0530 Subject: [PATCH 118/137] CPPSDK: template updates based on more complex schema generation (#153) --- .../templates/parameter-serialization/array.cpp | 10 +++++----- .../templates/parameter-serialization/enum.cpp | 4 ++-- .../templates/parameter-serialization/generic.cpp | 4 ++-- .../parameter-serialization/namespace.cpp | 1 + .../parameter-serialization/object-array.cpp | 12 ++++++------ .../object-empty-property.cpp | 4 ++-- .../templates/parameter-serialization/object.cpp | 12 ++++++------ .../parameter-serialization/property.cpp | 2 +- .../sub-property/anyOfSchemaShape.cpp | 2 +- .../sub-property/array.cpp | 10 ++++------ .../sub-property/const.cpp | 2 +- .../sub-property/namespace.cpp | 1 + .../sub-property/object-array.cpp | 8 ++------ .../sub-property/property.cpp | 2 +- .../result-instantiation/additionalProperties.cpp | 2 +- languages/cpp/templates/types/anyOfSchemaShape.h | 2 +- src/macrofier/types.mjs | 15 +++++++++------ 17 files changed, 46 insertions(+), 47 deletions(-) create mode 100644 languages/cpp/templates/parameter-serialization/namespace.cpp create mode 100644 languages/cpp/templates/parameter-serialization/sub-property/namespace.cpp diff --git a/languages/cpp/templates/parameter-serialization/array.cpp b/languages/cpp/templates/parameter-serialization/array.cpp index d45916ab..e6559cfb 100644 --- a/languages/cpp/templates/parameter-serialization/array.cpp +++ b/languages/cpp/templates/parameter-serialization/array.cpp @@ -1,7 +1,7 @@ - WPEFramework::Core::JSON::ArrayType ${Property}; + WPEFramework::Core::JSON::ArrayType ${property}Array; for (auto& element : ${property}) { -${if.object}${items.with.indent}${end.if.object}${if.non.object}${Property}.Add() = element;${end.if.non.object} +${if.object}${items.with.indent}${end.if.object}${if.non.object} ${property}Array.Add() = element;${end.if.non.object} } - WPEFramework::Core::JSON::Variant ${Property}Variant; - ${Property}Variant.Array(${Property}); - jsonParameters.Set(_T("${property}"), ${Property}Variant); + WPEFramework::Core::JSON::Variant ${property}Variant; + ${property}Variant.Array(${property}Array); + jsonParameters.Set(_T("${property}"), ${property}Variant); \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/enum.cpp b/languages/cpp/templates/parameter-serialization/enum.cpp index 991ea807..015c6bc6 100644 --- a/languages/cpp/templates/parameter-serialization/enum.cpp +++ b/languages/cpp/templates/parameter-serialization/enum.cpp @@ -1,3 +1,3 @@ ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonValue = ${property}${if.optional}.value()${end.if.optional}; - WPEFramework::Core::JSON::Variant ${Property}(jsonValue.Data()); - jsonParameters.Set(_T("${property}"), ${Property}); + WPEFramework::Core::JSON::Variant ${property}Variant(jsonValue.Data()); + jsonParameters.Set(_T("${property}"), ${property}Variant); diff --git a/languages/cpp/templates/parameter-serialization/generic.cpp b/languages/cpp/templates/parameter-serialization/generic.cpp index 566c7354..a2e1525b 100644 --- a/languages/cpp/templates/parameter-serialization/generic.cpp +++ b/languages/cpp/templates/parameter-serialization/generic.cpp @@ -1,2 +1,2 @@ - WPEFramework::Core::JSON::Variant ${Property}(${property}${if.optional}.value()${end.if.optional}); - jsonParameters.Set(_T("${property}"), ${Property}); + WPEFramework::Core::JSON::Variant ${property}Variant(${property}${if.optional}.value()${end.if.optional}); + jsonParameters.Set(_T("${property}"), ${property}Variant); diff --git a/languages/cpp/templates/parameter-serialization/namespace.cpp b/languages/cpp/templates/parameter-serialization/namespace.cpp new file mode 100644 index 00000000..b3afde8a --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/namespace.cpp @@ -0,0 +1 @@ +${if.namespace.notsame}${parent.Title}::${end.if.namespace.notsame} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/object-array.cpp b/languages/cpp/templates/parameter-serialization/object-array.cpp index 0965afae..e8d18cd4 100644 --- a/languages/cpp/templates/parameter-serialization/object-array.cpp +++ b/languages/cpp/templates/parameter-serialization/object-array.cpp @@ -1,7 +1,7 @@ - ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${Property}Container; + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${property}Container; ${properties} - string ${Property}Str; - ${Property}Container.ToString(${Property}Str); - WPEFramework::Core::JSON::VariantContainer ${Property}VariantContainer(${Property}Str); - WPEFramework::Core::JSON::Variant ${Property}Variant = ${Property}VariantContainer; - ${Property}.Add() = ${Property}Variant; + string ${property}Str; + ${property}Container.ToString(${property}Str); + WPEFramework::Core::JSON::VariantContainer ${property}VariantContainer(${property}Str); + WPEFramework::Core::JSON::Variant ${property}Variant = ${property}VariantContainer; + ${property}Array.Add() = ${property}Variant; \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/object-empty-property.cpp b/languages/cpp/templates/parameter-serialization/object-empty-property.cpp index 566c7354..a2e1525b 100644 --- a/languages/cpp/templates/parameter-serialization/object-empty-property.cpp +++ b/languages/cpp/templates/parameter-serialization/object-empty-property.cpp @@ -1,2 +1,2 @@ - WPEFramework::Core::JSON::Variant ${Property}(${property}${if.optional}.value()${end.if.optional}); - jsonParameters.Set(_T("${property}"), ${Property}); + WPEFramework::Core::JSON::Variant ${property}Variant(${property}${if.optional}.value()${end.if.optional}); + jsonParameters.Set(_T("${property}"), ${property}Variant); diff --git a/languages/cpp/templates/parameter-serialization/object.cpp b/languages/cpp/templates/parameter-serialization/object.cpp index ef2aa794..bd627da6 100644 --- a/languages/cpp/templates/parameter-serialization/object.cpp +++ b/languages/cpp/templates/parameter-serialization/object.cpp @@ -1,8 +1,8 @@ auto element = ${property}${if.impl.optional}.value()${end.if.impl.optional}; - ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${Property}Container; + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${property}Container; ${properties} - string ${Property}Str; - ${Property}Container.ToString(${Property}Str); - WPEFramework::Core::JSON::VariantContainer ${Property}VariantContainer(${Property}Str); - WPEFramework::Core::JSON::Variant ${Property} = ${Property}VariantContainer; - jsonParameters.Set(_T("${property}"), ${Property}); + string ${property}Str; + ${property}Container.ToString(${property}Str); + WPEFramework::Core::JSON::VariantContainer ${property}VariantContainer(${property}Str); + WPEFramework::Core::JSON::Variant ${property}Variant = ${property}VariantContainer; + jsonParameters.Set(_T("${property}"), ${property}Variant); diff --git a/languages/cpp/templates/parameter-serialization/property.cpp b/languages/cpp/templates/parameter-serialization/property.cpp index fbbe778a..e21d52c3 100644 --- a/languages/cpp/templates/parameter-serialization/property.cpp +++ b/languages/cpp/templates/parameter-serialization/property.cpp @@ -1 +1 @@ -${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.Title}Container.${Property} = element.${property}${if.optional}.value()${end.if.optional};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}Container.${Property} = element.${property}${if.optional}.value()${end.if.optional};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp b/languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp index ea65b36f..a2c3cdd1 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp @@ -1 +1 @@ - ${base.Title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}${if.optional}.value()${end.if.optional}; + ${base.title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}${if.optional}.value()${end.if.optional}; diff --git a/languages/cpp/templates/parameter-serialization/sub-property/array.cpp b/languages/cpp/templates/parameter-serialization/sub-property/array.cpp index 50bbc39e..d71654b0 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/array.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/array.cpp @@ -1,8 +1,6 @@ - WPEFramework::Core::JSON::ArrayType ${Property}; - ${type} ${property} = element.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}; + WPEFramework::Core::JSON::ArrayType<${json.type}> ${property}Array; + ${type} ${property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}; for (auto& element : ${property}) { -${if.object}${items.with.indent}${end.if.object}${if.non.object}${Property}.Add() = element;${end.if.non.object} +${if.object}${items.with.indent}${end.if.object}${if.non.object} ${property}Array.Add() = element;${end.if.non.object} } - WPEFramework::Core::JSON::Variant ${Property}Variant; - ${Property}Variant.Array(${Property}); - jsonParameters.Set(_T("${property}"), ${Property}Variant); + ${base.title}Container.${Property.dependency}Add(_T("${property}"), &${property}Array); \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/const.cpp b/languages/cpp/templates/parameter-serialization/sub-property/const.cpp index 498529d8..0b8a51ed 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/const.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/const.cpp @@ -1 +1 @@ - ${base.Title}Container.${Property.dependency}${Property} = element${property.dependency}.${property}${if.optional}.value()${end.if.optional}; + ${base.title}Container.${Property.dependency}${Property} = element${property.dependency}.${property}${if.optional}.value()${end.if.optional}; diff --git a/languages/cpp/templates/parameter-serialization/sub-property/namespace.cpp b/languages/cpp/templates/parameter-serialization/sub-property/namespace.cpp new file mode 100644 index 00000000..b3afde8a --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/sub-property/namespace.cpp @@ -0,0 +1 @@ +${if.namespace.notsame}${parent.Title}::${end.if.namespace.notsame} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp b/languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp index f52f229e..bbb6fabb 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp @@ -1,7 +1,3 @@ - ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${Property}Container; + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${property}Container; ${properties} - string ${Property}Str; - ${Property}Container.ToString(${Property}Str); - WPEFramework::Core::JSON::VariantContainer ${Property}VariantContainer(${Property}Str); - WPEFramework::Core::JSON::Variant ${Property}Variant = ${Property}VariantContainer; - ${Property}.Add() = ${Property}Variant; \ No newline at end of file + ${property}Array.Add() = ${property}Container; \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/property.cpp b/languages/cpp/templates/parameter-serialization/sub-property/property.cpp index a8ddffe4..81373225 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/property.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/property.cpp @@ -1 +1 @@ -${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.Title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}${if.optional}.value()${end.if.optional};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}${if.optional}.value()${end.if.optional};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} diff --git a/languages/cpp/templates/result-instantiation/additionalProperties.cpp b/languages/cpp/templates/result-instantiation/additionalProperties.cpp index 7f10732d..2d5f03d0 100644 --- a/languages/cpp/templates/result-instantiation/additionalProperties.cpp +++ b/languages/cpp/templates/result-instantiation/additionalProperties.cpp @@ -1,4 +1,4 @@ - WPEFramework::Core::JSON::VariantContainer::Iterator variants = jsonResult.Variants(); + WPEFramework::Core::JSON::VariantContainer::Iterator variants = jsonResult.Variants(); while (variants.Next()) { ${if.not.default} ${namespace}${key} key = WPEFramework::Core::EnumerateType<${namespace}${key}>(variants.Label(), false).Value();${end.if.not.default}${if.default} ${key} key = variants.Label();${end.if.default} ${property}.emplace(std::piecewise_construct, diff --git a/languages/cpp/templates/types/anyOfSchemaShape.h b/languages/cpp/templates/types/anyOfSchemaShape.h index c239e142..93a91ea4 100644 --- a/languages/cpp/templates/types/anyOfSchemaShape.h +++ b/languages/cpp/templates/types/anyOfSchemaShape.h @@ -1 +1 @@ -/* anyOf schema shape is not supported right now */ \ No newline at end of file +/* anyOf schema shape is not supported right now */ diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index f2a8089e..a7192bcc 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -129,9 +129,10 @@ const getTemplate = (name) => { const getXSchemaGroupFromProperties = (schema, title, properties, group) => { if (properties) { Object.entries(properties).forEach(([name, prop]) => { - if (schema.title === prop.title) { + if ((schema.title === prop.title) || (prop.items && prop.items.title === schema.title)) { group = title - } else { + } + else { group = getXSchemaGroupFromProperties(schema, title, prop.properties, group) } }) @@ -173,7 +174,7 @@ function insertSchemaMacros(content, schema, module, { name = '', parent = '', p .replace(/\$\{if\.namespace\.notsame}(.*?)\$\{end\.if\.namespace\.notsame\}/g, (module.info.title !== (parent || moduleTitle)) ? '$1' : '') .replace(/\$\{parent\.title\}/g, parent || moduleTitle) .replace(/\$\{parent\.Title\}/g, capitalize(parent || moduleTitle)) - .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, required ? '' : '$1') + .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, (Array.isArray(required) ? required.includes(property) : required) ? '' : '$1') .replace(/\$\{description\}/g, schema.description ? schema.description : '') .replace(/\$\{summary\}/g, schema.description ? schema.description.split('\n')[0] : '') .replace(/\$\{name\}/g, title) @@ -282,7 +283,7 @@ const insertObjectMacros = (content, schema, module, title, property, options) = } else { options2.property = options.property } - options2.required = schema.required && schema.required.includes(name) + options2.required = schema.required const schemaShape = getSchemaShape(localizedProp, module, options2) const type = getSchemaType(localizedProp, module, options2) // don't push properties w/ unsupported types @@ -517,7 +518,9 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren shape = insertObjectMacros(getTemplate(path.join(templateDir, 'object' + (array ? '-array' : '') + suffix)) || genericTemplate, schema, module, theTitle, property, { parentLevel, level: objectLevel, parent, property, required, templateDir, descriptions, destination, section, enums, namespace: true, primitive }) } result = result.replace(/\$\{shape\}/g, shape) - result = result.replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, required ? '' : '$1') + if (level === 0) { + result = result.replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, (Array.isArray(required) ? required.includes(property) : required) ? '' : '$1') + } return insertSchemaMacros(result, schema, module, { name: theTitle, parent, property, required, templateDir }) } else if (schema.anyOf || schema.oneOf) { @@ -574,7 +577,7 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren else if (schema.type === "array" && schema.items && !Array.isArray(schema.items)) { // array const items = getSchemaShape(schema.items, module, { templateDir, parent, property, required, parentLevel: parentLevel + 1, level, summary, descriptions, destination, enums: false, array: true, primitive }) - const shape = insertArrayMacros(getTemplate(path.join(templateDir, 'array' + suffix)) || genericTemplate, schema, module, level, items, schema.required) + const shape = insertArrayMacros(getTemplate(path.join(templateDir, 'array' + suffix)) || genericTemplate, schema, module, level, items, Array.isArray(required) ? required.includes(property) : required) result = result.replace(/\$\{shape\}/g, shape) .replace(/\$\{if\.object\}(.*?)\$\{end\.if\.object\}/gms, (schema.items.type === 'object') ? '$1' : '') .replace(/\$\{if\.non\.object\}(.*?)\$\{end\.if\.non\.object\}/gms, (schema.items.type !== 'object') ? '$1' : '') From e67900465971bb295eff4b4c44b89f17c1bfad22 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Sat, 18 Nov 2023 21:39:35 +0530 Subject: [PATCH 119/137] CPPSDK: polymorphic-pull method/event generation support added (#154) --- .../polymorphic-pull-event.h | 2 + .../declarations-override/polymorphic-pull.h | 5 ++ .../declarations/polymorphic-pull-event.h | 6 ++ .../templates/declarations/polymorphic-pull.h | 6 ++ .../methods/polymorphic-pull-event.cpp | 60 +++++++++++++++++++ .../templates/methods/polymorphic-pull.cpp | 23 +++++++ src/macrofier/engine.mjs | 12 +++- src/macrofier/types.mjs | 6 +- src/shared/modules.mjs | 7 +++ 9 files changed, 125 insertions(+), 2 deletions(-) diff --git a/languages/cpp/templates/declarations-override/polymorphic-pull-event.h b/languages/cpp/templates/declarations-override/polymorphic-pull-event.h index e69de29b..99a4f5e0 100644 --- a/languages/cpp/templates/declarations-override/polymorphic-pull-event.h +++ b/languages/cpp/templates/declarations-override/polymorphic-pull-event.h @@ -0,0 +1,2 @@ + void subscribe( 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-override/polymorphic-pull.h b/languages/cpp/templates/declarations-override/polymorphic-pull.h index e69de29b..47554196 100644 --- a/languages/cpp/templates/declarations-override/polymorphic-pull.h +++ b/languages/cpp/templates/declarations-override/polymorphic-pull.h @@ -0,0 +1,5 @@ + /* + ${method.name} + ${method.description} + */ + ${method.signature.result} ${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr )${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} override; diff --git a/languages/cpp/templates/declarations/polymorphic-pull-event.h b/languages/cpp/templates/declarations/polymorphic-pull-event.h index e69de29b..7baed2cf 100644 --- a/languages/cpp/templates/declarations/polymorphic-pull-event.h +++ b/languages/cpp/templates/declarations/polymorphic-pull-event.h @@ -0,0 +1,6 @@ + /* ${method.name} - ${method.description} */ + struct I${method.Name}Notification { + virtual ${method.pulls.type} ${method.name}( ${method.pulls.param.type} ) = 0; + }; + virtual void subscribe( I${method.Name}Notification& notification, Firebolt::Error *err = nullptr ) = 0; + virtual void unsubscribe( I${method.Name}Notification& notification, Firebolt::Error *err = nullptr ) = 0; diff --git a/languages/cpp/templates/declarations/polymorphic-pull.h b/languages/cpp/templates/declarations/polymorphic-pull.h index e69de29b..fa1890c5 100644 --- a/languages/cpp/templates/declarations/polymorphic-pull.h +++ b/languages/cpp/templates/declarations/polymorphic-pull.h @@ -0,0 +1,6 @@ + /* + ${method.name} + ${method.description} + ${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation}${end.if.deprecated} + */ + virtual ${method.signature.result} ${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr )${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} = 0; diff --git a/languages/cpp/templates/methods/polymorphic-pull-event.cpp b/languages/cpp/templates/methods/polymorphic-pull-event.cpp index e69de29b..2bcf6c5f 100644 --- a/languages/cpp/templates/methods/polymorphic-pull-event.cpp +++ b/languages/cpp/templates/methods/polymorphic-pull-event.cpp @@ -0,0 +1,60 @@ + /* ${method.rpc.name} - ${method.description} */ + static void ${method.name}InnerCallback( void* notification, const void* userData, void* jsonResponse ) + { +${event.callback.serialization} + ASSERT(proxyResponse.IsValid() == true); + + if (proxyResponse.IsValid() == true) { + ${method.pulls.param.json.type} jsonResult = proxyResponse->Parameters; + ${method.pulls.response.initialization} +${method.pulls.response.instantiation} + + I${info.Title}::I${method.Name}Notification& notifier = *(reinterpret_cast(notification)); + ${method.pulls.type} element = notifier.${method.name}(${method.pulls.param.title}); + Firebolt::Error status = Firebolt::Error::NotConnected; + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + JsonObject jsonParameters; + WPEFramework::Core::JSON::Variant CorrelationId = proxyResponse->CorrelationId.Value(); + jsonParameters.Set(_T("correlationId"), CorrelationId); + ${method.pulls.json.type} ${method.pulls.result.title}Container; + + ${method.pulls.result.serialization.with.indent} + string resultStr; + ${method.pulls.result.title}Container.ToString(resultStr); + WPEFramework::Core::JSON::VariantContainer resultContainer(resultStr); + WPEFramework::Core::JSON::Variant Result = resultContainer; + jsonParameters.Set(_T("result"), Result); + WPEFramework::Core::JSON::Boolean jsonResult; + + status = transport->Invoke("${info.title.lowercase}.${method.pulls.for}", jsonParameters, jsonResult); + if (status == Firebolt::Error::None) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully pushed with status as %d", jsonResult.Value()); + } + + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + proxyResponse.Release(); + } + } + void ${info.Title}Impl::subscribe( 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; + status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${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; + } + } diff --git a/languages/cpp/templates/methods/polymorphic-pull.cpp b/languages/cpp/templates/methods/polymorphic-pull.cpp index e69de29b..d919d349 100644 --- a/languages/cpp/templates/methods/polymorphic-pull.cpp +++ b/languages/cpp/templates/methods/polymorphic-pull.cpp @@ -0,0 +1,23 @@ + /* ${method.rpc.name} - ${method.description} */ + ${method.signature.result} ${info.Title}Impl::${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err ) ${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} + { + Firebolt::Error status = Firebolt::Error::NotConnected; +${if.result.nonvoid}${method.result.initialization}${end.if.result.nonvoid} + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + string correlationId = ""; + JsonObject jsonParameters; + ${method.params.serialization.with.indent} + ${method.result.json.type} jsonResult; + status = transport->Invoke("${info.title.lowercase}.${method.rpc.name}", jsonParameters, jsonResult); + if (status == Firebolt::Error::None) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); + ${if.result.nonvoid}${method.result.instantiation.with.indent}${end.if.result.nonvoid} + } + + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return${if.result.nonvoid} ${method.result.name}${end.if.result.nonvoid}; + } diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 8af37cdf..bb9399f2 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -1252,6 +1252,12 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) : '' + const pullsForParamTitle = pullsParams ? pullsParams.title.charAt(0).toLowerCase() + pullsParams.title.substring(1) : '' + const pullsForResultTitle = pullsResult ? pullsResult.title.charAt(0).toLowerCase() + pullsResult.title.substring(1) : '' + const pullsResponseInit = pullsParams ? types.getSchemaShape(pullsParams, json, { templateDir: 'result-initialization', property: pullsForParamTitle, required: pullsParams.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' + const pullsResponseInst = pullsParams ? types.getSchemaShape(pullsParams, json, { templateDir: 'result-instantiation', property: pullsForParamTitle, required: pullsParams.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' + const pullsResultSerialize = pullsResult ? types.getSchemaShape(pullsResult, json, { templateDir: 'parameter-serialization/sub-property', property: pullsForResultTitle, required: pullsResult.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' + const serializedParams = flattenedMethod.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'parameter-serialization', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n') const resultInst = types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-instantiation', property: flattenedMethod.result.name, required: flattenedMethod.result.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) // w/out primitive: true, getSchemaShape skips anonymous types, like primitives const resultInit = types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-initialization', property: flattenedMethod.result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) // w/out primitive: true, getSchemaShape skips anonymous types, like primitives @@ -1274,7 +1280,6 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) } } // hmm... how is this different from callbackSerializedList? i guess they get merged? - //console.log("event --- ", event) const callbackResponseInst = event ? (event.params && event.params.length ? (event.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'callback-response-instantiation', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join(', ')) + ', ' : '' ) + (types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-response-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })) : '' const resultType = result.schema ? types.getSchemaType(result.schema, json, { templateDir: state.typeTemplateDir }) : '' const resultJsonType = result.schema ? types.getSchemaType(result.schema, json, { templateDir: 'json-types' }) : '' @@ -1383,10 +1388,15 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.pulls\.type\}/g, pullsForType) .replace(/\$\{method\.pulls\.json\.type\}/g, pullsForJsonType) .replace(/\$\{method\.pulls\.result\}/g, pullsResultType) + .replace(/\$\{method\.pulls\.result\.title\}/g, pullsForResultTitle) .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\.title\}/g, pullsForParamTitle) .replace(/\$\{method\.pulls\.param\.json\.type\}/g, pullsForParamJsonType) + .replace(/\$\{method\.pulls\.response\.initialization\}/g, pullsResponseInit) + .replace(/\$\{method\.pulls\.response\.instantiation}/g, pullsResponseInst) + .replace(/\$\{method\.pulls\.result\.serialization\.with\.indent\}/g, indent(pullsResultSerialize, ' ')) .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/types.mjs b/src/macrofier/types.mjs index a7192bcc..d587559b 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -74,7 +74,11 @@ const safeName = value => value.split(':').pop().replace(/[\.\-]/g, '_').replace // TODO: This is what's left of getMethodSignatureParams. We need to figure out / handle C's `FireboltTypes_StringHandle` function getMethodSignatureParams(method, module, { destination, callback }) { const paramOptional = getTemplate('/parameters/optional') + let polymorphicPull = method.tags.find(t => t.name === 'polymorphic-pull') return method.params.map(param => { + if (polymorphicPull && (param.name === 'correlationId')) { + return + } let type = getSchemaType(param.schema, module, { destination, namespace : true }) if (callback && allocatedPrimitiveProxies[type]) { type = allocatedPrimitiveProxies[type] @@ -93,7 +97,7 @@ function getMethodSignatureParams(method, module, { destination, callback }) { } return (param.required ? paramRequired : paramOptional).replace(/\$\{method\.param\.name\}/g, param.name).replace(/\$\{method\.param\.type\}/g, type) - }).join(', ') + }).filter(param => param).join(', ') } function getMethodSignatureResult(method, module, { destination, callback }) { diff --git a/src/shared/modules.mjs b/src/shared/modules.mjs index 105ab8f7..355da86c 100644 --- a/src/shared/modules.mjs +++ b/src/shared/modules.mjs @@ -987,6 +987,7 @@ const createPolymorphicMethods = (method, json) => { } const isSubSchema = (schema) => schema.type === 'object' || (schema.type === 'string' && schema.enum) +const isSubEnumOfArraySchema = (schema) => (schema.type === 'array' && schema.items.enum) const addComponentSubSchemasNameForProperties = (key, schema) => { if ((schema.type === "object") && schema.properties) { @@ -998,6 +999,12 @@ const addComponentSubSchemasNameForProperties = (key, schema) => { } propSchema = addComponentSubSchemasNameForProperties(key, propSchema) } + else if (isSubEnumOfArraySchema(propSchema)) { + key = key + name.charAt(0).toUpperCase() + name.substring(1) + if (!propSchema.items.title) { + propSchema.items.title = key + } + } }) } From f31b5d730ff1fd4e6dafa6214458f04f4a762d38 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Tue, 5 Dec 2023 09:21:48 +0530 Subject: [PATCH 120/137] CPPSDK: provider support added (#156) --- languages/cpp/language.config.json | 1 + languages/cpp/src/shared/include/types.h | 1 + .../sub-property/property.cpp | 2 +- .../callback-result-instantiation/enum.cpp | 2 +- .../sub-property/array.cpp | 2 +- .../cpp/templates/codeblocks/interface.cpp | 47 +++++++ .../cpp/templates/codeblocks/interface.h | 12 ++ .../codeblocks/provider-subscribe.cpp | 1 + .../cpp/templates/codeblocks/provider.cpp | 1 + languages/cpp/templates/codeblocks/provider.h | 1 + .../cpp/templates/codeblocks/subscribe.cpp | 5 + .../declarations-override/calls-metrics.h | 1 - .../templates/declarations-override/provide.h | 1 + .../templates/declarations/calls-metrics.h | 1 - .../cpp/templates/declarations/provide.h | 1 + .../cpp/templates/interfaces/default.cpp | 17 +++ languages/cpp/templates/interfaces/default.h | 1 + .../cpp/templates/interfaces/focusable.cpp | 44 +++++++ .../cpp/templates/interfaces/focusable.h | 1 + languages/cpp/templates/json-types/integer.h | 2 +- .../cpp/templates/methods/calls-metrics.cpp | 1 - languages/cpp/templates/methods/default.cpp | 3 + .../methods/polymorphic-pull-event.cpp | 3 +- .../templates/methods/polymorphic-pull.cpp | 3 + languages/cpp/templates/methods/provide.cpp | 8 ++ .../cpp/templates/modules/include/module.h | 5 +- .../cpp/templates/modules/src/module_impl.cpp | 3 +- .../additionalProperties.cpp | 7 +- .../parameter-serialization/array.cpp | 10 +- .../parameter-serialization/enum.cpp | 8 +- .../parameter-serialization/generic.cpp | 7 +- .../parameter-serialization/object-array.cpp | 4 +- .../object-empty-property.cpp | 7 +- .../parameter-serialization/object.cpp | 15 ++- .../parameter-serialization/property.cpp | 4 +- .../sub-property/anyOfSchemaShape.cpp | 4 +- .../sub-property/array.cpp | 19 ++- .../sub-property/const.cpp | 4 +- .../sub-property/object-array.cpp | 4 +- .../sub-property/property.cpp | 4 +- .../sections/provider-interfaces.cpp | 1 + .../templates/sections/provider-interfaces.h | 21 ++-- .../templates/sections/provider-subscribe.cpp | 1 + src/macrofier/engine.mjs | 116 ++++++++++++++++-- src/macrofier/index.mjs | 2 + src/macrofier/types.mjs | 32 +++-- src/sdk/index.mjs | 1 + src/shared/modules.mjs | 91 +++++++------- 48 files changed, 418 insertions(+), 114 deletions(-) create mode 100644 languages/cpp/templates/codeblocks/interface.cpp create mode 100644 languages/cpp/templates/codeblocks/interface.h create mode 100644 languages/cpp/templates/codeblocks/provider-subscribe.cpp create mode 100644 languages/cpp/templates/codeblocks/provider.cpp create mode 100644 languages/cpp/templates/codeblocks/provider.h create mode 100644 languages/cpp/templates/codeblocks/subscribe.cpp create mode 100644 languages/cpp/templates/interfaces/default.cpp create mode 100644 languages/cpp/templates/interfaces/default.h create mode 100644 languages/cpp/templates/interfaces/focusable.cpp create mode 100644 languages/cpp/templates/interfaces/focusable.h create mode 100644 languages/cpp/templates/sections/provider-interfaces.cpp create mode 100644 languages/cpp/templates/sections/provider-subscribe.cpp diff --git a/languages/cpp/language.config.json b/languages/cpp/language.config.json index db9b7ddc..8c5f533e 100644 --- a/languages/cpp/language.config.json +++ b/languages/cpp/language.config.json @@ -6,6 +6,7 @@ "unwrapResultObjects": false, "createPolymorphicMethods": true, "excludeDeclarations": true, + "extractProviderSchema": true, "aggregateFiles": [ "/include/firebolt.h", "/src/firebolt.cpp" diff --git a/languages/cpp/src/shared/include/types.h b/languages/cpp/src/shared/include/types.h index 841bda7a..7546ca2f 100644 --- a/languages/cpp/src/shared/include/types.h +++ b/languages/cpp/src/shared/include/types.h @@ -24,4 +24,5 @@ #include #include #include +#include diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp index 0d95dcab..4276ebc4 100644 --- a/languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp @@ -1 +1 @@ -${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response.${Property.dependency}${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response.${Property.dependency}${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/enum.cpp b/languages/cpp/templates/callback-result-instantiation/enum.cpp index d5bc4150..6d8fa873 100644 --- a/languages/cpp/templates/callback-result-instantiation/enum.cpp +++ b/languages/cpp/templates/callback-result-instantiation/enum.cpp @@ -1 +1 @@ - ${if.namespace.notsame}${info.Title}::${end.if.namespace.notsame}${title} response = proxyResponse->Value(); \ No newline at end of file + ${property} = proxyResponse->Value(); \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp index 03910b83..8bf38da1 100644 --- a/languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp @@ -1,4 +1,4 @@ - ${if.impl.array.optional}${base.title}.${property} = std::make_optional<${type}>();${end.if.impl.array.optional} + ${if.impl.array.optional}${base.title}.${property} = std::make_optional<${type}>();${end.if.impl.array.optional} auto index(proxyResponse->${Property}.Elements()); while (index.Next() == true) { ${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}.push_back(index.Current().Value());${end.if.non.object} diff --git a/languages/cpp/templates/codeblocks/interface.cpp b/languages/cpp/templates/codeblocks/interface.cpp new file mode 100644 index 00000000..dff9252d --- /dev/null +++ b/languages/cpp/templates/codeblocks/interface.cpp @@ -0,0 +1,47 @@ + static void ProviderInvokeSession(std::string& methodName, JsonObject& jsonParameters, Firebolt::Error *err = nullptr) + { + Firebolt::Error status = Firebolt::Error::NotConnected; + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + + JsonObject jsonResult; + status = transport->Invoke(methodName, jsonParameters, jsonResult); + if (status == Firebolt::Error::None) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "%s is successfully invoked", methodName.c_str()); + } + + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + if (err != nullptr) { + *err = status; + } + } + static void ProviderFocusSession(std::string methodName, std::string& correlationId, Firebolt::Error *err = nullptr) + { + JsonObject jsonParameters; + WPEFramework::Core::JSON::Variant CorrelationId(correlationId); + jsonParameters.Set(_T("correlationId"), CorrelationId); + + ProviderInvokeSession(methodName, jsonParameters, err); + } + static void ProviderResultSession(std::string methodName, std::string& correlationId, ${provider.xresponse.name} result, Firebolt::Error *err = nullptr) + { + JsonObject jsonParameters; + WPEFramework::Core::JSON::Variant CorrelationId(correlationId); + jsonParameters.Set(_T("correlationId"), CorrelationId); + +${provider.xresponse.serialization} + ProviderInvokeSession(methodName, jsonParameters, err); + } + static void ProviderErrorSession(std::string methodName, std::string& correlationId, ${provider.xerror.name} result, Firebolt::Error *err = nullptr) + { + JsonObject jsonParameters; + WPEFramework::Core::JSON::Variant CorrelationId(correlationId); + jsonParameters.Set(_T("correlationId"), CorrelationId); + +${provider.xerror.serialization} + ProviderInvokeSession(methodName, jsonParameters, err); + } + +${methods} diff --git a/languages/cpp/templates/codeblocks/interface.h b/languages/cpp/templates/codeblocks/interface.h new file mode 100644 index 00000000..376426ee --- /dev/null +++ b/languages/cpp/templates/codeblocks/interface.h @@ -0,0 +1,12 @@ +struct I${info.Title}Session : virtual public IFocussableProviderSession { + virtual ~I${info.Title}Session() override = default; + + virtual void error( ${provider.xerror.name} error, Firebolt::Error *err = nullptr ) = 0; + virtual void result( ${provider.xresponse.name} result, Firebolt::Error *err = nullptr ) = 0; +}; + +struct I${info.Title}Provider { + virtual ~I${info.Title}Provider() = default; + +${methods} +}; \ No newline at end of file diff --git a/languages/cpp/templates/codeblocks/provider-subscribe.cpp b/languages/cpp/templates/codeblocks/provider-subscribe.cpp new file mode 100644 index 00000000..88c3dffe --- /dev/null +++ b/languages/cpp/templates/codeblocks/provider-subscribe.cpp @@ -0,0 +1 @@ +${subscribe} \ No newline at end of file diff --git a/languages/cpp/templates/codeblocks/provider.cpp b/languages/cpp/templates/codeblocks/provider.cpp new file mode 100644 index 00000000..5b4cf7b8 --- /dev/null +++ b/languages/cpp/templates/codeblocks/provider.cpp @@ -0,0 +1 @@ +${interface} \ No newline at end of file diff --git a/languages/cpp/templates/codeblocks/provider.h b/languages/cpp/templates/codeblocks/provider.h new file mode 100644 index 00000000..b2895fe0 --- /dev/null +++ b/languages/cpp/templates/codeblocks/provider.h @@ -0,0 +1 @@ +${interface} diff --git a/languages/cpp/templates/codeblocks/subscribe.cpp b/languages/cpp/templates/codeblocks/subscribe.cpp new file mode 100644 index 00000000..4039ca95 --- /dev/null +++ b/languages/cpp/templates/codeblocks/subscribe.cpp @@ -0,0 +1,5 @@ + eventName = _T("${info.title.lowercase}.onRequest${method.Name}"); + status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${info.Title}${method.Name}SessionInnerCallback, reinterpret_cast(&provider), nullptr); + if (status != Firebolt::Error::None) { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in %s subscribe = %d", eventName.c_str(), status); + } diff --git a/languages/cpp/templates/declarations-override/calls-metrics.h b/languages/cpp/templates/declarations-override/calls-metrics.h index 8b137891..e69de29b 100644 --- a/languages/cpp/templates/declarations-override/calls-metrics.h +++ b/languages/cpp/templates/declarations-override/calls-metrics.h @@ -1 +0,0 @@ - diff --git a/languages/cpp/templates/declarations-override/provide.h b/languages/cpp/templates/declarations-override/provide.h index e69de29b..5fca741f 100644 --- a/languages/cpp/templates/declarations-override/provide.h +++ b/languages/cpp/templates/declarations-override/provide.h @@ -0,0 +1 @@ + void provide( I${info.Title}Provider& provider ) override; diff --git a/languages/cpp/templates/declarations/calls-metrics.h b/languages/cpp/templates/declarations/calls-metrics.h index 8b137891..e69de29b 100644 --- a/languages/cpp/templates/declarations/calls-metrics.h +++ b/languages/cpp/templates/declarations/calls-metrics.h @@ -1 +0,0 @@ - diff --git a/languages/cpp/templates/declarations/provide.h b/languages/cpp/templates/declarations/provide.h index e69de29b..0cd03159 100644 --- a/languages/cpp/templates/declarations/provide.h +++ b/languages/cpp/templates/declarations/provide.h @@ -0,0 +1 @@ + virtual void provide( I${info.Title}Provider& provider ) = 0; diff --git a/languages/cpp/templates/interfaces/default.cpp b/languages/cpp/templates/interfaces/default.cpp new file mode 100644 index 00000000..4cba2764 --- /dev/null +++ b/languages/cpp/templates/interfaces/default.cpp @@ -0,0 +1,17 @@ + class ${info.Title}${method.Name}Session : virtual public IProviderSession { + public: + std::string correlationId () const override + { + return _correlationId; + } + + public: + std::string _correlationId; + }; + static void ${info.Title}${method.Name}SessionInnerCallback( void* provider, const void* userData, void* jsonResponse ) + { + //TODO: code to convert jsonResponse to ${method.name} session + I${info.Title}Provider& ${info.title.lowercase}Provider = *(reinterpret_cast(provider)); + ${info.title.lowercase}Provider.${method.name}( parameters, session ); + } + diff --git a/languages/cpp/templates/interfaces/default.h b/languages/cpp/templates/interfaces/default.h new file mode 100644 index 00000000..05ebc463 --- /dev/null +++ b/languages/cpp/templates/interfaces/default.h @@ -0,0 +1 @@ + virtual void ${method.name}( ${method.signature.params}, IProviderSession& session ) = 0; \ No newline at end of file diff --git a/languages/cpp/templates/interfaces/focusable.cpp b/languages/cpp/templates/interfaces/focusable.cpp new file mode 100644 index 00000000..9a8d859d --- /dev/null +++ b/languages/cpp/templates/interfaces/focusable.cpp @@ -0,0 +1,44 @@ + class ${info.Title}${method.Name}Session : virtual public I${info.Title}Session { + public: + ${info.Title}${method.Name}Session( const std::string& correlationId ) + : _correlationId(correlationId) + { + } + + std::string correlationId() const override + { + return _correlationId; + } + void focus( Firebolt::Error *err = nullptr ) override + { + ProviderFocusSession("${info.title.lowercase}.${method.name}Focus", _correlationId, err); + } + void result( ${provider.xresponse.name} response, Firebolt::Error *err = nullptr ) override + { + ProviderResultSession("${info.title.lowercase}.${method.name}Response", _correlationId, response, err); + } + void error( ${provider.xerror.name} error, Firebolt::Error *err = nullptr ) override + { + ProviderErrorSession("${info.title.lowercase}.${method.name}Error", _correlationId, error, err); + } + + public: + std::string _correlationId; + }; + static void ${info.Title}${method.Name}SessionInnerCallback( void* provider, const void* userData, void* jsonResponse ) + { +${event.callback.serialization} + ASSERT(proxyResponse.IsValid() == true); + + if (proxyResponse.IsValid() == true) { +${event.callback.initialization} + +${event.callback.instantiation} + proxyResponse.Release(); + + std::unique_ptr ${info.title.lowercase}${method.Name}Session = std::make_unique<${info.Title}${method.Name}Session>(${method.result.name}.correlationId); + I${info.Title}Provider& ${info.title.lowercase}Provider = *(reinterpret_cast(provider)); + ${info.title.lowercase}Provider.${method.name}(${method.result.name}.parameters, std::move(${info.title.lowercase}${method.Name}Session)); + } + } + diff --git a/languages/cpp/templates/interfaces/focusable.h b/languages/cpp/templates/interfaces/focusable.h new file mode 100644 index 00000000..a967e096 --- /dev/null +++ b/languages/cpp/templates/interfaces/focusable.h @@ -0,0 +1 @@ + virtual void ${method.name}( ${method.signature.params}, std::unique_ptr session ) = 0; diff --git a/languages/cpp/templates/json-types/integer.h b/languages/cpp/templates/json-types/integer.h index 4bf0dddb..b57fe26e 100644 --- a/languages/cpp/templates/json-types/integer.h +++ b/languages/cpp/templates/json-types/integer.h @@ -1 +1 @@ -WPEFramework::Core::JSON::DecSInt32 +WPEFramework::Core::JSON::DecSInt32 \ No newline at end of file diff --git a/languages/cpp/templates/methods/calls-metrics.cpp b/languages/cpp/templates/methods/calls-metrics.cpp index 8b137891..e69de29b 100644 --- a/languages/cpp/templates/methods/calls-metrics.cpp +++ b/languages/cpp/templates/methods/calls-metrics.cpp @@ -1 +0,0 @@ - diff --git a/languages/cpp/templates/methods/default.cpp b/languages/cpp/templates/methods/default.cpp index fbeaf160..f1fb6e71 100644 --- a/languages/cpp/templates/methods/default.cpp +++ b/languages/cpp/templates/methods/default.cpp @@ -18,6 +18,9 @@ } else { FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); } + if (err != nullptr) { + *err = status; + } return${if.result.nonvoid} ${method.result.name}${end.if.result.nonvoid}; } diff --git a/languages/cpp/templates/methods/polymorphic-pull-event.cpp b/languages/cpp/templates/methods/polymorphic-pull-event.cpp index 2bcf6c5f..ef7a837b 100644 --- a/languages/cpp/templates/methods/polymorphic-pull-event.cpp +++ b/languages/cpp/templates/methods/polymorphic-pull-event.cpp @@ -18,8 +18,9 @@ WPEFramework::Core::JSON::Variant CorrelationId = proxyResponse->CorrelationId.Value(); jsonParameters.Set(_T("correlationId"), CorrelationId); ${method.pulls.json.type} ${method.pulls.result.title}Container; - + { ${method.pulls.result.serialization.with.indent} + } string resultStr; ${method.pulls.result.title}Container.ToString(resultStr); WPEFramework::Core::JSON::VariantContainer resultContainer(resultStr); diff --git a/languages/cpp/templates/methods/polymorphic-pull.cpp b/languages/cpp/templates/methods/polymorphic-pull.cpp index d919d349..7f8368d2 100644 --- a/languages/cpp/templates/methods/polymorphic-pull.cpp +++ b/languages/cpp/templates/methods/polymorphic-pull.cpp @@ -18,6 +18,9 @@ } else { FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); } + if (err != nullptr) { + *err = status; + } return${if.result.nonvoid} ${method.result.name}${end.if.result.nonvoid}; } diff --git a/languages/cpp/templates/methods/provide.cpp b/languages/cpp/templates/methods/provide.cpp index e69de29b..85492d38 100644 --- a/languages/cpp/templates/methods/provide.cpp +++ b/languages/cpp/templates/methods/provide.cpp @@ -0,0 +1,8 @@ + void ${info.Title}Impl::provide( I${info.Title}Provider& provider ) + { + string eventName; + Firebolt::Error status = Firebolt::Error::None; + JsonObject jsonParameters; + + /* ${PROVIDERS_SUBSCRIBE} */ + } diff --git a/languages/cpp/templates/modules/include/module.h b/languages/cpp/templates/modules/include/module.h index de58e77a..04d52aef 100644 --- a/languages/cpp/templates/modules/include/module.h +++ b/languages/cpp/templates/modules/include/module.h @@ -29,15 +29,14 @@ namespace ${info.Title} { /* ${ENUMS} */${end.if.enums} ${if.types} // Types -/* ${TYPES} */ -${end.if.types} +/* ${TYPES} */${end.if.types} +${if.providers}/* ${PROVIDERS} */${end.if.providers} ${if.methods}struct I${info.Title} { virtual ~I${info.Title}() = default; // Methods & Events /* ${METHODS:declarations} */ - };${end.if.methods} } //namespace ${info.Title} diff --git a/languages/cpp/templates/modules/src/module_impl.cpp b/languages/cpp/templates/modules/src/module_impl.cpp index 072cd1fc..36c9b123 100644 --- a/languages/cpp/templates/modules/src/module_impl.cpp +++ b/languages/cpp/templates/modules/src/module_impl.cpp @@ -21,7 +21,8 @@ ${if.implementations} namespace Firebolt { namespace ${info.Title} { - +${if.providers} +/* ${PROVIDERS} */${end.if.providers} // Methods /* ${METHODS} */ diff --git a/languages/cpp/templates/parameter-serialization/additionalProperties.cpp b/languages/cpp/templates/parameter-serialization/additionalProperties.cpp index caa132d9..88c832d0 100644 --- a/languages/cpp/templates/parameter-serialization/additionalProperties.cpp +++ b/languages/cpp/templates/parameter-serialization/additionalProperties.cpp @@ -1,4 +1,7 @@ - ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}${title} map = ${property}${if.impl.optional}.value()${end.if.impl.optional}; + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}${title} map; + ${if.impl.optional}if (${property}.has_value()) { + map = ${property}.value(); + }${end.if.impl.optional}${if.impl.non.optional}map = ${property};${end.if.impl.non.optional} WPEFramework::Core::JSON::Variant ${property}Variant; for (auto element: map) { WPEFramework::Core::JSON::Variant jsonElement = element.second; @@ -6,4 +9,4 @@ jsonContainer.Set(element.first.c_str(), jsonElement); ${property}Variant = jsonContainer; } - jsonParameters.Set(_T("${property}"), ${property}Variant); + jsonParameters.Set(_T("${property}"), ${property}Variant); \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/array.cpp b/languages/cpp/templates/parameter-serialization/array.cpp index e6559cfb..f623711b 100644 --- a/languages/cpp/templates/parameter-serialization/array.cpp +++ b/languages/cpp/templates/parameter-serialization/array.cpp @@ -1,7 +1,11 @@ WPEFramework::Core::JSON::ArrayType ${property}Array; - for (auto& element : ${property}) { -${if.object}${items.with.indent}${end.if.object}${if.non.object} ${property}Array.Add() = element;${end.if.non.object} - } + ${if.impl.array.optional}if (${property}.has_value()) { + for (auto& element : ${property}.value()) { + ${if.object}${items.with.indent}${end.if.object}${if.non.object} ${property}Array.Add() = element;${end.if.non.object} + } + }${end.if.impl.array.optional}${if.impl.array.non.optional}for (auto& element : ${property}) { +${if.object}${items.with.indent}${end.if.object}${if.non.object} ${property}Array.Add() = element;${end.if.non.object} + }${end.if.impl.array.non.optional} WPEFramework::Core::JSON::Variant ${property}Variant; ${property}Variant.Array(${property}Array); jsonParameters.Set(_T("${property}"), ${property}Variant); \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/enum.cpp b/languages/cpp/templates/parameter-serialization/enum.cpp index 015c6bc6..167761a0 100644 --- a/languages/cpp/templates/parameter-serialization/enum.cpp +++ b/languages/cpp/templates/parameter-serialization/enum.cpp @@ -1,3 +1,7 @@ - ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonValue = ${property}${if.optional}.value()${end.if.optional}; + ${if.optional}if (${property}.has_value()) { + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonValue = ${property}.value(); + WPEFramework::Core::JSON::Variant ${property}Variant(jsonValue.Data()); + jsonParameters.Set(_T("${property}"), ${property}Variant); + }${end.if.optional}${if.non.optional}${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonValue = ${property}; WPEFramework::Core::JSON::Variant ${property}Variant(jsonValue.Data()); - jsonParameters.Set(_T("${property}"), ${property}Variant); + jsonParameters.Set(_T("${property}"), ${property}Variant);${end.if.non.optional} diff --git a/languages/cpp/templates/parameter-serialization/generic.cpp b/languages/cpp/templates/parameter-serialization/generic.cpp index a2e1525b..5ab016c3 100644 --- a/languages/cpp/templates/parameter-serialization/generic.cpp +++ b/languages/cpp/templates/parameter-serialization/generic.cpp @@ -1,2 +1,5 @@ - WPEFramework::Core::JSON::Variant ${property}Variant(${property}${if.optional}.value()${end.if.optional}); - jsonParameters.Set(_T("${property}"), ${property}Variant); + ${if.optional}if (${property}.has_value()) { + WPEFramework::Core::JSON::Variant ${property}Variant(${property}.value()); + jsonParameters.Set(_T("${property}"), ${property}Variant); + }${end.if.optional}${if.non.optional}WPEFramework::Core::JSON::Variant ${property}Variant(${property}); + jsonParameters.Set(_T("${property}"), ${property}Variant);${end.if.non.optional} diff --git a/languages/cpp/templates/parameter-serialization/object-array.cpp b/languages/cpp/templates/parameter-serialization/object-array.cpp index e8d18cd4..baedcd30 100644 --- a/languages/cpp/templates/parameter-serialization/object-array.cpp +++ b/languages/cpp/templates/parameter-serialization/object-array.cpp @@ -1,7 +1,9 @@ ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${property}Container; + { ${properties} + } string ${property}Str; ${property}Container.ToString(${property}Str); WPEFramework::Core::JSON::VariantContainer ${property}VariantContainer(${property}Str); WPEFramework::Core::JSON::Variant ${property}Variant = ${property}VariantContainer; - ${property}Array.Add() = ${property}Variant; \ No newline at end of file + ${property}Array.Add() = ${property}Variant; diff --git a/languages/cpp/templates/parameter-serialization/object-empty-property.cpp b/languages/cpp/templates/parameter-serialization/object-empty-property.cpp index a2e1525b..69893434 100644 --- a/languages/cpp/templates/parameter-serialization/object-empty-property.cpp +++ b/languages/cpp/templates/parameter-serialization/object-empty-property.cpp @@ -1,2 +1,5 @@ - WPEFramework::Core::JSON::Variant ${property}Variant(${property}${if.optional}.value()${end.if.optional}); - jsonParameters.Set(_T("${property}"), ${property}Variant); + ${if.optional}if (${property}.has_value()) { + WPEFramework::Core::JSON::Variant ${property}Variant(${property}.value()); + jsonParameters.Set(_T("${property}"), ${property}Variant); + }${end.if.optional}${if.non.optional}WPEFramework::Core::JSON::Variant ${property}Variant(${property}); + jsonParameters.Set(_T("${property}"), ${property}Variant);${end.if.non.optional} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/object.cpp b/languages/cpp/templates/parameter-serialization/object.cpp index bd627da6..4d0cbc08 100644 --- a/languages/cpp/templates/parameter-serialization/object.cpp +++ b/languages/cpp/templates/parameter-serialization/object.cpp @@ -1,8 +1,19 @@ - auto element = ${property}${if.impl.optional}.value()${end.if.impl.optional}; + ${if.impl.optional}if (${property}.has_value()) { + auto element = ${property}.value(); + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${property}Container; +${properties} + string ${property}Str; + ${property}Container.ToString(${property}Str); + WPEFramework::Core::JSON::VariantContainer ${property}VariantContainer(${property}Str); + WPEFramework::Core::JSON::Variant ${property}Variant = ${property}VariantContainer; + jsonParameters.Set(_T("${property}"), ${property}Variant); + }${end.if.impl.optional}${if.impl.non.optional}auto element = ${property}; ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${property}Container; + { ${properties} + } string ${property}Str; ${property}Container.ToString(${property}Str); WPEFramework::Core::JSON::VariantContainer ${property}VariantContainer(${property}Str); WPEFramework::Core::JSON::Variant ${property}Variant = ${property}VariantContainer; - jsonParameters.Set(_T("${property}"), ${property}Variant); + jsonParameters.Set(_T("${property}"), ${property}Variant);${end.if.impl.non.optional} diff --git a/languages/cpp/templates/parameter-serialization/property.cpp b/languages/cpp/templates/parameter-serialization/property.cpp index e21d52c3..d6bddfdb 100644 --- a/languages/cpp/templates/parameter-serialization/property.cpp +++ b/languages/cpp/templates/parameter-serialization/property.cpp @@ -1 +1,3 @@ -${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}Container.${Property} = element.${property}${if.optional}.value()${end.if.optional};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${if.optional}if (element.${property}.has_value()) { + ${base.title}Container.${Property} = element.${property}.value(); + }${end.if.optional}${if.non.optional}${base.title}Container.${Property} = element.${property};${end.if.non.optional}${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp b/languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp index a2c3cdd1..7ac47b35 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp @@ -1 +1,3 @@ - ${base.title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}${if.optional}.value()${end.if.optional}; + ${if.optional}if (element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}.has_value()) { + ${base.title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}.value(); + }${end.if.optional}${if.non.optional}${base.title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property};${end.if.non.optional} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/array.cpp b/languages/cpp/templates/parameter-serialization/sub-property/array.cpp index d71654b0..d04f5448 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/array.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/array.cpp @@ -1,6 +1,13 @@ - WPEFramework::Core::JSON::ArrayType<${json.type}> ${property}Array; - ${type} ${property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}; - for (auto& element : ${property}) { -${if.object}${items.with.indent}${end.if.object}${if.non.object} ${property}Array.Add() = element;${end.if.non.object} - } - ${base.title}Container.${Property.dependency}Add(_T("${property}"), &${property}Array); \ No newline at end of file + ${if.impl.array.optional}if (element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}.has_value()) { + WPEFramework::Core::JSON::ArrayType<${json.type}> ${property}Array; + ${type} ${property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}.value(); + for (auto& element : ${property}) { + ${if.object}${items.with.indent}${end.if.object}${if.non.object} ${property}Array.Add() = element;${end.if.non.object} + } + ${base.title}Container.${Property.dependency}Add(_T("${property}"), &${property}Array); + }${end.if.impl.array.optional}${if.impl.array.non.optional}WPEFramework::Core::JSON::ArrayType<${json.type}> ${property}Array; + ${type} ${property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}; + for (auto& element : ${property}) { +${if.object}${items.with.indent}${end.if.object}${if.non.object} ${property}Array.Add() = element;${end.if.non.object} + } + ${base.title}Container.${Property.dependency}Add(_T("${property}"), &${property}Array);${end.if.impl.array.non.optional} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/const.cpp b/languages/cpp/templates/parameter-serialization/sub-property/const.cpp index 0b8a51ed..8d41229f 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/const.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/const.cpp @@ -1 +1,3 @@ - ${base.title}Container.${Property.dependency}${Property} = element${property.dependency}.${property}${if.optional}.value()${end.if.optional}; + ${if.optional}if (element${property.dependency}.${property}.has_value()) { + ${base.title}Container.${Property.dependency}${Property} = element${property.dependency}.${property}.value(); + }${end.if.optional}${if.non.optional}${base.title}Container.${Property.dependency}${Property} = element${property.dependency}.${property};${end.if.non.optional} diff --git a/languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp b/languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp index bbb6fabb..a8bca812 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp @@ -1,3 +1,3 @@ - ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${property}Container; + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${property}Container; ${properties} - ${property}Array.Add() = ${property}Container; \ No newline at end of file + ${property}Array.Add() = ${property}Container; \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/property.cpp b/languages/cpp/templates/parameter-serialization/sub-property/property.cpp index 81373225..b7341e97 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/property.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/property.cpp @@ -1 +1,3 @@ -${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}${if.optional}.value()${end.if.optional};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${if.optional}if (element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}.has_value()) { + ${base.title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}.value(); + }${end.if.optional}${if.non.optional}${base.title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property};${end.if.non.optional}${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/sections/provider-interfaces.cpp b/languages/cpp/templates/sections/provider-interfaces.cpp new file mode 100644 index 00000000..0198e308 --- /dev/null +++ b/languages/cpp/templates/sections/provider-interfaces.cpp @@ -0,0 +1 @@ +${providers.list} \ No newline at end of file diff --git a/languages/cpp/templates/sections/provider-interfaces.h b/languages/cpp/templates/sections/provider-interfaces.h index 418d7abf..88134258 100644 --- a/languages/cpp/templates/sections/provider-interfaces.h +++ b/languages/cpp/templates/sections/provider-interfaces.h @@ -1,11 +1,14 @@ - // Provider Interfaces +// Provider Interfaces +struct IProviderSession { + virtual ~IProviderSession() = default; - interface ProviderSession { - correlationId(): string // Returns the correlation id of the current provider session - } - - interface FocusableProviderSession extends ProviderSession { - focus(): Promise // Requests that the provider app be moved into focus to prevent a user experience - } + virtual std::string correlationId() const = 0; +}; + +struct IFocussableProviderSession : virtual public IProviderSession { + virtual ~IFocussableProviderSession() override = default; + + virtual void focus( Firebolt::Error *err = nullptr ) = 0; +}; - ${providers.list} \ No newline at end of file +${providers.list} diff --git a/languages/cpp/templates/sections/provider-subscribe.cpp b/languages/cpp/templates/sections/provider-subscribe.cpp new file mode 100644 index 00000000..0198e308 --- /dev/null +++ b/languages/cpp/templates/sections/provider-subscribe.cpp @@ -0,0 +1 @@ +${providers.list} \ No newline at end of file diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index bb9399f2..4d438695 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -56,7 +56,8 @@ let config = { copySchemasIntoModules: false, extractSubSchemas: false, unwrapResultObjects: false, - excludeDeclarations: false + excludeDeclarations: false, + extractProviderSchema: false, } const state = { @@ -397,6 +398,17 @@ const promoteAndNameSubSchemas = (obj) => { // TODO: the `1` below is brittle... should find the index of the non-ListenResponse schema promoteSchema(method.result.schema.anyOf, 1, getPromotionNameFromContentDescriptor(method.result, ''), obj, '#/components/schemas') } + if (method.tags.find(t => t['x-error'])) { + method.tags.forEach(tag => { + if (tag['x-error']) { + const descriptor = { + name: obj.info.title + 'Error', + schema: tag['x-error'] + } + addContentDescriptorSubSchema(descriptor, '', obj) + } + }) + } }) // find non-primitive sub-schemas of components.schemas and name/promote them @@ -551,6 +563,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { } }) + const providerSubscribe = generateProviderSubscribe(obj, templates) const providerInterfaces = generateProviderInterfaces(obj, templates) const defaults = generateDefaults(obj, templates) @@ -567,6 +580,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { defaults, examples, providerInterfaces, + providerSubscribe, version: getSemanticVersion(obj), title: obj.info.title, description: obj.info.description, @@ -612,6 +626,7 @@ const insertMacros = (fContents = '', macros = {}) => { 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\.providers\}(.*?)\$\{end\.if\.providers\}/gms, macros.providerInterfaces.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) @@ -650,6 +665,7 @@ const insertMacros = (fContents = '', macros = {}) => { }) fContents = fContents.replace(/[ \t]*\/\* \$\{PROVIDERS\} \*\/[ \t]*\n/, macros.providerInterfaces) + fContents = fContents.replace(/[ \t]*\/\* \$\{PROVIDERS_SUBSCRIBE\} \*\/[ \t]*\n/, macros.providerSubscribe) fContents = fContents.replace(/[ \t]*\/\* \$\{IMPORTS\} \*\/[ \t]*\n/, macros.imports) fContents = fContents.replace(/[ \t]*\/\* \$\{INITIALIZATION\} \*\/[ \t]*\n/, macros.initialization) fContents = fContents.replace(/[ \t]*\/\* \$\{DEFAULTS\} \*\/[ \t]*\n/, macros.defaults) @@ -1263,11 +1279,11 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) const resultInit = types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-initialization', property: flattenedMethod.result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) // w/out primitive: true, getSchemaShape skips anonymous types, like primitives const serializedEventParams = event ? flattenedMethod.params.filter(p => p.name !== 'listen').map(param => types.getSchemaShape(param.schema, json, {templateDir: 'parameter-serialization', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n') : '' // this was wrong... check when we merge if it was fixed - const callbackSerializedList = event ? types.getSchemaShape(event.result.schema, json, { templateDir: event.params && event.params.length ? 'callback-serialization' : 'callback-result-serialization', property: result.name, required: event.result.schema.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' - const callbackInitialization = event ? ((event.params && event.params.length ? (event.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'callback-initialization', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n')) + '\n' : '' ) + (types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-initialization', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }))) : '' + const callbackSerializedList = event ? types.getSchemaShape(event.result.schema, json, { templateDir: event.params && event.params.length && !event.tags.find(t => t.name === 'provider') ? 'callback-serialization' : 'callback-result-serialization', property: result.name, required: event.result.schema.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' + const callbackInitialization = event ? ((event.params && event.params.length && !event.tags.find(t => t.name === 'provider') ? (event.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'callback-initialization', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n')) + '\n' : '' ) + (types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-initialization', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }))) : '' let callbackInstantiation = '' if (event) { - if (event.params && event.params.length) { + if (event.params && event.params.length && !event.tags.find(t => t.name === 'provider')) { callbackInstantiation = types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) let paramInstantiation = event.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'callback-context-instantiation', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n') let resultInstantiation = types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-context-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) @@ -1651,38 +1667,113 @@ function insertCapabilityMacros(template, capabilities, method, module) { return content.join() } +function generateProviderSubscribe(json, templates) { + const interfaces = getProvidedCapabilities(json) + const suffix = state.destination ? state.destination.split('.').pop() : '' + let template = getTemplate(suffix ? `/sections/provider-subscribe.${suffix}` : '/sections/provider-subscribe', templates) + const providers = reduce((acc, capability) => { + const template = insertProviderSubscribeMacros(getTemplate(suffix ? `/codeblocks/provider-subscribe.${suffix}` : '/codeblocks/provider-subscribe', templates), capability, json, templates) + return acc + template + }, '', interfaces) + + return interfaces.length ? template.replace(/\$\{providers\.list\}/g, providers) : '' +} + + function generateProviderInterfaces(json, templates) { const interfaces = getProvidedCapabilities(json) - let template = getTemplate('/sections/provider-interfaces', templates) + const suffix = state.destination ? state.destination.split('.').pop() : '' + let template = getTemplate(suffix ? `/sections/provider-interfaces.${suffix}` : '/sections/provider-interfaces', templates) + if (!template) { + template = getTemplate('/sections/provider-interfaces', templates) + } + const providers = reduce((acc, capability) => { - const template = insertProviderInterfaceMacros(getTemplate('/codeblocks/provider', templates), capability, json, templates) + let providerTemplate = getTemplate(suffix ? `/codeblocks/provider.${suffix}` : '/codeblocks/provider', templates) + if (!providerTemplate) { + providerTemplate = getTemplate('/codeblocks/provider', templates) + } + const template = insertProviderInterfaceMacros(providerTemplate, capability, json, templates) return acc + template }, '', interfaces) return interfaces.length ? template.replace(/\$\{providers\.list\}/g, providers) : '' } -function insertProviderInterfaceMacros(template, capability, moduleJson = {}, templates) { - const iface = getProviderInterface(capability, moduleJson, { destination: state.destination, section: state.section })//.map(method => { method.name = method.name.charAt(9).toLowerCase() + method.name.substr(10); return method } ) - +function getProviderInterfaceName(iface, capability, moduleJson = {}) { const uglyName = capability.split(":").slice(-2).map(capitalize).reverse().join('') + "Provider" let name = iface.length === 1 ? iface[0].name.charAt(0).toUpperCase() + iface[0].name.substr(1) + "Provider" : uglyName if (moduleJson.info['x-interface-names']) { name = moduleJson.info['x-interface-names'][capability] || name } + return name +} - let interfaceShape = getTemplate('/codeblocks/interface', templates) +function getProviderXValues(method) { + let xValues = [] + if (method.tags.find(t => t['x-error']) || method.tags.find(t => t['x-response'])) { + method.tags.forEach(tag => { + if (tag['x-response']) { + xValues['x-response'] = tag['x-response'] + } + if (tag['x-error']) { + xValues['x-error'] = tag['x-error'] + } + }) + } + return xValues +} + +function insertProviderXValues(template, moduleJson, xValues) { + if (xValues['x-response']) { + const xResponseInst = types.getSchemaShape(xValues['x-response'], moduleJson, { templateDir: 'parameter-serialization', property: 'result', required: true, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) + template = template.replace(/\$\{provider\.xresponse\.serialization\}/gms, xResponseInst) + .replace(/\$\{provider\.xresponse\.name\}/gms, xValues['x-response'].title) + } + if (xValues['x-error']) { + const xErrorInst = types.getSchemaShape(xValues['x-error'], moduleJson, { templateDir: 'parameter-serialization', property: 'result', required: true, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) + template = template.replace(/\$\{provider\.xerror\.serialization\}/gms, xErrorInst) + .replace(/\$\{provider\.xerror\.name\}/gms, xValues['x-error'].title) + } + return template +} + +function insertProviderSubscribeMacros(template, capability, moduleJson = {}, templates) { + const iface = getProviderInterface(capability, moduleJson, config.extractProviderSchema) + let name = getProviderInterfaceName(iface, capability, moduleJson) + + const suffix = state.destination ? state.destination.split('.').pop() : '' + template = template.replace(/\$\{subscribe\}/gms, iface.map(method => { + return insertMethodMacros(getTemplate(suffix ? `/codeblocks/subscribe.${suffix}` : '/codeblocks/subscribe', templates), method, moduleJson, { destination: state.destination, section: state.section }) + }).join('\n') + '\n') + return template +} + +function insertProviderInterfaceMacros(template, capability, moduleJson = {}, templates) { + const iface = getProviderInterface(capability, moduleJson, config.extractProviderSchema) + let name = getProviderInterfaceName(iface, capability, moduleJson) + let xValues + const suffix = state.destination ? state.destination.split('.').pop() : '' + let interfaceShape = getTemplate(suffix ? `/codeblocks/interface.${suffix}` : '/codeblocks/interface', templates) + if (!interfaceShape) { + interfaceShape = getTemplate('/codeblocks/interface', templates) + } interfaceShape = interfaceShape.replace(/\$\{name\}/g, name) .replace(/\$\{capability\}/g, capability) .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => { const focusable = method.tags.find(t => t['x-allow-focus']) - const interfaceDeclaration = getTemplate('/interfaces/' + (focusable ? 'focusable' : 'default'), templates) + const interfaceTemplate = '/interfaces/' + (focusable ? 'focusable' : 'default') + const interfaceDeclaration = getTemplate(suffix ? `${interfaceTemplate}.${suffix}` : interfaceTemplate, templates) + xValues = getProviderXValues(method) + method.tags.unshift({ + name: 'provider' + }) return insertMethodMacros(interfaceDeclaration, method, moduleJson, { destination: state.destination, section: state.section, isInterface: true }) }).join('') + '\n') - + if (iface.length === 0) { template = template.replace(/\$\{provider\.methods\}/gms, '') } @@ -1765,6 +1856,7 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te template = template.replace(/\$\{provider\}/g, name) template = template.replace(/\$\{interface\}/g, interfaceShape) template = template.replace(/\$\{capability\}/g, capability) + template = insertProviderXValues(template, moduleJson, xValues) return template } diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index b3ad15db..f2923717 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -54,6 +54,7 @@ const macrofy = async ( additionalSchemaTemplates, additionalMethodTemplates, excludeDeclarations, + extractProviderSchema, aggregateFiles, operators, primitives, @@ -97,6 +98,7 @@ const macrofy = async ( additionalSchemaTemplates, additionalMethodTemplates, excludeDeclarations, + extractProviderSchema, operators }) diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index d587559b..9acc285a 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -34,7 +34,7 @@ const stdPrimitives = [ "integer", "number", "boolean", "string" ] const isVoid = type => (type === 'void') ? true : false const isPrimitiveType = type => stdPrimitives.includes(type) ? true : false const allocatedPrimitiveProxies = {} - +const isObject = schema => (schema.type === 'object') || (Array.isArray(schema.type) && schema.type.includes("object")) function setTemplates(t) { Object.assign(templates, t) } @@ -178,8 +178,9 @@ function insertSchemaMacros(content, schema, module, { name = '', parent = '', p .replace(/\$\{if\.namespace\.notsame}(.*?)\$\{end\.if\.namespace\.notsame\}/g, (module.info.title !== (parent || moduleTitle)) ? '$1' : '') .replace(/\$\{parent\.title\}/g, parent || moduleTitle) .replace(/\$\{parent\.Title\}/g, capitalize(parent || moduleTitle)) - .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, (Array.isArray(required) ? required.includes(property) : required) ? '' : '$1') .replace(/\$\{description\}/g, schema.description ? schema.description : '') + .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, (Array.isArray(required) ? required.includes(property) : required) ? '' : '$1') + .replace(/\$\{if\.non.optional\}(.*?)\$\{end\.if\.non.optional\}/gms, (Array.isArray(required) ? required.includes(property) : required) ? '$1' : '') .replace(/\$\{summary\}/g, schema.description ? schema.description.split('\n')[0] : '') .replace(/\$\{name\}/g, title) .replace(/\$\{NAME\}/g, title.toUpperCase()) @@ -261,6 +262,7 @@ const insertObjectAdditionalPropertiesMacros = (content, schema, module, title, .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, '') .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/g, '') .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/g, options.required ? '' : '$1') + .replace(/\$\{if\.impl.non.optional\}(.*?)\$\{end\.if\.impl.non.optional\}/g, options.required ? '$1' : '') return content } @@ -303,15 +305,17 @@ const insertObjectMacros = (content, schema, module, title, property, options) = .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/gms, i === schema.properties.length - 1 ? '' : '$1') .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, schema.required && schema.required.includes(name) ? '' : '$1') + .replace(/\$\{if\.non.optional\}(.*?)\$\{end\.if\.non.optional\}/gms, schema.required && schema.required.includes(name) ? '$1' : '') .replace(/\$\{if\.base\.optional\}(.*?)\$\{end\.if\.base\.optional\}/gms, options.required ? '' : '$1') - .replace(/\$\{if\.non\.object\}(.*?)\$\{end\.if\.non\.object\}/gms, (localizedProp.type === 'object') ? '' : '$1') + .replace(/\$\{if\.non\.object\}(.*?)\$\{end\.if\.non\.object\}/gms, isObject(localizedProp) ? '' : '$1') .replace(/\$\{if\.non\.array\}(.*?)\$\{end\.if\.non\.array\}/gms, (localizedProp.type === 'array') ? '' : '$1') .replace(/\$\{if\.non\.anyOf\}(.*?)\$\{end\.if\.non\.anyOf\}/gms, (localizedProp.anyOf || localizedProp.anyOneOf) ? '' : '$1') .replace(/\$\{if\.non\.const\}(.*?)\$\{end\.if\.non\.const\}/gms, (typeof localizedProp.const === 'string') ? '' : '$1') let baseTitle = options.property - if (localizedProp.type === 'object') { + if (isObject(localizedProp)) { replacedTemplate = replacedTemplate .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, schema.required && schema.required.includes(name) ? '' : '$1') + .replace(/\$\{if\.impl.non.optional\}(.*?)\$\{end\.if\.impl.non.optional\}/gms, schema.required && schema.required.includes(name) ? '$1' : '') .replace(/\$\{property.dependency\}/g, ((options.level > 0) ? '${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}' : '') + objSeparator + name) .replace(/\$\{Property.dependency\}/g, ((options.level > 0) ? '${Property.dependency}' : '') + capitalize(name) + (objSeparator)) } @@ -368,7 +372,8 @@ const insertObjectMacros = (content, schema, module, title, property, options) = .replace(/\$\{description\}/g, prop.description || '') .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/gms, i === propertyNames.enum.length - 1 ? '' : '$1') - .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, schema.required && schema.required.includes(prop) ? '' : '$1')) + .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, schema.required && schema.required.includes(prop) ? '' : '$1') + .replace(/\$\{if\.non.optional\}(.*?)\$\{end\.if\.non.optional\}/gms, schema.required && schema.required.includes(prop) ? '$1' : '')) } }) } @@ -392,8 +397,9 @@ const insertArrayMacros = (content, schema, module, level = 0, items, required = content = content .replace(/\$\{json\.type\}/g, getSchemaType(schema.items, module, { templateDir: 'json-types', destination: state.destination, section: state.section, code: false, namespace: true })) .replace(/\$\{items\}/g, items) - .replace(/\$\{items\.with\.indent\}/g, indent(items, ' ')) + .replace(/\$\{items\.with\.indent\}/g, required ? indent(items, ' ') : indent(items, ' ')) .replace(/\$\{if\.impl.array.optional\}(.*?)\$\{end\.if\.impl.array.optional\}/gms, required ? '' : '$1') + .replace(/\$\{if\.impl.array.non.optional\}(.*?)\$\{end\.if\.impl.array.non.optional\}/gms, required ? '$1' : '') return content } @@ -511,7 +517,7 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren result = result.replace(/\$\{shape\}/g, shape) return insertSchemaMacros(result, schema, module, { name: theTitle, parent, property, required }) } - else if (schema.type === 'object') { + else if (isObject(schema)) { let shape const additionalPropertiesTemplate = getTemplate(path.join(templateDir, 'additionalProperties')) if (additionalPropertiesTemplate && schema.additionalProperties && (typeof schema.additionalProperties === 'object')) { @@ -524,6 +530,7 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren result = result.replace(/\$\{shape\}/g, shape) if (level === 0) { result = result.replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, (Array.isArray(required) ? required.includes(property) : required) ? '' : '$1') + result = result.replace(/\$\{if\.impl.non.optional\}(.*?)\$\{end\.if\.impl.non.optional\}/gms, (Array.isArray(required) ? required.includes(property) : required) ? '$1' : '') } return insertSchemaMacros(result, schema, module, { name: theTitle, parent, property, required, templateDir }) } @@ -583,7 +590,7 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren const items = getSchemaShape(schema.items, module, { templateDir, parent, property, required, parentLevel: parentLevel + 1, level, summary, descriptions, destination, enums: false, array: true, primitive }) const shape = insertArrayMacros(getTemplate(path.join(templateDir, 'array' + suffix)) || genericTemplate, schema, module, level, items, Array.isArray(required) ? required.includes(property) : required) result = result.replace(/\$\{shape\}/g, shape) - .replace(/\$\{if\.object\}(.*?)\$\{end\.if\.object\}/gms, (schema.items.type === 'object') ? '$1' : '') + .replace(/\$\{if\.object\}(.*?)\$\{end\.if\.object\}/gms, isObject(schema.items) ? '$1' : '') .replace(/\$\{if\.non\.object\}(.*?)\$\{end\.if\.non\.object\}/gms, (schema.items.type !== 'object') ? '$1' : '') return insertSchemaMacros(result, schema, module, { name: items, parent, property, required, templateDir }) } @@ -656,7 +663,7 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin const theTitle = insertSchemaMacros(namespaceStr + getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, { name: schema.title, parent: getXSchemaGroup(schema, module), recursive: false }) const allocatedProxy = event || result - const title = schema.type === "object" || schema.enum ? true : false + const title = schema.type === "object" || Array.isArray(schema.type) && schema.type.includes("object") || schema.enum ? true : false if (schema['$ref']) { if (schema['$ref'][0] === '#') { @@ -811,7 +818,12 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin } } else { - const template = getTemplate(path.join(templateDir, 'void')) || 'void' + let type + if (schema.title) { + const baseDir = (templateDir !== 'json-types' ? 'types': templateDir) + type = getPrimitiveType('string', baseDir) + } + const template = type || getTemplate(path.join(templateDir, 'void')) || 'void' // TODO this is TypeScript specific return wrap(template, code ? '`' : '') } diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index 763b6c9e..627e3346 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -70,6 +70,7 @@ const run = async ({ additionalSchemaTemplates: config.additionalSchemaTemplates, additionalMethodTemplates: config.additionalMethodTemplates, excludeDeclarations: config.excludeDeclarations, + extractProviderSchema: config.extractProviderSchema, staticModuleNames: staticModuleNames, hideExcluded: true, aggregateFiles: config.aggregateFiles, diff --git a/src/shared/modules.mjs b/src/shared/modules.mjs index 355da86c..c55d5af4 100644 --- a/src/shared/modules.mjs +++ b/src/shared/modules.mjs @@ -85,7 +85,7 @@ const getProviderInterfaceMethods = (capability, json) => { } -function getProviderInterface(capability, module) { +function getProviderInterface(capability, module, extractProviderSchema = false) { module = JSON.parse(JSON.stringify(module)) const iface = getProviderInterfaceMethods(capability, module).map(method => localizeDependencies(method, module, null, { mergeAllOfs: true })) @@ -95,62 +95,63 @@ function getProviderInterface(capability, module) { // remove `onRequest` method.name = method.name.charAt(9).toLowerCase() + method.name.substr(10) + + method.params = [ + { + "name": "parameters", + "required": true, + "schema": payload.properties.parameters + } + ] - method.params = [ - { - "name": "parameters", - "required": true, - "schema": payload.properties.parameters - } - ] - - let exampleResult = null - - if (method.tags.find(tag => tag['x-response'])) { - const result = method.tags.find(tag => tag['x-response'])['x-response'] + if (!extractProviderSchema) { + let exampleResult = null + + if (method.tags.find(tag => tag['x-response'])) { + const result = method.tags.find(tag => tag['x-response'])['x-response'] - method.result = { - "name": "result", - "schema": result - } + method.result = { + "name": "result", + "schema": result + } - if (result.examples && result.examples[0]) { - exampleResult = result.examples[0] + if (result.examples && result.examples[0]) { + exampleResult = result.examples[0] + } } - } - else { - method.result = { - "name": "result", - "schema": { - "const": null + else { + method.result = { + "name": "result", + "schema": { + "const": null + } } } - } - method.examples = method.examples.map( example => ( - { - params: [ - { - name: "parameters", - value: example.result.value.parameters - }, - { - name: "correlationId", - value: example.result.value.correlationId + method.examples = method.examples.map( example => ( + { + params: [ + { + name: "parameters", + value: example.result.value.parameters + }, + { + name: "correlationId", + value: example.result.value.correlationId + } + ], + result: { + name: "result", + value: exampleResult } - ], - result: { - name: "result", - value: exampleResult } - } - )) + )) - // remove event tag - method.tags = method.tags.filter(tag => tag.name !== 'event') + // remove event tag + method.tags = method.tags.filter(tag => tag.name !== 'event') + } }) - return iface } From 4c9e8705e568e80bb182a7866f33f4650af24324 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Tue, 12 Dec 2023 08:58:31 +0530 Subject: [PATCH 121/137] CPPSDK: check jsonrpc response values are set or not before assigning based on optional types (#157) --- .../src/shared/cmake/HelperFunctions.cmake | 2 +- languages/cpp/src/shared/src/Logger/Logger.h | 2 +- .../src/shared/src/Properties/Properties.h | 2 +- .../sub-property/object.cpp | 7 +++--- .../callback-result-instantiation/generic.cpp | 2 +- .../callback-result-instantiation/object.cpp | 2 +- .../property.cpp | 4 +++- .../sub-property/anyOfSchemaShape.cpp | 8 +++++-- .../sub-property/array.cpp | 13 +++++++---- .../sub-property/const.cpp | 4 +++- .../sub-property/object.cpp | 9 +++++--- .../sub-property/property.cpp | 4 +++- .../cpp/templates/codeblocks/interface.cpp | 10 ++++----- .../cpp/templates/codeblocks/module-init.cpp | 4 ++-- .../methods/polymorphic-pull-event.cpp | 2 +- .../additionalProperties.cpp | 2 +- .../parameter-serialization/enum.cpp | 2 +- .../parameter-serialization/generic.cpp | 2 +- .../parameter-serialization/object-array.cpp | 2 +- .../parameter-serialization/object.cpp | 2 +- .../sub-property/array.cpp | 2 +- .../sub-property/const.cpp | 2 +- .../sub-property/object-array.cpp | 2 ++ .../sub-property/object.cpp | 2 ++ .../templates/result-instantiation/array.cpp | 2 +- .../result-instantiation/object-array.cpp | 6 ++--- .../result-instantiation/property.cpp | 4 +++- .../sub-property/anyOfSchemaShape.cpp | 8 +++++-- .../sub-property/array.cpp | 13 +++++++---- .../sub-property/object-array.cpp | 2 ++ .../sub-property/object.cpp | 9 +++++--- .../sub-property/property.cpp | 4 +++- .../cpp/templates/sdk/scripts/install.sh | 2 +- languages/cpp/templates/types/object.h | 2 +- languages/cpp/templates/types/property.h | 2 +- .../javascript/templates/types/object.mjs | 2 +- .../javascript/templates/types/property.mjs | 2 +- src/macrofier/engine.mjs | 22 +++++++++++++++---- src/macrofier/types.mjs | 14 +++++++----- 39 files changed, 122 insertions(+), 65 deletions(-) diff --git a/languages/cpp/src/shared/cmake/HelperFunctions.cmake b/languages/cpp/src/shared/cmake/HelperFunctions.cmake index eb2ae296..4b5c4e09 100644 --- a/languages/cpp/src/shared/cmake/HelperFunctions.cmake +++ b/languages/cpp/src/shared/cmake/HelperFunctions.cmake @@ -62,7 +62,7 @@ function(InstallHeaders) if (headers) install( DIRECTORY "${source}/${directory}/${subdir}" - DESTINATION include/${dest} + DESTINATION include/${dest} FILES_MATCHING PATTERN "*.h") endif() endif() diff --git a/languages/cpp/src/shared/src/Logger/Logger.h b/languages/cpp/src/shared/src/Logger/Logger.h index ffe5a455..c88b87e8 100644 --- a/languages/cpp/src/shared/src/Logger/Logger.h +++ b/languages/cpp/src/shared/src/Logger/Logger.h @@ -53,7 +53,7 @@ namespace FireboltSDK { static void Log(LogLevel logLevel, Category category, const std::string& module, const std::string file, const std::string function, const uint16_t line, const std::string& format, ...); public: - template + template static const string Module() { return WPEFramework::Core::ClassNameOnly(typeid(CLASS).name()).Text(); diff --git a/languages/cpp/src/shared/src/Properties/Properties.h b/languages/cpp/src/shared/src/Properties/Properties.h index 52051397..3729ba6b 100644 --- a/languages/cpp/src/shared/src/Properties/Properties.h +++ b/languages/cpp/src/shared/src/Properties/Properties.h @@ -80,7 +80,7 @@ namespace FireboltSDK { } - template + template static Firebolt::Error Get(const string& propertyName, RESPONSETYPE& response) { Firebolt::Error status = Firebolt::Error::General; diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/object.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/object.cpp index ddd85ed9..1e549298 100644 --- a/languages/cpp/templates/callback-context-instantiation/sub-property/object.cpp +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/object.cpp @@ -1,3 +1,4 @@ -${if.impl.optional} - ${base.title}${property.dependency} = std::make_optional<${type}>();${end.if.impl.optional} -${properties} \ No newline at end of file +${if.impl.optional} ${base.title}${property.dependency} = std::make_optional<${type}>();${end.if.impl.optional} + { +${properties} + } \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/generic.cpp b/languages/cpp/templates/callback-result-instantiation/generic.cpp index 6d8fa873..4a22d102 100644 --- a/languages/cpp/templates/callback-result-instantiation/generic.cpp +++ b/languages/cpp/templates/callback-result-instantiation/generic.cpp @@ -1 +1 @@ - ${property} = proxyResponse->Value(); \ No newline at end of file + ${property} = proxyResponse->Value(); diff --git a/languages/cpp/templates/callback-result-instantiation/object.cpp b/languages/cpp/templates/callback-result-instantiation/object.cpp index c4569c3e..c04d0a50 100644 --- a/languages/cpp/templates/callback-result-instantiation/object.cpp +++ b/languages/cpp/templates/callback-result-instantiation/object.cpp @@ -1 +1 @@ -${properties} \ No newline at end of file +${properties} diff --git a/languages/cpp/templates/callback-result-instantiation/property.cpp b/languages/cpp/templates/callback-result-instantiation/property.cpp index db30050c..bb62934b 100644 --- a/languages/cpp/templates/callback-result-instantiation/property.cpp +++ b/languages/cpp/templates/callback-result-instantiation/property.cpp @@ -1 +1,3 @@ -${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}.${property} = proxyResponse->${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${if.optional}if (proxyResponse->${Property}.IsSet()) { + ${base.title}.${property} = proxyResponse->${Property}; + }${end.if.optional}${if.non.optional}${base.title}.${property} = proxyResponse->${Property};${end.if.non.optional}${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/anyOfSchemaShape.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/anyOfSchemaShape.cpp index 56f90f5b..0c62eef4 100644 --- a/languages/cpp/templates/callback-result-instantiation/sub-property/anyOfSchemaShape.cpp +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/anyOfSchemaShape.cpp @@ -1,3 +1,7 @@ - string ${property}Str; + ${if.optional}if (proxyResponse->${Property.dependency}${Property}.IsSet()) { + string ${property}Str; + proxyResponse->${Property.dependency}${Property}.ToString(${property}Str); + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = ${property}Str; + }${end.if.optional}${if.non.optional}string ${property}Str; proxyResponse->${Property.dependency}${Property}.ToString(${property}Str); - ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = ${property}Str; \ No newline at end of file + ${base.title}${property.dependency}.${property} = ${property}Str;${end.if.non.optional} diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp index 8bf38da1..b2131f27 100644 --- a/languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp @@ -1,5 +1,10 @@ - ${if.impl.array.optional}${base.title}.${property} = std::make_optional<${type}>();${end.if.impl.array.optional} - auto index(proxyResponse->${Property}.Elements()); + ${if.optional}if (proxyResponse->${Property}.IsSet()) { + ${base.title}.${property} = std::make_optional<${type}>(); + auto index(proxyResponse->${Property}.Elements()); + while (index.Next() == true) { + ${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}.${property}.value().push_back(index.Current().Value());${end.if.non.object} + } + }${end.if.optional}${if.non.optional}auto index(proxyResponse->${Property}.Elements()); while (index.Next() == true) { -${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}.push_back(index.Current().Value());${end.if.non.object} - } \ No newline at end of file +${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}.${property}.value().push_back(index.Current().Value());${end.if.non.object} + }${end.if.non.optional} diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/const.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/const.cpp index e84a8c35..b005a326 100644 --- a/languages/cpp/templates/callback-result-instantiation/sub-property/const.cpp +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/const.cpp @@ -1 +1,3 @@ - ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = proxyResponse->${Property.dependency}${Property}; \ No newline at end of file + ${if.optional}if (proxyResponse->${Property.dependency}${Property}.IsSet()) { + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = proxyResponse->${Property.dependency}${Property}; + }${end.if.optional}${if.non.optional}${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = proxyResponse->${Property.dependency}${Property};${end.if.non.optional} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp index b134dafe..cd86ff1a 100644 --- a/languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp @@ -1,3 +1,6 @@ -${if.impl.optional} - ${base.title}${property.dependency} = std::make_optional<${type}>();${end.if.impl.optional} -${properties} \ No newline at end of file +${if.optional} if (proxyResponse->${Property.dependency}IsSet()) { + ${base.title}${property.dependency} = std::make_optional<${type}>(); +${properties} + }${end.if.optional}${if.non.optional} { +${properties} + }${end.if.non.optional} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp index beff7b1e..f8bfa268 100644 --- a/languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp @@ -1 +1,3 @@ -${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = proxyResponse->${Property.dependency}${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${if.optional}if (proxyResponse->${Property.dependency}${Property}.IsSet()) { + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = proxyResponse->${Property.dependency}${Property}; + }${end.if.optional}${if.non.optional}${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = proxyResponse->${Property.dependency}${Property};${end.if.non.optional}${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} diff --git a/languages/cpp/templates/codeblocks/interface.cpp b/languages/cpp/templates/codeblocks/interface.cpp index dff9252d..b62df483 100644 --- a/languages/cpp/templates/codeblocks/interface.cpp +++ b/languages/cpp/templates/codeblocks/interface.cpp @@ -23,25 +23,25 @@ WPEFramework::Core::JSON::Variant CorrelationId(correlationId); jsonParameters.Set(_T("correlationId"), CorrelationId); - ProviderInvokeSession(methodName, jsonParameters, err); + ProviderInvokeSession(methodName, jsonParameters, err); } static void ProviderResultSession(std::string methodName, std::string& correlationId, ${provider.xresponse.name} result, Firebolt::Error *err = nullptr) { JsonObject jsonParameters; - WPEFramework::Core::JSON::Variant CorrelationId(correlationId); + WPEFramework::Core::JSON::Variant CorrelationId(correlationId); jsonParameters.Set(_T("correlationId"), CorrelationId); ${provider.xresponse.serialization} - ProviderInvokeSession(methodName, jsonParameters, err); + ProviderInvokeSession(methodName, jsonParameters, err); } static void ProviderErrorSession(std::string methodName, std::string& correlationId, ${provider.xerror.name} result, Firebolt::Error *err = nullptr) { JsonObject jsonParameters; - WPEFramework::Core::JSON::Variant CorrelationId(correlationId); + WPEFramework::Core::JSON::Variant CorrelationId(correlationId); jsonParameters.Set(_T("correlationId"), CorrelationId); ${provider.xerror.serialization} - ProviderInvokeSession(methodName, jsonParameters, err); + ProviderInvokeSession(methodName, jsonParameters, err); } ${methods} diff --git a/languages/cpp/templates/codeblocks/module-init.cpp b/languages/cpp/templates/codeblocks/module-init.cpp index 034ff7fe..4d166513 100644 --- a/languages/cpp/templates/codeblocks/module-init.cpp +++ b/languages/cpp/templates/codeblocks/module-init.cpp @@ -1,14 +1,14 @@ ${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; + ${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}; } diff --git a/languages/cpp/templates/methods/polymorphic-pull-event.cpp b/languages/cpp/templates/methods/polymorphic-pull-event.cpp index ef7a837b..54da22d6 100644 --- a/languages/cpp/templates/methods/polymorphic-pull-event.cpp +++ b/languages/cpp/templates/methods/polymorphic-pull-event.cpp @@ -14,7 +14,7 @@ Firebolt::Error status = Firebolt::Error::NotConnected; FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { - JsonObject jsonParameters; + JsonObject jsonParameters; WPEFramework::Core::JSON::Variant CorrelationId = proxyResponse->CorrelationId.Value(); jsonParameters.Set(_T("correlationId"), CorrelationId); ${method.pulls.json.type} ${method.pulls.result.title}Container; diff --git a/languages/cpp/templates/parameter-serialization/additionalProperties.cpp b/languages/cpp/templates/parameter-serialization/additionalProperties.cpp index 88c832d0..eea6f6a7 100644 --- a/languages/cpp/templates/parameter-serialization/additionalProperties.cpp +++ b/languages/cpp/templates/parameter-serialization/additionalProperties.cpp @@ -9,4 +9,4 @@ jsonContainer.Set(element.first.c_str(), jsonElement); ${property}Variant = jsonContainer; } - jsonParameters.Set(_T("${property}"), ${property}Variant); \ No newline at end of file + jsonParameters.Set(_T("${property}"), ${property}Variant); diff --git a/languages/cpp/templates/parameter-serialization/enum.cpp b/languages/cpp/templates/parameter-serialization/enum.cpp index 167761a0..478e1d8e 100644 --- a/languages/cpp/templates/parameter-serialization/enum.cpp +++ b/languages/cpp/templates/parameter-serialization/enum.cpp @@ -4,4 +4,4 @@ jsonParameters.Set(_T("${property}"), ${property}Variant); }${end.if.optional}${if.non.optional}${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonValue = ${property}; WPEFramework::Core::JSON::Variant ${property}Variant(jsonValue.Data()); - jsonParameters.Set(_T("${property}"), ${property}Variant);${end.if.non.optional} + jsonParameters.Set(_T("${property}"), ${property}Variant);${end.if.non.optional} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/generic.cpp b/languages/cpp/templates/parameter-serialization/generic.cpp index 5ab016c3..69893434 100644 --- a/languages/cpp/templates/parameter-serialization/generic.cpp +++ b/languages/cpp/templates/parameter-serialization/generic.cpp @@ -2,4 +2,4 @@ WPEFramework::Core::JSON::Variant ${property}Variant(${property}.value()); jsonParameters.Set(_T("${property}"), ${property}Variant); }${end.if.optional}${if.non.optional}WPEFramework::Core::JSON::Variant ${property}Variant(${property}); - jsonParameters.Set(_T("${property}"), ${property}Variant);${end.if.non.optional} + jsonParameters.Set(_T("${property}"), ${property}Variant);${end.if.non.optional} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/object-array.cpp b/languages/cpp/templates/parameter-serialization/object-array.cpp index baedcd30..a8426a59 100644 --- a/languages/cpp/templates/parameter-serialization/object-array.cpp +++ b/languages/cpp/templates/parameter-serialization/object-array.cpp @@ -6,4 +6,4 @@ ${property}Container.ToString(${property}Str); WPEFramework::Core::JSON::VariantContainer ${property}VariantContainer(${property}Str); WPEFramework::Core::JSON::Variant ${property}Variant = ${property}VariantContainer; - ${property}Array.Add() = ${property}Variant; + ${property}Array.Add() = ${property}Variant; \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/object.cpp b/languages/cpp/templates/parameter-serialization/object.cpp index 4d0cbc08..877b0d13 100644 --- a/languages/cpp/templates/parameter-serialization/object.cpp +++ b/languages/cpp/templates/parameter-serialization/object.cpp @@ -16,4 +16,4 @@ ${property}Container.ToString(${property}Str); WPEFramework::Core::JSON::VariantContainer ${property}VariantContainer(${property}Str); WPEFramework::Core::JSON::Variant ${property}Variant = ${property}VariantContainer; - jsonParameters.Set(_T("${property}"), ${property}Variant);${end.if.impl.non.optional} + jsonParameters.Set(_T("${property}"), ${property}Variant);${end.if.impl.non.optional} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/array.cpp b/languages/cpp/templates/parameter-serialization/sub-property/array.cpp index d04f5448..cf5bb5f2 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/array.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/array.cpp @@ -10,4 +10,4 @@ for (auto& element : ${property}) { ${if.object}${items.with.indent}${end.if.object}${if.non.object} ${property}Array.Add() = element;${end.if.non.object} } - ${base.title}Container.${Property.dependency}Add(_T("${property}"), &${property}Array);${end.if.impl.array.non.optional} \ No newline at end of file + ${base.title}Container.${Property.dependency}Add(_T("${property}"), &${property}Array);${end.if.impl.array.non.optional} diff --git a/languages/cpp/templates/parameter-serialization/sub-property/const.cpp b/languages/cpp/templates/parameter-serialization/sub-property/const.cpp index 8d41229f..fa81c8f4 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/const.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/const.cpp @@ -1,3 +1,3 @@ ${if.optional}if (element${property.dependency}.${property}.has_value()) { ${base.title}Container.${Property.dependency}${Property} = element${property.dependency}.${property}.value(); - }${end.if.optional}${if.non.optional}${base.title}Container.${Property.dependency}${Property} = element${property.dependency}.${property};${end.if.non.optional} + }${end.if.optional}${if.non.optional}${base.title}Container.${Property.dependency}${Property} = element${property.dependency}.${property};${end.if.non.optional} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp b/languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp index a8bca812..11c5b76b 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/object-array.cpp @@ -1,3 +1,5 @@ ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} ${property}Container; + { ${properties} + } ${property}Array.Add() = ${property}Container; \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/object.cpp b/languages/cpp/templates/parameter-serialization/sub-property/object.cpp index c04d0a50..086f7169 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/object.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/object.cpp @@ -1 +1,3 @@ + { ${properties} + } \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/array.cpp b/languages/cpp/templates/result-instantiation/array.cpp index 2fab5f07..0e2f01ef 100644 --- a/languages/cpp/templates/result-instantiation/array.cpp +++ b/languages/cpp/templates/result-instantiation/array.cpp @@ -1,4 +1,4 @@ auto index(jsonResult.Elements()); while (index.Next() == true) { -${if.object}${items.with.indent}${end.if.object}${if.non.object} ${property}.push_back(index.Current().Value());${end.if.non.object} + ${if.object}${items}${end.if.object}${if.non.object} ${property}.push_back(index.Current().Value());${end.if.non.object} } \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/object-array.cpp b/languages/cpp/templates/result-instantiation/object-array.cpp index 0c396b43..f992be35 100644 --- a/languages/cpp/templates/result-instantiation/object-array.cpp +++ b/languages/cpp/templates/result-instantiation/object-array.cpp @@ -1,4 +1,4 @@ - ${type} ${property}Result${level}; - ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonResult = index.Current(); + ${type} ${property}Result${level}; + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonResult = index.Current(); ${properties} - ${property}.push_back(${property}Result${level}); \ No newline at end of file + ${property}.push_back(${property}Result${level}); \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/property.cpp b/languages/cpp/templates/result-instantiation/property.cpp index fb6ca4d4..5d3c2db8 100644 --- a/languages/cpp/templates/result-instantiation/property.cpp +++ b/languages/cpp/templates/result-instantiation/property.cpp @@ -1 +1,3 @@ -${shape} ${if.non.anyOf}${if.non.array}${if.non.object}${base.title}Result${level}.${property} = jsonResult.${Property}.Value();${end.if.non.object}${end.if.non.array}${end.if.non.anyOf} +${shape} ${if.non.anyOf}${if.non.array}${if.non.object}${if.optional}if (jsonResult.${Property}.IsSet()) { + ${base.title}Result${level}.${property} = jsonResult.${Property}.Value(); + }${end.if.optional}${if.non.optional}${base.title}Result${level}.${property} = jsonResult.${Property}.Value();${end.if.non.optional}${end.if.non.object}${end.if.non.array}${end.if.non.anyOf} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/sub-property/anyOfSchemaShape.cpp b/languages/cpp/templates/result-instantiation/sub-property/anyOfSchemaShape.cpp index 1d5afa9b..75d9be83 100644 --- a/languages/cpp/templates/result-instantiation/sub-property/anyOfSchemaShape.cpp +++ b/languages/cpp/templates/result-instantiation/sub-property/anyOfSchemaShape.cpp @@ -1,3 +1,7 @@ - string ${property}Str; + ${if.optional}if (jsonResult.${Property.dependency}${Property}.IsSet()) { + string ${property}Str; + jsonResult.${Property.dependency}${Property}.ToString(${property}Str); + ${base.title}Result${level}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = ${property}Str; + }${end.if.optional}${if.non.optional}string ${property}Str; jsonResult.${Property.dependency}${Property}.ToString(${property}Str); - ${base.title}Result${level}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = ${property}Str; + ${base.title}Result${level}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = ${property}Str;${end.if.non.optional} diff --git a/languages/cpp/templates/result-instantiation/sub-property/array.cpp b/languages/cpp/templates/result-instantiation/sub-property/array.cpp index 5d401ef3..a9badd14 100644 --- a/languages/cpp/templates/result-instantiation/sub-property/array.cpp +++ b/languages/cpp/templates/result-instantiation/sub-property/array.cpp @@ -1,5 +1,10 @@ - ${if.impl.array.optional}${base.title}Result${level}.${property} = std::make_optional<${type}>();${end.if.impl.array.optional} - auto index(jsonResult.${Property}.Elements()); + ${if.optional}if (jsonResult.${Property}.IsSet()) { + ${base.title}Result${level}.${property} = std::make_optional<${type}>(); + auto index(jsonResult.${Property}.Elements()); + while (index.Next() == true) { + ${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}Result${level}.${property}.value().push_back(index.Current().Value());${end.if.non.object} + } + }${end.if.optional}${if.non.optional}auto index(jsonResult.${Property}.Elements()); while (index.Next() == true) { -${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}Result${level}.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}.push_back(index.Current().Value());${end.if.non.object} - } \ No newline at end of file + ${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}Result${level}.${property}.push_back(index.Current().Value());${end.if.non.object} + }${end.if.non.optional} diff --git a/languages/cpp/templates/result-instantiation/sub-property/object-array.cpp b/languages/cpp/templates/result-instantiation/sub-property/object-array.cpp index 87f0971d..1274a0da 100644 --- a/languages/cpp/templates/result-instantiation/sub-property/object-array.cpp +++ b/languages/cpp/templates/result-instantiation/sub-property/object-array.cpp @@ -1,4 +1,6 @@ ${type} ${property}Result${level}; ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonResult = index.Current(); + { ${properties} + } ${property}Result.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}.push_back(${property}Result${level}); \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/sub-property/object.cpp b/languages/cpp/templates/result-instantiation/sub-property/object.cpp index 2f526fef..bb793a66 100644 --- a/languages/cpp/templates/result-instantiation/sub-property/object.cpp +++ b/languages/cpp/templates/result-instantiation/sub-property/object.cpp @@ -1,3 +1,6 @@ -${if.impl.optional} - ${base.title}Result${level}${property.dependency} = std::make_optional<${type}>();${end.if.impl.optional} -${properties} \ No newline at end of file +${if.optional} if (jsonResult.${Property.dependency}IsSet()) { + ${base.title}Result${level}${property.dependency} = std::make_optional<${type}>(); +${properties} + }${end.if.optional}${if.non.optional} { +${properties} + }${end.if.non.optional} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/sub-property/property.cpp b/languages/cpp/templates/result-instantiation/sub-property/property.cpp index 6e938509..83d14805 100644 --- a/languages/cpp/templates/result-instantiation/sub-property/property.cpp +++ b/languages/cpp/templates/result-instantiation/sub-property/property.cpp @@ -1 +1,3 @@ -${shape} ${if.non.anyOf}${if.non.array}${if.non.object}${base.title}Result${level}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = jsonResult.${Property.dependency}${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf} \ No newline at end of file +${shape} ${if.non.anyOf}${if.non.array}${if.non.object}${if.optional}if (jsonResult.${Property.dependency}${Property}.IsSet()) { + ${base.title}Result${level}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = jsonResult.${Property.dependency}${Property}; + }${end.if.optional}${if.non.optional}${base.title}Result${level}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = jsonResult.${Property.dependency}${Property};${end.if.non.optional}${end.if.non.object}${end.if.non.array}${end.if.non.anyOf} diff --git a/languages/cpp/templates/sdk/scripts/install.sh b/languages/cpp/templates/sdk/scripts/install.sh index 2c4663af..2e8a956c 100755 --- a/languages/cpp/templates/sdk/scripts/install.sh +++ b/languages/cpp/templates/sdk/scripts/install.sh @@ -18,7 +18,7 @@ do case "${flag}" in i) InstallPath="${OPTARG}";; s) SdkPath="${OPTARG}";; - m) ModuleName="${OPTARG}";; + m) ModuleName="${OPTARG}";; h) usage && exit 1;; esac done diff --git a/languages/cpp/templates/types/object.h b/languages/cpp/templates/types/object.h index 88d35c97..4bf36f8e 100644 --- a/languages/cpp/templates/types/object.h +++ b/languages/cpp/templates/types/object.h @@ -1,3 +1,3 @@ struct ${title} { - ${properties} +${properties} }; \ No newline at end of file diff --git a/languages/cpp/templates/types/property.h b/languages/cpp/templates/types/property.h index 92de9ade..a0ea4ab1 100644 --- a/languages/cpp/templates/types/property.h +++ b/languages/cpp/templates/types/property.h @@ -1 +1 @@ -${if.optional}std::optional<${end.if.optional}${title}${if.optional}>${end.if.optional} ${property}; + ${if.optional}std::optional<${end.if.optional}${title}${if.optional}>${end.if.optional} ${property}; diff --git a/languages/javascript/templates/types/object.mjs b/languages/javascript/templates/types/object.mjs index 9c30308e..78965d52 100644 --- a/languages/javascript/templates/types/object.mjs +++ b/languages/javascript/templates/types/object.mjs @@ -1,3 +1,3 @@ { - ${properties} +${properties} } diff --git a/languages/javascript/templates/types/property.mjs b/languages/javascript/templates/types/property.mjs index 5d3db0f5..2fc6076f 100644 --- a/languages/javascript/templates/types/property.mjs +++ b/languages/javascript/templates/types/property.mjs @@ -1 +1 @@ -${property}${if.optional}?${end.if.optional}: ${title} // ${summary} \ No newline at end of file + ${property}${if.optional}?${end.if.optional}: ${title} // ${summary} \ No newline at end of file diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 523b297b..70023eb1 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -68,13 +68,27 @@ const state = { const capitalize = str => str[0].toUpperCase() + str.substr(1) -const indent = (str, padding) => { +const indent = (str, paddingStr, repeat = 1, endRepeat = 0) => { let first = true - return str.split('\n').map(line => { + let padding = '' + for (let i = 0; i < repeat; i++) { + padding += paddingStr + } + + let length = str.split('\n').length - 1 + let endPadding = '' + for (let i = 0; length && i < endRepeat; i++) { + endPadding += paddingStr + } + + return str.split('\n').map((line, index) => { if (first) { first = false return line } + else if (index === length && endPadding) { + return endPadding + line + } else { return padding + line } @@ -1288,7 +1302,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) let paramInstantiation = event.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'callback-context-instantiation', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n') let resultInstantiation = types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-context-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) callbackInstantiation = callbackInstantiation - .replace(/\$\{callback\.param\.instantiation\.with\.indent\}/g, indent(paramInstantiation, ' ')) + .replace(/\$\{callback\.param\.instantiation\.with\.indent\}/g, indent(paramInstantiation, ' ', 2)) .replace(/\$\{callback\.result\.instantiation\}/g, resultInstantiation) } else { @@ -1412,7 +1426,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.pulls\.param\.json\.type\}/g, pullsForParamJsonType) .replace(/\$\{method\.pulls\.response\.initialization\}/g, pullsResponseInit) .replace(/\$\{method\.pulls\.response\.instantiation}/g, pullsResponseInst) - .replace(/\$\{method\.pulls\.result\.serialization\.with\.indent\}/g, indent(pullsResultSerialize, ' ')) + .replace(/\$\{method\.pulls\.result\.serialization\.with\.indent\}/g, indent(pullsResultSerialize, ' ', 3, 2)) .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/types.mjs b/src/macrofier/types.mjs index 9acc285a..b8b76016 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -267,6 +267,7 @@ const insertObjectAdditionalPropertiesMacros = (content, schema, module, title, return content } +const getIndents = level => level ? ' ' : '' const insertObjectMacros = (content, schema, module, title, property, options) => { const options2 = options ? JSON.parse(JSON.stringify(options)) : {} options2.parent = title @@ -274,9 +275,9 @@ const insertObjectMacros = (content, schema, module, title, property, options) = options2.level = options.level + 1 options2.templateDir = options.templateDir ;(['properties', 'properties.register', 'properties.assign']).forEach(macro => { - const indent = (content.split('\n').find(line => line.includes("${" + macro + "}")) || '').match(/^\s+/) || [''][0] + const indent = getIndents(options.parentLevel || (options.level ? 1 : 0)) const templateType = macro.split('.').slice(1).join('') - const template = getTemplate(path.join(options.templateDir, 'property' + (templateType ? `-${templateType}` : ''))).replace(/\n/gms, indent + '\n') + const template = getTemplate(path.join(options.templateDir, 'property' + (templateType ? `-${templateType}` : ''))).replace(/\n/gms, '\n' + indent) const properties = [] if (schema.properties) { Object.entries(schema.properties).forEach(([name, prop], i) => { @@ -286,11 +287,12 @@ const insertObjectMacros = (content, schema, module, title, property, options) = const objSeparator = getTemplate(path.join(options2.templateDir, 'object-separator')) if (localizedProp.type === 'array' || localizedProp.anyOf || localizedProp.oneOf || (typeof localizedProp.const === 'string')) { options2.property = name + options2.required = schema.required } else { options2.property = options.property + options2.required = schema.required && schema.required.includes(name) } - options2.required = schema.required - const schemaShape = getSchemaShape(localizedProp, module, options2) + const schemaShape = indent + getSchemaShape(localizedProp, module, options2).replace(/\n/gms, '\n' + indent) const type = getSchemaType(localizedProp, module, options2) // don't push properties w/ unsupported types if (type) { @@ -331,7 +333,7 @@ const insertObjectMacros = (content, schema, module, title, property, options) = .replace(/\$\{obj\.separator}/g, objSeparator) .replace(/\$\{base.title\}/g, (baseTitle ? (baseTitle)[0].toLowerCase() + (baseTitle).substr(1) : '')).trimEnd() .replace(/\$\{base.Title\}/g, (baseTitle ? (baseTitle)[0].toUpperCase() + (baseTitle).substr(1) : '')).trimEnd() - properties.push((i !== 0 ? indent : '') + replacedTemplate) + properties.push(replacedTemplate) } }) } @@ -363,7 +365,7 @@ const insertObjectMacros = (content, schema, module, title, property, options) = if (type) { options2.property = prop const schemaShape = getSchemaShape(type, module, options2) - properties.push((i !== 0 ? indent : '') + template + properties.push(template .replace(/\$\{property\}/g, safeName(prop)) .replace(/\$\{Property\}/g, capitalize(safeName(prop))) .replace(/\$\{parent\.title\}/g, title) From c2cc7e59ac756d3d1156cc982934e41fa38b89c2 Mon Sep 17 00:00:00 2001 From: Jeremy LaCivita Date: Thu, 14 Dec 2023 12:00:02 -0500 Subject: [PATCH 122/137] fix: Copy allow-focus tag to use methods --- src/openrpc/index.mjs | 6 +++++- src/shared/modules.mjs | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/openrpc/index.mjs b/src/openrpc/index.mjs index e0819b7f..571429c6 100644 --- a/src/openrpc/index.mjs +++ b/src/openrpc/index.mjs @@ -17,7 +17,7 @@ */ import { readJson, readFiles, readDir, writeJson } from "../shared/filesystem.mjs" -import { addExternalMarkdown, addExternalSchemas, fireboltize } from "../shared/modules.mjs" +import { addExternalMarkdown, addExternalSchemas, fireboltize, fireboltizeMerged } from "../shared/modules.mjs" import path from "path" import { logHeader, logSuccess } from "../shared/io.mjs" @@ -87,6 +87,8 @@ const run = async ({ } + + // add methods from this module openrpc.methods.push(...json.methods) @@ -101,6 +103,8 @@ const run = async ({ logSuccess(`Generated the ${json.info.title} module.`) }) + openrpc = fireboltizeMerged(openrpc) + await writeJson(output, openrpc) console.log() diff --git a/src/shared/modules.mjs b/src/shared/modules.mjs index f1efc1bc..94137a54 100644 --- a/src/shared/modules.mjs +++ b/src/shared/modules.mjs @@ -746,6 +746,18 @@ const createResponseFromProvider = (provider, type, json) => { return response } +const copyAllowFocusTags = (json) => { + // for each allow focus provider method, set the value on any `use` methods that share the same capability + json.methods.filter(m => m.tags.find(t => t['x-allow-focus'] && t['x-provides'])).forEach(method => { + const cap = method.tags.find(t => t.name === "capabilities")['x-provides'] + json.methods.filter(m => m.tags.find(t => t['x-uses'] && t['x-uses'].includes(cap))).forEach(useMethod => { + useMethod.tags.find(t => t.name === "capabilities")['x-allow-focus'] = true + }) + }) + + return json +} + const generatePropertyEvents = json => { const properties = json.methods.filter( m => m.tags && m.tags.find( t => t.name == 'property')) || [] const readonlies = json.methods.filter( m => m.tags && m.tags.find( t => t.name == 'property:readonly')) || [] @@ -1021,6 +1033,12 @@ const fireboltize = (json) => { return json } +const fireboltizeMerged = (json) => { + json = copyAllowFocusTags(json) + + return json +} + const getExternalMarkdownPaths = obj => { return getExternalSchemaPaths(obj) .filter(x => /^file:/.test(getPathOr(null, x, obj))) @@ -1304,6 +1322,7 @@ export { getSchemas, getParamsFromMethod, fireboltize, + fireboltizeMerged, getPayloadFromEvent, getPathFromModule, providerHasNoParameters, From 8901760df09fa8ca1f895598bbd4ce5e93614061 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Fri, 15 Dec 2023 20:09:04 +0530 Subject: [PATCH 123/137] CPPSDK: calls metrics support added (#158) * CPPSDK: calls metrics support added --- .../sub-property/anyOfSchemaShape.cpp | 2 +- .../sub-property/const.cpp | 2 +- .../sub-property/generic.cpp | 2 +- .../sub-property/property.cpp | 2 +- .../sub-property/anyOfSchemaShape.cpp | 6 ++-- .../sub-property/const.cpp | 6 ++-- .../sub-property/object.cpp | 2 +- .../sub-property/property.cpp | 6 ++-- .../declarations-override/calls-metrics.h | 5 ++++ .../templates/declarations/calls-metrics.h | 6 ++++ .../cpp/templates/imports/calls-metrics.impl | 1 + .../cpp/templates/methods/calls-metrics.cpp | 29 ++++++++++++++++++ .../cpp/templates/modules/src/module_impl.h | 2 ++ .../sub-property/anyOfSchemaShape.cpp | 4 +-- .../sub-property/array.cpp | 4 +-- .../sub-property/const.cpp | 4 +-- .../sub-property/property.cpp | 4 +-- .../sub-property/anyOfSchemaShape.cpp | 6 ++-- .../sub-property/object.cpp | 2 +- .../sub-property/property.cpp | 6 ++-- src/macrofier/engine.mjs | 30 +++++++++++-------- src/macrofier/index.mjs | 2 +- src/macrofier/types.mjs | 2 +- 23 files changed, 92 insertions(+), 43 deletions(-) create mode 100644 languages/cpp/templates/imports/calls-metrics.impl diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/anyOfSchemaShape.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/anyOfSchemaShape.cpp index f8d48279..c1981c75 100644 --- a/languages/cpp/templates/callback-context-instantiation/sub-property/anyOfSchemaShape.cpp +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/anyOfSchemaShape.cpp @@ -1,3 +1,3 @@ string ${property}Str; - response.${Property.dependency}${Property}.ToString(${property}Str); + response${Property.dependency}.${Property}.ToString(${property}Str); ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = ${property}Str; diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/const.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/const.cpp index 41bc1feb..fe8fb5a0 100644 --- a/languages/cpp/templates/callback-context-instantiation/sub-property/const.cpp +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/const.cpp @@ -1 +1 @@ - ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response.${Property.dependency}${Property}; + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response${Property.dependency}.${Property}; diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/generic.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/generic.cpp index 41bc1feb..fe8fb5a0 100644 --- a/languages/cpp/templates/callback-context-instantiation/sub-property/generic.cpp +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/generic.cpp @@ -1 +1 @@ - ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response.${Property.dependency}${Property}; + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response${Property.dependency}.${Property}; diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp index 4276ebc4..1616b444 100644 --- a/languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp +++ b/languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp @@ -1 +1 @@ -${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response.${Property.dependency}${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response${Property.dependency}.${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/anyOfSchemaShape.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/anyOfSchemaShape.cpp index 0c62eef4..25269b21 100644 --- a/languages/cpp/templates/callback-result-instantiation/sub-property/anyOfSchemaShape.cpp +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/anyOfSchemaShape.cpp @@ -1,7 +1,7 @@ - ${if.optional}if (proxyResponse->${Property.dependency}${Property}.IsSet()) { + ${if.optional}if ((*proxyResponse)${Property.dependency}.${Property}.IsSet()) { string ${property}Str; - proxyResponse->${Property.dependency}${Property}.ToString(${property}Str); + (*proxyResponse)${Property.dependency}.${Property}.ToString(${property}Str); ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = ${property}Str; }${end.if.optional}${if.non.optional}string ${property}Str; - proxyResponse->${Property.dependency}${Property}.ToString(${property}Str); + (*proxyResponse)${Property.dependency}.${Property}.ToString(${property}Str); ${base.title}${property.dependency}.${property} = ${property}Str;${end.if.non.optional} diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/const.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/const.cpp index b005a326..d7969951 100644 --- a/languages/cpp/templates/callback-result-instantiation/sub-property/const.cpp +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/const.cpp @@ -1,3 +1,3 @@ - ${if.optional}if (proxyResponse->${Property.dependency}${Property}.IsSet()) { - ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = proxyResponse->${Property.dependency}${Property}; - }${end.if.optional}${if.non.optional}${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = proxyResponse->${Property.dependency}${Property};${end.if.non.optional} \ No newline at end of file + ${if.optional}if ((*proxyResponse)${Property.dependency}.${Property}.IsSet()) { + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = (*proxyResponse)${Property.dependency}.${Property}; + }${end.if.optional}${if.non.optional}${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = (*proxyResponse)${Property.dependency}.${Property};${end.if.non.optional} \ No newline at end of file diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp index cd86ff1a..f41b4a30 100644 --- a/languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/object.cpp @@ -1,4 +1,4 @@ -${if.optional} if (proxyResponse->${Property.dependency}IsSet()) { +${if.optional} if ((*proxyResponse)${Property.dependency}.IsSet()) { ${base.title}${property.dependency} = std::make_optional<${type}>(); ${properties} }${end.if.optional}${if.non.optional} { diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp index f8bfa268..8cd83ce0 100644 --- a/languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/property.cpp @@ -1,3 +1,3 @@ -${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${if.optional}if (proxyResponse->${Property.dependency}${Property}.IsSet()) { - ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = proxyResponse->${Property.dependency}${Property}; - }${end.if.optional}${if.non.optional}${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = proxyResponse->${Property.dependency}${Property};${end.if.non.optional}${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${if.optional}if ((*proxyResponse)${Property.dependency}.${Property}.IsSet()) { + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = (*proxyResponse)${Property.dependency}.${Property}; + }${end.if.optional}${if.non.optional}${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = (*proxyResponse)${Property.dependency}.${Property};${end.if.non.optional}${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} diff --git a/languages/cpp/templates/declarations-override/calls-metrics.h b/languages/cpp/templates/declarations-override/calls-metrics.h index e69de29b..47554196 100644 --- a/languages/cpp/templates/declarations-override/calls-metrics.h +++ b/languages/cpp/templates/declarations-override/calls-metrics.h @@ -0,0 +1,5 @@ + /* + ${method.name} + ${method.description} + */ + ${method.signature.result} ${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr )${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} override; diff --git a/languages/cpp/templates/declarations/calls-metrics.h b/languages/cpp/templates/declarations/calls-metrics.h index e69de29b..fa1890c5 100644 --- a/languages/cpp/templates/declarations/calls-metrics.h +++ b/languages/cpp/templates/declarations/calls-metrics.h @@ -0,0 +1,6 @@ + /* + ${method.name} + ${method.description} + ${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation}${end.if.deprecated} + */ + virtual ${method.signature.result} ${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr )${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} = 0; diff --git a/languages/cpp/templates/imports/calls-metrics.impl b/languages/cpp/templates/imports/calls-metrics.impl new file mode 100644 index 00000000..75fd87c6 --- /dev/null +++ b/languages/cpp/templates/imports/calls-metrics.impl @@ -0,0 +1 @@ +#include "metrics_impl.h" diff --git a/languages/cpp/templates/methods/calls-metrics.cpp b/languages/cpp/templates/methods/calls-metrics.cpp index e69de29b..67b67d22 100644 --- a/languages/cpp/templates/methods/calls-metrics.cpp +++ b/languages/cpp/templates/methods/calls-metrics.cpp @@ -0,0 +1,29 @@ + /* ${method.rpc.name} - ${method.description} */ + static void ${method.name}Dispatcher(const void* result) { + Metrics::MetricsImpl::${method.name}(${if.result.nonboolean}${if.result.nonvoid}(static_cast<${method.result.json.type}>(const_cast(result)))${end.if.result.nonvoid}${end.if.result.nonboolean}); + } + /* ${method.rpc.name} - ${method.description} */ + ${method.signature.result} ${info.Title}Impl::${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err ) ${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} + { + Firebolt::Error status = Firebolt::Error::NotConnected; +${if.result.nonvoid}${method.result.initialization}${end.if.result.nonvoid} + FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); + if (transport != nullptr) { + + JsonObject jsonParameters; + ${method.params.serialization.with.indent} + ${method.result.json.type} jsonResult; + status = transport->Invoke("${info.title.lowercase}.${method.rpc.name}", jsonParameters, jsonResult); + if (status == Firebolt::Error::None) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); + ${if.result.nonvoid}${method.result.instantiation.with.indent}${end.if.result.nonvoid} + WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(${method.name}Dispatcher, nullptr)); + WPEFramework::Core::IWorkerPool::Instance().Submit(job); + } + + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Transport err = %d", status); + } + + return${if.result.nonvoid} ${method.result.name}${end.if.result.nonvoid}; + } diff --git a/languages/cpp/templates/modules/src/module_impl.h b/languages/cpp/templates/modules/src/module_impl.h index 33e6e005..ce2837f4 100644 --- a/languages/cpp/templates/modules/src/module_impl.h +++ b/languages/cpp/templates/modules/src/module_impl.h @@ -16,6 +16,8 @@ * SPDX-License-Identifier: Apache-2.0 */ +#pragma once + #include "FireboltSDK.h" #include "IModule.h" /* ${IMPORTS} */ diff --git a/languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp b/languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp index 7ac47b35..5e750f10 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/anyOfSchemaShape.cpp @@ -1,3 +1,3 @@ ${if.optional}if (element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}.has_value()) { - ${base.title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}.value(); - }${end.if.optional}${if.non.optional}${base.title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property};${end.if.non.optional} \ No newline at end of file + ${base.title}Container${Property.dependency}.${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}.value(); + }${end.if.optional}${if.non.optional}${base.title}Container${Property.dependency}.${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property};${end.if.non.optional} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/array.cpp b/languages/cpp/templates/parameter-serialization/sub-property/array.cpp index cf5bb5f2..331d59a8 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/array.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/array.cpp @@ -4,10 +4,10 @@ for (auto& element : ${property}) { ${if.object}${items.with.indent}${end.if.object}${if.non.object} ${property}Array.Add() = element;${end.if.non.object} } - ${base.title}Container.${Property.dependency}Add(_T("${property}"), &${property}Array); + ${base.title}Container${Property.dependency}.${Property} = ${property}Array; }${end.if.impl.array.optional}${if.impl.array.non.optional}WPEFramework::Core::JSON::ArrayType<${json.type}> ${property}Array; ${type} ${property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}; for (auto& element : ${property}) { ${if.object}${items.with.indent}${end.if.object}${if.non.object} ${property}Array.Add() = element;${end.if.non.object} } - ${base.title}Container.${Property.dependency}Add(_T("${property}"), &${property}Array);${end.if.impl.array.non.optional} + ${base.title}Container${Property.dependency}.${Property} = ${property}Array;${end.if.impl.array.non.optional} diff --git a/languages/cpp/templates/parameter-serialization/sub-property/const.cpp b/languages/cpp/templates/parameter-serialization/sub-property/const.cpp index fa81c8f4..0d25c572 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/const.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/const.cpp @@ -1,3 +1,3 @@ ${if.optional}if (element${property.dependency}.${property}.has_value()) { - ${base.title}Container.${Property.dependency}${Property} = element${property.dependency}.${property}.value(); - }${end.if.optional}${if.non.optional}${base.title}Container.${Property.dependency}${Property} = element${property.dependency}.${property};${end.if.non.optional} \ No newline at end of file + ${base.title}Container${Property.dependency}.${Property} = element${property.dependency}.${property}.value(); + }${end.if.optional}${if.non.optional}${base.title}Container${Property.dependency}.${Property} = element${property.dependency}.${property};${end.if.non.optional} \ No newline at end of file diff --git a/languages/cpp/templates/parameter-serialization/sub-property/property.cpp b/languages/cpp/templates/parameter-serialization/sub-property/property.cpp index b7341e97..e52679d3 100644 --- a/languages/cpp/templates/parameter-serialization/sub-property/property.cpp +++ b/languages/cpp/templates/parameter-serialization/sub-property/property.cpp @@ -1,3 +1,3 @@ ${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${if.optional}if (element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}.has_value()) { - ${base.title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}.value(); - }${end.if.optional}${if.non.optional}${base.title}Container.${Property.dependency}${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property};${end.if.non.optional}${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file + ${base.title}Container${Property.dependency}.${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}.value(); + }${end.if.optional}${if.non.optional}${base.title}Container${Property.dependency}.${Property} = element${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property};${end.if.non.optional}${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/result-instantiation/sub-property/anyOfSchemaShape.cpp b/languages/cpp/templates/result-instantiation/sub-property/anyOfSchemaShape.cpp index 75d9be83..4398ae8b 100644 --- a/languages/cpp/templates/result-instantiation/sub-property/anyOfSchemaShape.cpp +++ b/languages/cpp/templates/result-instantiation/sub-property/anyOfSchemaShape.cpp @@ -1,7 +1,7 @@ - ${if.optional}if (jsonResult.${Property.dependency}${Property}.IsSet()) { + ${if.optional}if (jsonResult${Property.dependency}.${Property}.IsSet()) { string ${property}Str; - jsonResult.${Property.dependency}${Property}.ToString(${property}Str); + jsonResult${Property.dependency}.${Property}.ToString(${property}Str); ${base.title}Result${level}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = ${property}Str; }${end.if.optional}${if.non.optional}string ${property}Str; - jsonResult.${Property.dependency}${Property}.ToString(${property}Str); + jsonResult${Property.dependency}.${Property}.ToString(${property}Str); ${base.title}Result${level}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = ${property}Str;${end.if.non.optional} diff --git a/languages/cpp/templates/result-instantiation/sub-property/object.cpp b/languages/cpp/templates/result-instantiation/sub-property/object.cpp index bb793a66..4d789f75 100644 --- a/languages/cpp/templates/result-instantiation/sub-property/object.cpp +++ b/languages/cpp/templates/result-instantiation/sub-property/object.cpp @@ -1,4 +1,4 @@ -${if.optional} if (jsonResult.${Property.dependency}IsSet()) { +${if.optional} if (jsonResult${Property.dependency}.IsSet()) { ${base.title}Result${level}${property.dependency} = std::make_optional<${type}>(); ${properties} }${end.if.optional}${if.non.optional} { diff --git a/languages/cpp/templates/result-instantiation/sub-property/property.cpp b/languages/cpp/templates/result-instantiation/sub-property/property.cpp index 83d14805..98f5fbb4 100644 --- a/languages/cpp/templates/result-instantiation/sub-property/property.cpp +++ b/languages/cpp/templates/result-instantiation/sub-property/property.cpp @@ -1,3 +1,3 @@ -${shape} ${if.non.anyOf}${if.non.array}${if.non.object}${if.optional}if (jsonResult.${Property.dependency}${Property}.IsSet()) { - ${base.title}Result${level}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = jsonResult.${Property.dependency}${Property}; - }${end.if.optional}${if.non.optional}${base.title}Result${level}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = jsonResult.${Property.dependency}${Property};${end.if.non.optional}${end.if.non.object}${end.if.non.array}${end.if.non.anyOf} +${shape} ${if.non.anyOf}${if.non.array}${if.non.object}${if.optional}if (jsonResult${Property.dependency}.${Property}.IsSet()) { + ${base.title}Result${level}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = jsonResult${Property.dependency}.${Property}; + }${end.if.optional}${if.non.optional}${base.title}Result${level}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = jsonResult${Property.dependency}.${Property};${end.if.non.optional}${end.if.non.object}${end.if.non.array}${end.if.non.anyOf} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 70023eb1..f1f4e984 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -980,6 +980,20 @@ function getRelatedSchemaLinks(schema = {}, json = {}, templates = {}, options = return links } +function getTemplateFromDestination(destination, templateName, templates) { + const destinationArray = destination.split('/').pop().split(/[_.]+/) + + let template = '' + destinationArray.filter(value => value).every((suffix) => { + template = getTemplate(templateName +`.${suffix}`, templates) + return template ? false: true + }) + if (!template) { + template = getTemplate(templateName, templates) + } + return template +} + const generateImports = (json, templates, options = { destination: '' }) => { let imports = '' @@ -1011,21 +1025,11 @@ const generateImports = (json, templates, options = { destination: '' }) => { imports += getTemplate('/imports/x-method', templates) } - const suffix = options.destination.split('.').pop() if (callsMetrics(json).length) { - imports += getTemplate(suffix ? `/imports/calls-metrics.${suffix}` : '/imports/calls-metrics', 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('/imports/default', templates) + imports += getTemplateFromDestination(options.destination, '/imports/calls-metrics', templates) } + let template = getTemplateFromDestination(options.destination, '/imports/default', templates) if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0 && !json.info['x-uri-titles']) { imports += Object.keys(json['x-schemas']).map(shared => template.replace(/\$\{info.title.lowercase\}/g, shared.toLowerCase())).join('') } @@ -1312,6 +1316,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) // hmm... how is this different from callbackSerializedList? i guess they get merged? const callbackResponseInst = event ? (event.params && event.params.length ? (event.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'callback-response-instantiation', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join(', ')) + ', ' : '' ) + (types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-response-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })) : '' const resultType = result.schema ? types.getSchemaType(result.schema, json, { templateDir: state.typeTemplateDir }) : '' + const resultSchemaType = result.schema.type const resultJsonType = result.schema ? types.getSchemaType(result.schema, json, { templateDir: 'json-types' }) : '' const resultParams = generateResultParams(result.schema, json, templates, { name: result.name}) @@ -1357,6 +1362,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .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.nonboolean\}(.*?)\$\{end\.if\.result.nonboolean\}/gms, resultSchemaType && resultSchemaType !== 'boolean' ? '$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' : '') diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index f2923717..c6cf1595 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -133,7 +133,7 @@ const macrofy = async ( const staticCodeList = staticContent ? await readDir(staticContent, { recursive: true }) : [] const staticModules = staticModuleNames.map(name => ( { info: { title: name } } )) - + let modules if (hidePrivate) { modules = moduleList.map(name => getModule(name, openrpc, copySchemasIntoModules, extractSubSchemas)).filter(hasPublicAPIs) diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index b8b76016..435db418 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -319,7 +319,7 @@ const insertObjectMacros = (content, schema, module, title, property, options) = .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, schema.required && schema.required.includes(name) ? '' : '$1') .replace(/\$\{if\.impl.non.optional\}(.*?)\$\{end\.if\.impl.non.optional\}/gms, schema.required && schema.required.includes(name) ? '$1' : '') .replace(/\$\{property.dependency\}/g, ((options.level > 0) ? '${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}' : '') + objSeparator + name) - .replace(/\$\{Property.dependency\}/g, ((options.level > 0) ? '${Property.dependency}' : '') + capitalize(name) + (objSeparator)) + .replace(/\$\{Property.dependency\}/g, ((options.level > 0) ? '${Property.dependency}' : '') + (objSeparator) + capitalize(name)) } else { if (options2.level <= 1) { From 4a637898fd43b60e7e8958ad8cb5b0bde12daa7a Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Tue, 19 Dec 2023 20:50:19 +0530 Subject: [PATCH 124/137] CPPSDK: handle patternProperties (#160) --- .../patternProperties.cpp | 9 +++ src/macrofier/types.mjs | 59 ++++++++++++++++--- 2 files changed, 59 insertions(+), 9 deletions(-) create mode 100644 languages/cpp/templates/parameter-serialization/patternProperties.cpp diff --git a/languages/cpp/templates/parameter-serialization/patternProperties.cpp b/languages/cpp/templates/parameter-serialization/patternProperties.cpp new file mode 100644 index 00000000..9346bb6b --- /dev/null +++ b/languages/cpp/templates/parameter-serialization/patternProperties.cpp @@ -0,0 +1,9 @@ + ${if.impl.optional}if (${property}.has_value()) { + WPEFramework::Core::JSON::VariantContainer ${property}Container; + ${property}Container.FromString(${property}.value()); + WPEFramework::Core::JSON::Variant ${property}Variant(${property}Container); + jsonParameters.Set(_T("${property}"), ${property}Variant); + }${end.if.impl.optional}${if.impl.non.optional}WPEFramework::Core::JSON::VariantContainer ${property}Container; + ${property}Container.FromString(${property}); + WPEFramework::Core::JSON::Variant ${property}Variant(${property}Container); + jsonParameters.Set(_T("${property}"), ${property}Variant);${end.if.impl.non.optional} diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index 435db418..1d2378c0 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -267,6 +267,36 @@ const insertObjectAdditionalPropertiesMacros = (content, schema, module, title, return content } +const insertObjectPatternPropertiesMacros = (content, schema, module, title, options) => { + const options2 = options ? JSON.parse(JSON.stringify(options)) : {} + options2.parent = title + options2.level = options.level + 1 + options2.required = options.required + + let patternSchema; + Object.entries(schema.patternProperties).forEach(([pattern, sch]) => { + patternSchema = sch + }) + + if (patternSchema) { + const shape = getSchemaShape(patternSchema, module, options2) + let type = getSchemaType(patternSchema, module, options2).trimEnd() + const propertyNames = localizeDependencies(schema, module).propertyNames + + content = content + .replace(/\$\{shape\}/g, shape) + .replace(/\$\{parent\.title\}/g, title) + .replace(/\$\{title\}/g, title) + .replace(/\$\{type\}/g, type) + .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, '') + .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/g, '') + .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/g, options.required ? '' : '$1') + .replace(/\$\{if\.impl.non.optional\}(.*?)\$\{end\.if\.impl.non.optional\}/g, options.required ? '$1' : '') + } + + return content +} + const getIndents = level => level ? ' ' : '' const insertObjectMacros = (content, schema, module, title, property, options) => { const options2 = options ? JSON.parse(JSON.stringify(options)) : {} @@ -526,8 +556,13 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren shape = insertObjectAdditionalPropertiesMacros(additionalPropertiesTemplate, schema, module, theTitle, { level, parent, templateDir, namespace: true, required }) } else { - let objectLevel = array ? 0 : level - shape = insertObjectMacros(getTemplate(path.join(templateDir, 'object' + (array ? '-array' : '') + suffix)) || genericTemplate, schema, module, theTitle, property, { parentLevel, level: objectLevel, parent, property, required, templateDir, descriptions, destination, section, enums, namespace: true, primitive }) + const patternPropertiesTemplate = getTemplate(path.join(templateDir, 'patternProperties')) + if (patternPropertiesTemplate && schema.patternProperties) { + shape = insertObjectPatternPropertiesMacros(patternPropertiesTemplate, schema, module, theTitle, { level, parent, templateDir, namespace: true, required }) + } else { + let objectLevel = array ? 0 : level + shape = insertObjectMacros(getTemplate(path.join(templateDir, 'object' + (array ? '-array' : '') + suffix)) || genericTemplate, schema, module, theTitle, property, { parentLevel, level: objectLevel, parent, property, required, templateDir, descriptions, destination, section, enums, namespace: true, primitive }) + } } result = result.replace(/\$\{shape\}/g, shape) if (level === 0) { @@ -806,17 +841,23 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin // } } else if (schema.type) { - const template = getTemplate(path.join(templateDir, 'additionalProperties')) + let template = getTemplate(path.join(templateDir, 'additionalProperties')) if (schema.additionalProperties && template ) { return insertSchemaMacros(getTemplate(path.join(templateDir, 'Title')), schema, module, { name: theTitle, recursive: false }) } else { - // TODO: this assumes that when type is an array of types, that it's one other primative & 'null', which isn't necessarily true. - const schemaType = !Array.isArray(schema.type) ? schema.type : schema.type.find(t => t !== 'null') - const baseDir = (templateDir !== 'json-types' ? 'types': templateDir) - const primitive = getPrimitiveType(schemaType, baseDir) - const type = allocatedProxy ? allocatedPrimitiveProxies[schemaType] || primitive : primitive - return wrap(type, code ? '`' : '') + template = getTemplate(path.join(templateDir, 'patternProperties')) + if (schema.paternProperties && template ) { + return insertSchemaMacros(getTemplate(path.join(templateDir, 'Title')), schema, module, { name: theTitle, recursive: false }) + } + else { + // TODO: this assumes that when type is an array of types, that it's one other primative & 'null', which isn't necessarily true. + const schemaType = !Array.isArray(schema.type) ? schema.type : schema.type.find(t => t !== 'null') + const baseDir = (templateDir !== 'json-types' ? 'types': templateDir) + const primitive = getPrimitiveType(schemaType, baseDir) + const type = allocatedProxy ? allocatedPrimitiveProxies[schemaType] || primitive : primitive + return wrap(type, code ? '`' : '') + } } } else { From c2004830afc6129b6431ed0a8d04aa6ceeeaabde Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 21 Dec 2023 08:48:32 +0530 Subject: [PATCH 125/137] CPPSDK: polymorphic method schema creation changes (#159) --- languages/cpp/templates/codeblocks/setter.cpp | 4 ++-- .../cpp/templates/declarations-override/setter.h | 2 +- languages/cpp/templates/declarations/event.h | 2 +- .../templates/declarations/polymorphic-pull-event.h | 2 +- languages/cpp/templates/declarations/setter.h | 2 +- languages/cpp/templates/methods/calls-metrics.cpp | 8 ++++---- languages/cpp/templates/methods/default.cpp | 6 +++--- languages/cpp/templates/methods/event.cpp | 4 ++-- .../cpp/templates/methods/polymorphic-pull-event.cpp | 6 +++--- languages/cpp/templates/methods/polymorphic-pull.cpp | 6 +++--- languages/cpp/templates/methods/property.cpp | 4 ++-- src/macrofier/engine.mjs | 10 +++++----- src/macrofier/types.mjs | 8 ++++---- src/openrpc/index.mjs | 4 +--- src/shared/modules.mjs | 11 ++++++----- 15 files changed, 39 insertions(+), 40 deletions(-) diff --git a/languages/cpp/templates/codeblocks/setter.cpp b/languages/cpp/templates/codeblocks/setter.cpp index fa0e0901..8038cf8a 100644 --- a/languages/cpp/templates/codeblocks/setter.cpp +++ b/languages/cpp/templates/codeblocks/setter.cpp @@ -1,8 +1,8 @@ - /* ${method.rpc.name} - ${method.description} */ + /* ${method.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}"); + const string method = _T("${info.title.lowercase}.${method.name}"); JsonObject jsonParameters; ${if.params}${method.params.serialization}${end.if.params} diff --git a/languages/cpp/templates/declarations-override/setter.h b/languages/cpp/templates/declarations-override/setter.h index 8a843dc9..752833ff 100644 --- a/languages/cpp/templates/declarations-override/setter.h +++ b/languages/cpp/templates/declarations-override/setter.h @@ -1,5 +1,5 @@ /* - * ${method.rpc.name} + * ${method.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/event.h b/languages/cpp/templates/declarations/event.h index a29c245c..e9284523 100644 --- a/languages/cpp/templates/declarations/event.h +++ b/languages/cpp/templates/declarations/event.h @@ -1,6 +1,6 @@ /* ${method.name} - ${method.description} */ struct I${method.Name}Notification { - virtual void ${method.name}( ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${event.result.type} ) = 0; + virtual void ${method.rpc.name}( ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${event.result.type} ) = 0; }; // signature callback params: ${event.signature.callback.params} // method result properties : ${method.result.properties} diff --git a/languages/cpp/templates/declarations/polymorphic-pull-event.h b/languages/cpp/templates/declarations/polymorphic-pull-event.h index 7baed2cf..cb6e8dee 100644 --- a/languages/cpp/templates/declarations/polymorphic-pull-event.h +++ b/languages/cpp/templates/declarations/polymorphic-pull-event.h @@ -1,6 +1,6 @@ /* ${method.name} - ${method.description} */ struct I${method.Name}Notification { - virtual ${method.pulls.type} ${method.name}( ${method.pulls.param.type} ) = 0; + virtual ${method.pulls.type} ${method.rpc.name}( ${method.pulls.param.type} ) = 0; }; virtual void subscribe( I${method.Name}Notification& notification, Firebolt::Error *err = nullptr ) = 0; virtual void unsubscribe( I${method.Name}Notification& notification, Firebolt::Error *err = nullptr ) = 0; diff --git a/languages/cpp/templates/declarations/setter.h b/languages/cpp/templates/declarations/setter.h index 77659fcd..115f39f0 100644 --- a/languages/cpp/templates/declarations/setter.h +++ b/languages/cpp/templates/declarations/setter.h @@ -1,5 +1,5 @@ /* - ${method.rpc.name} + ${method.name} ${method.description} */ virtual void ${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr ) = 0; diff --git a/languages/cpp/templates/methods/calls-metrics.cpp b/languages/cpp/templates/methods/calls-metrics.cpp index 67b67d22..1b6765c6 100644 --- a/languages/cpp/templates/methods/calls-metrics.cpp +++ b/languages/cpp/templates/methods/calls-metrics.cpp @@ -1,8 +1,8 @@ - /* ${method.rpc.name} - ${method.description} */ + /* ${method.name} - ${method.description} */ static void ${method.name}Dispatcher(const void* result) { Metrics::MetricsImpl::${method.name}(${if.result.nonboolean}${if.result.nonvoid}(static_cast<${method.result.json.type}>(const_cast(result)))${end.if.result.nonvoid}${end.if.result.nonboolean}); } - /* ${method.rpc.name} - ${method.description} */ + /* ${method.name} - ${method.description} */ ${method.signature.result} ${info.Title}Impl::${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err ) ${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} { Firebolt::Error status = Firebolt::Error::NotConnected; @@ -13,9 +13,9 @@ JsonObject jsonParameters; ${method.params.serialization.with.indent} ${method.result.json.type} jsonResult; - status = transport->Invoke("${info.title.lowercase}.${method.rpc.name}", jsonParameters, jsonResult); + status = transport->Invoke("${info.title.lowercase}.${method.name}", jsonParameters, jsonResult); if (status == Firebolt::Error::None) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully invoked"); ${if.result.nonvoid}${method.result.instantiation.with.indent}${end.if.result.nonvoid} WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(${method.name}Dispatcher, nullptr)); WPEFramework::Core::IWorkerPool::Instance().Submit(job); diff --git a/languages/cpp/templates/methods/default.cpp b/languages/cpp/templates/methods/default.cpp index f1fb6e71..0b5b31bf 100644 --- a/languages/cpp/templates/methods/default.cpp +++ b/languages/cpp/templates/methods/default.cpp @@ -1,4 +1,4 @@ - /* ${method.rpc.name} - ${method.description} */ + /* ${method.name} - ${method.description} */ ${method.signature.result} ${info.Title}Impl::${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err ) ${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} { Firebolt::Error status = Firebolt::Error::NotConnected; @@ -9,9 +9,9 @@ JsonObject jsonParameters; ${method.params.serialization.with.indent} ${method.result.json.type} jsonResult; - status = transport->Invoke("${info.title.lowercase}.${method.rpc.name}", jsonParameters, jsonResult); + status = transport->Invoke("${info.title.lowercase}.${method.name}", jsonParameters, jsonResult); if (status == Firebolt::Error::None) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully invoked"); ${if.result.nonvoid}${method.result.instantiation.with.indent}${end.if.result.nonvoid} } diff --git a/languages/cpp/templates/methods/event.cpp b/languages/cpp/templates/methods/event.cpp index b46f2208..ec3ba93f 100644 --- a/languages/cpp/templates/methods/event.cpp +++ b/languages/cpp/templates/methods/event.cpp @@ -1,4 +1,4 @@ - /* ${method.rpc.name} - ${method.description} */ + /* ${method.name} - ${method.description} */ static void ${method.name}InnerCallback( void* notification, const void* userData, void* jsonResponse ) { ${event.callback.serialization} @@ -11,7 +11,7 @@ proxyResponse.Release(); I${info.Title}::I${method.Name}Notification& notifier = *(reinterpret_cast(notification)); - notifier.${method.name}(${event.callback.response.instantiation}); + notifier.${method.rpc.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 ) diff --git a/languages/cpp/templates/methods/polymorphic-pull-event.cpp b/languages/cpp/templates/methods/polymorphic-pull-event.cpp index 54da22d6..43a33df5 100644 --- a/languages/cpp/templates/methods/polymorphic-pull-event.cpp +++ b/languages/cpp/templates/methods/polymorphic-pull-event.cpp @@ -1,4 +1,4 @@ - /* ${method.rpc.name} - ${method.description} */ + /* ${method.name} - ${method.description} */ static void ${method.name}InnerCallback( void* notification, const void* userData, void* jsonResponse ) { ${event.callback.serialization} @@ -10,7 +10,7 @@ ${method.pulls.response.instantiation} I${info.Title}::I${method.Name}Notification& notifier = *(reinterpret_cast(notification)); - ${method.pulls.type} element = notifier.${method.name}(${method.pulls.param.title}); + ${method.pulls.type} element = notifier.${method.rpc.name}(${method.pulls.param.title}); Firebolt::Error status = Firebolt::Error::NotConnected; FireboltSDK::Transport* transport = FireboltSDK::Accessor::Instance().GetTransport(); if (transport != nullptr) { @@ -30,7 +30,7 @@ status = transport->Invoke("${info.title.lowercase}.${method.pulls.for}", jsonParameters, jsonResult); if (status == Firebolt::Error::None) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully pushed with status as %d", jsonResult.Value()); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully pushed with status as %d", jsonResult.Value()); } } else { diff --git a/languages/cpp/templates/methods/polymorphic-pull.cpp b/languages/cpp/templates/methods/polymorphic-pull.cpp index 7f8368d2..1146f2d1 100644 --- a/languages/cpp/templates/methods/polymorphic-pull.cpp +++ b/languages/cpp/templates/methods/polymorphic-pull.cpp @@ -1,4 +1,4 @@ - /* ${method.rpc.name} - ${method.description} */ + /* ${method.name} - ${method.description} */ ${method.signature.result} ${info.Title}Impl::${method.name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err ) ${if.result.nonvoid}${if.params.empty} const${end.if.params.empty}${end.if.result.nonvoid} { Firebolt::Error status = Firebolt::Error::NotConnected; @@ -9,9 +9,9 @@ JsonObject jsonParameters; ${method.params.serialization.with.indent} ${method.result.json.type} jsonResult; - status = transport->Invoke("${info.title.lowercase}.${method.rpc.name}", jsonParameters, jsonResult); + status = transport->Invoke("${info.title.lowercase}.${method.name}", jsonParameters, jsonResult); if (status == Firebolt::Error::None) { - FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.rpc.name} is successfully invoked"); + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully invoked"); ${if.result.nonvoid}${method.result.instantiation.with.indent}${end.if.result.nonvoid} } diff --git a/languages/cpp/templates/methods/property.cpp b/languages/cpp/templates/methods/property.cpp index 4fbe9fc4..607a6527 100644 --- a/languages/cpp/templates/methods/property.cpp +++ b/languages/cpp/templates/methods/property.cpp @@ -1,7 +1,7 @@ - /* ${method.rpc.name} - ${method.description} */ + /* ${method.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}"); + const string method = _T("${info.title.lowercase}.${method.name}"); ${if.params}${method.params.serialization}${end.if.params} ${method.result.json} jsonResult; ${method.result.initialization} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index f1f4e984..339c9785 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -503,10 +503,6 @@ return obj } const generateMacros = (obj, templates, languages, options = {}) => { - // for languages that don't support nested schemas, let's promote them to first-class schemas w/ titles - if (config.extractSubSchemas) { - obj = promoteAndNameSubSchemas(obj) - } if (options.createPolymorphicMethods) { let methods = [] obj.methods && obj.methods.forEach(method => { @@ -522,6 +518,10 @@ const generateMacros = (obj, templates, languages, options = {}) => { }) obj.methods = methods } + // for languages that don't support nested schemas, let's promote them to first-class schemas w/ titles + if (config.extractSubSchemas) { + obj = promoteAndNameSubSchemas(obj) + } // config.mergeAnyOfs = true // if (config.mergeAnyOfs) { @@ -1347,7 +1347,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\.rpc\.name\}/g, methodObj.title || methodObj.name) + .replace(/\$\{method\.rpc\.name\}/g, methodObj.rpc_name || methodObj.name) .replace(/\$\{method\.summary\}/g, methodObj.summary) .replace(/\$\{method\.description\}/g, methodObj.description || methodObj.summary) diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index 1d2378c0..393a7e75 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -336,8 +336,8 @@ const insertObjectMacros = (content, schema, module, title, property, options) = .replace(/\$\{description\}/g, prop.description || '') .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/gms, i === schema.properties.length - 1 ? '' : '$1') - .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, schema.required && schema.required.includes(name) ? '' : '$1') - .replace(/\$\{if\.non.optional\}(.*?)\$\{end\.if\.non.optional\}/gms, schema.required && schema.required.includes(name) ? '$1' : '') + .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, ((schema.required && schema.required.includes(name)) || (localizedProp.required && localizedProp.required === true)) ? '' : '$1') + .replace(/\$\{if\.non.optional\}(.*?)\$\{end\.if\.non.optional\}/gms, ((schema.required && schema.required.includes(name)) || (localizedProp.required && localizedProp.required === true)) ? '$1' : '') .replace(/\$\{if\.base\.optional\}(.*?)\$\{end\.if\.base\.optional\}/gms, options.required ? '' : '$1') .replace(/\$\{if\.non\.object\}(.*?)\$\{end\.if\.non\.object\}/gms, isObject(localizedProp) ? '' : '$1') .replace(/\$\{if\.non\.array\}(.*?)\$\{end\.if\.non\.array\}/gms, (localizedProp.type === 'array') ? '' : '$1') @@ -346,8 +346,8 @@ const insertObjectMacros = (content, schema, module, title, property, options) = let baseTitle = options.property if (isObject(localizedProp)) { replacedTemplate = replacedTemplate - .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, schema.required && schema.required.includes(name) ? '' : '$1') - .replace(/\$\{if\.impl.non.optional\}(.*?)\$\{end\.if\.impl.non.optional\}/gms, schema.required && schema.required.includes(name) ? '$1' : '') + .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, ((schema.required && schema.required.includes(name)) || (localizedProp.required && localizedProp.required === true)) ? '' : '$1') + .replace(/\$\{if\.impl.non.optional\}(.*?)\$\{end\.if\.impl.non.optional\}/gms, ((schema.required && schema.required.includes(name)) || (localizedProp.required && localizedProp.required === true)) ? '$1' : '') .replace(/\$\{property.dependency\}/g, ((options.level > 0) ? '${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}' : '') + objSeparator + name) .replace(/\$\{Property.dependency\}/g, ((options.level > 0) ? '${Property.dependency}' : '') + (objSeparator) + capitalize(name)) } diff --git a/src/openrpc/index.mjs b/src/openrpc/index.mjs index 571429c6..b1f6175a 100644 --- a/src/openrpc/index.mjs +++ b/src/openrpc/index.mjs @@ -87,8 +87,6 @@ const run = async ({ } - - // add methods from this module openrpc.methods.push(...json.methods) @@ -113,4 +111,4 @@ const run = async ({ return Promise.resolve() } -export default run \ No newline at end of file +export default run diff --git a/src/shared/modules.mjs b/src/shared/modules.mjs index 02490c18..fc28aa66 100644 --- a/src/shared/modules.mjs +++ b/src/shared/modules.mjs @@ -886,7 +886,7 @@ const getAnyOfSchema = (inType, json) => { const generateAnyOfSchema = (anyOf, name, summary) => { let anyOfType = {} - anyOfType["name"] = name[0].toLowerCase() + name.substr(1) + anyOfType["name"] = name; anyOfType["summary"] = summary anyOfType["schema"] = anyOf return anyOfType @@ -896,7 +896,7 @@ const generateParamsAnyOfSchema = (methodParams, anyOf, anyOfTypes, title, summa let params = [] methodParams.forEach(p => { if (p.schema.anyOf === anyOfTypes) { - let anyOfType = generateAnyOfSchema(anyOf, title, summary) + let anyOfType = generateAnyOfSchema(anyOf, p.name, summary) anyOfType.required = p.required params.push(anyOfType) } @@ -937,6 +937,7 @@ const createPolymorphicMethods = (method, json) => { let anyOfTypes let methodParams = [] let methodResult = Object.assign({}, method.result) + method.params.forEach(p => { if (p.schema) { let param = getAnyOfSchema(p, json) @@ -979,12 +980,12 @@ const createPolymorphicMethods = (method, json) => { let localized = localizeDependencies(anyOf, json) let title = localized.title || localized.name || '' let summary = localized.summary || localized.description || '' - polymorphicMethodSchema.title = method.name - polymorphicMethodSchema.name = foundAnyOfParams ? `${method.name}With${title}` : `${method.name}${title}` + polymorphicMethodSchema.rpc_name = method.name + polymorphicMethodSchema.name = foundAnyOfResult && isEventMethod(method) ? `${method.name}${title}` : method.name polymorphicMethodSchema.tags = method.tags polymorphicMethodSchema.params = foundAnyOfParams ? generateParamsAnyOfSchema(methodParams, anyOf, anyOfTypes, title, summary) : methodParams polymorphicMethodSchema.result = Object.assign({}, method.result) - polymorphicMethodSchema.result.schema = foundAnyOfResult ? generateResultAnyOfSchema(method, methodResult, anyOf, anyOfTypes, title, summary) : methodResult + polymorphicMethodSchema.result.schema = foundAnyOfResult ? generateResultAnyOfSchema(method, methodResult, anyOf, anyOfTypes, title, summary) : methodResult.schema polymorphicMethodSchema.examples = method.examples polymorphicMethodSchemas.push(Object.assign({}, polymorphicMethodSchema)) }) From f3593b13531314cebcc24e83061cd93ae33a0d14 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Wed, 3 Jan 2024 22:45:53 +0530 Subject: [PATCH 126/137] CPPSDK: changes to handle context params (#161) --- .../additionalProperties.cpp | 6 ---- .../callback-context-instantiation/anyOf.cpp | 1 - .../callback-context-instantiation/array.cpp | 6 ---- .../callback-context-instantiation/enum.cpp | 3 -- .../callback-context-instantiation/object.cpp | 8 ----- .../property.cpp | 1 - .../sub-property/anyOfSchemaShape.cpp | 3 -- .../sub-property/array.cpp | 5 ---- .../sub-property/const.cpp | 1 - .../sub-property/generic.cpp | 1 - .../sub-property/object-array.cpp | 4 --- .../sub-property/object.cpp | 4 --- .../sub-property/property.cpp | 1 - .../callback-context-instantiation/tuple.cpp | 4 --- .../generic.cpp | 1 + .../primitive.cpp | 1 + .../callback-instantiation/generic.cpp | 30 ++++++++++++------- .../generic.cpp} | 2 +- .../additionalProperties.cpp | 4 +++ .../callback-value-instantiation/anyOf.cpp | 1 + .../callback-value-instantiation/array.cpp | 4 +++ .../callback-value-instantiation/enum.cpp | 1 + .../callback-value-instantiation/generic.cpp | 1 + .../namespace.cpp | 0 .../callback-value-instantiation/object.cpp | 6 ++++ .../primitive.cpp | 1 + .../callback-value-instantiation/property.cpp | 1 + .../ref.h | 0 .../callback-value-instantiation/string.cpp | 1 + .../sub-property/anyOf.cpp | 0 .../sub-property/anyOfSchemaShape.cpp | 3 ++ .../sub-property/array.cpp | 5 ++++ .../sub-property/const.cpp | 1 + .../sub-property/generic.cpp | 1 + .../sub-property/namespace.cpp | 0 .../sub-property/object-array.cpp | 4 +++ .../sub-property/object-separator.cpp | 0 .../sub-property/object.cpp | 4 +++ .../sub-property/property.cpp | 1 + .../sub-property/ref.h | 1 + .../sub-property/title.cpp | 0 .../title.cpp | 0 .../callback-value-instantiation/tuple.cpp | 2 ++ languages/cpp/templates/declarations/event.h | 2 +- src/macrofier/engine.mjs | 26 +++++++++++----- src/macrofier/types.mjs | 7 ++++- 46 files changed, 90 insertions(+), 69 deletions(-) delete mode 100644 languages/cpp/templates/callback-context-instantiation/additionalProperties.cpp delete mode 100644 languages/cpp/templates/callback-context-instantiation/anyOf.cpp delete mode 100644 languages/cpp/templates/callback-context-instantiation/array.cpp delete mode 100644 languages/cpp/templates/callback-context-instantiation/enum.cpp delete mode 100644 languages/cpp/templates/callback-context-instantiation/object.cpp delete mode 100644 languages/cpp/templates/callback-context-instantiation/property.cpp delete mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/anyOfSchemaShape.cpp delete mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/array.cpp delete mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/const.cpp delete mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/generic.cpp delete mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/object-array.cpp delete mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/object.cpp delete mode 100644 languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp delete mode 100644 languages/cpp/templates/callback-context-instantiation/tuple.cpp create mode 100644 languages/cpp/templates/callback-initialization-optional/generic.cpp create mode 100644 languages/cpp/templates/callback-initialization-optional/primitive.cpp rename languages/cpp/templates/{callback-context-instantiation/string.cpp => callback-value-initialization/generic.cpp} (54%) create mode 100644 languages/cpp/templates/callback-value-instantiation/additionalProperties.cpp create mode 100644 languages/cpp/templates/callback-value-instantiation/anyOf.cpp create mode 100644 languages/cpp/templates/callback-value-instantiation/array.cpp create mode 100644 languages/cpp/templates/callback-value-instantiation/enum.cpp create mode 100644 languages/cpp/templates/callback-value-instantiation/generic.cpp rename languages/cpp/templates/{callback-context-instantiation => callback-value-instantiation}/namespace.cpp (100%) create mode 100644 languages/cpp/templates/callback-value-instantiation/object.cpp create mode 100644 languages/cpp/templates/callback-value-instantiation/primitive.cpp create mode 100644 languages/cpp/templates/callback-value-instantiation/property.cpp rename languages/cpp/templates/{callback-context-instantiation/sub-property => callback-value-instantiation}/ref.h (100%) create mode 100644 languages/cpp/templates/callback-value-instantiation/string.cpp rename languages/cpp/templates/{callback-context-instantiation => callback-value-instantiation}/sub-property/anyOf.cpp (100%) create mode 100644 languages/cpp/templates/callback-value-instantiation/sub-property/anyOfSchemaShape.cpp create mode 100644 languages/cpp/templates/callback-value-instantiation/sub-property/array.cpp create mode 100644 languages/cpp/templates/callback-value-instantiation/sub-property/const.cpp create mode 100644 languages/cpp/templates/callback-value-instantiation/sub-property/generic.cpp rename languages/cpp/templates/{callback-context-instantiation => callback-value-instantiation}/sub-property/namespace.cpp (100%) create mode 100644 languages/cpp/templates/callback-value-instantiation/sub-property/object-array.cpp rename languages/cpp/templates/{callback-context-instantiation => callback-value-instantiation}/sub-property/object-separator.cpp (100%) create mode 100644 languages/cpp/templates/callback-value-instantiation/sub-property/object.cpp create mode 100644 languages/cpp/templates/callback-value-instantiation/sub-property/property.cpp create mode 100644 languages/cpp/templates/callback-value-instantiation/sub-property/ref.h rename languages/cpp/templates/{callback-context-instantiation => callback-value-instantiation}/sub-property/title.cpp (100%) rename languages/cpp/templates/{callback-context-instantiation => callback-value-instantiation}/title.cpp (100%) create mode 100644 languages/cpp/templates/callback-value-instantiation/tuple.cpp diff --git a/languages/cpp/templates/callback-context-instantiation/additionalProperties.cpp b/languages/cpp/templates/callback-context-instantiation/additionalProperties.cpp deleted file mode 100644 index cecd2df5..00000000 --- a/languages/cpp/templates/callback-context-instantiation/additionalProperties.cpp +++ /dev/null @@ -1,6 +0,0 @@ - if (strcmp(elements.Label(), "${property}") == 0) { - ${if.namespace.notsame}${info.Title}::${end.if.namespace.notsame}JsonData_${title}::Iterator elements = elements.Current().Variants(); - while (elements.Next()) { - ${property}.insert(elements.Label(), elements.Current().${additional.type}; - } - } diff --git a/languages/cpp/templates/callback-context-instantiation/anyOf.cpp b/languages/cpp/templates/callback-context-instantiation/anyOf.cpp deleted file mode 100644 index 120561dd..00000000 --- a/languages/cpp/templates/callback-context-instantiation/anyOf.cpp +++ /dev/null @@ -1 +0,0 @@ - ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/array.cpp b/languages/cpp/templates/callback-context-instantiation/array.cpp deleted file mode 100644 index 63e7c4fa..00000000 --- a/languages/cpp/templates/callback-context-instantiation/array.cpp +++ /dev/null @@ -1,6 +0,0 @@ - if (strcmp(elements.Label(), "${property}") == 0) { - auto index(element.Current().Elements()); - while (index.Next() == true) { - ${property}.push_back(index.Current().Value()); - } - } \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/enum.cpp b/languages/cpp/templates/callback-context-instantiation/enum.cpp deleted file mode 100644 index 75545c29..00000000 --- a/languages/cpp/templates/callback-context-instantiation/enum.cpp +++ /dev/null @@ -1,3 +0,0 @@ - if (strcmp(elements.Label(), "${property}") == 0) { - ${property} = WPEFramework::Core::EnumerateType<${if.namespace.notsame}${info.Title}::${end.if.namespace.notsame}${title}>(elements.Current().String().c_str(), false).Value(); - } diff --git a/languages/cpp/templates/callback-context-instantiation/object.cpp b/languages/cpp/templates/callback-context-instantiation/object.cpp deleted file mode 100644 index 53bea7d7..00000000 --- a/languages/cpp/templates/callback-context-instantiation/object.cpp +++ /dev/null @@ -1,8 +0,0 @@ - if (strcmp(elements.Label(), "${property}") == 0) { - WPEFramework::Core::JSON::VariantContainer container = elements.Current().Object(); - std::string strContainer; - container.ToString(strContainer); - ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} response; - response.FromString(strContainer); -${properties} - } \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/property.cpp b/languages/cpp/templates/callback-context-instantiation/property.cpp deleted file mode 100644 index a4e489d0..00000000 --- a/languages/cpp/templates/callback-context-instantiation/property.cpp +++ /dev/null @@ -1 +0,0 @@ -${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}.${property} = response.${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/anyOfSchemaShape.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/anyOfSchemaShape.cpp deleted file mode 100644 index c1981c75..00000000 --- a/languages/cpp/templates/callback-context-instantiation/sub-property/anyOfSchemaShape.cpp +++ /dev/null @@ -1,3 +0,0 @@ - string ${property}Str; - response${Property.dependency}.${Property}.ToString(${property}Str); - ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = ${property}Str; diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/array.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/array.cpp deleted file mode 100644 index 006b4322..00000000 --- a/languages/cpp/templates/callback-context-instantiation/sub-property/array.cpp +++ /dev/null @@ -1,5 +0,0 @@ - ${if.impl.array.optional}${base.title}.${property} = std::make_optional<${type}>();${end.if.impl.array.optional} - auto index(response.${Property}.Elements()); - while (index.Next() == true) { -${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}.push_back(index.Current().Value());${end.if.non.object} - } \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/const.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/const.cpp deleted file mode 100644 index fe8fb5a0..00000000 --- a/languages/cpp/templates/callback-context-instantiation/sub-property/const.cpp +++ /dev/null @@ -1 +0,0 @@ - ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response${Property.dependency}.${Property}; diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/generic.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/generic.cpp deleted file mode 100644 index fe8fb5a0..00000000 --- a/languages/cpp/templates/callback-context-instantiation/sub-property/generic.cpp +++ /dev/null @@ -1 +0,0 @@ - ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response${Property.dependency}.${Property}; diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/object-array.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/object-array.cpp deleted file mode 100644 index 4a4eecb7..00000000 --- a/languages/cpp/templates/callback-context-instantiation/sub-property/object-array.cpp +++ /dev/null @@ -1,4 +0,0 @@ - ${type} ${property}Result${level}; - ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonResult = index.Current(); -${properties} - ${base.title}.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}.push_back(${property}Result${level}); \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/object.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/object.cpp deleted file mode 100644 index 1e549298..00000000 --- a/languages/cpp/templates/callback-context-instantiation/sub-property/object.cpp +++ /dev/null @@ -1,4 +0,0 @@ -${if.impl.optional} ${base.title}${property.dependency} = std::make_optional<${type}>();${end.if.impl.optional} - { -${properties} - } \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp b/languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp deleted file mode 100644 index 1616b444..00000000 --- a/languages/cpp/templates/callback-context-instantiation/sub-property/property.cpp +++ /dev/null @@ -1 +0,0 @@ -${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response${Property.dependency}.${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/tuple.cpp b/languages/cpp/templates/callback-context-instantiation/tuple.cpp deleted file mode 100644 index c2934799..00000000 --- a/languages/cpp/templates/callback-context-instantiation/tuple.cpp +++ /dev/null @@ -1,4 +0,0 @@ - if (strcmp(elements.Label(), "${property}") == 0) { - ${property}.first = elements.Current().Get(0); - ${property}.second = elements.Current().Get(1); - } \ No newline at end of file diff --git a/languages/cpp/templates/callback-initialization-optional/generic.cpp b/languages/cpp/templates/callback-initialization-optional/generic.cpp new file mode 100644 index 00000000..fc9cb1dd --- /dev/null +++ b/languages/cpp/templates/callback-initialization-optional/generic.cpp @@ -0,0 +1 @@ + std::optional<${type}> ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/callback-initialization-optional/primitive.cpp b/languages/cpp/templates/callback-initialization-optional/primitive.cpp new file mode 100644 index 00000000..23bbace7 --- /dev/null +++ b/languages/cpp/templates/callback-initialization-optional/primitive.cpp @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/cpp/templates/callback-instantiation/generic.cpp b/languages/cpp/templates/callback-instantiation/generic.cpp index 3b0b6489..c4204a65 100644 --- a/languages/cpp/templates/callback-instantiation/generic.cpp +++ b/languages/cpp/templates/callback-instantiation/generic.cpp @@ -1,12 +1,22 @@ - WPEFramework::Core::JSON::VariantContainer::Iterator elements = proxyResponse->Variants(); - while (elements.Next()) { -${callback.result.instantiation} - else if (strcmp(elements.Label(), "context") == 0) { - WPEFramework::Core::JSON::VariantContainer::Iterator params = elements.Current().Object().Variants(); - while (params.Next()) { - ${callback.param.instantiation.with.indent} + std::string str; + proxyResponse->ToString(str); + WPEFramework::Core::JSON::VariantContainer variantContainer(str); + WPEFramework::Core::JSON::Variant resultVariant; + if (variantContainer.HasLabel("context") == true) { + WPEFramework::Core::JSON::VariantContainer::Iterator elements = variantContainer.Variants(); + while (elements.Next()) { + ${callback.result.initialization.with.indent} + else if (strcmp(elements.Label(), "context") == 0) { + WPEFramework::Core::JSON::VariantContainer::Iterator params = elements.Current().Object().Variants(); + while (params.Next()) { + ${callback.param.instantiation.with.indent} + } + } else { + ASSERT(false); } - } else { - ASSERT(false); } - } \ No newline at end of file + } else { + resultVariant = variantContainer; + } + +${callback.result.instantiation} diff --git a/languages/cpp/templates/callback-context-instantiation/string.cpp b/languages/cpp/templates/callback-value-initialization/generic.cpp similarity index 54% rename from languages/cpp/templates/callback-context-instantiation/string.cpp rename to languages/cpp/templates/callback-value-initialization/generic.cpp index e0a62ec1..e1538b8a 100644 --- a/languages/cpp/templates/callback-context-instantiation/string.cpp +++ b/languages/cpp/templates/callback-value-initialization/generic.cpp @@ -1,3 +1,3 @@ if (strcmp(elements.Label(), "${property}") == 0) { - ${property} = elements.Current().Value().c_str(); + resultVariant = elements.Current(); } \ No newline at end of file diff --git a/languages/cpp/templates/callback-value-instantiation/additionalProperties.cpp b/languages/cpp/templates/callback-value-instantiation/additionalProperties.cpp new file mode 100644 index 00000000..8d5b8f69 --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/additionalProperties.cpp @@ -0,0 +1,4 @@ + ${if.namespace.notsame}${info.Title}::${end.if.namespace.notsame}JsonData_${title}::Iterator elements = resultVariant.Variants(); + while (elements.Next()) { + ${property}.insert(elements.Label(), elements.Current().${additional.type}; + } \ No newline at end of file diff --git a/languages/cpp/templates/callback-value-instantiation/anyOf.cpp b/languages/cpp/templates/callback-value-instantiation/anyOf.cpp new file mode 100644 index 00000000..51f4817e --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/anyOf.cpp @@ -0,0 +1 @@ + ${property}; \ No newline at end of file diff --git a/languages/cpp/templates/callback-value-instantiation/array.cpp b/languages/cpp/templates/callback-value-instantiation/array.cpp new file mode 100644 index 00000000..003dd0c7 --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/array.cpp @@ -0,0 +1,4 @@ + auto index(element.Current().Elements()); + while (index.Next() == true) { + ${property}.push_back(resultVariant.Value()); + } \ No newline at end of file diff --git a/languages/cpp/templates/callback-value-instantiation/enum.cpp b/languages/cpp/templates/callback-value-instantiation/enum.cpp new file mode 100644 index 00000000..b61f87c9 --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/enum.cpp @@ -0,0 +1 @@ + ${property} = WPEFramework::Core::EnumerateType<${if.namespace.notsame}${info.Title}::${end.if.namespace.notsame}${title}>(resultVariant.String().c_str(), false).Value(); diff --git a/languages/cpp/templates/callback-value-instantiation/generic.cpp b/languages/cpp/templates/callback-value-instantiation/generic.cpp new file mode 100644 index 00000000..ee9af58f --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/generic.cpp @@ -0,0 +1 @@ + ${property} = resultVariant.Value(); \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/namespace.cpp b/languages/cpp/templates/callback-value-instantiation/namespace.cpp similarity index 100% rename from languages/cpp/templates/callback-context-instantiation/namespace.cpp rename to languages/cpp/templates/callback-value-instantiation/namespace.cpp diff --git a/languages/cpp/templates/callback-value-instantiation/object.cpp b/languages/cpp/templates/callback-value-instantiation/object.cpp new file mode 100644 index 00000000..f60624b9 --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/object.cpp @@ -0,0 +1,6 @@ + WPEFramework::Core::JSON::VariantContainer container = resultVariant.Object(); + std::string strContainer; + container.ToString(strContainer); + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} response; + response.FromString(strContainer); +${properties} \ No newline at end of file diff --git a/languages/cpp/templates/callback-value-instantiation/primitive.cpp b/languages/cpp/templates/callback-value-instantiation/primitive.cpp new file mode 100644 index 00000000..23bbace7 --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/primitive.cpp @@ -0,0 +1 @@ +${type} \ No newline at end of file diff --git a/languages/cpp/templates/callback-value-instantiation/property.cpp b/languages/cpp/templates/callback-value-instantiation/property.cpp new file mode 100644 index 00000000..c9d1326e --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/property.cpp @@ -0,0 +1 @@ +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}.${property} = response.${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/ref.h b/languages/cpp/templates/callback-value-instantiation/ref.h similarity index 100% rename from languages/cpp/templates/callback-context-instantiation/sub-property/ref.h rename to languages/cpp/templates/callback-value-instantiation/ref.h diff --git a/languages/cpp/templates/callback-value-instantiation/string.cpp b/languages/cpp/templates/callback-value-instantiation/string.cpp new file mode 100644 index 00000000..e5179870 --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/string.cpp @@ -0,0 +1 @@ + ${property} = resultVariant.Value().c_str(); \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/anyOf.cpp b/languages/cpp/templates/callback-value-instantiation/sub-property/anyOf.cpp similarity index 100% rename from languages/cpp/templates/callback-context-instantiation/sub-property/anyOf.cpp rename to languages/cpp/templates/callback-value-instantiation/sub-property/anyOf.cpp diff --git a/languages/cpp/templates/callback-value-instantiation/sub-property/anyOfSchemaShape.cpp b/languages/cpp/templates/callback-value-instantiation/sub-property/anyOfSchemaShape.cpp new file mode 100644 index 00000000..ec176ef3 --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/sub-property/anyOfSchemaShape.cpp @@ -0,0 +1,3 @@ + string ${property}Str; + response${Property.dependency}.${Property}.ToString(${property}Str); + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = ${property}Str; diff --git a/languages/cpp/templates/callback-value-instantiation/sub-property/array.cpp b/languages/cpp/templates/callback-value-instantiation/sub-property/array.cpp new file mode 100644 index 00000000..0fe4db79 --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/sub-property/array.cpp @@ -0,0 +1,5 @@ + ${if.impl.array.optional}${base.title}.${property} = std::make_optional<${type}>();${end.if.impl.array.optional} + auto index(response.${Property}.Elements()); + while (index.Next() == true) { +${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}.push_back(index.Current().Value());${end.if.non.object} + } \ No newline at end of file diff --git a/languages/cpp/templates/callback-value-instantiation/sub-property/const.cpp b/languages/cpp/templates/callback-value-instantiation/sub-property/const.cpp new file mode 100644 index 00000000..9d8917da --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/sub-property/const.cpp @@ -0,0 +1 @@ + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response${Property.dependency}.${Property}; diff --git a/languages/cpp/templates/callback-value-instantiation/sub-property/generic.cpp b/languages/cpp/templates/callback-value-instantiation/sub-property/generic.cpp new file mode 100644 index 00000000..9d8917da --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/sub-property/generic.cpp @@ -0,0 +1 @@ + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response${Property.dependency}.${Property}; diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/namespace.cpp b/languages/cpp/templates/callback-value-instantiation/sub-property/namespace.cpp similarity index 100% rename from languages/cpp/templates/callback-context-instantiation/sub-property/namespace.cpp rename to languages/cpp/templates/callback-value-instantiation/sub-property/namespace.cpp diff --git a/languages/cpp/templates/callback-value-instantiation/sub-property/object-array.cpp b/languages/cpp/templates/callback-value-instantiation/sub-property/object-array.cpp new file mode 100644 index 00000000..ea737fd0 --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/sub-property/object-array.cpp @@ -0,0 +1,4 @@ + ${type} ${property}Result${level}; + ${if.namespace.notsame}Firebolt::${info.Title}::${end.if.namespace.notsame}JsonData_${title} jsonResult = index.Current(); +${properties} + ${base.title}.${property}${if.impl.array.optional}.value()${end.if.impl.array.optional}.push_back(${property}Result${level}); \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/object-separator.cpp b/languages/cpp/templates/callback-value-instantiation/sub-property/object-separator.cpp similarity index 100% rename from languages/cpp/templates/callback-context-instantiation/sub-property/object-separator.cpp rename to languages/cpp/templates/callback-value-instantiation/sub-property/object-separator.cpp diff --git a/languages/cpp/templates/callback-value-instantiation/sub-property/object.cpp b/languages/cpp/templates/callback-value-instantiation/sub-property/object.cpp new file mode 100644 index 00000000..e3462f94 --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/sub-property/object.cpp @@ -0,0 +1,4 @@ +${if.impl.optional} ${base.title}${property.dependency} = std::make_optional<${type}>();${end.if.impl.optional} + { +${properties} + } \ No newline at end of file diff --git a/languages/cpp/templates/callback-value-instantiation/sub-property/property.cpp b/languages/cpp/templates/callback-value-instantiation/sub-property/property.cpp new file mode 100644 index 00000000..2df36ee8 --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/sub-property/property.cpp @@ -0,0 +1 @@ +${shape} ${if.non.const}${if.non.anyOf}${if.non.array}${if.non.object}${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = response${Property.dependency}.${Property};${end.if.non.object}${end.if.non.array}${end.if.non.anyOf}${end.if.non.const} \ No newline at end of file diff --git a/languages/cpp/templates/callback-value-instantiation/sub-property/ref.h b/languages/cpp/templates/callback-value-instantiation/sub-property/ref.h new file mode 100644 index 00000000..4da5b5d9 --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/sub-property/ref.h @@ -0,0 +1 @@ +${shape} \ No newline at end of file diff --git a/languages/cpp/templates/callback-context-instantiation/sub-property/title.cpp b/languages/cpp/templates/callback-value-instantiation/sub-property/title.cpp similarity index 100% rename from languages/cpp/templates/callback-context-instantiation/sub-property/title.cpp rename to languages/cpp/templates/callback-value-instantiation/sub-property/title.cpp diff --git a/languages/cpp/templates/callback-context-instantiation/title.cpp b/languages/cpp/templates/callback-value-instantiation/title.cpp similarity index 100% rename from languages/cpp/templates/callback-context-instantiation/title.cpp rename to languages/cpp/templates/callback-value-instantiation/title.cpp diff --git a/languages/cpp/templates/callback-value-instantiation/tuple.cpp b/languages/cpp/templates/callback-value-instantiation/tuple.cpp new file mode 100644 index 00000000..2180211f --- /dev/null +++ b/languages/cpp/templates/callback-value-instantiation/tuple.cpp @@ -0,0 +1,2 @@ + ${property}.first = resultVariant.Get(0); + ${property}.second = resultVariant.Get(1); \ No newline at end of file diff --git a/languages/cpp/templates/declarations/event.h b/languages/cpp/templates/declarations/event.h index e9284523..29803793 100644 --- a/languages/cpp/templates/declarations/event.h +++ b/languages/cpp/templates/declarations/event.h @@ -1,6 +1,6 @@ /* ${method.name} - ${method.description} */ struct I${method.Name}Notification { - virtual void ${method.rpc.name}( ${event.signature.callback.params}${if.event.params}, ${end.if.event.params}${event.result.type} ) = 0; + virtual void ${method.rpc.name}( ${event.signature.callback.params}${if.event.callback.params}, ${end.if.event.callback.params}${event.result.type} ) = 0; }; // signature callback params: ${event.signature.callback.params} // method result properties : ${method.result.properties} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 339c9785..0dd10375 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -265,6 +265,14 @@ const isPropertyMethod = (m) => { return hasTag(m, 'property') || hasTag(m, 'property:immutable') || hasTag(m, 'property:readonly') } +const eventHasOptionalParam = (event) => { + return event.params.length && event.params.find(param => !(param.required && param.required === true)) +} + +const isOptionalParam = (param) => { + return (!(param.required && param.required === true)) +} + // Pick methods that call RCP out of the methods array const rpcMethodsOrEmptyArray = compose( option([]), @@ -1297,16 +1305,18 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) const resultInit = types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-initialization', property: flattenedMethod.result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) // w/out primitive: true, getSchemaShape skips anonymous types, like primitives const serializedEventParams = event ? flattenedMethod.params.filter(p => p.name !== 'listen').map(param => types.getSchemaShape(param.schema, json, {templateDir: 'parameter-serialization', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n') : '' // this was wrong... check when we merge if it was fixed - const callbackSerializedList = event ? types.getSchemaShape(event.result.schema, json, { templateDir: event.params && event.params.length && !event.tags.find(t => t.name === 'provider') ? 'callback-serialization' : 'callback-result-serialization', property: result.name, required: event.result.schema.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' - const callbackInitialization = event ? ((event.params && event.params.length && !event.tags.find(t => t.name === 'provider') ? (event.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'callback-initialization', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n')) + '\n' : '' ) + (types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-initialization', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }))) : '' + const callbackSerializedList = event ? types.getSchemaShape(event.result.schema, json, { templateDir: eventHasOptionalParam(event) && !event.tags.find(t => t.name === 'provider') ? 'callback-serialization' : 'callback-result-serialization', property: result.name, required: event.result.schema.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' + const callbackInitialization = event ? (eventHasOptionalParam(event) && !event.tags.find(t => t.name === 'provider') ? (event.params.map(param => isOptionalParam(param) ? types.getSchemaShape(param.schema, json, { templateDir: 'callback-initialization-optional', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '').filter(param => param).join('\n') + '\n') : '' ) + (types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-initialization', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })) : '' let callbackInstantiation = '' if (event) { - if (event.params && event.params.length && !event.tags.find(t => t.name === 'provider')) { + if (eventHasOptionalParam(event) && !event.tags.find(t => t.name === 'provider')) { callbackInstantiation = types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) - let paramInstantiation = event.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'callback-context-instantiation', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n') - let resultInstantiation = types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-context-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) + let paramInstantiation = event.params.map(param => isOptionalParam(param) ? types.getSchemaShape(param.schema, json, { templateDir: 'callback-context-instantiation', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '').filter(param => param).join('\n') + let resultInitialization = types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-value-initialization', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) + let resultInstantiation = types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-value-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) callbackInstantiation = callbackInstantiation - .replace(/\$\{callback\.param\.instantiation\.with\.indent\}/g, indent(paramInstantiation, ' ', 2)) + .replace(/\$\{callback\.param\.instantiation\.with\.indent\}/g, indent(paramInstantiation, ' ', 3)) + .replace(/\$\{callback\.result\.initialization\.with\.indent\}/g, indent(resultInitialization, ' ', 1)) .replace(/\$\{callback\.result\.instantiation\}/g, resultInstantiation) } else { @@ -1314,7 +1324,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) } } // hmm... how is this different from callbackSerializedList? i guess they get merged? - const callbackResponseInst = event ? (event.params && event.params.length ? (event.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'callback-response-instantiation', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join(', ')) + ', ' : '' ) + (types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-response-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })) : '' + const callbackResponseInst = event ? (eventHasOptionalParam(event) ? (event.params.map(param => isOptionalParam(param) ? types.getSchemaShape(param.schema, json, { templateDir: 'callback-response-instantiation', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '').filter(param => param).join(', ') + ', ') : '' ) + (types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-response-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })) : '' const resultType = result.schema ? types.getSchemaType(result.schema, json, { templateDir: state.typeTemplateDir }) : '' const resultSchemaType = result.schema.type const resultJsonType = result.schema ? types.getSchemaType(result.schema, json, { templateDir: 'json-types' }) : '' @@ -1345,7 +1355,6 @@ 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\.rpc\.name\}/g, methodObj.rpc_name || methodObj.name) .replace(/\$\{method\.summary\}/g, methodObj.summary) @@ -1381,6 +1390,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{event\.params\}/g, eventParams) .replace(/\$\{event\.params\.table\.rows\}/g, eventParamsRows) .replace(/\$\{if\.event\.params\}(.*?)\$\{end\.if\.event\.params\}/gms, event && event.params.length ? '$1' : '') + .replace(/\$\{if\.event\.callback\.params\}(.*?)\$\{end\.if\.event\.callback\.params\}/gms, event && eventHasOptionalParam(event) ? '$1' : '') .replace(/\$\{event\.signature\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section }) : '') .replace(/\$\{event\.signature\.callback\.params\}/g, event ? types.getMethodSignatureParams(event, json, { destination: state.destination, section: state.section, callback: true }) : '') .replace(/\$\{event\.params\.serialization\}/g, serializedEventParams) diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index 393a7e75..632d0b11 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -96,7 +96,12 @@ function getMethodSignatureParams(method, module, { destination, callback }) { paramRequired = getTemplate('/parameters/default') } - return (param.required ? paramRequired : paramOptional).replace(/\$\{method\.param\.name\}/g, param.name).replace(/\$\{method\.param\.type\}/g, type) + if (callback) { + return (!(param.required && param.required === true) ? paramOptional.replace(/\$\{method\.param\.name\}/g, param.name).replace(/\$\{method\.param\.type\}/g, type) : '') + } + else { + return (param.required ? paramRequired : paramOptional).replace(/\$\{method\.param\.name\}/g, param.name).replace(/\$\{method\.param\.type\}/g, type) + } }).filter(param => param).join(', ') } From 651c8d64164284f46520c2f17cd4aec5076fd11d Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Wed, 17 Jan 2024 18:44:16 +0530 Subject: [PATCH 127/137] CPPSDK: warning fix during promoteAndNameSubSchemas (#163) --- src/macrofier/engine.mjs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 0dd10375..9cd824ba 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -387,9 +387,6 @@ const getPromotionNameFromContentDescriptor = (descriptor, prefix) => { const promoteSchema = (location, property, title, document, destinationPath) => { const destination = getJsonPath(destinationPath, document) - if (destination[title]) { - console.log('Warning: Generated schema `' + title + '` already exists...') - } destination[title] = location[property] destination[title].title = title location[property] = { From 66c6feb76a53bbc7c768d53ef4ac24cbccd8f932 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Wed, 31 Jan 2024 08:54:59 +0530 Subject: [PATCH 128/137] Check template for codeblocks exists or not before trying to generate (#164) --- src/macrofier/engine.mjs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 9cd824ba..badf7756 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -363,9 +363,22 @@ const makeProviderMethod = x => x.name["onRequest".length].toLowerCase() + x.nam //import { default as platform } from '../Platform/defaults' const generateAggregateMacros = (openrpc, modules, templates, library) => Object.values(modules) .reduce((acc, module) => { - acc.exports += insertMacros(getTemplate('/codeblocks/export', templates) + '\n', generateMacros(module, templates)) - acc.mockImports += insertMacros(getTemplate('/codeblocks/mock-import', templates) + '\n', generateMacros(module, templates)) - acc.mockObjects += insertMacros(getTemplate('/codeblocks/mock-parameter', templates) + '\n', generateMacros(module, templates)) + + let template = getTemplate('/codeblocks/export', templates) + if (template) { + acc.exports += insertMacros(template + '\n', generateMacros(module, templates)) + } + + template = getTemplate('/codeblocks/mock-import', templates) + if (template) { + acc.mockImports += insertMacros(template + '\n', generateMacros(module, templates)) + } + + template = getTemplate('/codeblocks/mock-parameter', templates) + if (template) { + acc.mockObjects += insertMacros(template + '\n', generateMacros(module, templates)) + } + return acc }, { exports: '', From 30e8133ca8dcd5b93f23256afe03bced91af445a Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Wed, 31 Jan 2024 08:56:22 +0530 Subject: [PATCH 129/137] Optimization of generation time: generate macros only based on the schemhema template requirement if it is set (#165) --- languages/cpp/language.config.json | 7 +- .../codeblocks/module-include-private.cpp | 2 +- languages/javascript/language.config.json | 3 +- src/macrofier/engine.mjs | 82 +++++++++++-------- src/macrofier/index.mjs | 4 +- src/sdk/index.mjs | 1 + 6 files changed, 59 insertions(+), 40 deletions(-) diff --git a/languages/cpp/language.config.json b/languages/cpp/language.config.json index 8c5f533e..724a1359 100644 --- a/languages/cpp/language.config.json +++ b/languages/cpp/language.config.json @@ -25,5 +25,10 @@ "primitives": {}, "langVersion" : "c++17", "additionalSchemaTemplates": [ "json-types" ], - "additionalMethodTemplates": [ "declarations", "declarations-override" ] + "additionalMethodTemplates": [ "declarations", "declarations-override" ], + "templateExtensionMap": { + "methods": [ "impl.cpp", "cpp" ], + "declarations": [ "h" ], + "declarations-override": [ "impl.h" ] + } } diff --git a/languages/cpp/templates/codeblocks/module-include-private.cpp b/languages/cpp/templates/codeblocks/module-include-private.cpp index 6d23ec5c..b311fedd 100644 --- a/languages/cpp/templates/codeblocks/module-include-private.cpp +++ b/languages/cpp/templates/codeblocks/module-include-private.cpp @@ -1,2 +1,2 @@ ${if.modules}#include "${info.title.lowercase}_impl.h" -${end.if.modules}${module.includes.private} +${end.if.modules}${module.includes.private} \ No newline at end of file diff --git a/languages/javascript/language.config.json b/languages/javascript/language.config.json index 529ac99a..19b4659d 100644 --- a/languages/javascript/language.config.json +++ b/languages/javascript/language.config.json @@ -7,7 +7,6 @@ ], "createModuleDirectories": true, "copySchemasIntoModules": true, - "aggregateFile": "/index.d.ts", "aggregateFiles": [ "/index.d.ts" ], @@ -25,4 +24,4 @@ "object": "object" }, "additionalMethodTemplates": [ "declarations" ] -} \ No newline at end of file +} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index badf7756..26219021 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -573,7 +573,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, options.type) Array.from(new Set(['methods'].concat(config.additionalMethodTemplates))).filter(dir => dir).forEach(dir => { @@ -657,16 +657,24 @@ 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.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\.providers\}(.*?)\$\{end\.if\.providers\}/gms, macros.providerInterfaces.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.methods.trim() || macros.events.methods.trim()) ? '$1' : '') + let methods = '' + Array.from(new Set(['methods'].concat(config.additionalMethodTemplates))).filter(dir => dir).every(dir => { + if (macros.methods[dir]) { + methods = macros.methods[dir] + return false + } + return true + }) + fContents = fContents.replace(/\$\{if\.methods\}(.*?)\$\{end\.if\.methods\}/gms, methods.trim() || macros.events.methods.trim() ? '$1' : '') + fContents = fContents.replace(/\$\{if\.implementations\}(.*?)\$\{end\.if\.implementations\}/gms, (methods.trim() || macros.events.methods.trim() || macros.schemas.types.trim()) ? '$1' : '') + fContents = fContents.replace(/\$\{if\.modules\}(.*?)\$\{end\.if\.modules\}/gms, (methods.trim() || macros.events.methods.trim()) ? '$1' : '') + + fContents = fContents.replace(/\$\{if\.providers\}(.*?)\$\{end\.if\.providers\}/gms, macros.providerInterfaces.trim() ? '$1' : '') // Output the originally supported non-configurable methods & events macros fContents = fContents.replace(/[ \t]*\/\* \$\{METHODS\} \*\/[ \t]*\n/, macros.methods.methods) @@ -1174,7 +1182,7 @@ function generateMethodResult(type, templates) { return result } -function generateMethods(json = {}, examples = {}, templates = {}) { +function generateMethods(json = {}, examples = {}, templates = {}, type = '') { const methods = compose( option([]), getMethods @@ -1190,18 +1198,20 @@ function generateMethods(json = {}, examples = {}, templates = {}) { event: isEventMethod(methodObj) } + const suffix = state.destination && config.templateExtensionMap ? state.destination.split(state.destination.includes('_') ? '_' : '.').pop() : '' + // 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 => { - if (dir.includes('declarations')) { + if (dir.includes('declarations') && (suffix && config.templateExtensionMap[dir] ? config.templateExtensionMap[dir].includes(suffix) : true)) { const template = getTemplateForDeclaration(methodObj, templates, dir) if (template && template.length) { - result.declaration[dir] = insertMethodMacros(template, methodObj, json, templates, examples) + result.declaration[dir] = insertMethodMacros(template, methodObj, json, templates, '', examples) } } - else if (dir.includes('methods')) { + else if (dir.includes('methods') && (suffix && config.templateExtensionMap[dir] ? config.templateExtensionMap[dir].includes(suffix) : true)) { const template = getTemplateForMethod(methodObj, templates, dir) if (template && template.length) { - result.body[dir] = insertMethodMacros(template, methodObj, json, templates, examples) + result.body[dir] = insertMethodMacros(template, methodObj, json, templates, type, examples) } } }) @@ -1228,7 +1238,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, type = '', examples = {}) { const moduleName = getModuleName(json) const info = { @@ -1292,49 +1302,49 @@ 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, type, 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, type, 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, type, 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 - const pullsResultType = pullsResult && types.getSchemaShape(pullsResult, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) + const pullsResultType = (pullsResult && (type === 'methods')) ? types.getSchemaShape(pullsResult, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) : '' const pullsForType = pullsResult && types.getSchemaType(pullsResult, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) - const pullsParamsType = pullsParams ? types.getSchemaShape(pullsParams, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) : '' + const pullsParamsType = (pullsParams && (type === 'methods')) ? types.getSchemaShape(pullsParams, json, { destination: state.destination, templateDir: state.typeTemplateDir, section: state.section }) : '' const pullsForParamTitle = pullsParams ? pullsParams.title.charAt(0).toLowerCase() + pullsParams.title.substring(1) : '' const pullsForResultTitle = pullsResult ? pullsResult.title.charAt(0).toLowerCase() + pullsResult.title.substring(1) : '' - const pullsResponseInit = pullsParams ? types.getSchemaShape(pullsParams, json, { templateDir: 'result-initialization', property: pullsForParamTitle, required: pullsParams.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' - const pullsResponseInst = pullsParams ? types.getSchemaShape(pullsParams, json, { templateDir: 'result-instantiation', property: pullsForParamTitle, required: pullsParams.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' - const pullsResultSerialize = pullsResult ? types.getSchemaShape(pullsResult, json, { templateDir: 'parameter-serialization/sub-property', property: pullsForResultTitle, required: pullsResult.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' - - const serializedParams = flattenedMethod.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'parameter-serialization', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n') - const resultInst = types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-instantiation', property: flattenedMethod.result.name, required: flattenedMethod.result.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) // w/out primitive: true, getSchemaShape skips anonymous types, like primitives - const resultInit = types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-initialization', property: flattenedMethod.result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) // w/out primitive: true, getSchemaShape skips anonymous types, like primitives - const serializedEventParams = event ? flattenedMethod.params.filter(p => p.name !== 'listen').map(param => types.getSchemaShape(param.schema, json, {templateDir: 'parameter-serialization', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n') : '' + const pullsResponseInit = (pullsParams && (type === 'methods')) ? types.getSchemaShape(pullsParams, json, { templateDir: 'result-initialization', property: pullsForParamTitle, required: pullsParams.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' + const pullsResponseInst = (pullsParams && (type === 'methods')) ? types.getSchemaShape(pullsParams, json, { templateDir: 'result-instantiation', property: pullsForParamTitle, required: pullsParams.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' + const pullsResultSerialize = (pullsResult && (type === 'methods')) ? types.getSchemaShape(pullsResult, json, { templateDir: 'parameter-serialization/sub-property', property: pullsForResultTitle, required: pullsResult.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' + + const serializedParams = (type === 'methods') ? flattenedMethod.params.map(param => types.getSchemaShape(param.schema, json, { templateDir: 'parameter-serialization', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n') : '' + const resultInst = (type === 'methods') ? types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-instantiation', property: flattenedMethod.result.name, required: flattenedMethod.result.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' // w/out primitive: true, getSchemaShape skips anonymous types, like primitives + const resultInit = (type === 'methods') ? types.getSchemaShape(flattenedMethod.result.schema, json, { templateDir: 'result-initialization', property: flattenedMethod.result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' // w/out primitive: true, getSchemaShape skips anonymous types, like primitives + const serializedEventParams = event && (type === 'methods') ? flattenedMethod.params.filter(p => p.name !== 'listen').map(param => types.getSchemaShape(param.schema, json, {templateDir: 'parameter-serialization', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })).join('\n') : '' // this was wrong... check when we merge if it was fixed - const callbackSerializedList = event ? types.getSchemaShape(event.result.schema, json, { templateDir: eventHasOptionalParam(event) && !event.tags.find(t => t.name === 'provider') ? 'callback-serialization' : 'callback-result-serialization', property: result.name, required: event.result.schema.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' - const callbackInitialization = event ? (eventHasOptionalParam(event) && !event.tags.find(t => t.name === 'provider') ? (event.params.map(param => isOptionalParam(param) ? types.getSchemaShape(param.schema, json, { templateDir: 'callback-initialization-optional', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '').filter(param => param).join('\n') + '\n') : '' ) + (types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-initialization', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })) : '' + const callbackSerializedList = event && (type === 'methods') ? types.getSchemaShape(event.result.schema, json, { templateDir: eventHasOptionalParam(event) && !event.tags.find(t => t.name === 'provider') ? 'callback-serialization' : 'callback-result-serialization', property: result.name, required: event.result.schema.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' + const callbackInitialization = event && (type === 'methods') ? (eventHasOptionalParam(event) && !event.tags.find(t => t.name === 'provider') ? (event.params.map(param => isOptionalParam(param) ? types.getSchemaShape(param.schema, json, { templateDir: 'callback-initialization-optional', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '').filter(param => param).join('\n') + '\n') : '' ) + (types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-initialization', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })) : '' let callbackInstantiation = '' if (event) { if (eventHasOptionalParam(event) && !event.tags.find(t => t.name === 'provider')) { - callbackInstantiation = types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) - let paramInstantiation = event.params.map(param => isOptionalParam(param) ? types.getSchemaShape(param.schema, json, { templateDir: 'callback-context-instantiation', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '').filter(param => param).join('\n') - let resultInitialization = types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-value-initialization', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) - let resultInstantiation = types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-value-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) + callbackInstantiation = (type === 'methods') ? types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' + let paramInstantiation = (type === 'methods') ? event.params.map(param => isOptionalParam(param) ? types.getSchemaShape(param.schema, json, { templateDir: 'callback-context-instantiation', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '').filter(param => param).join('\n') : '' + let resultInitialization = (type === 'methods') ? types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-value-initialization', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' + let resultInstantiation = (type === 'methods') ? types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-value-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' callbackInstantiation = callbackInstantiation .replace(/\$\{callback\.param\.instantiation\.with\.indent\}/g, indent(paramInstantiation, ' ', 3)) .replace(/\$\{callback\.result\.initialization\.with\.indent\}/g, indent(resultInitialization, ' ', 1)) .replace(/\$\{callback\.result\.instantiation\}/g, resultInstantiation) } else { - callbackInstantiation = types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-result-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) + callbackInstantiation = (type === 'methods') ? types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-result-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '' } } // hmm... how is this different from callbackSerializedList? i guess they get merged? - const callbackResponseInst = event ? (eventHasOptionalParam(event) ? (event.params.map(param => isOptionalParam(param) ? types.getSchemaShape(param.schema, json, { templateDir: 'callback-response-instantiation', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '').filter(param => param).join(', ') + ', ') : '' ) + (types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-response-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })) : '' + const callbackResponseInst = event && (type === 'methods') ? (eventHasOptionalParam(event) ? (event.params.map(param => isOptionalParam(param) ? types.getSchemaShape(param.schema, json, { templateDir: 'callback-response-instantiation', property: param.name, required: param.required, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true }) : '').filter(param => param).join(', ') + ', ') : '' ) + (types.getSchemaShape(event.result.schema, json, { templateDir: 'callback-response-instantiation', property: result.name, destination: state.destination, section: state.section, primitive: true, skipTitleOnce: true })) : '' const resultType = result.schema ? types.getSchemaType(result.schema, json, { templateDir: state.typeTemplateDir }) : '' const resultSchemaType = result.schema.type const resultJsonType = result.schema ? types.getSchemaType(result.schema, json, { templateDir: 'json-types' }) : '' @@ -1785,7 +1795,7 @@ function insertProviderSubscribeMacros(template, capability, moduleJson = {}, te const suffix = state.destination ? state.destination.split('.').pop() : '' template = template.replace(/\$\{subscribe\}/gms, iface.map(method => { - return insertMethodMacros(getTemplate(suffix ? `/codeblocks/subscribe.${suffix}` : '/codeblocks/subscribe', templates), method, moduleJson, { destination: state.destination, section: state.section }) + return insertMethodMacros(getTemplate(suffix ? `/codeblocks/subscribe.${suffix}` : '/codeblocks/subscribe', templates), method, moduleJson, templates) }).join('\n') + '\n') return template } @@ -1810,7 +1820,9 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te method.tags.unshift({ name: 'provider' }) - return insertMethodMacros(interfaceDeclaration, method, moduleJson, { destination: state.destination, section: state.section, isInterface: true }) + + let type = config.templateExtensionMap && config.templateExtensionMap['methods'] && config.templateExtensionMap['methods'].includes(suffix) ? 'methods' : 'declarations' + return insertMethodMacros(interfaceDeclaration, method, moduleJson, templates, type) }).join('') + '\n') if (iface.length === 0) { diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index c6cf1595..99a1a3e0 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -53,6 +53,7 @@ const macrofy = async ( convertTuplesToArraysOrObjects, additionalSchemaTemplates, additionalMethodTemplates, + templateExtensionMap, excludeDeclarations, extractProviderSchema, aggregateFiles, @@ -97,6 +98,7 @@ const macrofy = async ( allocatedPrimitiveProxies, additionalSchemaTemplates, additionalMethodTemplates, + templateExtensionMap, excludeDeclarations, extractProviderSchema, operators @@ -181,7 +183,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, createPolymorphicMethods: createPolymorphicMethods, destination: t}) + const macros = engine.generateMacros(module, templates, exampleTemplates, {hideExcluded: hideExcluded, copySchemasIntoModules: copySchemasIntoModules, createPolymorphicMethods: createPolymorphicMethods, destination: t, type: 'methods'}) 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 diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index 627e3346..f6fd0f5e 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -69,6 +69,7 @@ const run = async ({ allocatedPrimitiveProxies: config.allocatedPrimitiveProxies, additionalSchemaTemplates: config.additionalSchemaTemplates, additionalMethodTemplates: config.additionalMethodTemplates, + templateExtensionMap: config.templateExtensionMap, excludeDeclarations: config.excludeDeclarations, extractProviderSchema: config.extractProviderSchema, staticModuleNames: staticModuleNames, From 6c20a9045f6d2a275bbd1096e48e4f666c33c5c1 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Tue, 13 Feb 2024 15:43:45 +0530 Subject: [PATCH 130/137] Updates based on MAC testing (#167) --- languages/cpp/src/shared/src/CMakeLists.txt | 5 +++++ .../cpp/templates/sdk/scripts/install.sh | 22 +++++++++---------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/languages/cpp/src/shared/src/CMakeLists.txt b/languages/cpp/src/shared/src/CMakeLists.txt index 960af8de..bff98101 100644 --- a/languages/cpp/src/shared/src/CMakeLists.txt +++ b/languages/cpp/src/shared/src/CMakeLists.txt @@ -31,11 +31,16 @@ add_library(${TARGET} ${FIREBOLT_LIBRARY_TYPE} ) set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +find_package(${NAMESPACE}WebSocket CONFIG REQUIRED) find_package(${NAMESPACE}WebSocket CONFIG REQUIRED) +find_package(${NAMESPACE}Core CONFIG REQUIRED) target_link_libraries(${TARGET} PUBLIC ${NAMESPACE}WebSocket::${NAMESPACE}WebSocket + ${NAMESPACE}Core::${NAMESPACE}Core + ${NAMESPACE}WebSocket::${NAMESPACE}WebSocket ) target_include_directories(${TARGET} diff --git a/languages/cpp/templates/sdk/scripts/install.sh b/languages/cpp/templates/sdk/scripts/install.sh index 2e8a956c..b1aa8892 100755 --- a/languages/cpp/templates/sdk/scripts/install.sh +++ b/languages/cpp/templates/sdk/scripts/install.sh @@ -40,18 +40,18 @@ ReleasePath=${InstallPath}/${ReleaseName} rm -rf ${ReleasePath} mkdir -p ${ReleasePath} -cp -ar ${SdkPath}/src ${ReleasePath} -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}/cpptest ${ReleasePath}/test +cp -aR ${SdkPath}/src ${ReleasePath} +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}/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 -sed -i '/enable test/d' ${ReleasePath}/build.sh -sed -i '/EnableTest="OFF"/d' ${ReleasePath}/build.sh -sed -i 's/ -DENABLE_TESTS=${EnableTest}//g' ${ReleasePath}/build.sh +sed -i'' -e '/EnableTest="ON";;/d' ${ReleasePath}/build.sh +sed -i'' -e 's/getopts p:s:tch/getopts p:s:ch/g' ${ReleasePath}/build.sh +sed -i'' -e '/enable test/d' ${ReleasePath}/build.sh +sed -i'' -e '/EnableTest="OFF"/d' ${ReleasePath}/build.sh +sed -i'' -e 's/ -DENABLE_TESTS=${EnableTest}//g' ${ReleasePath}/build.sh cd ${ReleasePath}/../ tar -cvzf ${ReleaseName}.tgz ${ReleaseName}/* From 50031be554e743b0f9ff9242d88117315f36f1a0 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Fri, 23 Feb 2024 21:26:38 +0530 Subject: [PATCH 131/137] CPPSDK: proceed to install only the build is successfully done and some cleanup (#169) --- languages/cpp/templates/modules/src/module_impl.cpp | 2 -- languages/cpp/templates/schemas/src/module_common.cpp | 4 +--- languages/cpp/templates/sdk/scripts/build.sh | 6 +++++- languages/cpp/templates/sections/enum.cpp | 5 ----- 4 files changed, 6 insertions(+), 11 deletions(-) delete mode 100644 languages/cpp/templates/sections/enum.cpp diff --git a/languages/cpp/templates/modules/src/module_impl.cpp b/languages/cpp/templates/modules/src/module_impl.cpp index 36c9b123..abdbecd6 100644 --- a/languages/cpp/templates/modules/src/module_impl.cpp +++ b/languages/cpp/templates/modules/src/module_impl.cpp @@ -35,7 +35,5 @@ namespace ${info.Title} { namespace WPEFramework { - /* ${ENUMS} */ - }${end.if.enums} diff --git a/languages/cpp/templates/schemas/src/module_common.cpp b/languages/cpp/templates/schemas/src/module_common.cpp index 87498ab8..7d9d13af 100644 --- a/languages/cpp/templates/schemas/src/module_common.cpp +++ b/languages/cpp/templates/schemas/src/module_common.cpp @@ -23,7 +23,5 @@ namespace WPEFramework { - /* ${ENUMS} */ - -}${end.if.enums} +}${end.if.enums} \ No newline at end of file diff --git a/languages/cpp/templates/sdk/scripts/build.sh b/languages/cpp/templates/sdk/scripts/build.sh index 149cd1ae..296ae5dd 100755 --- a/languages/cpp/templates/sdk/scripts/build.sh +++ b/languages/cpp/templates/sdk/scripts/build.sh @@ -35,6 +35,10 @@ then rm -rf ${SdkPath}/build fi +rm -rf ${SdkPath}/build/src/libFireboltSDK.so cmake -B${SdkPath}/build -S${SdkPath} -DSYSROOT_PATH=${SysrootPath} -DENABLE_TESTS=${EnableTest} -DHIDE_NON_EXTERNAL_SYMBOLS=OFF -DFIREBOLT_ENABLE_STATIC_LIB=${EnableStaticLib} cmake --build ${SdkPath}/build -cmake --install ${SdkPath}/build --prefix=${SdkPath}/build/Firebolt/usr +if [ -f "${SdkPath}/build/src/libFireboltSDK.so" ]; +then + cmake --install ${SdkPath}/build --prefix=${SdkPath}/build/Firebolt/usr +fi diff --git a/languages/cpp/templates/sections/enum.cpp b/languages/cpp/templates/sections/enum.cpp deleted file mode 100644 index e5165c61..00000000 --- a/languages/cpp/templates/sections/enum.cpp +++ /dev/null @@ -1,5 +0,0 @@ -namespace WPEFramework { - -${schema.list} - -} From 80acfba221c44f70c4d85499d4c5dbc527236ddb Mon Sep 17 00:00:00 2001 From: HaseenaSainul Date: Fri, 1 Mar 2024 04:34:39 -0500 Subject: [PATCH 132/137] merge conflict fixes --- src/macrofier/engine.mjs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 5bf20ddd..84276fb0 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -797,7 +797,7 @@ const convertEnumTemplate = (schema, templateName, templates) => { const template = getTemplate(templateName, templates).split('\n') for (var i = 0; i < template.length; i++) { if (template[i].indexOf('${key}') >= 0) { - template[i] = enumSchema.enum.map(value => { + template[i] = enumSchema.enum.map((value, id) => { const safeName = getSafeEnumKeyName(value) return template[i].replace(/\$\{key\}/g, safeName) .replace(/\$\{value\}/g, value) @@ -823,8 +823,8 @@ const generateEventEnums = (json, templates, options = { destination: '' }) => { return compose( option(''), map(val => { - let template = getTemplate(`/sections/enum.${suffix}`, templates) - return template ? template.replace(/\$\{schema.list\}/g, val) : val + let template = val ? getTemplate(`/sections/enum.${suffix}`, templates) : val + return template ? template.replace(/\$\{schema.list\}/g, val.trimEnd()) : val }), map(reduce((acc, val) => acc.concat(val).concat('\n'), '')), map(map((schema) => convertEnumTemplate(schema, suffix ? `/types/enum.${suffix}` : '/types/enum', templates))), @@ -1269,7 +1269,7 @@ function insertMethodMacros(template, methodObj, json, templates, type = '', exa } } - const paramDelimiter = config.operators ? config.operators.paramDelimiter : ', ' + const paramDelimiter = config.operators ? config.operators.paramDelimiter : '' const temporalItemName = isTemporalSetMethod(methodObj) ? methodObj.result.schema.items && methodObj.result.schema.items.title || 'Item' : '' const temporalAddName = isTemporalSetMethod(methodObj) ? `on${temporalItemName}Available` : '' From 5e8edf34872ccf2b6c150f29e8417e1feca71da1 Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Tue, 5 Mar 2024 21:43:09 +0530 Subject: [PATCH 133/137] feature/cpp branch alignment based on next branch merging for both openrpc and apis (#171) --- .../sub-property/array.cpp | 12 ++++++------ languages/cpp/templates/methods/property.cpp | 1 + .../templates/declarations/default.js | 2 +- .../javascript/templates/schemas/default.js | 1 - .../javascript/templates/types/default.mjs | 5 +---- languages/javascript/templates/types/enum.mjs | 3 --- languages/javascript/templates/types/enum.ts | 3 --- .../javascript/templates/types/property.mjs | 2 +- src/macrofier/engine.mjs | 18 ++++++++++++++---- src/macrofier/types.mjs | 10 ++++------ 10 files changed, 28 insertions(+), 29 deletions(-) diff --git a/languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp b/languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp index b2131f27..c9775b99 100644 --- a/languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp +++ b/languages/cpp/templates/callback-result-instantiation/sub-property/array.cpp @@ -1,10 +1,10 @@ - ${if.optional}if (proxyResponse->${Property}.IsSet()) { - ${base.title}.${property} = std::make_optional<${type}>(); - auto index(proxyResponse->${Property}.Elements()); + ${if.optional}if ((*proxyResponse)${Property.dependency}.${Property}.IsSet()) { + ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property} = std::make_optional<${type}>(); + auto index((*proxyResponse)${Property.dependency}.${Property}.Elements()); while (index.Next() == true) { - ${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}.${property}.value().push_back(index.Current().Value());${end.if.non.object} + ${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}.value().push_back(index.Current().Value());${end.if.non.object} } - }${end.if.optional}${if.non.optional}auto index(proxyResponse->${Property}.Elements()); + }${end.if.optional}${if.non.optional}auto index((*proxyResponse)${Property.dependency}.${Property}.Elements()); while (index.Next() == true) { -${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}.${property}.value().push_back(index.Current().Value());${end.if.non.object} +${if.object}${items.with.indent}${end.if.object}${if.non.object} ${base.title}${property.dependency}${if.impl.optional}.value()${end.if.impl.optional}.${property}.value().push_back(index.Current().Value());${end.if.non.object} }${end.if.non.optional} diff --git a/languages/cpp/templates/methods/property.cpp b/languages/cpp/templates/methods/property.cpp index 607a6527..ce38ebd0 100644 --- a/languages/cpp/templates/methods/property.cpp +++ b/languages/cpp/templates/methods/property.cpp @@ -2,6 +2,7 @@ ${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.name}"); + ${if.params}JsonObject jsonParameters;${end.if.params} ${if.params}${method.params.serialization}${end.if.params} ${method.result.json} jsonResult; ${method.result.initialization} diff --git a/languages/javascript/templates/declarations/default.js b/languages/javascript/templates/declarations/default.js index 6eb4d88d..950ffac9 100644 --- a/languages/javascript/templates/declarations/default.js +++ b/languages/javascript/templates/declarations/default.js @@ -3,4 +3,4 @@ * ${method.params.annotations}${if.deprecated} * @deprecated ${method.deprecation} ${end.if.deprecated} */ -function ${method.name}(${method.signature.params}): Promise<${method.result.type}> + function ${method.name}(${method.signature.params}): Promise<${method.result.type}> diff --git a/languages/javascript/templates/schemas/default.js b/languages/javascript/templates/schemas/default.js index bc9ab873..f00b1e37 100644 --- a/languages/javascript/templates/schemas/default.js +++ b/languages/javascript/templates/schemas/default.js @@ -1,5 +1,4 @@ /** * ${schema.description} */ - ${schema.shape} diff --git a/languages/javascript/templates/types/default.mjs b/languages/javascript/templates/types/default.mjs index 8723ec3a..3d9103b2 100644 --- a/languages/javascript/templates/types/default.mjs +++ b/languages/javascript/templates/types/default.mjs @@ -1,4 +1 @@ -/* - * ${title} - ${description} - */ -type ${title} = ${shape} +type ${title} = ${shape} \ No newline at end of file diff --git a/languages/javascript/templates/types/enum.mjs b/languages/javascript/templates/types/enum.mjs index 35529071..ae4a06b6 100644 --- a/languages/javascript/templates/types/enum.mjs +++ b/languages/javascript/templates/types/enum.mjs @@ -1,6 +1,3 @@ -/* - * ${title} - ${description} - */ ${title}: { ${key}: '${value}', }, diff --git a/languages/javascript/templates/types/enum.ts b/languages/javascript/templates/types/enum.ts index 16c14463..0743ba85 100644 --- a/languages/javascript/templates/types/enum.ts +++ b/languages/javascript/templates/types/enum.ts @@ -1,6 +1,3 @@ -/* - * ${title} - ${description} - */ enum ${title} { ${key} = '${value}', } diff --git a/languages/javascript/templates/types/property.mjs b/languages/javascript/templates/types/property.mjs index 2fc6076f..fac92c94 100644 --- a/languages/javascript/templates/types/property.mjs +++ b/languages/javascript/templates/types/property.mjs @@ -1 +1 @@ - ${property}${if.optional}?${end.if.optional}: ${title} // ${summary} \ No newline at end of file + ${property}${if.optional}?${end.if.optional}: ${title} // ${summary} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 84276fb0..cbdf0669 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -818,7 +818,7 @@ const enumFinder = compose( filter(([_key, val]) => isObject(val)) ) -const generateEventEnums = (json, templates, options = { destination: '' }) => { +const generateEnums = (json, templates, options = { destination: '' }) => { const suffix = options.destination.split('.').pop() return compose( option(''), @@ -855,7 +855,7 @@ const generateEvents = (json, templates) => { return acc }, null) - return generateEventEnums(obj, templates) + return generateEnums(obj, templates) } function generateDefaults(json = {}, templates) { @@ -1732,7 +1732,11 @@ function generateProviderSubscribe(json, templates) { function generateProviderInterfaces(json, templates) { const interfaces = getProvidedCapabilities(json) const suffix = state.destination ? state.destination.split('.').pop() : '' - let template = getTemplate(suffix ? `/sections/provider-interfaces.${suffix}` : '/sections/provider-interfaces', templates) + + let template + if (suffix) { + template = getTemplate(`/sections/provider-interfaces.${suffix}`, templates) + } if (!template) { template = getTemplate('/sections/provider-interfaces', templates) } @@ -1814,8 +1818,14 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te .replace(/\$\{capability\}/g, capability) .replace(/[ \t]*\$\{methods\}[ \t]*\n/g, iface.map(method => { const focusable = method.tags.find(t => t['x-allow-focus']) + let interfaceDeclaration; const interfaceTemplate = '/interfaces/' + (focusable ? 'focusable' : 'default') - const interfaceDeclaration = getTemplate(suffix ? `${interfaceTemplate}.${suffix}` : interfaceTemplate, templates) + if (suffix) { + interfaceDeclaration = getTemplate(`${interfaceTemplate}.${suffix}`, templates) + } + if (!interfaceDeclaration) { + interfaceDeclaration = getTemplate(interfaceTemplate, templates) + } xValues = getProviderXValues(method) method.tags.unshift({ name: 'provider' diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index 632d0b11..9d22fe49 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -17,7 +17,7 @@ */ import deepmerge from 'deepmerge' -import { getPath, localizeDependencies } from '../shared/json-schema.mjs' +import { getPath, localizeDependencies, getSafeEnumKeyName } from '../shared/json-schema.mjs' import path from "path" let convertTuplesToArraysOrObjects = false @@ -69,8 +69,6 @@ const indent = (str, padding) => { } } -const safeName = value => value.split(':').pop().replace(/[\.\-]/g, '_').replace(/\+/g, '_plus').replace(/([a-z])([A-Z0-9])/g, '$1_$2').toUpperCase() - // TODO: This is what's left of getMethodSignatureParams. We need to figure out / handle C's `FireboltTypes_StringHandle` function getMethodSignatureParams(method, module, { destination, callback }) { const paramOptional = getTemplate('/parameters/optional') @@ -215,7 +213,7 @@ const insertEnumMacros = (content, schema, module, name, suffix, templateDir = " if (!value) { value = getTemplate(path.join(templateDir, 'unset' + suffix)) } - value ? values.push(template[i].replace(/\$\{key\}/g, safeName(value)) + value ? values.push(template[i].replace(/\$\{key\}/g, getSafeEnumKeyName(value)) .replace(/\$\{value\}/g, value)) : '' }) template[i] = values.map((value, id) => { @@ -401,8 +399,8 @@ const insertObjectMacros = (content, schema, module, title, property, options) = options2.property = prop const schemaShape = getSchemaShape(type, module, options2) properties.push(template - .replace(/\$\{property\}/g, safeName(prop)) - .replace(/\$\{Property\}/g, capitalize(safeName(prop))) + .replace(/\$\{property\}/g, getSafeEnumKeyName(prop)) + .replace(/\$\{Property\}/g, capitalize(getSafeEnumKeyName(prop))) .replace(/\$\{parent\.title\}/g, title) .replace(/\$\{title\}/g, getSchemaType(type, module, options2)) .replace(/\$\{shape\}/g, schemaShape) From 67088b1fe46fe474aee47599f1b84a110c33365d Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Thu, 7 Mar 2024 13:27:10 +0530 Subject: [PATCH 134/137] CPPSDK: update install script to handle version parsing for file based and prebuild install cases (#173) --- languages/cpp/templates/sdk/scripts/install.sh | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/languages/cpp/templates/sdk/scripts/install.sh b/languages/cpp/templates/sdk/scripts/install.sh index b1aa8892..b31556a2 100755 --- a/languages/cpp/templates/sdk/scripts/install.sh +++ b/languages/cpp/templates/sdk/scripts/install.sh @@ -26,9 +26,16 @@ done GetVersion() { PackagePath=${SdkPath}/../../../../../../package-lock.json - InputKey="name\": \"@firebolt-js/openrpc" - LineNo="$(grep -n "${InputKey}" ${PackagePath} | head -n 1 | cut -d: -f1)" - VersionLine=$((LineNo++)) + InputKey="\"@firebolt-js/openrpc\":" + Line=$(grep -n "${InputKey}" ${PackagePath}) + if [[ "${Line}" == *"file:"* ]]; then + InputKey="name\": \"@firebolt-js/openrpc" + Line=$(grep -n "${InputKey}" ${PackagePath}) + LineNo="$(echo ${Line} | head -n 1 | cut -d: -f1)" + VersionLine=$((LineNo++)) + else + LineNo="$(echo ${Line} | head -n 1 | cut -d: -f1)" + fi eval "array=(`sed -n "${LineNo}p" < ${PackagePath} | sed 's/\"/\n/g'`)" Version=${array[2]} } From 2f7017af5fafe4f48abd18de2fea76592340a5fd Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Tue, 12 Mar 2024 09:03:10 +0530 Subject: [PATCH 135/137] Update to align generated firebolt.d.ts sync with same is next branch (#172) --- .../javascript/templates/types/default.ts | 1 + .../javascript/templates/types/generic.mjs | 1 + .../javascript/templates/types/property.mjs | 2 +- src/macrofier/engine.mjs | 2 +- src/macrofier/types.mjs | 51 ++++++++++++++----- 5 files changed, 41 insertions(+), 16 deletions(-) create mode 100644 languages/javascript/templates/types/default.ts create mode 100644 languages/javascript/templates/types/generic.mjs diff --git a/languages/javascript/templates/types/default.ts b/languages/javascript/templates/types/default.ts new file mode 100644 index 00000000..3d9103b2 --- /dev/null +++ b/languages/javascript/templates/types/default.ts @@ -0,0 +1 @@ +type ${title} = ${shape} \ No newline at end of file diff --git a/languages/javascript/templates/types/generic.mjs b/languages/javascript/templates/types/generic.mjs new file mode 100644 index 00000000..a60cb41f --- /dev/null +++ b/languages/javascript/templates/types/generic.mjs @@ -0,0 +1 @@ +${title} \ No newline at end of file diff --git a/languages/javascript/templates/types/property.mjs b/languages/javascript/templates/types/property.mjs index fac92c94..66bf6f73 100644 --- a/languages/javascript/templates/types/property.mjs +++ b/languages/javascript/templates/types/property.mjs @@ -1 +1 @@ - ${property}${if.optional}?${end.if.optional}: ${title} // ${summary} + ${property}${if.optional}?${end.if.optional}: ${title}${if.summary} // ${summary}${end.if.summary} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index cbdf0669..490abe1b 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -935,7 +935,7 @@ function generateSchemas(json, templates, options) { else { content = content.replace(/\$\{if\.description\}(.*?)\{end\.if\.description\}/gms, '$1') } - const schemaShape = types.getSchemaShape(schema, json, { templateDir: state.typeTemplateDir, destination: state.destination, section: options.section }) + const schemaShape = types.getSchemaShape(schema, json, { templateDir: state.typeTemplateDir, destination: state.destination, section: options.section, primitive: config.primitives ? Object.keys(config.primitives).length > 0 : false }) content = content .replace(/\$\{schema.title\}/, (schema.title || name)) diff --git a/src/macrofier/types.mjs b/src/macrofier/types.mjs index 9d22fe49..55ef7b7e 100644 --- a/src/macrofier/types.mjs +++ b/src/macrofier/types.mjs @@ -168,9 +168,22 @@ const getXSchemaGroup = (schema, module) => { return group } +function getSchemaDescription(schema, module) { + let description = schema.description || '' + if (schema.type === 'array' && schema.items) { + schema = schema.items + } + if (schema['$ref'] && (schema['$ref'][0] === '#')) { + const refSchema = getPath(schema['$ref'], module) + description = (refSchema && refSchema.description) || description + } + return description +} + function insertSchemaMacros(content, schema, module, { name = '', parent = '', property = '', required = false, recursive = true, templateDir = 'types'}) { const title = name || schema.title || '' - let moduleTitle = getXSchemaGroup(schema, module) + const moduleTitle = getXSchemaGroup(schema, module) + const description = getSchemaDescription(schema, module) content = content .replace(/\$\{title\}/g, title) @@ -181,10 +194,11 @@ function insertSchemaMacros(content, schema, module, { name = '', parent = '', p .replace(/\$\{if\.namespace\.notsame}(.*?)\$\{end\.if\.namespace\.notsame\}/g, (module.info.title !== (parent || moduleTitle)) ? '$1' : '') .replace(/\$\{parent\.title\}/g, parent || moduleTitle) .replace(/\$\{parent\.Title\}/g, capitalize(parent || moduleTitle)) - .replace(/\$\{description\}/g, schema.description ? schema.description : '') + .replace(/\$\{description\}/g, description) .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, (Array.isArray(required) ? required.includes(property) : required) ? '' : '$1') .replace(/\$\{if\.non.optional\}(.*?)\$\{end\.if\.non.optional\}/gms, (Array.isArray(required) ? required.includes(property) : required) ? '$1' : '') - .replace(/\$\{summary\}/g, schema.description ? schema.description.split('\n')[0] : '') + .replace(/\$\{if\.summary\}(.*?)\$\{end\.if\.summary\}/gms, description ? '$1' : '') + .replace(/\$\{summary\}/g, description ? description.split('\n')[0] : '') .replace(/\$\{name\}/g, title) .replace(/\$\{NAME\}/g, title.toUpperCase()) .replace(/\$\{info.title\}/g, moduleTitle) @@ -329,6 +343,7 @@ const insertObjectMacros = (content, schema, module, title, property, options) = const type = getSchemaType(localizedProp, module, options2) // don't push properties w/ unsupported types if (type) { + const description = getSchemaDescription(prop, module) let replacedTemplate = template .replace(/(^\s+)/g, '$1'.repeat(options2.level)) .replace(/\$\{property\}/g, name) @@ -336,8 +351,9 @@ const insertObjectMacros = (content, schema, module, title, property, options) = .replace(/\$\{parent\.title\}/g, title) .replace(/\$\{title\}/g, type) .replace(/\$\{shape\}/g, schemaShape) - .replace(/\$\{description\}/g, prop.description || '') - .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') + .replace(/\$\{description\}/g, description) + .replace(/\$\{if\.summary\}(.*?)\$\{end\.if\.summary\}/gms, description ? '$1' : '') + .replace(/\$\{summary\}/g, description ? description.split('\n')[0] : '') .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/gms, i === schema.properties.length - 1 ? '' : '$1') .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, ((schema.required && schema.required.includes(name)) || (localizedProp.required && localizedProp.required === true)) ? '' : '$1') .replace(/\$\{if\.non.optional\}(.*?)\$\{end\.if\.non.optional\}/gms, ((schema.required && schema.required.includes(name)) || (localizedProp.required && localizedProp.required === true)) ? '$1' : '') @@ -347,6 +363,7 @@ const insertObjectMacros = (content, schema, module, title, property, options) = .replace(/\$\{if\.non\.anyOf\}(.*?)\$\{end\.if\.non\.anyOf\}/gms, (localizedProp.anyOf || localizedProp.anyOneOf) ? '' : '$1') .replace(/\$\{if\.non\.const\}(.*?)\$\{end\.if\.non\.const\}/gms, (typeof localizedProp.const === 'string') ? '' : '$1') let baseTitle = options.property + if (isObject(localizedProp)) { replacedTemplate = replacedTemplate .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, ((schema.required && schema.required.includes(name)) || (localizedProp.required && localizedProp.required === true)) ? '' : '$1') @@ -398,14 +415,16 @@ const insertObjectMacros = (content, schema, module, title, property, options) = if (type) { options2.property = prop const schemaShape = getSchemaShape(type, module, options2) + const description = getSchemaDescription(prop, module) properties.push(template .replace(/\$\{property\}/g, getSafeEnumKeyName(prop)) .replace(/\$\{Property\}/g, capitalize(getSafeEnumKeyName(prop))) .replace(/\$\{parent\.title\}/g, title) .replace(/\$\{title\}/g, getSchemaType(type, module, options2)) .replace(/\$\{shape\}/g, schemaShape) - .replace(/\$\{description\}/g, prop.description || '') - .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') + .replace(/\$\{description\}/g, description) + .replace(/\$\{if\.summary\}(.*?)\$\{end\.if\.summary\}/gms, description ? '$1' : '') + .replace(/\$\{summary\}/g, description ? description.split('\n')[0] : '') .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/gms, i === propertyNames.enum.length - 1 ? '' : '$1') .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, schema.required && schema.required.includes(prop) ? '' : '$1') .replace(/\$\{if\.non.optional\}(.*?)\$\{end\.if\.non.optional\}/gms, schema.required && schema.required.includes(prop) ? '$1' : '')) @@ -451,6 +470,7 @@ const insertTupleMacros = (content, schema, module, title, options) => { const doMacroWork = (str, prop, i, indent) => { const schemaShape = getSchemaShape(prop, module, options) + const description = getSchemaDescription(prop, module) return (i !== 0 ? indent : '') + str .replace(/\$\{property\}/g, prop['x-property']) @@ -458,8 +478,9 @@ const insertTupleMacros = (content, schema, module, title, options) => { .replace(/\$\{parent\.title\}/g, title) .replace(/\$\{shape\}/g, schemaShape) .replace(/\$\{title\}/g, getSchemaType(prop, module, options)) - .replace(/\$\{description\}/g, prop.description || '') - .replace(/\$\{summary\}/g, prop.description ? prop.description.split('\n')[0] : '') + .replace(/\$\{description\}/g, description) + .replace(/\$\{if\.summary\}(.*?)\$\{end\.if\.summary\}/gms, description ? '$1' : '') + .replace(/\$\{summary\}/g, description ? description.split('\n')[0] : '') .replace(/\$\{delimiter\}(.*?)\$\{end.delimiter\}/g, i === schema.items.length - 1 ? '' : '$1') .replace(/\$\{if\.optional\}(.*?)\$\{end\.if\.optional\}/gms, '') .replace(/\$\{if\.impl.optional\}(.*?)\$\{end\.if\.impl.optional\}/gms, '') @@ -471,9 +492,9 @@ const insertTupleMacros = (content, schema, module, title, options) => { return content } -const getPrimitiveType = (type, templateDir = 'types') => { +const getPrimitiveType = (type, templateDir = 'types', title = false) => { const template = getTemplate(path.join(templateDir, type)) || getTemplate(path.join(templateDir, 'generic')) - return (primitives[type] || template) + return (title ? template : primitives[type] || template) } const pickBestType = types => Array.isArray(types) ? types.find(t => t !== 'null') : types @@ -511,7 +532,7 @@ const sanitize = (schema) => { return result } -function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', parent = '', property = '', required = false, parentLevel = 0, level = 0, summary, descriptions = true, destination, section, enums = true, skipTitleOnce = false, array = false, primitive = false } = {}) { +function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', parent = '', property = '', required = false, parentLevel = 0, level = 0, summary, descriptions = true, destination, section, enums = true, skipTitleOnce = false, array = false, primitive = false, type = false } = {}) { schema = sanitize(schema) state.destination = destination state.section = section @@ -522,7 +543,7 @@ function getSchemaShape(schema = {}, module = {}, { templateDir = 'types', paren const suffix = destination && ('.' + destination.split('.').pop()) || '' const theTitle = insertSchemaMacros(getTemplate(path.join(templateDir, 'title' + suffix)), schema, module, { name: schema.title, parent, property, required, recursive: false }) - let result = level === 0 && !primitive ? getTemplate(path.join(templateDir, 'default' + suffix)) : '${shape}' + let result = getTemplate(path.join(templateDir, 'default' + suffix)) || '${shape}' let genericTemplate = getTemplate(path.join(templateDir, 'generic' + suffix)) if (enums && level === 0 && Array.isArray(schema.enum) && ((schema.type === "string") || (schema.type[0] === "string"))) { @@ -857,8 +878,10 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin // TODO: this assumes that when type is an array of types, that it's one other primative & 'null', which isn't necessarily true. const schemaType = !Array.isArray(schema.type) ? schema.type : schema.type.find(t => t !== 'null') const baseDir = (templateDir !== 'json-types' ? 'types': templateDir) - const primitive = getPrimitiveType(schemaType, baseDir) + let primitive = getPrimitiveType(schemaType, baseDir, schema.title ? true: false) + primitive = primitive ? primitive.replace(/\$\{title\}/g, schema.title) : primitive const type = allocatedProxy ? allocatedPrimitiveProxies[schemaType] || primitive : primitive + return wrap(type, code ? '`' : '') } } From d79396f33918fec647c49dec1d39db760a07faaf Mon Sep 17 00:00:00 2001 From: HaseenaSainul <41037131+HaseenaSainul@users.noreply.github.com> Date: Tue, 19 Mar 2024 22:25:57 +0530 Subject: [PATCH 136/137] CPPSDK : Add Async communication support and CPP code generation for x-uses + x-allow-focus=true (#170) --- .../cpp/src/shared/src/Accessor/Accessor.h | 3 + languages/cpp/src/shared/src/Async/Async.cpp | 78 +++++++ languages/cpp/src/shared/src/Async/Async.h | 203 ++++++++++++++++++ languages/cpp/src/shared/src/CMakeLists.txt | 1 + languages/cpp/src/shared/src/Event/Event.cpp | 16 +- languages/cpp/src/shared/src/Event/Event.h | 1 + languages/cpp/src/shared/src/FireboltSDK.h | 1 + .../cpp/src/shared/src/Transport/Transport.h | 87 +++++--- .../cpp/templates/codeblocks/interface.h | 4 +- .../declarations-override/allowsFocus.h | 6 + .../cpp/templates/declarations/allowsFocus.h | 6 + .../cpp/templates/interfaces/focusable.cpp | 4 +- .../cpp/templates/methods/allowsFocus.cpp | 45 ++++ .../cpp/templates/modules/include/module.h | 2 +- .../cpp/templates/sections/xuses-interfaces.h | 7 + src/macrofier/engine.mjs | 20 +- src/shared/modules.mjs | 14 ++ 17 files changed, 455 insertions(+), 43 deletions(-) create mode 100644 languages/cpp/src/shared/src/Async/Async.cpp create mode 100644 languages/cpp/src/shared/src/Async/Async.h create mode 100644 languages/cpp/templates/declarations-override/allowsFocus.h create mode 100644 languages/cpp/templates/declarations/allowsFocus.h create mode 100644 languages/cpp/templates/methods/allowsFocus.cpp create mode 100644 languages/cpp/templates/sections/xuses-interfaces.h diff --git a/languages/cpp/src/shared/src/Accessor/Accessor.h b/languages/cpp/src/shared/src/Accessor/Accessor.h index 29dd7dda..5441368b 100644 --- a/languages/cpp/src/shared/src/Accessor/Accessor.h +++ b/languages/cpp/src/shared/src/Accessor/Accessor.h @@ -21,6 +21,7 @@ #include "Module.h" #include "WorkerPool.h" #include "Transport/Transport.h" +#include "Async/Async.h" #include "Event/Event.h" #include "Logger/Logger.h" @@ -108,6 +109,7 @@ namespace FireboltSDK { { Firebolt::Error status = CreateTransport(_config.WsUrl.Value().c_str(), listener, _config.WaitTime.Value()); if (status == Firebolt::Error::None) { + Async::Instance().Configure(_transport); status = CreateEventHandler(); } return status; @@ -118,6 +120,7 @@ namespace FireboltSDK { Firebolt::Error status = Firebolt::Error::None; status = DestroyTransport(); if (status == Firebolt::Error::None) { + Async::Dispose(); status = DestroyEventHandler(); } return status; diff --git a/languages/cpp/src/shared/src/Async/Async.cpp b/languages/cpp/src/shared/src/Async/Async.cpp new file mode 100644 index 00000000..f9994d7d --- /dev/null +++ b/languages/cpp/src/shared/src/Async/Async.cpp @@ -0,0 +1,78 @@ +/* + * 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 "Transport/Transport.h" +#include "Async.h" + +namespace FireboltSDK { + Async* Async::_singleton = nullptr; + Async::Async() + : _methodMap() + , _adminLock() + , _transport(nullptr) + { + ASSERT(_singleton == nullptr); + _singleton = this; + } + + Async::~Async() /* override */ + { + Clear(); + _transport = nullptr; + _singleton = nullptr; + } + + /* static */ Async& Async::Instance() + { + static Async *instance = new Async(); + ASSERT(instance != nullptr); + return *instance; + } + + /* static */ void Async::Dispose() + { + ASSERT(_singleton != nullptr); + + if (_singleton != nullptr) { + delete _singleton; + } + } + + void Async::Configure(Transport* transport) + { + _transport = transport; + } + + void Async::Clear() + { + _adminLock.Lock(); + MethodMap::iterator index = _methodMap.begin(); + while (index != _methodMap.end()) { + CallbackMap::iterator callbackIndex = index->second.begin(); + while (callbackIndex != index->second.end()) { + if (IsValidJob(callbackIndex->second)) { + WPEFramework::Core::IWorkerPool::Instance().Revoke(callbackIndex->second.job); + } + callbackIndex = index->second.erase(callbackIndex); + } + index = _methodMap.erase(index); + } + _adminLock.Unlock(); + } +} + diff --git a/languages/cpp/src/shared/src/Async/Async.h b/languages/cpp/src/shared/src/Async/Async.h new file mode 100644 index 00000000..a141b9e5 --- /dev/null +++ b/languages/cpp/src/shared/src/Async/Async.h @@ -0,0 +1,203 @@ +/* + * 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 "Module.h" + +namespace FireboltSDK { + + class Async { + private: + Async(); + public: + virtual ~Async(); + Async(const Async&) = delete; + Async& operator= (const Async&) = delete; + + public: + typedef std::function DispatchFunction; + + class Job : public WPEFramework::Core::IDispatch { + protected: + Job(Async& parent, const string& method, const DispatchFunction lambda, void* usercb) + : _parent(parent) + , _method(method) + , _lambda(lambda) + , _usercb(usercb) + { + } + + public: + Job() = delete; + Job(const Job&) = delete; + Job& operator=(const Job&) = delete; + + ~Job() = default; + + public: + static WPEFramework::Core::ProxyType Create(Async& parent, const string& method, const DispatchFunction lambda, void* usercb); + + void Dispatch() override + { + _lambda(_parent, _usercb); + } + + private: + Async& _parent; + string _method; + DispatchFunction _lambda; + void* _usercb; + }; + + public: + struct CallbackData { + const DispatchFunction lambda; + WPEFramework::Core::ProxyType job; + uint32_t id; + }; + + using CallbackMap = std::map; + using MethodMap = std::map; + + private: + static constexpr uint32_t DefaultId = 0xFFFFFFFF; + static constexpr uint32_t DefaultWaitTime = WPEFramework::Core::infinite; + + public: + static Async& Instance(); + static void Dispose(); + void Configure(Transport* transport); + + public: + template + Firebolt::Error Invoke(const string& method, const PARAMETERS& parameters, const CALLBACK& callback, void* usercb, uint32_t waitTime = DefaultWaitTime) + { + Firebolt::Error status = Firebolt::Error::None; + if (_transport != nullptr) { + Transport* transport = _transport; + std::function actualCallback = callback; + DispatchFunction lambda = [actualCallback, transport, method, parameters, waitTime](Async& parent, void* usercb) -> Firebolt::Error { + RESPONSE response; + uint32_t id = DefaultId; + Firebolt::Error status = transport->InvokeAsync(method, parameters, id); + if (status == Firebolt::Error::None && parent.IsActive(method, usercb) == true) { + parent.UpdateEntry(method, usercb, id); + status = transport->WaitForResponse(id, response, waitTime); + if (status == Firebolt::Error::None && parent.IsActive(method, usercb) == true) { + WPEFramework::Core::ProxyType* jsonResponse = new WPEFramework::Core::ProxyType(); + *jsonResponse = WPEFramework::Core::ProxyType::Create(); + (*jsonResponse)->FromString(response); + actualCallback(usercb, jsonResponse, status); + parent.RemoveEntry(method, usercb); + } + + } + return (status); + }; + + _adminLock.Lock(); + WPEFramework::Core::ProxyType job = WPEFramework::Core::ProxyType(WPEFramework::Core::ProxyType::Create(*this, method, lambda, usercb)); + CallbackData callbackData = {lambda, job, DefaultId}; + MethodMap::iterator index = _methodMap.find(method); + if (index != _methodMap.end()) { + CallbackMap::iterator callbackIndex = index->second.find(usercb); + if (callbackIndex == index->second.end()) { + index->second.emplace(std::piecewise_construct, std::forward_as_tuple(usercb), std::forward_as_tuple(callbackData)); + } + } else { + + CallbackMap callbackMap; + callbackMap.emplace(std::piecewise_construct, std::forward_as_tuple(usercb), std::forward_as_tuple(callbackData)); + _methodMap.emplace(std::piecewise_construct, std::forward_as_tuple(method), std::forward_as_tuple(callbackMap)); + } + _adminLock.Unlock(); + + WPEFramework::Core::IWorkerPool::Instance().Submit(job); + } + + return status; + } + + Firebolt::Error Abort(const string& method, void* usercb) + { + RemoveEntry(method, usercb); + return (Firebolt::Error::None); + } + + void UpdateEntry(const string& method, void* usercb, uint32_t id) + { + _adminLock.Lock(); + MethodMap::iterator index = _methodMap.find(method); + if (index != _methodMap.end()) { + CallbackMap::iterator callbackIndex = index->second.find(usercb); + if (callbackIndex != index->second.end()) { + callbackIndex->second.id = id; + } + } + _adminLock.Unlock(); + } + + void RemoveEntry(const string& method, void* usercb) + { + _adminLock.Lock(); + MethodMap::iterator index = _methodMap.find(method); + if (index != _methodMap.end()) { + CallbackMap::iterator callbackIndex = index->second.find(usercb); + if (callbackIndex != index->second.end()) { + if (IsValidJob(callbackIndex->second)) { + WPEFramework::Core::IWorkerPool::Instance().Revoke(callbackIndex->second.job); + } + index->second.erase(callbackIndex); + if (index->second.size() == 0) { + _methodMap.erase(index); + } + } + } + _adminLock.Unlock(); + } + + bool IsActive(const string& method, void* usercb) + { + bool valid = false; + _adminLock.Lock(); + MethodMap::iterator index = _methodMap.find(method); + if (index != _methodMap.end()) { + CallbackMap::iterator callbackIndex = index->second.find(usercb); + if (callbackIndex != index->second.end()) { + valid = true; + } + } + _adminLock.Unlock(); + return valid; + } + + private: + void Clear(); + inline bool IsValidJob(CallbackData& callbackData) { + return (callbackData.job.IsValid() && (callbackData.id == DefaultId)); + } + + private: + MethodMap _methodMap; + WPEFramework::Core::CriticalSection _adminLock; + Transport* _transport; + + static Async* _singleton; + }; +} diff --git a/languages/cpp/src/shared/src/CMakeLists.txt b/languages/cpp/src/shared/src/CMakeLists.txt index bff98101..222ba35f 100644 --- a/languages/cpp/src/shared/src/CMakeLists.txt +++ b/languages/cpp/src/shared/src/CMakeLists.txt @@ -28,6 +28,7 @@ add_library(${TARGET} ${FIREBOLT_LIBRARY_TYPE} Transport/Transport.cpp Accessor/Accessor.cpp Event/Event.cpp + Async/Async.cpp ) set(CMAKE_POSITION_INDEPENDENT_CODE ON) diff --git a/languages/cpp/src/shared/src/Event/Event.cpp b/languages/cpp/src/shared/src/Event/Event.cpp index 2438e3c4..5d739d70 100644 --- a/languages/cpp/src/shared/src/Event/Event.cpp +++ b/languages/cpp/src/shared/src/Event/Event.cpp @@ -126,7 +126,7 @@ namespace FireboltSDK { { Firebolt::Error status = Firebolt::Error::None; _adminLock.Lock(); - EventMap::iterator eventIndex = _eventMap.find(eventName); + EventMap::iterator eventIndex = _eventMap.begin(); if (eventIndex != _eventMap.end()) { CallbackMap::iterator callbackIndex = eventIndex->second.find(usercb); if (callbackIndex->second.state != State::EXECUTING) { @@ -146,4 +146,18 @@ namespace FireboltSDK { return status; } + + void Event::Clear() + { + EventMap::iterator eventIndex = _eventMap.begin(); + while (eventIndex != _eventMap.end()) { + CallbackMap::iterator callbackIndex = eventIndex->second.begin(); + while (callbackIndex != eventIndex->second.end()) { + callbackIndex = eventIndex->second.erase(callbackIndex); + } + eventIndex = _eventMap.erase(eventIndex); + } + _adminLock.Unlock(); + } + } diff --git a/languages/cpp/src/shared/src/Event/Event.h b/languages/cpp/src/shared/src/Event/Event.h index cf2fdced..7299fde0 100644 --- a/languages/cpp/src/shared/src/Event/Event.h +++ b/languages/cpp/src/shared/src/Event/Event.h @@ -149,6 +149,7 @@ namespace FireboltSDK { Firebolt::Error Revoke(const string& eventName, void* usercb); private: + void Clear(); Firebolt::Error ValidateResponse(const WPEFramework::Core::ProxyType& jsonResponse, bool& enabled) override; Firebolt::Error Dispatch(const string& eventName, const WPEFramework::Core::ProxyType& jsonResponse) override; diff --git a/languages/cpp/src/shared/src/FireboltSDK.h b/languages/cpp/src/shared/src/FireboltSDK.h index d78687dc..3b608cce 100644 --- a/languages/cpp/src/shared/src/FireboltSDK.h +++ b/languages/cpp/src/shared/src/FireboltSDK.h @@ -21,6 +21,7 @@ #include "Transport/Transport.h" #include "Properties/Properties.h" #include "Accessor/Accessor.h" +#include "Async/Async.h" #include "Logger/Logger.h" #include "TypesPriv.h" #include "types.h" diff --git a/languages/cpp/src/shared/src/Transport/Transport.h b/languages/cpp/src/shared/src/Transport/Transport.h index e705c5c1..0caa7603 100644 --- a/languages/cpp/src/shared/src/Transport/Transport.h +++ b/languages/cpp/src/shared/src/Transport/Transport.h @@ -587,6 +587,58 @@ namespace FireboltSDK { return (result); } + template + Firebolt::Error InvokeAsync(const string& method, const PARAMETERS& parameters, uint32_t& id) + { + Entry slot; + id = _channel->Sequence(); + return Send(method, parameters, id); + } + + template + Firebolt::Error WaitForResponse(const uint32_t& id, RESPONSE& response, const uint32_t waitTime) + { + int32_t result = WPEFramework::Core::ERROR_TIMEDOUT; + _adminLock.Lock(); + typename PendingMap::iterator index = _pendingQueue.find(id); + Entry& slot(index->second); + _adminLock.Unlock(); + + if (slot.WaitForResponse(waitTime) == true) { + WPEFramework::Core::ProxyType jsonResponse = slot.Response(); + + // See if we have a jsonResponse, maybe it was just the connection + // that closed? + if (jsonResponse.IsValid() == true) { + if (jsonResponse->Error.IsSet() == true) { + result = jsonResponse->Error.Code.Value(); + } + else { + result = WPEFramework::Core::ERROR_NONE; + if ((jsonResponse->Result.IsSet() == true) + && (jsonResponse->Result.Value().empty() == false)) { + FromMessage((INTERFACE*)&response, *jsonResponse); + } + } + } + } else { + result = WPEFramework::Core::ERROR_TIMEDOUT; + } + _adminLock.Lock(); + _pendingQueue.erase(id); + _adminLock.Unlock(); + return FireboltErrorValue(result); + } + + void Abort(uint32_t id) + { + _adminLock.Lock(); + typename PendingMap::iterator index = _pendingQueue.find(id); + Entry& slot(index->second); + _adminLock.Unlock(); + slot.Abort(id); + } + template Firebolt::Error Subscribe(const string& eventName, const string& parameters, RESPONSE& response) { @@ -790,41 +842,6 @@ namespace FireboltSDK { return FireboltErrorValue(result); } - template - Firebolt::Error WaitForResponse(const uint32_t& id, RESPONSE& response, const uint32_t waitTime) - { - int32_t result = WPEFramework::Core::ERROR_TIMEDOUT; - _adminLock.Lock(); - typename PendingMap::iterator index = _pendingQueue.find(id); - Entry& slot(index->second); - _adminLock.Unlock(); - - if (slot.WaitForResponse(waitTime) == true) { - WPEFramework::Core::ProxyType jsonResponse = slot.Response(); - - // See if we have a jsonResponse, maybe it was just the connection - // that closed? - if (jsonResponse.IsValid() == true) { - if (jsonResponse->Error.IsSet() == true) { - result = jsonResponse->Error.Code.Value(); - } - else { - result = WPEFramework::Core::ERROR_NONE; - if ((jsonResponse->Result.IsSet() == true) - && (jsonResponse->Result.Value().empty() == false)) { - FromMessage((INTERFACE*)&response, *jsonResponse); - } - } - } - } else { - result = WPEFramework::Core::ERROR_TIMEDOUT; - } - _adminLock.Lock(); - _pendingQueue.erase(id); - _adminLock.Unlock(); - return FireboltErrorValue(result); - } - static constexpr uint32_t WAITSLOT_TIME = 100; template Firebolt::Error WaitForEventResponse(const uint32_t& id, const string& eventName, RESPONSE& response, const uint32_t waitTime) diff --git a/languages/cpp/templates/codeblocks/interface.h b/languages/cpp/templates/codeblocks/interface.h index 376426ee..eb299a9c 100644 --- a/languages/cpp/templates/codeblocks/interface.h +++ b/languages/cpp/templates/codeblocks/interface.h @@ -1,8 +1,8 @@ struct I${info.Title}Session : virtual public IFocussableProviderSession { virtual ~I${info.Title}Session() override = default; - virtual void error( ${provider.xerror.name} error, Firebolt::Error *err = nullptr ) = 0; - virtual void result( ${provider.xresponse.name} result, Firebolt::Error *err = nullptr ) = 0; + virtual void error( ${provider.xerror.name} error, Firebolt::Error *err = nullptr ) = 0; + virtual void result( ${provider.xresponse.name} result, Firebolt::Error *err = nullptr ) = 0; }; struct I${info.Title}Provider { diff --git a/languages/cpp/templates/declarations-override/allowsFocus.h b/languages/cpp/templates/declarations-override/allowsFocus.h new file mode 100644 index 00000000..e48d9e75 --- /dev/null +++ b/languages/cpp/templates/declarations-override/allowsFocus.h @@ -0,0 +1,6 @@ + /* + ${method.name} + ${method.description} + */ + void request${method.Name}(${method.signature.params}${if.params}, ${end.if.params}I${info.Title}AsyncResponse& response, Firebolt::Error *err = nullptr ) override; + void abort${method.Name}(I${info.Title}AsyncResponse& response, Firebolt::Error *err = nullptr) override; diff --git a/languages/cpp/templates/declarations/allowsFocus.h b/languages/cpp/templates/declarations/allowsFocus.h new file mode 100644 index 00000000..707a6ff1 --- /dev/null +++ b/languages/cpp/templates/declarations/allowsFocus.h @@ -0,0 +1,6 @@ + /* + ${method.name} + ${method.description} + */ + virtual void request${method.Name}(${method.signature.params}${if.params}, ${end.if.params}I${info.Title}AsyncResponse& response, Firebolt::Error *err = nullptr ) = 0; + virtual void abort${method.Name}(I${info.Title}AsyncResponse& response, Firebolt::Error *err = nullptr) = 0; diff --git a/languages/cpp/templates/interfaces/focusable.cpp b/languages/cpp/templates/interfaces/focusable.cpp index 9a8d859d..caf7ba46 100644 --- a/languages/cpp/templates/interfaces/focusable.cpp +++ b/languages/cpp/templates/interfaces/focusable.cpp @@ -13,11 +13,11 @@ { ProviderFocusSession("${info.title.lowercase}.${method.name}Focus", _correlationId, err); } - void result( ${provider.xresponse.name} response, Firebolt::Error *err = nullptr ) override + void result( ${provider.xresponse.name} response, Firebolt::Error *err = nullptr ) override { ProviderResultSession("${info.title.lowercase}.${method.name}Response", _correlationId, response, err); } - void error( ${provider.xerror.name} error, Firebolt::Error *err = nullptr ) override + void error( ${provider.xerror.name} error, Firebolt::Error *err = nullptr ) override { ProviderErrorSession("${info.title.lowercase}.${method.name}Error", _correlationId, error, err); } diff --git a/languages/cpp/templates/methods/allowsFocus.cpp b/languages/cpp/templates/methods/allowsFocus.cpp new file mode 100644 index 00000000..d990ba96 --- /dev/null +++ b/languages/cpp/templates/methods/allowsFocus.cpp @@ -0,0 +1,45 @@ + + /* ${method.name}AsyncResponseInnerCallback */ + static void ${method.name}AsyncResponseInnerCallback(void* notification, void* jsonResponse, Firebolt::Error status) + { + WPEFramework::Core::ProxyType<${method.result.json.type}>& proxyResponse = *(reinterpret_cast*>(jsonResponse)); + + ASSERT(proxyResponse.IsValid() == true); + + if (proxyResponse.IsValid() == true) { + + ${if.result.nonvoid}${method.result.initialization}${end.if.result.nonvoid} + ${method.result.json.type} jsonResult(proxyResponse->Value().c_str()); +${if.result.nonvoid}${method.result.instantiation}${end.if.result.nonvoid} + proxyResponse.Release(); + + I${info.Title}AsyncResponse& notifier = *(reinterpret_cast(notification)); + notifier.response(${method.result.name}, &status); + } + } + + /* ${method.name} - ${method.description} */ + void ${info.Title}Impl::request${method.Name}(${method.signature.params}${if.params}, ${end.if.params}I${info.Title}AsyncResponse& response, Firebolt::Error *err) + { + JsonObject jsonParameters; +${method.params.serialization} + + Firebolt::Error status = FireboltSDK::Async::Instance().Invoke<${method.result.json.type}>(_T("${info.title.lowercase}.${method.name}"), jsonParameters, ${method.name}AsyncResponseInnerCallback, reinterpret_cast(&response)); + if (status == Firebolt::Error::None) { + FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "${info.Title}.${method.name} is successfully invoked"); + } else { + FIREBOLT_LOG_ERROR(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module(), "Error in getting Async::Invoke err = %d", status); + } + + if (err != nullptr) { + *err = status; + } + return; + } + void ${info.Title}Impl::abort${method.Name}(I${info.Title}AsyncResponse& response, Firebolt::Error *err) + { + Firebolt::Error status = FireboltSDK::Async::Instance().Abort(_T("${info.title.lowercase}.${method.name}"), reinterpret_cast(&response)); + if (err != nullptr) { + *err = status; + } + } diff --git a/languages/cpp/templates/modules/include/module.h b/languages/cpp/templates/modules/include/module.h index 04d52aef..ff3b1080 100644 --- a/languages/cpp/templates/modules/include/module.h +++ b/languages/cpp/templates/modules/include/module.h @@ -30,7 +30,7 @@ namespace ${info.Title} { ${if.types} // Types /* ${TYPES} */${end.if.types} -${if.providers}/* ${PROVIDERS} */${end.if.providers} +${if.providers}/* ${PROVIDERS} */${end.if.providers}${if.xuses}/* ${XUSES} */${end.if.xuses} ${if.methods}struct I${info.Title} { virtual ~I${info.Title}() = default; diff --git a/languages/cpp/templates/sections/xuses-interfaces.h b/languages/cpp/templates/sections/xuses-interfaces.h new file mode 100644 index 00000000..b5b580c7 --- /dev/null +++ b/languages/cpp/templates/sections/xuses-interfaces.h @@ -0,0 +1,7 @@ +struct I${info.Title}AsyncResponse { + + virtual ~I${info.Title}AsyncResponse() = default; + + virtual void response(const std::string& result, Firebolt::Error *err) = 0; +}; + diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 490abe1b..efe4607a 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -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, createPolymorphicMethods, isExcludedMethod, isCallsMetricsMethod } from '../shared/modules.mjs' +import { isRPCOnlyMethod, isProviderInterfaceMethod, getProviderInterface, getPayloadFromEvent, providerHasNoParameters, isTemporalSetMethod, hasMethodAttributes, getMethodAttributes, isEventMethodWithContext, getSemanticVersion, getSetterFor, getProvidedCapabilities, isPolymorphicPullMethod, hasPublicAPIs, isAllowFocusMethod, hasAllowFocusMethods, createPolymorphicMethods, isExcludedMethod, isCallsMetricsMethod } from '../shared/modules.mjs' import isEmpty from 'crocks/core/isEmpty.js' import { getPath as getJsonPath, getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies, isDefinitionReferencedBySchema, mergeAnyOf, mergeOneOf, getSafeEnumKeyName } from '../shared/json-schema.mjs' @@ -108,7 +108,7 @@ const getTemplate = (name, templates) => { } const getTemplateTypeForMethod = (method, type, templates) => { - const name = method.tags && method.tags.map(tag => tag.name.split(":").shift()).find(tag => Object.keys(templates).find(name => name.startsWith(`/${type}/${tag}.`))) || 'default' + const name = method.tags ? (isAllowFocusMethod(method) && Object.keys(templates).find(name => name.startsWith(`/${type}/allowsFocus.`))) ? 'allowsFocus' : (method.tags.map(tag => tag.name.split(":").shift()).find(tag => Object.keys(templates).find(name => name.startsWith(`/${type}/${tag}.`)))) || 'default' : 'default' const path = `/${type}/${name}` return getTemplate(path, templates) } @@ -595,6 +595,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { } }) + const xusesInterfaces = generateXUsesInterfaces(obj, templates) const providerSubscribe = generateProviderSubscribe(obj, templates) const providerInterfaces = generateProviderInterfaces(obj, templates) const defaults = generateDefaults(obj, templates) @@ -611,6 +612,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { eventsEnum, defaults, examples, + xusesInterfaces, providerInterfaces, providerSubscribe, version: getSemanticVersion(obj), @@ -674,6 +676,7 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{if\.implementations\}(.*?)\$\{end\.if\.implementations\}/gms, (methods.trim() || macros.events.methods.trim() || macros.schemas.types.trim()) ? '$1' : '') fContents = fContents.replace(/\$\{if\.modules\}(.*?)\$\{end\.if\.modules\}/gms, (methods.trim() || macros.events.methods.trim()) ? '$1' : '') + fContents = fContents.replace(/\$\{if\.xuses\}(.*?)\$\{end\.if\.xuses\}/gms, macros.xusesInterfaces.trim() ? '$1' : '') fContents = fContents.replace(/\$\{if\.providers\}(.*?)\$\{end\.if\.providers\}/gms, macros.providerInterfaces.trim() ? '$1' : '') // Output the originally supported non-configurable methods & events macros @@ -705,6 +708,7 @@ const insertMacros = (fContents = '', macros = {}) => { }) fContents = fContents.replace(/[ \t]*\/\* \$\{PROVIDERS\} \*\/[ \t]*\n/, macros.providerInterfaces) + fContents = fContents.replace(/[ \t]*\/\* \$\{XUSES\} \*\/[ \t]*\n/, macros.xusesInterfaces) fContents = fContents.replace(/[ \t]*\/\* \$\{PROVIDERS_SUBSCRIBE\} \*\/[ \t]*\n/, macros.providerSubscribe) fContents = fContents.replace(/[ \t]*\/\* \$\{IMPORTS\} \*\/[ \t]*\n/, macros.imports) fContents = fContents.replace(/[ \t]*\/\* \$\{INITIALIZATION\} \*\/[ \t]*\n/, macros.initialization) @@ -1717,6 +1721,18 @@ function insertCapabilityMacros(template, capabilities, method, module) { return content.join() } +function generateXUsesInterfaces(json, templates) { + let template = '' + if (hasAllowFocusMethods(json)) { + const suffix = state.destination ? state.destination.split('.').pop() : '' + template = getTemplate(suffix ? `/sections/xuses-interfaces.${suffix}` : '/sections/xuses-interfaces', templates) + if (!template) { + template = getTemplate('/sections/xuses-interfaces', templates) + } + } + return template +} + function generateProviderSubscribe(json, templates) { const interfaces = getProvidedCapabilities(json) const suffix = state.destination ? state.destination.split('.').pop() : '' diff --git a/src/shared/modules.mjs b/src/shared/modules.mjs index 6ef65f23..768356f0 100644 --- a/src/shared/modules.mjs +++ b/src/shared/modules.mjs @@ -289,6 +289,16 @@ const isPolymorphicReducer = compose( getPath(['tags']) ) +const isAllowFocusMethod = compose( + option(false), + map(_ => true), + chain(find(and( + hasProp('x-uses'), + propSatisfies('x-allow-focus', focus => (focus === true)) + ))), + getPath(['tags']) +) + const hasTitle = compose( option(false), map(isString), @@ -359,6 +369,8 @@ const getPublicEvents = compose( const hasPublicInterfaces = json => json.methods && json.methods.filter(m => m.tags && m.tags.find(t=>t['x-provides'])).length > 0 const hasPublicAPIs = json => hasPublicInterfaces(json) || (json.methods && json.methods.filter( method => !method.tags.find(tag => tag.name === 'rpc-only')).length > 0) +const hasAllowFocusMethods = json => json.methods && json.methods.filter(m => isAllowFocusMethod(m)).length > 0 + const eventDefaults = event => { event.tags = [ @@ -1423,6 +1435,8 @@ export { isPublicEventMethod, hasPublicAPIs, hasPublicInterfaces, + isAllowFocusMethod, + hasAllowFocusMethods, isPolymorphicReducer, isPolymorphicPullMethod, isTemporalSetMethod, From ebbe55abd92b577e943344a11e3d486ff44cc1d3 Mon Sep 17 00:00:00 2001 From: HaseenaSainul Date: Thu, 28 Mar 2024 00:47:15 -0400 Subject: [PATCH 137/137] CPPSDK: remove reduntant code --- src/macrofier/engine.mjs | 41 ---------------------------------------- src/shared/modules.mjs | 3 --- 2 files changed, 44 deletions(-) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index efe4607a..0696e5ff 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -484,42 +484,6 @@ const promoteAndNameSubSchemas = (obj) => { return obj } -const skip = ['NavigationIntent'] -const findAll = (tag, obj, transform) => { - if (Array.isArray(obj)) { - obj.forEach(item => findAll(tag, item, transform)) - } - else if (obj && (typeof obj === "object")) { - Object.keys(obj).forEach(key => { - if (!skip.includes(key)) { - if (key === tag) { - if (obj[key].find(schema => schema.$ref.endsWith('/ListenResponse'))) { - - } - else { - Object.assign(obj, transform(obj)) - delete obj[key] - console.dir(obj) - findAll(tag, obj, transform) - } - } - else { - findAll(tag, obj[key], transform) - } - } - }) - } -} - -const mergeAnyOfs = (obj) => { - // make a copy so we don't polute our inputs - obj = JSON.parse(JSON.stringify(obj)) - - findAll('anyOf', obj, anyOf => mergeAnyOf(anyOf)) - -return obj -} - const generateMacros = (obj, templates, languages, options = {}) => { if (options.createPolymorphicMethods) { let methods = [] @@ -541,11 +505,6 @@ const generateMacros = (obj, templates, languages, options = {}) => { obj = promoteAndNameSubSchemas(obj) } - // config.mergeAnyOfs = true - // if (config.mergeAnyOfs) { - // obj = mergeAnyOfs(obj) - // } - // grab the options so we don't have to pass them from method to method Object.assign(state, options) diff --git a/src/shared/modules.mjs b/src/shared/modules.mjs index 768356f0..81335115 100644 --- a/src/shared/modules.mjs +++ b/src/shared/modules.mjs @@ -1112,9 +1112,6 @@ const addComponentSubSchemasName = (obj, schemas) => { key = key.charAt(0).toUpperCase() + key.substring(1) componentSchema = addComponentSubSchemasNameForProperties(key, componentSchema) }) - if (!schema.title && !key) { - schema.title = capitalize(key) - } }) return schemas