Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/enum key prefix name #191

Open
wants to merge 2 commits into
base: next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 2 additions & 7 deletions languages/c/src/types/NativeHelpers.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ const getNativeType = (json, fireboltString = false) => {
}
else if (jsonType === 'null' ) {
type = 'void'
}
}
return type
}

Expand Down Expand Up @@ -125,18 +125,13 @@ const getArrayAccessors = (arrayName, propertyType, valueType) => {
return res
}

const enumValue = (val,prefix) => {
const keyName = getSafeEnumKeyName(val)
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 += schema.enum.map(e => getSafeEnumKeyName(val, prefix)).join(',\n')
str += `\n} ${prefix};\n`
return str
}
Expand Down
18 changes: 9 additions & 9 deletions src/macrofier/engine.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,7 @@ const promoteAndNameSubSchemas = (obj) => {
}
})
if (isSubSchema(method.result.schema)) {
addContentDescriptorSubSchema(method.result, '', obj)
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
Expand Down Expand Up @@ -618,7 +618,7 @@ const insertAggregateMacros = (fContents = '', aggregateMacros = {}) => {
fContents = fContents.replace(/[ \t]*\/\* \$\{MOCK_OBJECTS\} \*\/[ \t]*\n/, aggregateMacros.mockObjects)
fContents = fContents.replace(/\$\{readable\}/g, aggregateMacros.version.readable)
fContents = fContents.replace(/\$\{package.name\}/g, aggregateMacros.library)

return fContents
}

Expand Down Expand Up @@ -1319,7 +1319,7 @@ function insertMethodMacros(template, methodObj, json, templates, type = '', exa
const subscriberName = subscriber.name.toLowerCase();
return subscriberName && strippedEventName === subscriberName;
})

