Update Dependencies

This commit is contained in:
TheBrokenRail 2025-02-21 19:06:09 -05:00
parent 16ab0983a7
commit fa7446151e
14 changed files with 619 additions and 756 deletions

View File

@ -1,2 +0,0 @@
/build
/node_modules

View File

@ -1,36 +0,0 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"no-constant-condition": [
"error",
{
"checkLoops": false
}
],
"quotes": [
"error",
"single",
{
"allowTemplateLiterals": true
}
],
"semi": "error",
"indent": [
"error",
4,
{
"SwitchCase": 1
}
],
"eqeqeq": "error"
}
}

54
eslint.config.mjs Normal file
View File

@ -0,0 +1,54 @@
// @ts-check
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
import * as path from 'node:path';
import * as url from 'node:url';
export default tseslint.config(
eslint.configs.recommended,
tseslint.configs.strictTypeChecked,
tseslint.configs.stylisticTypeChecked,
{
languageOptions: {
parserOptions: {
projectService: {
allowDefaultProject: [
'eslint.config.mjs'
]
},
tsconfigRootDir: path.dirname(url.fileURLToPath(import.meta.url))
}
},
rules: {
'@typescript-eslint/no-unnecessary-condition': [
'error',
{
allowConstantLoopConditions: 'only-allowed-literals'
}
],
quotes: [
'error',
'single',
{
allowTemplateLiterals: true
}
],
semi: 'error',
indent: [
'error',
4,
{
SwitchCase: 1
}
],
eqeqeq: 'error'
}
},
{
ignores: [
'build/',
'node_modules/'
]
}
);

1033
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -6,17 +6,16 @@
"scripts": { "scripts": {
"build": "tsc", "build": "tsc",
"start": "npm run build && node build/index.js", "start": "npm run build && node build/index.js",
"lint": "eslint . --ext .ts" "lint": "eslint ."
}, },
"author": "TheBrokenRail", "author": "TheBrokenRail",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@tsconfig/node-lts": "^18.12.5", "@tsconfig/node18": "^18.2.4",
"@tsconfig/strictest": "^2.0.2", "@tsconfig/strictest": "^2.0.5",
"@types/node": "^20.10.6", "@types/node": "^22.13.4",
"@typescript-eslint/eslint-plugin": "^6.17.0", "eslint": "^9.20.1",
"@typescript-eslint/parser": "^6.17.0", "typescript": "^5.7.3",
"eslint": "^8.56.0", "typescript-eslint": "^8.24.0"
"typescript": "^5.3.3"
} }
} }

View File

