/** * The Mojibake library * * This file is distributed under the MIT License. See LICENSE for details. */ import { readFileSync } from 'fs'; import hljs from 'highlight.js/lib/core'; import c from 'highlight.js/lib/languages/c'; import cpp from 'highlight.js/lib/languages/cpp'; import functions, { MojibakeArg, MojibakeExamples, MojibakeFunction, MojibakeReturnCase, MojibakeSpecRef, Section } from './functions'; import { caseModes, caseType, caseTypeValues, categories, collationStrengths, collationVariableWeightings, directions, encodings, encodingValues, filterFlags, filterFlagValues, identifierProfiles, malformedPolicies, normalizations, planes, planeValues, statuses, terminalWidthProfiles } from './types'; // mjb_locale values in enum order, with their language names, read from src/locales.h. const localeNames = Array.from( readFileSync('../../src/locales.h', 'utf-8').matchAll(/^\s+(MJB_LOCALE_\w+),?\s*\/\/ (.+)$/gm), match => match[1] === 'MJB_LOCALE_NOT_SET' ? match[1] : `${match[1]} (${match[2].trim()})` ); const mojibakeTypes = new Set(); for(const fn of functions) { for(const type of [fn.ret, ...fn.args.map(arg => arg.type)]) { for(const match of type.matchAll(/\bmjb_[a-z0-9_]+\b/g)) { mojibakeTypes.add(match[0]); } } } hljs.registerLanguage('c', api => { const language = c(api); const keywords = language.keywords as Record; keywords.type.push(...mojibakeTypes); return language; }); hljs.registerLanguage('cpp', api => { const language = cpp(api); const keywords = language.keywords as Record; keywords.type.push(...mojibakeTypes); return language; }); // Display names of the example languages, in tab order. const exampleLanguages: Record = { c: 'C', cpp: 'C++', }; export class CFunction implements MojibakeFunction { public comment: string; public ret: string; public name: string; public attributes: string[]; public args: MojibakeArg[]; public variadic?: boolean; public wasm: boolean; public wasmName?: string; public section: Section; public details?: string; public returns?: MojibakeReturnCase[]; public examples?: MojibakeExamples; public related?: string[]; public specs?: MojibakeSpecRef[]; constructor(fn: MojibakeFunction) { this.comment = fn.comment; this.ret = fn.ret; this.name = fn.name; this.attributes = fn.attributes; this.args = fn.args; this.variadic = fn.variadic; this.wasm = fn.wasm; this.wasmName = fn.wasmName; this.section = fn.section; this.details = fn.details; this.returns = fn.returns; this.examples = fn.examples; this.related = fn.related; this.specs = fn.specs; if(!this.ret.endsWith('*')) { this.ret += ' '; } } isWASM() { return this.wasm; } public static wasmFunctionName(wasmName?: string, name?: string): string { return wasmName ?? CFunction.snakeToCamel(CFunction.functionName(name ?? '')); } getArgs(): string[] { const args = this.args.map((arg, index) => `${arg.type}${arg.type.endsWith('*') ? '' : ' '}${arg.name}`); if(this.variadic) { args.push('...'); } return args.length ? args : ['void']; } getName() { return this.name; } getSection() { return this.section; } getLabelName(arg: number) { return this.args[arg].name.replace(/_/g, ' '); } isInternal() { return this.name.startsWith('initialize'); } formatC(): string { const attributes = ['MJB_EXPORT', ...this.attributes].join(' '); return `// ${this.comment}\n${attributes} ${this.ret}${this.getName()}(${this.getArgs().join(', ')});`; } formatSignature(): string { const args = this.getArgs(); const fn = args.length === 1 && args[0] === 'void' ? `${this.ret}${this.getName()}(void);` : `${this.ret}${this.getName()}(\n ${this.getArgs().join(',\n ')}\n);`; return fn; } private formatLine(line: string, nl = '\n', maxLine: number = 100): string { const words = line.split(/\s+/); let nlLength = nl === '\n' ? 0 : nl.length; let ret = ''; let i = 0; let addedNl = false; for(const word of words) { if(i + word.length + 1 > maxLine) { ret += nl; i = nlLength; addedNl = true; } ret += `${i > 0 && !addedNl ? ' ' : ''}${word}`; i += word.length + 1; addedNl = false; } return ret; } formatMD(): string { let ret = `## \`${this.getName()}\`\n\n${this.comment}\n\n`; ret += `\`\`\`c\n${this.formatSignature()}\n\`\`\``; if(this.details) { ret += "\n\n" + this.formatLine(this.details); } if(this.args.length) { ret += '\n\n' + this.args.map(arg => { let line = `- \`${arg.name}\` - ${arg.description}`; if(arg.ownership) { line += `. ${arg.ownership}`; } return this.formatLine(line, '\n '); }).join('\n'); } if(this.returns?.length) { ret += '\n\n**Returns**\n\n' + this.returns.map( value => this.formatLine(`- \`${value.value}\` - ${value.description}`, '\n ') ).join('\n'); } if(this.examples?.c) { ret += `\n\n**Example**\n\n\`\`\`c\n${this.examples.c}\n\`\`\``; } if(this.related?.length) { ret += '\n\n'; ret += this.formatLine('See also: ' + this.related.map( name => `[\`${name}\`](#${name})` ).join(', ') + '.'); } if(this.specs?.length) { ret += '\n\nSpecifications: ' + this.specs.map( spec => `[${spec.name}](${spec.url})` ).join(', ') + '.'; } return ret; } formatJSON(): string { return JSON.stringify({ comment: this.comment, ret: this.ret.trimEnd(), name: this.getName(), args: this.args, variadic: this.variadic, wasm: this.wasm, wasmName: CFunction.wasmFunctionName(this.wasmName, this.name), section: this.section, details: this.details, returns: this.returns, examples: this.examples, related: this.related, specs: this.specs, }); } formatWASM(): string { return `\\"_${this.getName()}\\"`; } formatHTML(relatedLinkTargets = new Set()): string { const fn = this.formatSignature(); const hasWASMForm = this.isWASM(); const toggleLabel = hasWASMForm ? 'Try it' : 'Details'; const toggleAriaLabel = hasWASMForm ? `Try ${this.getName()} in your browser` : `Show details for ${this.getName()}`; const searchText = CFunction.escapeHTML(`${this.getName()} ${this.comment}`.toLowerCase()); return `