result.schema = JSON.parse(JSON.stringify(getPayloadFromEvent(methodObj)))
event.result.schema = getPayloadFromEvent(event)
event.params = event.params.filter(p => p.name !== 'listen')
Expand Down Expand Up @@ -1388,7 +1388,7 @@ function insertMethodMacros(template, methodObj, json, templates, type = '', exa
const pullsForParamType = pullsParams ? types.getSchemaType(pullsParams, json, { destination: state.destination, section: state.section }) : ''
const pullsForJsonType = pullsResult ? types.getSchemaType(pullsResult, json, { templateDir: 'json-types' }) : ''
const pullsForParamJsonType = pullsParams ? types.getSchemaType(pullsParams, json, { templateDir: 'json-types' }) : ''

const pullsEventParamName = event ? types.getSchemaInstantiation(event.result, json, event.name, { instantiationType: 'pull.param.name' }) : ''

let seeAlso = ''
Expand All @@ -1407,7 +1407,7 @@ function insertMethodMacros(template, methodObj, json, templates, type = '', exa
}

let signature

if (Object.keys(languages).length && template.indexOf('${method.signature}') >= 0) {
const lang = languages[Object.keys(languages)[0]]
signature = getTemplateForDeclaration(methodObj, templates, 'declarations')
Expand Down Expand Up @@ -1691,7 +1691,7 @@ function generateResultParams(result, json, templates, { name = '' } = {}) {
return Object.entries(result.properties).map( ([name, type]) => template
.replace(/\$\{method\.param\.name\}/g, name)
.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
).join(', ') // most languages separate params w/ a comma, so leaving this here for now
}
// tuples get unwrapped
else if (config.unwrapResultObjects && result.type && result.type === 'array' && Array.isArray(result.items)) {
Expand Down Expand Up @@ -1749,7 +1749,7 @@ function insertParameterMacros(template, param, method, module) {
.replace(/\$\{method.param.constraints\}/g, constraints) //getType(param))

return template

}

function insertCapabilityMacros(template, capabilities, method, module) {
Expand Down Expand Up @@ -1883,9 +1883,9 @@ function insertProviderInterfaceMacros(template, capability, moduleJson = {}, te
let name = getProviderInterfaceName(iface, capability, moduleJson)
let xValues
const suffix = state.destination ? state.destination.split('.').pop() : ''

// Determine if any method has the 'x-allow-focus' tag set to true
const hasFocusableMethods = iface.some(method =>
const hasFocusableMethods = iface.some(method =>
method.tags.some(tag => tag['x-allow-focus'] === true)
)

Expand Down
18 changes: 9 additions & 9 deletions src/macrofier/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ const macrofy = async (

const outputFiles = Object.fromEntries(Object.entries(await readFiles( staticCodeList, staticContent))
.map( ([n, v]) => [path.join(output, n), v]))

let primaryOutput = []

Object.keys(templates).forEach(file => {
Expand Down Expand Up @@ -196,14 +196,14 @@ const macrofy = async (
templatesPerModule.forEach(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
content = engine.insertAggregateMacros(content, aggregateMacros)
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.toLowerCase()).replace(/index/, module.info.title))

outputFiles[location] = content
logSuccess(`Generated macros for module ${path.relative(output, location)}`)
})
Expand Down Expand Up @@ -231,7 +231,7 @@ const macrofy = async (

if (!checked.includes(entry)) {
imports = importedFiles(code, base)
checked.push(entry)
checked.push(entry)
}

imports = imports.map(imp => Array.from(new Set([imp, ...treeShake(imp, path.dirname(imp).substring(output.length), checked)]))).flat()
Expand All @@ -255,7 +255,7 @@ const macrofy = async (
// Grab all schema groups w/ a URI string. These came from some external json-schema that was bundled into the OpenRPC
const externalSchemas = {}
openrpc['x-schemas']
&& Object.entries(openrpc['x-schemas']).forEach(([name, schema]) => {
&& Object.entries(openrpc['x-schemas']).forEach(([name, schema]) => {
if (schema.uri) {
const id = schema.uri
externalSchemas[id] = externalSchemas[id] || { $id: id, info: {title: name }, methods: []}
Expand Down Expand Up @@ -289,19 +289,19 @@ const macrofy = async (
}
})
})

// Output any schema templates for each bundled external schema document
Object.values(externalSchemas).forEach( document => {
if (templatesPerSchema) {
templatesPerSchema.forEach( 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
content = engine.insertMacros(content, macros)

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)}`)
})
Expand Down
8 changes: 4 additions & 4 deletions src/macrofier/types.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,8 @@ const insertEnumMacros = (content, schema, module, name, suffix, templateDir = "
schema.enum.map(value => {
if (!value) {
value = getTemplate(path.join(templateDir, 'unset' + suffix))
}
value ? values.push(template[i].replace(/\$\{key\}/g, getSafeEnumKeyName(value))
}
value ? values.push(template[i].replace(/\$\{key\}/g, getSafeEnumKeyName(value, schema.enumKeyPrefix))
.replace(/\$\{value\}/g, value)) : ''
})
template[i] = values.map((value, id) => {
Expand Down Expand Up @@ -549,7 +549,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 = 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"))) {
Expand Down Expand Up @@ -862,7 +862,7 @@ function getSchemaType(schema, module, { destination, templateDir = 'types', lin
const shape = insertAnyOfMacros(getTemplate(path.join(templateDir, 'anyOf' + suffix)), schema, module, theTitle)
return insertSchemaMacros(shape, schema, module, { name: theTitle, recursive: false })


// if (event) {
// return getSchemaType((schema.oneOf || schema.anyOf)[0], module, { destination, link, title, code, asPath, baseUrl })
// }
Expand Down
31 changes: 19 additions & 12 deletions src/shared/json-schema.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const objectPaths = obj => {
return isObject(value) ?
product.concat(paths(value, fullPath))
: product.concat(fullPath)
}, []) : []
}, []) : []
}
return paths(obj);
}
Expand Down Expand Up @@ -100,7 +100,7 @@ const replaceUri = (existing, replacement, schema) => {
Object.keys(schema).forEach(key => {
replaceUri(existing, replacement, schema[key])
})
}
}
}

const replaceRef = (existing, replacement, schema) => {
Expand Down Expand Up @@ -206,7 +206,7 @@ const getPropertiesInSchema = (json, document) => {

return props
}

return null
}

Expand Down Expand Up @@ -244,7 +244,7 @@ function getSchemaConstraints(schema, module, options = { delimiter: '\n' }) {
typeof schema.exclusiveMinimum === 'number' ? constraints.push(`exclusiveMinimum: ${schema.exclusiveMinimum}`) : null
typeof schema.multipleOf === 'number' ? constraints.push(`multipleOf: ${schema.multipleOf}`) : null

return constraints.join(options.delimiter)
return constraints.join(options.delimiter)
}
else if (schema.type === 'array' && schema.items) {
let constraints = []
Expand All @@ -256,7 +256,7 @@ function getSchemaConstraints(schema, module, options = { delimiter: '\n' }) {
constraints = [getSchemaConstraints(schema.items, module, options)]
}

return constraints.join(options.delimiter)
return constraints.join(options.delimiter)
}
else if (schema.oneOf || schema.anyOf) {
return '' //See OpenRPC Schema for `oneOf` and `anyOf` details'
Expand Down Expand Up @@ -524,12 +524,19 @@ const getSafeKeyName = (value) => value.split(':').pop()
.replace(/[\.\-]/g, '_') // replace dots and dashes
.replace(/\+/g, '_plus') // change + to _plus

const getSafeEnumKeyName = (value) => value.split(':').pop() // use last portion of urn:style:values
.replace(/[\.\-]/g, '_') // replace dots and dashes
.replace(/\+/g, '_plus') // change + to _plus
.replace(/([a-z])([A-Z0-9])/g, '$1_$2') // camel -> snake case
.replace(/^([0-9]+(\.[0-9]+)?)/, 'v$1') // insert `v` in front of things that look like version numbers
.toUpperCase()
const getSafeEnumKeyName = function(value, keyPrefix = '') {
if (keyPrefix != '') {
value = keyPrefix + '_' + value
}

let key = value.split(':').pop() // use last portion of urn:style:values
.replace(/\+/g, '_plus') // change + to _plus
.replace(/[\.\-\/\;]/g, '_') // replace special characters
.replace(/([a-z])([A-Z0-9])/g, '$1_$2') // camel -> snake case
.replace(/^([0-9]+\_([0-9]+)?)/, 'v$1') // insert `v` in front of things that look like version numbers

return key.toUpperCase()
}

export {
getSchemaConstraints,
Expand All @@ -552,4 +559,4 @@ export {
mergeAnyOf,
mergeOneOf,
dereferenceAndMergeAllOfs
}
}
Loading
Loading