@ -1,28 +1,47 @@
import * as fs from 'node:fs'; import * as fs from 'node:fs';
import * as path from 'node:path'; import * as path from 'node:path';
// Constants
export const INDENT = ' '; export const INDENT = ' ';
export const POINTER_SIZE = 4; export const POINTER_SIZE = 4;
export const RTTI_SIZE = POINTER_SIZE; export const RTTI_SIZE = POINTER_SIZE;
export const EXTENSION = '.def'; export const EXTENSION = '.def';
export const STRUCTURE_FILES: {[id: string]: string} = {}; export const STRUCTURE_FILES: Record<string, string> = {};
export const COMMENT = '//';
export const INTERNAL = '__';
export const LEAN_HEADER_GUARD = '#ifndef LEAN_SYMBOLS_HEADER\n';
// Read Definition File
export function readDefinition(name: string) { export function readDefinition(name: string) {
if (!STRUCTURE_FILES[name]) { if (!STRUCTURE_FILES[name]) {
throw new Error(`Missing Definition File: ${name}${EXTENSION}`); throw new Error(`Missing Definition File: ${name}${EXTENSION}`);
} }
return fs.readFileSync(STRUCTURE_FILES[name]!, {encoding: 'utf8'}); return fs.readFileSync(STRUCTURE_FILES[name], {encoding: 'utf8'});
} }
export function syntaxError(message?: string) { // Error Handling
throw new Error('Syntax Error' + (message ? `: ${message}` : '')); export function extendErrorMessage(e: unknown, message: string) {
let extra: string | null = null;
if (typeof e === 'string') {
extra = e;
} else if (e instanceof Error) {
extra = e.message;
}
if (extra) {
message += ': ' + extra;
}
return message;
} }
export function syntaxError(message?: string): never {
throw new Error(extendErrorMessage(message, 'Syntax Error'));
}
// Convert 'int x' Into {type: 'int', name: 'x'}
export function parseTypeAndName(piece: string) { export function parseTypeAndName(piece: string) {
// Split On Last Space // Split On Last Space
const index = piece.lastIndexOf(' '); const index = piece.lastIndexOf(' ');
if (index === -1) { if (index === -1) {
syntaxError('Unable To Find Name/Type Divider'); syntaxError('Unable To Find Name/Type Divider');
} }
let name = piece.substring(index + 1)!; let name = piece.substring(index + 1);
let type = piece.substring(0, index)!; let type = piece.substring(0, index);
// Move Asterisks From Name To Type // Move Asterisks From Name To Type
while (name.startsWith('*') || name.startsWith('&')) { while (name.startsWith('*') || name.startsWith('&')) {
const x = name.substring(0, 1); const x = name.substring(0, 1);
@ -35,6 +54,7 @@ export function parseTypeAndName(piece: string) {
// Return // Return
return {type, name}; return {type, name};
} }
// Convert To Uppercase-Snake-Case
export function toUpperSnakeCase(str: string) { export function toUpperSnakeCase(str: string) {
let wasUpper = false; let wasUpper = false;
let nextIsUpper = false; let nextIsUpper = false;
@ -57,19 +77,22 @@ export function toUpperSnakeCase(str: string) {
} }
return out; return out;
} }
// Convert 'int' To 'int ' But Leave 'int *' As Is
export function formatType(type: string) { export function formatType(type: string) {
if (!type.endsWith('*') && !type.endsWith('&')) { if (!type.endsWith('*') && !type.endsWith('&')) {
type += ' '; type += ' ';
} }
return type; return type;
} }
export const COMMENT = '//'; // Convert Number To Hexadecimal
export function toHex(x: number) { export function toHex(x: number) {
return '0x' + x.toString(16); return '0x' + x.toString(16);
} }
// Generate C++ Size Assertion
export function assertSize(name: string, size: number) { export function assertSize(name: string, size: number) {
return `static_assert(sizeof(${name}) == ${toHex(size)}, "Invalid Size");\n`; return `static_assert(sizeof(${name}) == ${toHex(size)}, "Invalid Size");\n`;
} }
// Parse Integer With Error Checking
export function safeParseInt(str: string) { export function safeParseInt(str: string) {
const x = parseInt(str); const x = parseInt(str);
if (isNaN(x)) { if (isNaN(x)) {
@ -77,31 +100,45 @@ export function safeParseInt(str: string) {
} }
return x; return x;
} }
// Generate "Self" Argument For Functions
export function getSelfArg(type: string) { export function getSelfArg(type: string) {
return `${type} *self`; return `${type} *self`;
} }
// Prepend Argument To Function
export function prependArg(args: string, arg: string) { export function prependArg(args: string, arg: string) {
if (args !== '()') { if (args !== '()') {
arg += ', '; arg += ', ';
} }
return '(' + arg + args.substring(1); return '(' + arg + args.substring(1);
} }
// Get Data Directory
export function getDataDir() { export function getDataDir() {
return path.join(__dirname, '..', 'data'); return path.join(__dirname, '..', 'data');
} }
export function formatFile(file: string, options: {[key: string]: string}) { // Format File From Data Directory
file = path.join(getDataDir(), file); export function formatFile(file: string, options: Record<string, string>) {
let data = fs.readFileSync(file, {encoding: 'utf8'}); // Include Other Files
const dataDir = getDataDir();
const otherFiles = fs.readdirSync(dataDir);
for (let otherFile of otherFiles) {
otherFile = path.join(dataDir, otherFile);
options[`include ${otherFile}`] = fs.readFileSync(otherFile, 'utf8');
}
// Format
file = path.join(dataDir, file);
let data = fs.readFileSync(file, 'utf8');
for (const key in options) { for (const key in options) {
data = data.replace(`{{ ${key} }}`, options[key]!); const value = options[key];
if (value) {
data = data.replace(`{{ ${key} }}`, value);
}
} }
return data.trim() + '\n'; return data.trim() + '\n';
} }
export const INTERNAL = '__'; // Generate Code That Will Disable C++ Construction
export function preventConstruction(self: string) { export function preventConstruction(self: string) {
let out = ''; let out = '';
out += `${INDENT}${INTERNAL}PREVENT_CONSTRUCTION(${self});\n`; out += `${INDENT}${INTERNAL}PREVENT_CONSTRUCTION(${self});\n`;
out += `${INDENT}${INTERNAL}PREVENT_COPY(${self});\n`; out += `${INDENT}${INTERNAL}PREVENT_COPY(${self});\n`;
return out; return out;
} }
export const LEAN_HEADER_GUARD = '#ifndef LEAN_SYMBOLS_HEADER\n';

View File

@ -1,45 +1,56 @@
import * as fs from 'node:fs'; import * as fs from 'node:fs';
import * as path from 'node:path'; import * as path from 'node:path';
import { STRUCTURE_FILES, EXTENSION, formatFile, getDataDir } from './common'; import { STRUCTURE_FILES, EXTENSION, formatFile, getDataDir, extendErrorMessage } from './common';
import { getStructure } from './map'; import { getStructure } from './map';
import { Struct } from './struct'; import { Struct } from './struct';
// Arguments // Handle Errors
if (process.argv.length < 5) { process.on('uncaughtException', function (e) {
console.log('USAGE: npm start -- <Source Output File> <Header Output File> <Input Files...>'); console.error('Error: ' + e.message);
process.exit(1); process.exit(1);
});
// Arguments
function nextArgument() {
const out = process.argv.shift();
if (!out) {
throw new Error('Not Enough Arguments!');
}
return out;
} }
process.argv.shift(); nextArgument();
process.argv.shift(); nextArgument();
// Output Files
function invalidFileType(file: string) { function invalidFileType(file: string) {
throw new Error(`Invalid File Type: ${file}`); throw new Error(`Invalid File Type: ${file}`);
} }
const sourceOutput = process.argv.shift()!; const sourceOutput = nextArgument();
fs.rmSync(sourceOutput, {force: true, recursive: true}); fs.rmSync(sourceOutput, {force: true, recursive: true});
fs.mkdirSync(sourceOutput, {recursive: true}); fs.mkdirSync(sourceOutput, {recursive: true});
const headerOutput = process.argv.shift()!; const headerOutput = nextArgument();
if (!headerOutput.endsWith('.h')) { if (!headerOutput.endsWith('.h')) {
invalidFileType(headerOutput); invalidFileType(headerOutput);
} }
// Input Files
const extraHeaderFiles: string[] = []; const extraHeaderFiles: string[] = [];
while (process.argv.length > 0) { while (process.argv.length > 0) {
const file = process.argv.shift()!; const filePath = nextArgument();
if (file.endsWith(EXTENSION)) { const file = path.parse(filePath);
if (file.ext === EXTENSION) {
// Get Class Name // Get Class Name
const parts = file.split('/'); const fullName = file.base;
let name = parts[parts.length - 1]!; const name = file.name;
name = name.substring(0, name.length - EXTENSION.length);
// Store // Store
if (name in STRUCTURE_FILES) { if (name in STRUCTURE_FILES) {
throw new Error(`Multiple Definition Files Provided: ${name}${EXTENSION}`); throw new Error(`Multiple Definition Files Provided: ${fullName}`);
} }
STRUCTURE_FILES[name] = file; STRUCTURE_FILES[name] = filePath;
} else if (file.endsWith('.h')) { } else if (file.ext === '.h') {
// Extra Headers // Extra Headers
extraHeaderFiles.push(file); extraHeaderFiles.push(filePath);
} else { } else {
// Invalid File Type // Invalid File Type
invalidFileType(file); invalidFileType(filePath);
} }
} }
@ -67,7 +78,7 @@ function loadSymbols() {
// Sort Structures By Dependency // Sort Structures By Dependency
function dependencySort(structureObjects: Struct[]) { function dependencySort(structureObjects: Struct[]) {
let loops = 0; let loops = 0;
const MAX_LOOPS = 100; const MAX_LOOPS = 1000;
while (true) { while (true) {
if (loops > MAX_LOOPS) { if (loops > MAX_LOOPS) {
throw new Error('Unable To Sort Dependencies'); throw new Error('Unable To Sort Dependencies');
@ -118,8 +129,7 @@ function makeHeaderPart() {
try { try {
structures += structure.generate(); structures += structure.generate();
} catch (e) { } catch (e) {
console.log(`Error Generating Header: ${name}: ${e instanceof Error ? e.stack : e}`); throw new Error(extendErrorMessage(e, 'Error Generating Header: ' + name));
process.exit(1);
} }
structures += '\n'; structures += '\n';
} }
@ -172,8 +182,7 @@ function makeCompiledCode(outputDir: string) {
try { try {
declarations += structure.generateCode().trim(); declarations += structure.generateCode().trim();
} catch (e) { } catch (e) {
console.log(`Error Generating Code: ${name}: ${e instanceof Error ? e.stack : e}`); throw new Error(extendErrorMessage(e, 'Error Generating Code: ' + name));
process.exit(1);
} }
declarations += '\n'; declarations += '\n';

View File

@ -1,28 +1,32 @@
import { COMMENT, EXTENSION, getSelfArg, parseTypeAndName, prependArg, readDefinition, safeParseInt, syntaxError } from './common'; import { COMMENT, extendErrorMessage, EXTENSION, getSelfArg, parseTypeAndName, prependArg, readDefinition, safeParseInt, syntaxError } from './common';
import { Method } from './method'; import { Method } from './method';
import { Property, StaticProperty } from './property'; import { Property, StaticProperty } from './property';
import { Struct } from './struct'; import { Struct } from './struct';
// Error Handling // Error Handling
export class ErrorOnLine { export class ErrorOnLine extends Error {
readonly error: unknown; constructor (e: unknown, file: string, line: number) {
readonly file: string; // Get Message
readonly line: number; let message: string;
constructor (error: unknown, file: string, line: number) { if (e instanceof ErrorOnLine) {
this.error = error; message = e.message;
this.file = file; } else {
this.line = line; message = extendErrorMessage(e, file + ':' + line.toString());
}
// Call Constructor
super(message);
Object.setPrototypeOf(this, ErrorOnLine.prototype);
} }
} }
// Parse Property // Parse Property
function parseProperty(args: string) { function parseProperty(args: string) {
const parts = args.split(' = '); const [a, b] = args.split(' = ');
if (parts.length !== 2) { if (!a || !b) {
syntaxError('Invalid Piece Count'); syntaxError('Invalid Piece Count');
} }
const {type, name} = parseTypeAndName(parts[0]!); const {type, name} = parseTypeAndName(a);
const offset = safeParseInt(parts[1]!); const offset = safeParseInt(b);
return {type, name, offset}; return {type, name, offset};
} }
@ -35,10 +39,10 @@ function parseMethod(args: string, self: string, insertSelfArg: boolean, isInher
const start = args.substring(0, argsStart).trim(); const start = args.substring(0, argsStart).trim();
const {type, name} = parseTypeAndName(start); const {type, name} = parseTypeAndName(start);
const end = args.substring(argsStart).trim().split(' = '); const end = args.substring(argsStart).trim().split(' = ');
if (end.length !== 2) { if (!end[0] || !end[1]) {
syntaxError('Invalid Piece Count'); syntaxError('Invalid Piece Count');
} }
let methodArgs = end[0]!; let methodArgs = end[0];
if (!methodArgs.startsWith('(') || !methodArgs.endsWith(')')) { if (!methodArgs.startsWith('(') || !methodArgs.endsWith(')')) {
syntaxError('Invalid Method Arguments'); syntaxError('Invalid Method Arguments');
} }
@ -46,7 +50,7 @@ function parseMethod(args: string, self: string, insertSelfArg: boolean, isInher
const selfArg = getSelfArg(self); const selfArg = getSelfArg(self);
methodArgs = prependArg(methodArgs, selfArg); methodArgs = prependArg(methodArgs, selfArg);
} }
const address = safeParseInt(end[1]!); const address = safeParseInt(end[1]);
return new Method(self, name, type, methodArgs, address, isInherited, !insertSelfArg); return new Method(self, name, type, methodArgs, address, isInherited, !insertSelfArg);
} }
@ -197,9 +201,6 @@ export function load(target: Struct, name: string, isExtended: boolean) {
} }
} }
} catch (e) { } catch (e) {
if (e instanceof ErrorOnLine) {
throw e;
}
// Find Line Number // Find Line Number
let lineNumber = 1; let lineNumber = 1;
for (let i = 0; i <= startOfCommand; i++) { for (let i = 0; i <= startOfCommand; i++) {

View File

@ -1,14 +1,14 @@
import { Struct } from './struct'; import { Struct } from './struct';
import { ErrorOnLine, load } from './loader'; import { load } from './loader';
// Store Loaded Structures // Store Loaded Structures
const structures: {[id: string]: Struct} = {}; const structures: Record<string, Struct> = {};
// Get Or Load Structure // Get Or Load Structure
export function getStructure(name: string) { export function getStructure(name: string) {
if (name in structures) { if (structures[name]) {
// Already Loaded // Already Loaded
return structures[name]!; return structures[name];
} else { } else {
// Load Structure // Load Structure
try { try {
@ -20,14 +20,11 @@ export function getStructure(name: string) {
// Return // Return
return target; return target;
} catch (e) { } catch (e) {
let error = e; let message = 'Error Loading ' + name;
let extra = ''; if (e instanceof Error) {
if (e instanceof ErrorOnLine) { message += ': ' + e.message;
extra = `${e.file}:${e.line}: `;
error = e.error;
} }
console.log(`Error Loading ${name}: ${extra}${error instanceof Error ? error.stack : error}`); throw new Error(message);
process.exit(1);
} }
} }
} }

View File

@ -21,7 +21,7 @@ export class Method {
} }
// Getters // Getters
getName(separator: string = '_') { getName(separator = '_') {
return this.self + separator + this.shortName; return this.self + separator + this.shortName;
} }
getType() { getType() {

View File

@ -49,11 +49,6 @@ export class Property {
} }
export class StaticProperty extends Property { export class StaticProperty extends Property {
// Constructor
constructor(address: number, type: string, name: string, self: string) {
super(address, type, name, self);
}
// Reference // Reference
referenceDefinition(addSelf: boolean) { referenceDefinition(addSelf: boolean) {
return `${this.type()} &${addSelf ? this.prettyName() : this.name()}`; return `${this.type()} &${addSelf ? this.prettyName() : this.name()}`;

View File

@ -85,7 +85,7 @@ export class Struct {
this.#isSimple = true; this.#isSimple = true;
} }
#checkSimple() { #checkSimple() {
const checks = [ const checks: [string, boolean][] = [
['Cannot Inherit', this.#directParent !== null], ['Cannot Inherit', this.#directParent !== null],
['Must Have A Defined Size', this.#size === null], ['Must Have A Defined Size', this.#size === null],
['Cannot Have A VTable', this.#vtable !== null] ['Cannot Have A VTable', this.#vtable !== null]
@ -113,10 +113,9 @@ export class Struct {
// Add Properties // Add Properties
let out = ''; let out = '';
for (let i = 0; i < sortedProperties.length; i++) { let lastProperty: Property | null = null;
const property = sortedProperties[i]!; let i = 0;
const lastProperty = sortedProperties[i - 1]; for (const property of sortedProperties) {
// Padding // Padding
let offsetFromLastProperty = property.offset; let offsetFromLastProperty = property.offset;
if (lastProperty) { if (lastProperty) {
@ -127,13 +126,17 @@ export class Struct {
paddingSize += ` - sizeof(${lastProperty.type()})`; paddingSize += ` - sizeof(${lastProperty.type()})`;
} }
if (!this.#isSimple) { if (!this.#isSimple) {
out += `${INDENT}uchar ${INTERNAL}padding${i}[${paddingSize}];\n`; out += `${INDENT}uchar ${INTERNAL}padding${i.toString()}[${paddingSize}];\n`;
} }
// The Actual Property // The Actual Property
if (property !== sizeProperty) { if (property !== sizeProperty) {
out += `${INDENT}${property.type()} ${property.name()};\n`; out += `${INDENT}${property.type()} ${property.name()};\n`;
} }
// Advance
lastProperty = property;
i++;
} }
return out; return out;
} }
@ -171,9 +174,7 @@ export class Struct {
if (this.#vtable !== null) { if (this.#vtable !== null) {
const virtualMethods = this.#vtable.getMethods(); const virtualMethods = this.#vtable.getMethods();
for (const method of virtualMethods) { for (const method of virtualMethods) {
if (method) { out += this.#generateMethod(method, true);
out += this.#generateMethod(method, true);
}
} }
} }
// Allocation Method // Allocation Method
@ -241,8 +242,7 @@ export class Struct {
out += `};\n`; out += `};\n`;
// Sanity Check Offsets // Sanity Check Offsets
for (let i = 0; i < this.#properties.length; i++) { for (const property of this.#properties) {
const property = this.#properties[i]!;
const name = property.name(); const name = property.name();
const offset = property.offset; const offset = property.offset;
out += `static_assert(offsetof(${this.name}, ${name}) == ${toHex(offset)}, "Invalid Offset");\n`; out += `static_assert(offsetof(${this.name}, ${name}) == ${toHex(offset)}, "Invalid Offset");\n`;

View File

@ -43,7 +43,7 @@ export class VTable {
} }
// Add // Add
const index = offset / POINTER_SIZE; const index = offset / POINTER_SIZE;
if (target[index]) { if (index in target) {
throw new Error(`Duplicate Virtual Method At Offset: ${toHex(offset)}`); throw new Error(`Duplicate Virtual Method At Offset: ${toHex(offset)}`);
} }
target[index] = method; target[index] = method;
@ -88,11 +88,11 @@ export class VTable {
// Get Parent Method // Get Parent Method
#getParentSelf(method: Method, parent: string | null) { #getParentSelf(method: Method, parent: string | null) {
if (method.isInherited) { if (method.isInherited && parent) {
// Parent Exists // Parent Exists
let out: string; let out: string;
if (structuresWithVTableAddress.includes(parent!)) { if (structuresWithVTableAddress.includes(parent)) {
out = parent!; out = parent;
} else { } else {
// Unable To Determine // Unable To Determine
out = this.#self; out = this.#self;
@ -119,11 +119,9 @@ export class VTable {
let typedefs = ''; let typedefs = '';
let methodsOut = ''; let methodsOut = '';
for (const info of methods) { for (const info of methods) {
if (info) { typedefs += info.generateTypedefs();
typedefs += info.generateTypedefs(); if (this.canGenerateWrappers()) {
if (this.canGenerateWrappers()) { methodsOut += info.generate(false, true);
methodsOut += info.generate(false, true);
}
} }
} }
out += typedefs; out += typedefs;
@ -139,7 +137,7 @@ export class VTable {
if (info) { if (info) {
out += info.getProperty(); out += info.getProperty();
} else { } else {
out += `${INDENT}void *unknown${i};\n`; out += `${INDENT}void *unknown${i.toString()};\n`;
} }
} }
if (this.#size === null) { if (this.#size === null) {
@ -178,9 +176,7 @@ export class VTable {
if (this.canGenerateWrappers()) { if (this.canGenerateWrappers()) {
const methods = this.getMethods(); const methods = this.getMethods();
for (const info of methods) { for (const info of methods) {
if (info) { out += info.generate(true, true, this.#getParentSelf(info, directParent));
out += info.generate(true, true, this.#getParentSelf(info, directParent));
}
} }
} }

View File

@ -1,11 +1,11 @@
{ {
"extends": [ "extends": [
"@tsconfig/strictest/tsconfig", "@tsconfig/strictest/tsconfig",
"@tsconfig/node-lts/tsconfig" "@tsconfig/node18/tsconfig"
], ],
"compilerOptions": { "compilerOptions": {
"rootDir": "./src", "outDir": "build",
"outDir": "./build" "rootDir": "src"
}, },
"include": [ "include": [
"src" "src"