${this.getName()}

${this.comment}

${hljs.highlight(fn, { language: 'c' }).value}
${this.documentationHTML(relatedLinkTargets)}
${hasWASMForm ? this.formInputHTML() : '' }
`; } private static escapeHTML(value: string): string { return value.replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } private static formatInlineText(value: string): string { return CFunction.escapeHTML(value).replace(/`([^`]+)`/g, '$1'); } private documentationHTML(relatedLinkTargets: Set): string { let ret = ''; if(this.details) { ret += `\n

${CFunction.formatInlineText(this.details)}

`; } if(this.returns?.length) { ret += '\n

Returns

\n
    '; for(const returnCase of this.returns) { ret += `\n
  • ${CFunction.escapeHTML(returnCase.value)} - ` + `${CFunction.formatInlineText(returnCase.description)}
  • `; } ret += '\n
'; } ret += this.examplesHTML(); if(this.related?.length) { ret += '\n

Related

\n
    '; for(const name of this.related) { const escapedName = CFunction.escapeHTML(name); if(relatedLinkTargets.has(name)) { ret += `\n
  • ${escapedName}
  • `; } else { ret += `\n
  • ${escapedName}
  • `; } } ret += '\n
'; } if(this.specs?.length) { ret += '\n

Specifications

\n '; } if(!ret) { return ''; } return `
${ret}\n
`; } private examplesHTML(): string { const languages = (Object.keys(exampleLanguages) as (keyof MojibakeExamples)[]) .filter(language => this.examples?.[language]); if(!languages.length) { return ''; } const code = (language: keyof MojibakeExamples) => `
${
        hljs.highlight(this.examples?.[language] as string, { language }).value
      }
`; if(languages.length === 1) { return `\n

Example

\n ${code(languages[0])}`; } const id = (language: string) => `${this.getName()}-example-${language}`; let tabs = ''; let panels = ''; languages.forEach((language, index) => { const selected = index === 0; tabs += `\n `; panels += `\n
${code(language)}
`; }); return '\n

Examples

' + `\n
${tabs}\n
${panels}`; } private getDescription(arg: number): string { let ret = this.args[arg].wasm_generated ? `${this.args[arg].description} (automatically generated)` : this.args[arg].description; if(this.args[arg].type === 'mjb_codepoint') { ret += ' (U+XXXXX, 0xXXXXX or XXXXX hexadecimal format)'; } return ret; } private getInput(arg: number, type = 'text'): string { const disabled = this.args[arg].wasm_generated; const name = `${this.getName()}-${this.args[arg].name}`; const description = this.getDescription(arg); let ret = `
`; ret += ``; return ret + '
'; } private getTextInput(arg: number): string { const disabled = this.args[arg].wasm_generated; const name = `${this.getName()}-${this.args[arg].name}-encoding`; const options = encodings.map((encoding, i) => ``).join(''); let ret = this.getInput(arg); ret += `
`; ret += ``; return ret + '
'; } private getCheckbox(arg: number): string { const disabled = this.args[arg].wasm_generated; const name = `${this.getName()}-${this.args[arg].name}`; let ret = `
` + ``; return ret + '
'; } private getSelectInput(arg: number, options: string[], values: number[]|null = null): string { const disabled = this.args[arg].wasm_generated; const name = `${this.getName()}-${this.args[arg].name}`; const description = this.getDescription(arg); let ret = `
`; ret += `
'; } private getBitfieldInput(arg: number, options: string[], values: number[], message = ''): string { const disabled = this.args[arg].wasm_generated; const name = `${this.getName()}-${this.args[arg].name}`; const description = this.getDescription(arg); let ret = `
` + `${this.getLabelName(arg)}${description}. ` + `${message}
`; for(let i = 0; i < options.length; ++i) { const id = `${name}-${i}`; ret += `
`; } return ret + '
'; } private formInputHTML(): string { let ret = `\n
'; let i = 0; for(const arg of this.args) { ret += `\n `; const type = arg.type; switch(type) { case 'bool': ret += this.getCheckbox(i); break; // case 'bool *': case 'char *': case 'const char *': ret += this.getInput(i); break; // case 'const mjb_bidi_paragraph *': case 'const mjb_text *': ret += this.getTextInput(i); break; // case 'const size_t *': // case 'int *': // case 'int32_t *': // case 'mjb_alloc_fn': // case 'mjb_bidi_paragraph *': // case 'mjb_bidi_run *': // case 'mjb_block_info *': // case 'mjb_buffer_character *': case 'mjb_caseless_mode': ret += this.getSelectInput(i, caseModes, null); break; case 'mjb_category': ret += this.getSelectInput(i, categories, null); break; // case 'mjb_character *': case 'mjb_codepoint': ret += this.getInput(i); break; // case 'mjb_codepoint *': case 'mjb_collation_variable_weighting': ret += this.getSelectInput(i, collationVariableWeightings, null); break; case 'mjb_collation_strength': ret += this.getSelectInput(i, collationStrengths, null); break; case 'mjb_direction': ret += this.getSelectInput(i, directions, null); break; // case 'mjb_east_asian_width *': // case 'mjb_emoji_properties *': // case 'mjb_emoji_sequence *': case 'mjb_encoding': ret += this.getSelectInput(i, encodings, encodingValues); break; case 'mjb_filter_flags': ret += this.getBitfieldInput(i, filterFlags, filterFlagValues, 'Leave all unchecked for MJB_FILTER_NONE.'); break; // case 'mjb_for_each_codepoint_fn': // case 'mjb_free_fn': case 'mjb_identifier_profile': ret += this.getSelectInput(i, identifierProfiles, null); break; // case 'mjb_idna_info *': case 'mjb_locale': ret += this.getSelectInput(i, localeNames); break; case 'mjb_malformed_policy': ret += this.getSelectInput(i, malformedPolicies); break; // case 'mjb_locale_id *': case 'mjb_map_case_type': ret += this.getSelectInput(i, caseType, caseTypeValues); break; // case 'mjb_line_break_state *': // case 'mjb_sentence_break_state *': // case 'mjb_grapheme_break_state *': // case 'mjb_word_break_state *': case 'mjb_normalization': ret += this.getSelectInput(i, normalizations); break; // case 'mjb_numeric_value *': case 'mjb_plane': ret += this.getSelectInput(i, planes, planeValues); break; case 'mjb_property': // TODO: generate from mjb_property enum ret += this.getInput(i); break; // case 'mjb_quick_check_result *': // case 'mjb_realloc_fn': // case 'mjb_result *': // case 'mjb_script *': // case 'mjb_script_set_kind *': case 'mjb_status': ret += this.getSelectInput(i, statuses); break; // case 'mjb_string *': case 'mjb_terminal_width_profile': ret += this.getSelectInput(i, terminalWidthProfiles); break; case 'size_t': ret += this.getInput(i); break; // case 'size_t *': // case 'va_list': // case 'void *': } ++i; } ret += `\n
\n
\n`; return ret; } public formatEventListener(): string { return `document.getElementById('${this.getName()}-submit').addEventListener('click', () => { callFunction('${this.getName()}'); });` } public static snakeToCamel(str: string): string { return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()); } public static functionName(cName: string): string { return cName.replace(/^mjb_/, ''); } private methodCall(): string { const args = this.args.filter(arg => !arg.wasm_generated); const argStrings = args.map(arg => `getArg('${this.getName()}-${arg.name}')`); return `mojibake.${CFunction.snakeToCamel(this.name)}(${argStrings.join(', ')})`; } } export function cfns(): CFunction[] { const names = new Set(functions.map(item => item.name)); for(const item of functions) { for(const related of item.related ?? []) { if(!names.has(related)) { throw new Error(`${item.name}: unknown related function "${related}"`); } } } return functions.map(item => new CFunction(item)); }