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

View File

@ -1,28 +1,47 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
// Constants
export const INDENT = ' ';
export const POINTER_SIZE = 4;
export const RTTI_SIZE = POINTER_SIZE;
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) {
if (!STRUCTURE_FILES[name]) {
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) {
throw new Error('Syntax Error' + (message ? `: ${message}` : ''));
// Error Handling
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) {
// Split On Last Space
const index = piece.lastIndexOf(' ');
if (index === -1) {
syntaxError('Unable To Find Name/Type Divider');
}
let name = piece.substring(index + 1)!;
let type = piece.substring(0, index)!;
let name = piece.substring(index + 1);
let type = piece.substring(0, index);
// Move Asterisks From Name To Type
while (name.startsWith('*') || name.startsWith('&')) {
const x = name.substring(0, 1);
@ -35,6 +54,7 @@ export function parseTypeAndName(piece: string) {
// Return
return {type, name};
}
// Convert To Uppercase-Snake-Case
export function toUpperSnakeCase(str: string) {
let wasUpper = false;
let nextIsUpper = false;
@ -57,19 +77,22 @@ export function toUpperSnakeCase(str: string) {
}
return out;
}
// Convert 'int' To 'int ' But Leave 'int *' As Is
export function formatType(type: string) {
if (!type.endsWith('*') && !type.endsWith('&')) {
type += ' ';
}
return type;
}
export const COMMENT = '//';
// Convert Number To Hexadecimal
export function toHex(x: number) {
return '0x' + x.toString(16);
}
// Generate C++ Size Assertion
export function assertSize(name: string, size: number) {
return `static_assert(sizeof(${name}) == ${toHex(size)}, "Invalid Size");\n`;
}
// Parse Integer With Error Checking
export function safeParseInt(str: string) {
const x = parseInt(str);
if (isNaN(x)) {
@ -77,31 +100,45 @@ export function safeParseInt(str: string) {
}
return x;
}
// Generate "Self" Argument For Functions
export function getSelfArg(type: string) {
return `${type} *self`;
}
// Prepend Argument To Function
export function prependArg(args: string, arg: string) {
if (args !== '()') {
arg += ', ';
}
return '(' + arg + args.substring(1);
}
// Get Data Directory
export function getDataDir() {
return path.join(__dirname, '..', 'data');
}
export function formatFile(file: string, options: {[key: string]: string}) {
file = path.join(getDataDir(), file);
let data = fs.readFileSync(file, {encoding: 'utf8'});
// Format File From Data Directory
export function formatFile(file: string, options: Record<string, string>) {
// 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) {
data = data.replace(`{{ ${key} }}`, options[key]!);
const value = options[key];
if (value) {
data = data.replace(`{{ ${key} }}`, value);
}
}
return data.trim() + '\n';
}
export const INTERNAL = '__';
// Generate Code That Will Disable C++ Construction
export function preventConstruction(self: string) {
let out = '';
out += `${INDENT}${INTERNAL}PREVENT_CONSTRUCTION(${self});\n`;
out += `${INDENT}${INTERNAL}PREVENT_COPY(${self});\n`;
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 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 { Struct } from './struct';
// Arguments
if (process.argv.length < 5) {
console.log('USAGE: npm start -- <Source Output File> <Header Output File> <Input Files...>');
// Handle Errors
process.on('uncaughtException', function (e) {
console.error('Error: ' + e.message);
process.exit(1);
});
// Arguments
function nextArgument() {
const out = process.argv.shift();
if (!out) {
throw new Error('Not Enough Arguments!');
}
process.argv.shift();
process.argv.shift();
return out;
}
nextArgument();
nextArgument();
// Output Files
function invalidFileType(file: string) {
throw new Error(`Invalid File Type: ${file}`);
}
const sourceOutput = process.argv.shift()!;
const sourceOutput = nextArgument();
fs.rmSync(sourceOutput, {force: true, recursive: true});
fs.mkdirSync(sourceOutput, {recursive: true});
const headerOutput = process.argv.shift()!;
const headerOutput = nextArgument();
if (!headerOutput.endsWith('.h')) {
invalidFileType(headerOutput);
}
// Input Files
const extraHeaderFiles: string[] = [];
while (process.argv.length > 0) {
const file = process.argv.shift()!;
if (file.endsWith(EXTENSION)) {
const filePath = nextArgument();
const file = path.parse(filePath);
if (file.ext === EXTENSION) {
// Get Class Name
const parts = file.split('/');
let name = parts[parts.length - 1]!;
name = name.substring(0, name.length - EXTENSION.length);
const fullName = file.base;
const name = file.name;
// Store
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;
} else if (file.endsWith('.h')) {
STRUCTURE_FILES[name] = filePath;
} else if (file.ext === '.h') {
// Extra Headers
extraHeaderFiles.push(file);
extraHeaderFiles.push(filePath);
} else {
// Invalid File Type
invalidFileType(file);
invalidFileType(filePath);
}
}
@ -67,7 +78,7 @@ function loadSymbols() {
// Sort Structures By Dependency
function dependencySort(structureObjects: Struct[]) {
let loops = 0;
const MAX_LOOPS = 100;
const MAX_LOOPS = 1000;
while (true) {
if (loops > MAX_LOOPS) {
throw new Error('Unable To Sort Dependencies');
@ -118,8 +129,7 @@ function makeHeaderPart() {
try {
structures += structure.generate();
} catch (e) {
console.log(`Error Generating Header: ${name}: ${e instanceof Error ? e.stack : e}`);
process.exit(1);
throw new Error(extendErrorMessage(e, 'Error Generating Header: ' + name));
}
structures += '\n';
}
@ -172,8 +182,7 @@ function makeCompiledCode(outputDir: string) {
try {
declarations += structure.generateCode().trim();
} catch (e) {
console.log(`Error Generating Code: ${name}: ${e instanceof Error ? e.stack : e}`);
process.exit(1);
throw new Error(extendErrorMessage(e, 'Error Generating Code: ' + name));
}
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 { Property, StaticProperty } from './property';
import { Struct } from './struct';
// Error Handling
export class ErrorOnLine {
readonly error: unknown;
readonly file: string;
readonly line: number;
constructor (error: unknown, file: string, line: number) {
this.error = error;
this.file = file;
this.line = line;
export class ErrorOnLine extends Error {
constructor (e: unknown, file: string, line: number) {
// Get Message
let message: string;
if (e instanceof ErrorOnLine) {
message = e.message;
} else {
message = extendErrorMessage(e, file + ':' + line.toString());
}
// Call Constructor
super(message);
Object.setPrototypeOf(this, ErrorOnLine.prototype);
}
}
// Parse Property
function parseProperty(args: string) {
const parts = args.split(' = ');
if (parts.length !== 2) {
const [a, b] = args.split(' = ');
if (!a || !b) {
syntaxError('Invalid Piece Count');
}
const {type, name} = parseTypeAndName(parts[0]!);
const offset = safeParseInt(parts[1]!);
const {type, name} = parseTypeAndName(a);
const offset = safeParseInt(b);
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 {type, name} = parseTypeAndName(start);
const end = args.substring(argsStart).trim().split(' = ');
if (end.length !== 2) {
if (!end[0] || !end[1]) {
syntaxError('Invalid Piece Count');
}
let methodArgs = end[0]!;
let methodArgs = end[0];
if (!methodArgs.startsWith('(') || !methodArgs.endsWith(')')) {
syntaxError('Invalid Method Arguments');
}
@ -46,7 +50,7 @@ function parseMethod(args: string, self: string, insertSelfArg: boolean, isInher
const selfArg = getSelfArg(self);
methodArgs = prependArg(methodArgs, selfArg);
}
const address = safeParseInt(end[1]!);
const address = safeParseInt(end[1]);
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) {
if (e instanceof ErrorOnLine) {
throw e;
}
// Find Line Number
let lineNumber = 1;
for (let i = 0; i <= startOfCommand; i++) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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