Compare commits
2 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
cd20feda59 | ||
|
db3879f7a5 |
2
.eslintignore
Normal file
2
.eslintignore
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
/build
|
||||||
|
/node_modules
|
36
.eslintrc
Normal file
36
.eslintrc
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
@ -1,24 +0,0 @@
|
|||||||
name: 'CI'
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
|
|
||||||
# Jobs
|
|
||||||
jobs:
|
|
||||||
# Build Project
|
|
||||||
build:
|
|
||||||
name: Build
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout Repository
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
# Dependencies
|
|
||||||
- name: Install Dependencies
|
|
||||||
run: npm ci
|
|
||||||
# Test
|
|
||||||
- name: Test
|
|
||||||
run: npm test
|
|
||||||
# Lint
|
|
||||||
- name: Lint
|
|
||||||
run: npm run lint
|
|
117
data/function.h
117
data/function.h
@ -1,117 +0,0 @@
|
|||||||
#include <functional>
|
|
||||||
#include <utility>
|
|
||||||
|
|
||||||
// Information Interface
|
|
||||||
template <typename Ret, typename... Args>
|
|
||||||
class __FunctionInfo {
|
|
||||||
typedef Ret (*type)(Args...);
|
|
||||||
public:
|
|
||||||
[[nodiscard]] virtual bool can_overwrite() const = 0;
|
|
||||||
[[nodiscard]] virtual type get() const = 0;
|
|
||||||
[[nodiscard]] virtual type *get_addr() const = 0;
|
|
||||||
virtual void update(type new_func) = 0;
|
|
||||||
virtual ~__FunctionInfo() = default;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Thunks
|
|
||||||
typedef void *(*thunk_enabler_t)(void *target, void *thunk);
|
|
||||||
extern thunk_enabler_t thunk_enabler;
|
|
||||||
|
|
||||||
// Function
|
|
||||||
template <unsigned int, typename T>
|
|
||||||
class __Function;
|
|
||||||
template <unsigned int discriminator, typename Ret, typename... Args>
|
|
||||||
class __Function<discriminator, Ret(Args...)> final {
|
|
||||||
// Prevent Copying
|
|
||||||
__PREVENT_COPY(__Function);
|
|
||||||
__PREVENT_DESTRUCTION(__Function);
|
|
||||||
|
|
||||||
// Instance
|
|
||||||
static __Function *instance;
|
|
||||||
|
|
||||||
// Current Function
|
|
||||||
typedef __FunctionInfo<Ret, Args...> *func_t;
|
|
||||||
const func_t func;
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Types
|
|
||||||
typedef Ret (*ptr_type)(Args...);
|
|
||||||
typedef std::function<Ret(Args...)> type;
|
|
||||||
typedef std::function<Ret(const type &, Args...)> overwrite_type;
|
|
||||||
|
|
||||||
// State
|
|
||||||
const bool enabled;
|
|
||||||
const char *const name;
|
|
||||||
|
|
||||||
// Backup Of Original Function Pointer
|
|
||||||
const ptr_type backup;
|
|
||||||
|
|
||||||
#ifdef {{ BUILDING_SYMBOLS_GUARD }}
|
|
||||||
// Constructor
|
|
||||||
__Function(const char *const name_, const func_t func_):
|
|
||||||
func(func_),
|
|
||||||
enabled(func->can_overwrite()),
|
|
||||||
name(name_),
|
|
||||||
backup(func->get())
|
|
||||||
{
|
|
||||||
instance = this;
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
// Prevent Construction
|
|
||||||
__PREVENT_JUST_CONSTRUCTION(__Function);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Overwrite Function
|
|
||||||
[[nodiscard]] bool overwrite(const overwrite_type &target) {
|
|
||||||
// Check If Enabled
|
|
||||||
if (!enabled) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
// Enable Thunk
|
|
||||||
enable_thunk();
|
|
||||||
// Overwrite
|
|
||||||
type original = get_thunk_target();
|
|
||||||
thunk_target = [original, target](Args... args) {
|
|
||||||
return target(original, std::forward<Args>(args)...);
|
|
||||||
};
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Getters
|
|
||||||
[[nodiscard]] ptr_type get(const bool result_will_be_stored) {
|
|
||||||
if (!enabled) {
|
|
||||||
return nullptr;
|
|
||||||
} else {
|
|
||||||
if (result_will_be_stored) {
|
|
||||||
enable_thunk();
|
|
||||||
}
|
|
||||||
return func->get();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
[[nodiscard]] ptr_type *get_vtable_addr() const {
|
|
||||||
return func->get_addr();
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
// Thunk
|
|
||||||
[[nodiscard]] type get_thunk_target() const {
|
|
||||||
if (thunk_target) {
|
|
||||||
return thunk_target;
|
|
||||||
} else {
|
|
||||||
return backup;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
static Ret thunk(Args... args) {
|
|
||||||
return instance->get_thunk_target()(std::forward<Args>(args)...);
|
|
||||||
}
|
|
||||||
// Enable Thunk
|
|
||||||
type thunk_target;
|
|
||||||
bool thunk_enabled = false;
|
|
||||||
void enable_thunk() {
|
|
||||||
if (!thunk_enabled && enabled) {
|
|
||||||
ptr_type real_thunk = (ptr_type) thunk_enabler((void *) backup, (void *) thunk);
|
|
||||||
func->update(real_thunk);
|
|
||||||
thunk_enabled = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
@ -1,16 +0,0 @@
|
|||||||
#define __PREVENT_DESTRUCTION(self) \
|
|
||||||
~self() = delete
|
|
||||||
#define __PREVENT_JUST_CONSTRUCTION(self) \
|
|
||||||
self() = delete
|
|
||||||
#define __PREVENT_CONSTRUCTION(self) \
|
|
||||||
__PREVENT_JUST_CONSTRUCTION(self); \
|
|
||||||
__PREVENT_DESTRUCTION(self)
|
|
||||||
#define __PREVENT_COPY(self) \
|
|
||||||
self(const self &) = delete; \
|
|
||||||
self &operator=(const self &) = delete
|
|
||||||
template <typename T>
|
|
||||||
static constexpr decltype(sizeof(T)) __real_sizeof() {
|
|
||||||
return sizeof(std::conditional_t<std::is_reference_v<T>, void *, T>);
|
|
||||||
}
|
|
||||||
template <typename T>
|
|
||||||
using __make_reference = T &;
|
|
69
data/out.cpp
69
data/out.cpp
@ -1,69 +0,0 @@
|
|||||||
#define {{ BUILDING_SYMBOLS_GUARD }}
|
|
||||||
#include "{{ headerPath }}"
|
|
||||||
|
|
||||||
// Global Instance
|
|
||||||
template <unsigned int id, typename Ret, typename... Args>
|
|
||||||
__Function<id, Ret(Args...)> *__Function<id, Ret(Args...)>::instance;
|
|
||||||
|
|
||||||
// Normal Function Information
|
|
||||||
template <typename Ret, typename... Args>
|
|
||||||
class __NormalFunctionInfo final : public __FunctionInfo<Ret, Args...> {
|
|
||||||
typedef Ret (*type)(Args...);
|
|
||||||
type func;
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
explicit __NormalFunctionInfo(const type func_):
|
|
||||||
func(func_) {}
|
|
||||||
// Functions
|
|
||||||
[[nodiscard]] bool can_overwrite() const override {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
[[nodiscard]] type get() const override {
|
|
||||||
return func;
|
|
||||||
}
|
|
||||||
[[nodiscard]] type *get_addr() const override {
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
void update(const type new_func) override {
|
|
||||||
func = new_func;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Virtual Function Information
|
|
||||||
template <typename Ret, typename... Args>
|
|
||||||
class __VirtualFunctionInfo final : public __FunctionInfo<Ret, Args...> {
|
|
||||||
typedef Ret (*type)(Args...);
|
|
||||||
type *const addr;
|
|
||||||
void *const parent;
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
__VirtualFunctionInfo(type *const addr_, void *const parent_):
|
|
||||||
addr(addr_),
|
|
||||||
parent(parent_) {}
|
|
||||||
// Functions
|
|
||||||
[[nodiscard]] bool can_overwrite() const override {
|
|
||||||
// If this function's address matches its parent's,
|
|
||||||
// then it was just inherited and does not actually exist.
|
|
||||||
// Overwriting this function would also overwrite its parent
|
|
||||||
// which would cause undesired behavior.
|
|
||||||
return get() != parent;
|
|
||||||
}
|
|
||||||
[[nodiscard]] type get() const override {
|
|
||||||
return *get_addr();
|
|
||||||
}
|
|
||||||
[[nodiscard]] type *get_addr() const override {
|
|
||||||
return addr;
|
|
||||||
}
|
|
||||||
void update(const type new_func) override {
|
|
||||||
// Address Should Have Already Been Updated
|
|
||||||
if (get() != new_func) {
|
|
||||||
__builtin_trap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
#undef super
|
|
||||||
|
|
||||||
// Disable Warnings
|
|
||||||
#pragma GCC diagnostic ignored "-Winvalid-offsetof"
|
|
||||||
|
|
||||||
{{ main }}
|
|
42
data/out.h
42
data/out.h
@ -1,42 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
// Check Architecture
|
|
||||||
#ifndef __arm__
|
|
||||||
#error "Symbols Are ARM-Only"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Type Traits
|
|
||||||
#include <type_traits>
|
|
||||||
|
|
||||||
// Internal Macros
|
|
||||||
{{ include internal.h }}
|
|
||||||
|
|
||||||
// Function Object
|
|
||||||
{{ include function.h }}
|
|
||||||
|
|
||||||
// Headers
|
|
||||||
#include <cstddef>
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
#include <map>
|
|
||||||
#include <cstring>
|
|
||||||
|
|
||||||
// Shortcuts
|
|
||||||
typedef unsigned char uchar;
|
|
||||||
typedef unsigned short ushort;
|
|
||||||
typedef unsigned int uint;
|
|
||||||
|
|
||||||
// Forward Declarations
|
|
||||||
{{ forwardDeclarations }}
|
|
||||||
|
|
||||||
// Extra Headers
|
|
||||||
{{ extraHeaders }}
|
|
||||||
|
|
||||||
// Warnings
|
|
||||||
#pragma GCC diagnostic push
|
|
||||||
#pragma GCC diagnostic ignored "-Wshadow"
|
|
||||||
|
|
||||||
{{ main }}
|
|
||||||
|
|
||||||
// Cleanup Warnings
|
|
||||||
#pragma GCC diagnostic pop
|
|
@ -1,84 +0,0 @@
|
|||||||
// @ts-check
|
|
||||||
import eslint from '@eslint/js';
|
|
||||||
import tseslint from 'typescript-eslint';
|
|
||||||
import stylistic from '@stylistic/eslint-plugin';
|
|
||||||
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,
|
|
||||||
stylistic.configs.recommended,
|
|
||||||
{
|
|
||||||
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'
|
|
||||||
}
|
|
||||||
],
|
|
||||||
'@stylistic/quotes': [
|
|
||||||
'error',
|
|
||||||
'single',
|
|
||||||
{
|
|
||||||
allowTemplateLiterals: 'avoidEscape'
|
|
||||||
}
|
|
||||||
],
|
|
||||||
'@stylistic/indent': [
|
|
||||||
'error',
|
|
||||||
4,
|
|
||||||
{
|
|
||||||
SwitchCase: 1
|
|
||||||
}
|
|
||||||
],
|
|
||||||
'@stylistic/comma-dangle': [
|
|
||||||
'error',
|
|
||||||
'never'
|
|
||||||
],
|
|
||||||
'@stylistic/quote-props': [
|
|
||||||
'error',
|
|
||||||
'as-needed'
|
|
||||||
],
|
|
||||||
'@stylistic/semi': [
|
|
||||||
'error',
|
|
||||||
'always'
|
|
||||||
],
|
|
||||||
'@stylistic/eol-last': [
|
|
||||||
'error',
|
|
||||||
'never'
|
|
||||||
],
|
|
||||||
'@stylistic/lines-between-class-members': 'off',
|
|
||||||
'@stylistic/object-curly-spacing': 'off',
|
|
||||||
'@stylistic/brace-style': [
|
|
||||||
'error',
|
|
||||||
'1tbs'
|
|
||||||
],
|
|
||||||
eqeqeq: 'error'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
ignores: [
|
|
||||||
'build/',
|
|
||||||
'node_modules/'
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
files: [
|
|
||||||
'src/test/**/*'
|
|
||||||
],
|
|
||||||
rules: {
|
|
||||||
'@typescript-eslint/no-floating-promises': 'off'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
963
package-lock.json
generated
963
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
20
package.json
20
package.json
@ -4,20 +4,18 @@
|
|||||||
"description": "",
|
"description": "",
|
||||||
"main": "build/index.js",
|
"main": "build/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "rm -rf build && tsc",
|
"start": "tsc && node build/index.js",
|
||||||
"start": "npm run build && node build/index.js",
|
"lint": "eslint . --ext .ts"
|
||||||
"lint": "eslint .",
|
|
||||||
"test": "npm run build && node --test build/test"
|
|
||||||
},
|
},
|
||||||
"author": "TheBrokenRail",
|
"author": "TheBrokenRail",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@stylistic/eslint-plugin": "^4.0.1",
|
"@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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
192
src/common.ts
192
src/common.ts
@ -1,71 +1,38 @@
|
|||||||
import * as fs from 'node:fs';
|
import * as fs from 'node:fs';
|
||||||
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: Record<string, string> = {};
|
export const STRUCTURE_FILES: {[id: string]: string} = {};
|
||||||
export const COMMENT = '//';
|
|
||||||
export const INTERNAL = '__';
|
|
||||||
export const BUILDING_SYMBOLS_GUARD = 'BUILDING_SYMBOLS_LIB';
|
|
||||||
// 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'});
|
||||||
}
|
}
|
||||||
// Error Handling
|
export function syntaxError(message?: string) {
|
||||||
export function extendErrorMessage(e: unknown, message: string) {
|
throw new Error('Syntax Error' + (message ? `: ${message}` : ''));
|
||||||
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'}
|
|
||||||
const POINTER_TOKENS = ['*', '&'];
|
|
||||||
export function parseTypeAndName(piece: string) {
|
export function parseTypeAndName(piece: string) {
|
||||||
piece = piece.trim();
|
|
||||||
// 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 (POINTER_TOKENS.some(x => name.startsWith(x))) {
|
while (name.startsWith('*')) {
|
||||||
const x = name.substring(0, 1);
|
|
||||||
name = name.substring(1);
|
name = name.substring(1);
|
||||||
if (!POINTER_TOKENS.some(x => type.endsWith(x))) {
|
if (!type.endsWith('*')) {
|
||||||
type += ' ';
|
type += ' ';
|
||||||
}
|
}
|
||||||
type += x;
|
type += '*';
|
||||||
}
|
|
||||||
// Trim
|
|
||||||
name = name.trim();
|
|
||||||
if (name.length === 0) {
|
|
||||||
syntaxError();
|
|
||||||
}
|
|
||||||
type = type.trim();
|
|
||||||
if (type.length === 0) {
|
|
||||||
syntaxError();
|
|
||||||
}
|
}
|
||||||
// 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;
|
||||||
@ -88,134 +55,69 @@ 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) {
|
||||||
type = type.trim();
|
if (!type.endsWith('*')) {
|
||||||
if (!POINTER_TOKENS.some(x => type.endsWith(x))) {
|
|
||||||
type += ' ';
|
type += ' ';
|
||||||
}
|
}
|
||||||
return type;
|
return type;
|
||||||
}
|
}
|
||||||
// Convert Number To Hexadecimal
|
export const COMMENT = '//';
|
||||||
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`;
|
let out = '';
|
||||||
|
// Define Size Macro
|
||||||
|
const macro = toUpperSnakeCase(name) + '_SIZE';
|
||||||
|
out += `#define ${macro} ${toHex(size)}\n`;
|
||||||
|
// Check Size
|
||||||
|
out += `static_assert(sizeof(${name}) == ${macro}, "Invalid Size");\n`;
|
||||||
|
// Return
|
||||||
|
return out;
|
||||||
}
|
}
|
||||||
// Parse Integer With Error Checking
|
|
||||||
export function safeParseInt(str: string) {
|
export function safeParseInt(str: string) {
|
||||||
str = str.trim();
|
|
||||||
const x = parseInt(str);
|
const x = parseInt(str);
|
||||||
if (isNaN(x)) {
|
if (isNaN(x)) {
|
||||||
throw new Error('Invalid Integer: ' + str);
|
throw new Error('Invalid Integer: ' + str);
|
||||||
}
|
}
|
||||||
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 getArgNames(args: string) {
|
||||||
|
// Remove Parentheses
|
||||||
|
args = args.substring(1, args.length - 1);
|
||||||
|
if (args.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
// Split
|
||||||
|
const argsList = args.split(',');
|
||||||
|
// Parse
|
||||||
|
const out = [];
|
||||||
|
for (let arg of argsList) {
|
||||||
|
arg = arg.trim();
|
||||||
|
// Remove Type
|
||||||
|
const nameStart = Math.max(arg.lastIndexOf(' '), arg.lastIndexOf('*')) + 1;
|
||||||
|
arg = arg.substring(nameStart);
|
||||||
|
// Collect
|
||||||
|
out.push(arg);
|
||||||
|
}
|
||||||
|
// Return
|
||||||
|
return out;
|
||||||
|
}
|
||||||
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 removeFirstArg(args: string) {
|
||||||
export function getDataDir() {
|
let index = args.indexOf(',');
|
||||||
return path.join(__dirname, '..', 'data');
|
if (index === -1) {
|
||||||
}
|
index = args.indexOf(')');
|
||||||
// Format File From Data Directory
|
} else {
|
||||||
export function formatFile(file: string, options: Record<string, string>, includeOtherFiles = true) {
|
index++;
|
||||||
const newOptions = Object.assign({}, options);
|
|
||||||
const dataDir = getDataDir();
|
|
||||||
// Include Other Files
|
|
||||||
if (includeOtherFiles) {
|
|
||||||
const otherFiles = fs.readdirSync(dataDir);
|
|
||||||
for (const otherFile of otherFiles) {
|
|
||||||
newOptions[`include ${otherFile}`] = formatFile(otherFile, options, false);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
// Format
|
return '(' + args.substring(index).trim();
|
||||||
file = path.join(dataDir, file);
|
|
||||||
let data = fs.readFileSync(file, 'utf8');
|
|
||||||
for (const key in newOptions) {
|
|
||||||
let value = newOptions[key];
|
|
||||||
if (value) {
|
|
||||||
value = value.trim();
|
|
||||||
data = data.replace(`{{ ${key} }}`, value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return data.trim() + '\n';
|
|
||||||
}
|
|
||||||
// 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;
|
|
||||||
}
|
|
||||||
// Remove Array Information From Variable Name
|
|
||||||
export function extractArrayInfo(name: string) {
|
|
||||||
let arrayInfo = '';
|
|
||||||
const arrayInfoIndex = name.indexOf('[');
|
|
||||||
if (arrayInfoIndex !== -1) {
|
|
||||||
arrayInfo = name.substring(arrayInfoIndex);
|
|
||||||
name = name.substring(0, arrayInfoIndex);
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
name,
|
|
||||||
arrayInfo
|
|
||||||
};
|
|
||||||
}
|
|
||||||
// Forward Function Arguments Into Call
|
|
||||||
export function forwardArguments(args: string, extra: string[]) {
|
|
||||||
const separator = ',';
|
|
||||||
const openingParen = '(';
|
|
||||||
const opening = ['<', openingParen, '['];
|
|
||||||
const closingParen = ')';
|
|
||||||
const closing = ['>', closingParen, ']'];
|
|
||||||
// Remove Enclosing Parenthesis
|
|
||||||
args = args.trim();
|
|
||||||
if (!args.startsWith(openingParen) || !args.endsWith(closingParen)) {
|
|
||||||
syntaxError();
|
|
||||||
}
|
|
||||||
args = args.substring(openingParen.length, args.length - closingParen.length);
|
|
||||||
// Parse
|
|
||||||
const parts: string[] = [];
|
|
||||||
let start = 0;
|
|
||||||
const stack = [];
|
|
||||||
for (let i = 0; i < args.length; i++) {
|
|
||||||
const c = args.charAt(i);
|
|
||||||
if (stack.length === 0 && c === separator) {
|
|
||||||
parts.push(args.substring(start, i));
|
|
||||||
start = i + 1;
|
|
||||||
} else if (opening.includes(c)) {
|
|
||||||
stack.push(c);
|
|
||||||
} else {
|
|
||||||
const i = closing.indexOf(c);
|
|
||||||
if (i !== -1) {
|
|
||||||
const x = stack.pop();
|
|
||||||
if (x !== opening[i]) {
|
|
||||||
syntaxError();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (stack.length !== 0) {
|
|
||||||
syntaxError();
|
|
||||||
}
|
|
||||||
if (start < args.length) {
|
|
||||||
parts.push(args.substring(start));
|
|
||||||
}
|
|
||||||
// Handle
|
|
||||||
const out: string[] = [];
|
|
||||||
for (const part of parts) {
|
|
||||||
out.push(extractArrayInfo(parseTypeAndName(part.trim()).name).name);
|
|
||||||
}
|
|
||||||
out.unshift(...extra);
|
|
||||||
return openingParen + out.join(separator + ' ') + closingParen;
|
|
||||||
}
|
}
|
171
src/index.ts
171
src/index.ts
@ -1,56 +1,45 @@
|
|||||||
import * as fs from 'node:fs';
|
import * as fs from 'node:fs';
|
||||||
import * as path from 'node:path';
|
import { STRUCTURE_FILES, EXTENSION, INDENT } from './common';
|
||||||
import { STRUCTURE_FILES, EXTENSION, formatFile, getDataDir, extendErrorMessage, BUILDING_SYMBOLS_GUARD } from './common';
|
|
||||||
import { getStructure } from './map';
|
import { getStructure } from './map';
|
||||||
import { Struct } from './struct';
|
import { Struct } from './struct';
|
||||||
|
|
||||||
// Handle Errors
|
|
||||||
process.on('uncaughtException', function (e) {
|
|
||||||
console.error('Error: ' + e.message);
|
|
||||||
process.exit(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Arguments
|
// Arguments
|
||||||
function nextArgument() {
|
if (process.argv.length < 5) {
|
||||||
const out = process.argv.shift();
|
console.log('USAGE: npm start -- <Source Output File> <Header Output File> <Input Files...>');
|
||||||
if (!out) {
|
process.exit(1);
|
||||||
throw new Error('Not Enough Arguments!');
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
}
|
||||||
nextArgument();
|
process.argv.shift();
|
||||||
nextArgument();
|
process.argv.shift();
|
||||||
// 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 = nextArgument();
|
const sourceOutput = process.argv.shift()!;
|
||||||
fs.rmSync(sourceOutput, {force: true, recursive: true});
|
if (!sourceOutput.endsWith('.cpp')) {
|
||||||
fs.mkdirSync(sourceOutput, {recursive: true});
|
invalidFileType(sourceOutput);
|
||||||
const headerOutput = nextArgument();
|
}
|
||||||
|
const headerOutput = process.argv.shift()!;
|
||||||
if (!headerOutput.endsWith('.h')) {
|
if (!headerOutput.endsWith('.h')) {
|
||||||
invalidFileType(headerOutput);
|
invalidFileType(headerOutput);
|
||||||
}
|
}
|
||||||
// Input Files
|
const extraHeaders: string[] = [];
|
||||||
const extraHeaderFiles: string[] = [];
|
|
||||||
while (process.argv.length > 0) {
|
while (process.argv.length > 0) {
|
||||||
const filePath = nextArgument();
|
const file = process.argv.shift()!;
|
||||||
const file = path.parse(filePath);
|
if (file.endsWith(EXTENSION)) {
|
||||||
if (file.ext === EXTENSION) {
|
|
||||||
// Get Class Name
|
// Get Class Name
|
||||||
const fullName = file.base;
|
const parts = file.split('/');
|
||||||
const name = file.name;
|
let name = parts[parts.length - 1]!;
|
||||||
|
name = name.substring(0, name.length - EXTENSION.length);
|
||||||
// Store
|
// Store
|
||||||
if (STRUCTURE_FILES[name]) {
|
if (name in STRUCTURE_FILES) {
|
||||||
throw new Error(`Multiple Definition Files Provided: ${fullName}`);
|
throw new Error(`Multiple Definition Files Provided: ${name}${EXTENSION}`);
|
||||||
}
|
}
|
||||||
STRUCTURE_FILES[name] = filePath;
|
STRUCTURE_FILES[name] = file;
|
||||||
} else if (file.ext === '.h') {
|
} else if (file.endsWith('.h')) {
|
||||||
// Extra Headers
|
// Extra Headers
|
||||||
extraHeaderFiles.push(filePath);
|
extraHeaders.push(file);
|
||||||
} else {
|
} else {
|
||||||
// Invalid File Type
|
// Invalid File Type
|
||||||
invalidFileType(filePath);
|
invalidFileType(file);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -63,9 +52,9 @@ function loadSymbols() {
|
|||||||
}
|
}
|
||||||
// Sort
|
// Sort
|
||||||
structureObjects.sort((a, b) => {
|
structureObjects.sort((a, b) => {
|
||||||
if (a.name > b.name) {
|
if (a.getName() > b.getName()) {
|
||||||
return 1;
|
return 1;
|
||||||
} else if (a.name < b.name) {
|
} else if (a.getName() < b.getName()) {
|
||||||
return -1;
|
return -1;
|
||||||
} else {
|
} else {
|
||||||
return 0;
|
return 0;
|
||||||
@ -78,7 +67,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 = 1000;
|
const MAX_LOOPS = 100;
|
||||||
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');
|
||||||
@ -123,75 +112,105 @@ function makeHeaderPart() {
|
|||||||
|
|
||||||
// Generate Code
|
// Generate Code
|
||||||
let structures = '';
|
let structures = '';
|
||||||
|
let isFirst = true;
|
||||||
for (const structure of structureObjects) {
|
for (const structure of structureObjects) {
|
||||||
const name = structure.name;
|
const name = structure.getName();
|
||||||
|
if (isFirst) {
|
||||||
|
isFirst = false;
|
||||||
|
} else {
|
||||||
|
structures += '\n';
|
||||||
|
}
|
||||||
structures += `// ${name}\n`;
|
structures += `// ${name}\n`;
|
||||||
try {
|
try {
|
||||||
structures += structure.generate();
|
structures += structure.generate();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw new Error(extendErrorMessage(e, 'Generating Header: ' + name));
|
console.log(`Error Generating Header: ${name}: ${e instanceof Error ? e.stack : e}`);
|
||||||
|
process.exit(1);
|
||||||
}
|
}
|
||||||
structures += '\n';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return
|
// Return
|
||||||
return structures;
|
let result = '';
|
||||||
|
result += '// Init\n';
|
||||||
|
result += 'void init_symbols();\n\n';
|
||||||
|
result += structures;
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create Main Header
|
// Create Main Header
|
||||||
function makeMainHeader(output: string) {
|
function makeMainHeader(output: string) {
|
||||||
// Forward Declarations
|
let result = '';
|
||||||
let forwardDeclarations = '';
|
result += '#pragma once\n';
|
||||||
|
result += '\n// Check Architecture\n';
|
||||||
|
result += '#ifndef __arm__\n';
|
||||||
|
result += '#error "Symbols Are ARM-Only"\n';
|
||||||
|
result += '#endif\n';
|
||||||
|
result += '\n// Shortcuts\n';
|
||||||
|
result += 'typedef unsigned char uchar;\n';
|
||||||
|
result += 'typedef unsigned short ushort;\n';
|
||||||
|
result += 'typedef unsigned int uint;\n';
|
||||||
|
result += '\n// Forward Declarations\n';
|
||||||
for (const name in STRUCTURE_FILES) {
|
for (const name in STRUCTURE_FILES) {
|
||||||
forwardDeclarations += `typedef struct ${name} ${name};\n`;
|
result += `typedef struct ${name} ${name};\n`;
|
||||||
}
|
}
|
||||||
forwardDeclarations = forwardDeclarations.trim();
|
result += '\n// Extra Headers\n';
|
||||||
// Extra Headers
|
for (const file of extraHeaders) {
|
||||||
let extraHeaders = '';
|
result += fs.readFileSync(file, {encoding: 'utf8'});
|
||||||
for (const file of extraHeaderFiles) {
|
|
||||||
extraHeaders += fs.readFileSync(file, {encoding: 'utf8'});
|
|
||||||
}
|
}
|
||||||
extraHeaders = extraHeaders.trim();
|
result += '\n// Headers\n';
|
||||||
// Main
|
result += '#include <cstddef>\n';
|
||||||
const main = makeHeaderPart().trim();
|
result += '#include <string>\n';
|
||||||
// Write
|
result += '#include <vector>\n';
|
||||||
const result = formatFile('out.h', {BUILDING_SYMBOLS_GUARD, forwardDeclarations, extraHeaders, main, data: getDataDir()});
|
result += '#include <map>\n';
|
||||||
|
result += '\n// Warnings\n';
|
||||||
|
result += '#pragma GCC diagnostic push\n';
|
||||||
|
result += '#pragma GCC diagnostic ignored "-Winvalid-offsetof"\n';
|
||||||
|
result += '#pragma GCC diagnostic ignored "-Wshadow"\n\n';
|
||||||
|
result += makeHeaderPart();
|
||||||
|
result += '\n// Cleanup Warnings\n';
|
||||||
|
result += '#pragma GCC diagnostic pop\n';
|
||||||
fs.writeFileSync(output, result);
|
fs.writeFileSync(output, result);
|
||||||
}
|
}
|
||||||
makeMainHeader(headerOutput);
|
makeMainHeader(headerOutput);
|
||||||
|
|
||||||
// Generate Compiled Code
|
// Generate Compiled Code
|
||||||
function makeCompiledCode(outputDir: string) {
|
function makeCompiledCode(output: string) {
|
||||||
// Load Symbols
|
// Load Symbols
|
||||||
const structureObjects = loadSymbols();
|
const structureObjects = loadSymbols();
|
||||||
|
|
||||||
// Generate
|
// Generate
|
||||||
let first = true;
|
let declarations = '';
|
||||||
|
let init = '';
|
||||||
|
let isFirst = true;
|
||||||
for (const structure of structureObjects) {
|
for (const structure of structureObjects) {
|
||||||
// Thunks
|
const name = structure.getName();
|
||||||
let declarations = '';
|
if (isFirst) {
|
||||||
if (first) {
|
isFirst = false;
|
||||||
first = false;
|
} else {
|
||||||
declarations += '// Thunk Enabler\n';
|
declarations += '\n';
|
||||||
declarations += 'thunk_enabler_t thunk_enabler;\n\n';
|
init += '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Structure
|
|
||||||
const name = structure.name;
|
|
||||||
declarations += `// ${name}\n`;
|
declarations += `// ${name}\n`;
|
||||||
|
init += `${INDENT}// ${name}\n`;
|
||||||
try {
|
try {
|
||||||
declarations += structure.generateCode().trim();
|
const code = structure.generateCode();
|
||||||
|
declarations += code.functions;
|
||||||
|
init += code.init;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw new Error(extendErrorMessage(e, 'Generating Code: ' + name));
|
console.log(`Error Generating Code: ${name}: ${e instanceof Error ? e.stack : e}`);
|
||||||
|
process.exit(1);
|
||||||
}
|
}
|
||||||
declarations += '\n';
|
|
||||||
|
|
||||||
// Write
|
|
||||||
const headerPath = fs.realpathSync(headerOutput);
|
|
||||||
const main = declarations.trim();
|
|
||||||
const result = formatFile('out.cpp', {BUILDING_SYMBOLS_GUARD, headerPath, main, data: getDataDir()});
|
|
||||||
const output = path.join(outputDir, name + '.cpp');
|
|
||||||
fs.writeFileSync(output, result);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Write
|
||||||
|
let result = '';
|
||||||
|
result += `#include "${fs.realpathSync(headerOutput)}"\n`;
|
||||||
|
result += '\n#include <cstring>\n';
|
||||||
|
result += '\n// Init\n';
|
||||||
|
result += 'void init_symbols() {\n';
|
||||||
|
result += init;
|
||||||
|
result += '}\n\n';
|
||||||
|
result += declarations;
|
||||||
|
fs.writeFileSync(output, result);
|
||||||
}
|
}
|
||||||
makeCompiledCode(sourceOutput);
|
makeCompiledCode(sourceOutput);
|
||||||
|
@ -1,53 +1,52 @@
|
|||||||
import { COMMENT, extendErrorMessage, EXTENSION, parseTypeAndName, readDefinition, safeParseInt, syntaxError } from './common';
|
import { COMMENT, 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
|
||||||
class ErrorOnLine extends Error {
|
export class ErrorOnLine {
|
||||||
constructor(e: unknown, file: string, line: number) {
|
readonly error: unknown;
|
||||||
// Get Message
|
readonly file: string;
|
||||||
let message: string;
|
readonly line: number;
|
||||||
if (e instanceof ErrorOnLine) {
|
constructor (error: unknown, file: string, line: number) {
|
||||||
message = e.message;
|
this.error = error;
|
||||||
} else {
|
this.file = file;
|
||||||
message = extendErrorMessage(e, file + ':' + line.toString());
|
this.line = line;
|
||||||
}
|
|
||||||
// Call Constructor
|
|
||||||
super(message);
|
|
||||||
Object.setPrototypeOf(this, ErrorOnLine.prototype);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse Property
|
// Parse Property
|
||||||
export const OFFSET_SEPARATOR = ' = ';
|
function parseProperty(args: string) {
|
||||||
export function parseProperty(args: string) {
|
const parts = args.split(' = ');
|
||||||
const [a, b] = args.split(OFFSET_SEPARATOR);
|
if (parts.length !== 2) {
|
||||||
if (!a || !b) {
|
|
||||||
syntaxError('Invalid Piece Count');
|
syntaxError('Invalid Piece Count');
|
||||||
}
|
}
|
||||||
const {type, name} = parseTypeAndName(a);
|
const {type, name} = parseTypeAndName(parts[0]!);
|
||||||
const offset = safeParseInt(b);
|
const offset = safeParseInt(parts[1]!);
|
||||||
return {type, name, offset};
|
return {type, name, offset};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse Method
|
// Parse Method
|
||||||
export function parseMethod(args: string, self: string, insertSelfArg: boolean, isInherited: boolean) {
|
function parseMethod(args: string, self: string, insertSelfArg: boolean, isInherited: boolean) {
|
||||||
const argsStart = args.indexOf('(');
|
const argsStart = args.indexOf('(');
|
||||||
if (argsStart === -1) {
|
if (argsStart === -1) {
|
||||||
syntaxError('Cannot Find Arguments');
|
syntaxError('Cannot Find Arguments');
|
||||||
}
|
}
|
||||||
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(OFFSET_SEPARATOR);
|
const end = args.substring(argsStart).trim().split(' = ');
|
||||||
if (!end[0] || !end[1]) {
|
if (end.length !== 2) {
|
||||||
syntaxError('Invalid Piece Count');
|
syntaxError('Invalid Piece Count');
|
||||||
}
|
}
|
||||||
const methodArgs = end[0].trim();
|
let methodArgs = end[0]!;
|
||||||
if (!methodArgs.startsWith('(') || !methodArgs.endsWith(')')) {
|
if (!methodArgs.startsWith('(') || !methodArgs.endsWith(')')) {
|
||||||
syntaxError('Invalid Method Arguments');
|
syntaxError('Invalid Method Arguments');
|
||||||
}
|
}
|
||||||
const address = safeParseInt(end[1]);
|
if (insertSelfArg) {
|
||||||
|
const selfArg = getSelfArg(self);
|
||||||
|
methodArgs = prependArg(methodArgs, selfArg);
|
||||||
|
}
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -117,29 +116,29 @@ export function load(target: Struct, name: string, isExtended: boolean) {
|
|||||||
case 'vtable-size': {
|
case 'vtable-size': {
|
||||||
// Set VTable Size
|
// Set VTable Size
|
||||||
if (!isExtended) {
|
if (!isExtended) {
|
||||||
target.getVTable().setSize(safeParseInt(args));
|
target.setVTableSize(safeParseInt(args));
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'vtable': {
|
case 'vtable': {
|
||||||
// Set VTable Address
|
// Set VTable Address
|
||||||
const vtable = target.getVTable();
|
target.ensureVTable();
|
||||||
if (!isExtended && args.length > 0) {
|
if (!isExtended && args.length > 0) {
|
||||||
vtable.setAddress(safeParseInt(args));
|
target.setVTableAddress(safeParseInt(args));
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'property': {
|
case 'property': {
|
||||||
// Add Property
|
// Add Property
|
||||||
const info = parseProperty(args);
|
const info = parseProperty(args);
|
||||||
target.addProperty(new Property(info.offset, info.type, info.name, target.name));
|
target.addProperty(new Property(info.offset, info.type, info.name, target.getName()));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'static-property': {
|
case 'static-property': {
|
||||||
// Add Static Property
|
// Add Static Property
|
||||||
if (!isExtended) {
|
if (!isExtended) {
|
||||||
const info = parseProperty(args);
|
const info = parseProperty(args);
|
||||||
target.addStaticProperty(new StaticProperty(info.offset, info.type, info.name, target.name));
|
target.addStaticProperty(new StaticProperty(info.offset, info.type, info.name, target.getName()));
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@ -151,14 +150,14 @@ export function load(target: Struct, name: string, isExtended: boolean) {
|
|||||||
}
|
}
|
||||||
case 'virtual-method': {
|
case 'virtual-method': {
|
||||||
// Add Virtual Method
|
// Add Virtual Method
|
||||||
const method = parseMethod(args, target.name, true, isExtended);
|
const method = parseMethod(args, target.getName(), true, isExtended);
|
||||||
target.addMethod(method, true);
|
target.addMethod(method, true);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'static-method': {
|
case 'static-method': {
|
||||||
// Add Static Method
|
// Add Static Method
|
||||||
if (!isExtended) {
|
if (!isExtended) {
|
||||||
const method = parseMethod(args, target.name, false, false);
|
const method = parseMethod(args, target.getName(), false, false);
|
||||||
target.addMethod(method, false);
|
target.addMethod(method, false);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@ -166,30 +165,23 @@ export function load(target: Struct, name: string, isExtended: boolean) {
|
|||||||
case 'constructor': {
|
case 'constructor': {
|
||||||
// Constructor
|
// Constructor
|
||||||
if (!isExtended) {
|
if (!isExtended) {
|
||||||
let data = `${target.name} *constructor`;
|
let data = `${target.getName()} *constructor`;
|
||||||
if (args.startsWith('(')) {
|
if (args.startsWith('(')) {
|
||||||
// No Custom Name
|
// No Custom Name
|
||||||
|
data += ' ';
|
||||||
} else {
|
} else {
|
||||||
// Use Custom Name
|
// Use Custom Name
|
||||||
data += '_';
|
data += '_';
|
||||||
}
|
}
|
||||||
data += args;
|
data += args;
|
||||||
const method = parseMethod(data, target.name, true, false);
|
const method = parseMethod(data, target.getName(), true, false);
|
||||||
target.addMethod(method, false);
|
target.addMethod(method, false);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'vtable-destructor-offset': {
|
case 'vtable-destructor-offset': {
|
||||||
// Set VTable Destructor Offset
|
// Set VTable Destructor Offset
|
||||||
target.getVTable().setDestructorOffset(safeParseInt(args));
|
target.setVTableDestructorOffset(safeParseInt(args));
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'mark-as-simple': {
|
|
||||||
// Mark As Simple
|
|
||||||
if (isExtended) {
|
|
||||||
throw new Error('Cannot Extend Simple Structure');
|
|
||||||
}
|
|
||||||
target.markAsSimple();
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default: {
|
default: {
|
||||||
@ -197,6 +189,9 @@ 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++) {
|
||||||
|
18
src/map.ts
18
src/map.ts
@ -1,15 +1,14 @@
|
|||||||
import { Struct } from './struct';
|
import { Struct } from './struct';
|
||||||
import { load } from './loader';
|
import { ErrorOnLine, load } from './loader';
|
||||||
import { extendErrorMessage } from './common';
|
|
||||||
|
|
||||||
// Store Loaded Structures
|
// Store Loaded Structures
|
||||||
const structures: Record<string, Struct> = {};
|
const structures: {[id: string]: Struct} = {};
|
||||||
|
|
||||||
// Get Or Load Structure
|
// Get Or Load Structure
|
||||||
export function getStructure(name: string) {
|
export function getStructure(name: string) {
|
||||||
if (structures[name]) {
|
if (name in structures) {
|
||||||
// Already Loaded
|
// Already Loaded
|
||||||
return structures[name];
|
return structures[name]!;
|
||||||
} else {
|
} else {
|
||||||
// Load Structure
|
// Load Structure
|
||||||
try {
|
try {
|
||||||
@ -21,7 +20,14 @@ export function getStructure(name: string) {
|
|||||||
// Return
|
// Return
|
||||||
return target;
|
return target;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw new Error(extendErrorMessage(e, 'Loading ' + name));
|
let error = e;
|
||||||
|
let extra = '';
|
||||||
|
if (e instanceof ErrorOnLine) {
|
||||||
|
extra = `${e.file}:${e.line}: `;
|
||||||
|
error = e.error;
|
||||||
|
}
|
||||||
|
console.log(`Error Loading ${name}: ${extra}${error instanceof Error ? error.stack : error}`);
|
||||||
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,86 +1,73 @@
|
|||||||
import { INDENT, INTERNAL, formatType, getSelfArg, prependArg, toHex } from './common';
|
import { INDENT, formatType, getArgNames } from './common';
|
||||||
|
|
||||||
// A Template Parameter So Each Template Instantiation Is Unique
|
|
||||||
let nextDiscriminator = 0;
|
|
||||||
|
|
||||||
// An Individual Method
|
|
||||||
export class Method {
|
export class Method {
|
||||||
readonly #discriminator: number;
|
|
||||||
readonly self: string;
|
readonly self: string;
|
||||||
readonly shortName: string;
|
readonly shortName: string;
|
||||||
readonly returnType: string;
|
readonly returnType: string;
|
||||||
readonly #args: string;
|
readonly args: string;
|
||||||
readonly address: number;
|
readonly address: number;
|
||||||
readonly isInherited: boolean;
|
readonly isInherited: boolean;
|
||||||
|
readonly hasVarargs: boolean;
|
||||||
readonly isStatic: boolean;
|
readonly isStatic: boolean;
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
constructor(self: string, name: string, returnType: string, args: string, address: number, isInherited: boolean, isStatic: boolean) {
|
constructor(self: string, name: string, returnType: string, args: string, address: number, isInherited: boolean, isStatic: boolean) {
|
||||||
this.#discriminator = nextDiscriminator++;
|
|
||||||
this.self = self;
|
this.self = self;
|
||||||
this.shortName = name;
|
this.shortName = name;
|
||||||
this.returnType = returnType;
|
this.returnType = returnType;
|
||||||
this.#args = args;
|
this.args = args;
|
||||||
this.address = address;
|
this.address = address;
|
||||||
this.isInherited = isInherited;
|
this.isInherited = isInherited;
|
||||||
|
this.hasVarargs = this.args.includes('...');
|
||||||
this.isStatic = isStatic;
|
this.isStatic = isStatic;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Getters
|
// Get Type
|
||||||
getName(separator = '_') {
|
getNameWithCustomSelf(self: string) {
|
||||||
return this.self + separator + this.shortName;
|
return `${self}_${this.shortName}`;
|
||||||
|
}
|
||||||
|
getName() {
|
||||||
|
return this.getNameWithCustomSelf(this.self);
|
||||||
}
|
}
|
||||||
getType() {
|
getType() {
|
||||||
return this.getName() + '_t';
|
return `${this.getName()}_t`;
|
||||||
}
|
|
||||||
#getRawType() {
|
|
||||||
return INTERNAL + 'raw_' + this.getType();
|
|
||||||
}
|
|
||||||
getProperty() {
|
|
||||||
return `${INDENT}${this.#getRawType()} *${this.shortName};\n`;
|
|
||||||
}
|
|
||||||
#getFullType() {
|
|
||||||
return `${INTERNAL}Function<${this.#discriminator.toString()}, ${this.#getRawType()}>`;
|
|
||||||
}
|
|
||||||
doesReturnValue() {
|
|
||||||
return this.returnType.trim() !== 'void';
|
|
||||||
}
|
|
||||||
getArgs(includeSelf = true) {
|
|
||||||
let args = this.#args.trim();
|
|
||||||
if (includeSelf && !this.isStatic) {
|
|
||||||
const selfArg = getSelfArg(this.self);
|
|
||||||
args = prependArg(args, selfArg);
|
|
||||||
}
|
|
||||||
return args;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Typedefs
|
// Generate Type Definition
|
||||||
generateTypedefs() {
|
generateTypedef() {
|
||||||
let out = '';
|
let out = '';
|
||||||
out += `typedef ${formatType(this.returnType)}${this.#getRawType()}${this.getArgs()};\n`;
|
|
||||||
out += `typedef const std::function<${this.#getRawType()}> &${this.getType()};\n`;
|
// Normal Definition
|
||||||
|
const returnType = formatType(this.returnType);
|
||||||
|
out += `typedef ${returnType}(*${this.getType()})${this.args};\n`;
|
||||||
|
|
||||||
|
// Fancy Overwrite Does Not Support Varargs
|
||||||
|
if (!this.hasVarargs) {
|
||||||
|
// Overwrite Helper
|
||||||
|
out += `#define __overwrite_helper_for_${this.getName()}(method, original) \\\n`;
|
||||||
|
out += `${INDENT}[]${this.args} { \\\n`;
|
||||||
|
out += `${INDENT}${INDENT}${returnType.trim() === 'void' ? '' : 'return '}method(${['original'].concat(getArgNames(this.args)).join(', ')}); \\\n`;
|
||||||
|
out += `${INDENT}}\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Overwrite Helper
|
// Generate Variable Definition
|
||||||
#getVirtualCall(self: string = this.self) {
|
generateDefinition(nameSuffix?: string) {
|
||||||
return `${self}_vtable::base->${this.shortName}`;
|
return `${this.getType()} ${this.getName()}${nameSuffix !== undefined ? nameSuffix : ''};\n`;
|
||||||
}
|
}
|
||||||
generate(code: boolean, isVirtual: boolean, parentSelf?: string) {
|
|
||||||
let out = '';
|
// Generate "New Method" Test
|
||||||
out += 'extern ';
|
generateNewMethodTest(parent: string | null, prefix: string, suffix: string) {
|
||||||
out += `${this.#getFullType()} *const ${this.getName()}`;
|
let out = `#define __is_new_method_${this.getName()}() (`;
|
||||||
if (code) {
|
if (!this.isInherited) {
|
||||||
out += ` = new ${this.#getFullType()}(${JSON.stringify(this.getName('::'))}, `;
|
out += 'true';
|
||||||
if (isVirtual) {
|
} else {
|
||||||
const parentMethod = parentSelf ? this.#getVirtualCall(parentSelf) : 'nullptr';
|
out += `((void *) ${prefix}${this.getName()}${suffix}) != ((void *) ${prefix}${this.getNameWithCustomSelf(parent!)}${suffix})`;
|
||||||
out += `new ${INTERNAL}VirtualFunctionInfo(&${this.#getVirtualCall()}, (void *) ${parentMethod})`;
|
|
||||||
} else {
|
|
||||||
out += `new ${INTERNAL}NormalFunctionInfo((${this.#getRawType()} *) ${toHex(this.address)})`;
|
|
||||||
}
|
|
||||||
out += ')';
|
|
||||||
}
|
}
|
||||||
out += ';\n';
|
out += ')\n';
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,6 +1,5 @@
|
|||||||
import { extractArrayInfo, formatType, INTERNAL } from './common';
|
import { formatType } from './common';
|
||||||
|
|
||||||
// A Single Property
|
|
||||||
export class Property {
|
export class Property {
|
||||||
readonly offset: number;
|
readonly offset: number;
|
||||||
readonly #type: string;
|
readonly #type: string;
|
||||||
@ -16,36 +15,46 @@ export class Property {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Getters
|
// Getters
|
||||||
parts() {
|
type() {
|
||||||
const info = extractArrayInfo(this.#name);
|
return `__type_${this.fullName()}`;
|
||||||
return {
|
}
|
||||||
type: formatType(this.#type),
|
typedef() {
|
||||||
name: info.name,
|
let arrayInfo = '';
|
||||||
arrayInfo: info.arrayInfo
|
const arrayInfoIndex = this.#name.indexOf('[');
|
||||||
};
|
if (arrayInfoIndex !== -1) {
|
||||||
|
arrayInfo = this.#name.substring(arrayInfoIndex);
|
||||||
|
}
|
||||||
|
return `typedef ${formatType(this.#type)}${this.type()}${arrayInfo};\n`;
|
||||||
}
|
}
|
||||||
name() {
|
name() {
|
||||||
return this.parts().name;
|
let name = this.#name;
|
||||||
}
|
const arrayInfoIndex = this.#name.indexOf('[');
|
||||||
#fullName(separator: string) {
|
if (arrayInfoIndex !== -1) {
|
||||||
return this.#self + separator + this.name();
|
name = name.substring(0, arrayInfoIndex);
|
||||||
|
}
|
||||||
|
return name;
|
||||||
}
|
}
|
||||||
fullName() {
|
fullName() {
|
||||||
return this.#fullName('_');
|
return `${this.#self}_${this.name()}`;
|
||||||
}
|
|
||||||
prettyName() {
|
|
||||||
return this.#fullName('::');
|
|
||||||
}
|
}
|
||||||
rawType() {
|
rawType() {
|
||||||
return this.#type;
|
return this.#type;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// A Single Static Property
|
|
||||||
export class StaticProperty extends Property {
|
export class StaticProperty extends Property {
|
||||||
// Reference
|
// Constructor
|
||||||
referenceDefinition(addSelf: boolean) {
|
constructor(address: number, type: string, name: string, self: string) {
|
||||||
const parts = this.parts();
|
super(address, type, name, self);
|
||||||
return `${INTERNAL}make_reference<${parts.type.trim()}${parts.arrayInfo}> ${addSelf ? this.prettyName() : this.name()}`;
|
}
|
||||||
|
|
||||||
|
// Generate Variable Definition
|
||||||
|
globalPointerDefinition() {
|
||||||
|
return `${this.type()} *${this.fullName()}_pointer;\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate Macro
|
||||||
|
macro() {
|
||||||
|
return `#define ${this.fullName()} (*${this.fullName()}_pointer)\n`;
|
||||||
}
|
}
|
||||||
}
|
}
|
242
src/struct.ts
242
src/struct.ts
@ -1,11 +1,10 @@
|
|||||||
import { INDENT, STRUCTURE_FILES, toHex, assertSize, INTERNAL, preventConstruction, BUILDING_SYMBOLS_GUARD, formatType, forwardArguments } from './common';
|
import { INDENT, STRUCTURE_FILES, toHex, assertSize, formatType, getArgNames, removeFirstArg } from './common';
|
||||||
import { Method } from './method';
|
import { Method } from './method';
|
||||||
import { Property, StaticProperty } from './property';
|
import { Property, StaticProperty } from './property';
|
||||||
import { VTable } from './vtable';
|
import { VTable } from './vtable';
|
||||||
|
|
||||||
// A Structure/Class
|
|
||||||
export class Struct {
|
export class Struct {
|
||||||
readonly name: string;
|
readonly #name: string;
|
||||||
#vtable: VTable | null;
|
#vtable: VTable | null;
|
||||||
readonly #methods: Method[];
|
readonly #methods: Method[];
|
||||||
readonly #properties: Property[];
|
readonly #properties: Property[];
|
||||||
@ -13,11 +12,10 @@ export class Struct {
|
|||||||
readonly #dependencies: string[];
|
readonly #dependencies: string[];
|
||||||
readonly #staticProperties: StaticProperty[];
|
readonly #staticProperties: StaticProperty[];
|
||||||
#directParent: string | null;
|
#directParent: string | null;
|
||||||
#isSimple: boolean;
|
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
constructor(name: string) {
|
constructor(name: string) {
|
||||||
this.name = name;
|
this.#name = name;
|
||||||
this.#methods = [];
|
this.#methods = [];
|
||||||
this.#properties = [];
|
this.#properties = [];
|
||||||
this.#vtable = null;
|
this.#vtable = null;
|
||||||
@ -25,7 +23,6 @@ export class Struct {
|
|||||||
this.#dependencies = [];
|
this.#dependencies = [];
|
||||||
this.#staticProperties = [];
|
this.#staticProperties = [];
|
||||||
this.#directParent = null;
|
this.#directParent = null;
|
||||||
this.#isSimple = false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dependencies
|
// Dependencies
|
||||||
@ -37,29 +34,39 @@ export class Struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Ensure VTable Exists
|
// Ensure VTable Exists
|
||||||
getVTable() {
|
ensureVTable() {
|
||||||
if (this.#vtable === null) {
|
if (this.#vtable === null) {
|
||||||
this.#vtable = new VTable(this.name);
|
this.#vtable = new VTable(this.#name);
|
||||||
this.addProperty(this.#vtable.property);
|
this.addProperty(this.#vtable.property);
|
||||||
}
|
}
|
||||||
return this.#vtable;
|
}
|
||||||
|
|
||||||
|
// Set VTable Destructor Offset
|
||||||
|
setVTableDestructorOffset(offset: number) {
|
||||||
|
this.ensureVTable();
|
||||||
|
this.#vtable!.setDestructorOffset(offset);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Setters
|
// Setters
|
||||||
setSize(size: number) {
|
setSize(size: number) {
|
||||||
this.#size = size;
|
this.#size = size;
|
||||||
}
|
}
|
||||||
|
// Getters
|
||||||
|
getName() {
|
||||||
|
return this.#name;
|
||||||
|
}
|
||||||
|
|
||||||
// Add Method
|
// Add Method
|
||||||
addMethod(method: Method, isVirtual: boolean) {
|
addMethod(method: Method, isVirtual: boolean) {
|
||||||
if (method.returnType !== this.name && method.returnType in STRUCTURE_FILES) {
|
if (method.returnType !== this.#name && method.returnType in STRUCTURE_FILES) {
|
||||||
this.#addDependency(method.returnType);
|
this.#addDependency(method.returnType);
|
||||||
}
|
}
|
||||||
if (isVirtual) {
|
if (isVirtual) {
|
||||||
if (method.self !== this.name) {
|
if (method.self !== this.#name) {
|
||||||
throw new Error();
|
throw new Error();
|
||||||
}
|
}
|
||||||
this.getVTable().add(method);
|
this.ensureVTable();
|
||||||
|
this.#vtable!.add(method);
|
||||||
} else {
|
} else {
|
||||||
if (method.isInherited) {
|
if (method.isInherited) {
|
||||||
this.#addDependency(method.self);
|
this.#addDependency(method.self);
|
||||||
@ -72,7 +79,7 @@ export class Struct {
|
|||||||
this.#properties.push(property);
|
this.#properties.push(property);
|
||||||
// Add Dependency If Needed
|
// Add Dependency If Needed
|
||||||
const type = property.rawType();
|
const type = property.rawType();
|
||||||
if (STRUCTURE_FILES[type]) {
|
if (type in STRUCTURE_FILES) {
|
||||||
this.#addDependency(type);
|
this.#addDependency(type);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -81,21 +88,14 @@ export class Struct {
|
|||||||
this.#staticProperties.push(property);
|
this.#staticProperties.push(property);
|
||||||
}
|
}
|
||||||
|
|
||||||
// "Simple" Structures
|
// Configure VTable
|
||||||
markAsSimple() {
|
setVTableSize(size: number) {
|
||||||
this.#isSimple = true;
|
this.ensureVTable();
|
||||||
|
this.#vtable!.setSize(size);
|
||||||
}
|
}
|
||||||
#checkSimple() {
|
setVTableAddress(address: number) {
|
||||||
const checks: [string, boolean][] = [
|
this.ensureVTable();
|
||||||
['Cannot Inherit', this.#directParent !== null],
|
this.#vtable!.setAddress(address);
|
||||||
['Must Have A Defined Size', this.#size === null],
|
|
||||||
['Cannot Have A VTable', this.#vtable !== null]
|
|
||||||
];
|
|
||||||
for (const check of checks) {
|
|
||||||
if (check[1]) {
|
|
||||||
throw new Error('Simple Structures ' + check[0]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate Properties
|
// Generate Properties
|
||||||
@ -114,9 +114,10 @@ export class Struct {
|
|||||||
|
|
||||||
// Add Properties
|
// Add Properties
|
||||||
let out = '';
|
let out = '';
|
||||||
let lastProperty: Property | null = null;
|
for (let i = 0; i < sortedProperties.length; i++) {
|
||||||
let i = 0;
|
const property = sortedProperties[i]!;
|
||||||
for (const property of sortedProperties) {
|
const lastProperty = sortedProperties[i - 1];
|
||||||
|
|
||||||
// Padding
|
// Padding
|
||||||
let offsetFromLastProperty = property.offset;
|
let offsetFromLastProperty = property.offset;
|
||||||
if (lastProperty) {
|
if (lastProperty) {
|
||||||
@ -124,77 +125,64 @@ export class Struct {
|
|||||||
}
|
}
|
||||||
let paddingSize = toHex(offsetFromLastProperty);
|
let paddingSize = toHex(offsetFromLastProperty);
|
||||||
if (lastProperty) {
|
if (lastProperty) {
|
||||||
const parts = lastProperty.parts();
|
paddingSize += ` - sizeof(${lastProperty.type()})`;
|
||||||
paddingSize += ` - ${INTERNAL}real_sizeof<${parts.type.trim()}${parts.arrayInfo}>()`;
|
|
||||||
}
|
|
||||||
if (!this.#isSimple) {
|
|
||||||
out += `${INDENT}uchar ${INTERNAL}padding${i.toString()}[${paddingSize}];\n`;
|
|
||||||
}
|
}
|
||||||
|
out += `${INDENT}uchar __padding${i}[${paddingSize}];\n`;
|
||||||
|
|
||||||
// The Actual Property
|
// The Actual Property
|
||||||
if (property !== sizeProperty) {
|
if (property !== sizeProperty) {
|
||||||
const parts = property.parts();
|
out += `${INDENT}${property.type()} ${property.name()};\n`;
|
||||||
out += `${INDENT}${parts.type}${parts.name}${parts.arrayInfo};\n`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Advance
|
|
||||||
lastProperty = property;
|
|
||||||
i++;
|
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate C++ Method Shortcuts
|
// Generate C++ Method Shortcuts
|
||||||
#generateMethod(method: Method, isVirtual: boolean) {
|
|
||||||
let out = '';
|
|
||||||
out += INDENT;
|
|
||||||
if (method.isStatic) {
|
|
||||||
out += 'static ';
|
|
||||||
}
|
|
||||||
const args = method.getArgs(false);
|
|
||||||
out += formatType(method.returnType) + method.shortName + args + ' {\n';
|
|
||||||
out += INDENT + INDENT;
|
|
||||||
if (method.doesReturnValue()) {
|
|
||||||
out += 'return ';
|
|
||||||
}
|
|
||||||
if (isVirtual) {
|
|
||||||
out += `this->vtable->${method.shortName}`;
|
|
||||||
} else {
|
|
||||||
out += `${method.getName()}->get(false)`;
|
|
||||||
}
|
|
||||||
const extra = [];
|
|
||||||
if (!method.isStatic) {
|
|
||||||
extra.push(`(${method.self} *) this`);
|
|
||||||
}
|
|
||||||
out += forwardArguments(args, extra) + ';\n';
|
|
||||||
out += `${INDENT}}\n`;
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
#generateMethods() {
|
#generateMethods() {
|
||||||
let out = '';
|
let out = '';
|
||||||
out += `#ifndef ${BUILDING_SYMBOLS_GUARD}\n`;
|
|
||||||
// Normal Methods
|
// Normal Methods
|
||||||
|
const getArgsOuter = (method: Method) => {
|
||||||
|
let out = method.args;
|
||||||
|
if (!method.isStatic) {
|
||||||
|
// Remove "self"
|
||||||
|
out = removeFirstArg(out);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
const getArgsInner = (method: Method) => {
|
||||||
|
const list = getArgNames(method.args);
|
||||||
|
if (!method.isStatic) {
|
||||||
|
// Replace "self" With "this"
|
||||||
|
list[0] = `(${method.self} *) this`;
|
||||||
|
}
|
||||||
|
return list.join(', ');
|
||||||
|
};
|
||||||
for (const method of this.#methods) {
|
for (const method of this.#methods) {
|
||||||
out += this.#generateMethod(method, false);
|
if (!method.hasVarargs) {
|
||||||
|
const returnType = method.returnType;
|
||||||
|
const shortName = method.shortName;
|
||||||
|
const fullName = method.getName();
|
||||||
|
const args = getArgsOuter(method);
|
||||||
|
out += `${INDENT}inline ${formatType(returnType)}${shortName}${args} { \\\n`;
|
||||||
|
out += `${INDENT}${INDENT}${returnType.trim() === 'void' ? '' : 'return '}${fullName}(${getArgsInner(method)});\n`;
|
||||||
|
out += `${INDENT}}\n`;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Virtual Methods
|
// Virtual Methods
|
||||||
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) {
|
if (method && !method.hasVarargs) {
|
||||||
out += this.#generateMethod(method, true);
|
const returnType = method.returnType;
|
||||||
|
const shortName = method.shortName;
|
||||||
|
const args = getArgsOuter(method);
|
||||||
|
out += `${INDENT}inline ${formatType(returnType)}${shortName}${args} { \\\n`;
|
||||||
|
out += `${INDENT}${INDENT}${returnType.trim() === 'void' ? '' : 'return '}this->vtable->${shortName}(${getArgsInner(method)});\n`;
|
||||||
|
out += `${INDENT}}\n`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Allocation Method
|
|
||||||
if (this.#size !== null) {
|
|
||||||
// THIS DOES NOT CONSTRUCT THE OBJECT
|
|
||||||
out += `${INDENT}static ${this.name} *allocate() {\n`;
|
|
||||||
out += `${INDENT}${INDENT}return (${this.name} *) ::operator new(sizeof(${this.name}));\n`;
|
|
||||||
out += `${INDENT}}\n`;
|
|
||||||
}
|
|
||||||
// Return
|
// Return
|
||||||
out += '#endif\n';
|
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -202,43 +190,56 @@ export class Struct {
|
|||||||
generate() {
|
generate() {
|
||||||
let out = '';
|
let out = '';
|
||||||
|
|
||||||
// Check "Simple" Status
|
// Static Properties
|
||||||
if (this.#isSimple) {
|
for (const property of this.#staticProperties) {
|
||||||
this.#checkSimple();
|
out += property.typedef();
|
||||||
|
out += `extern ${property.globalPointerDefinition()}`;
|
||||||
|
out += property.macro();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Methods
|
||||||
|
for (const method of this.#methods) {
|
||||||
|
if (!method.isInherited) {
|
||||||
|
out += method.generateTypedef();
|
||||||
|
out += `extern ${method.generateDefinition()}`;
|
||||||
|
out += `extern ${method.generateDefinition('_unedited')}`;
|
||||||
|
out += method.generateNewMethodTest(this.#directParent, '', '');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// VTable
|
// VTable
|
||||||
if (this.#vtable !== null) {
|
if (this.#vtable !== null) {
|
||||||
out += this.#vtable.generate();
|
out += this.#vtable.generate(this.#directParent);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Method Wrappers
|
// Property Typedefs
|
||||||
let typedefs = '';
|
for (const property of this.#properties) {
|
||||||
let methodsOut = '';
|
out += property.typedef();
|
||||||
for (const method of this.#methods) {
|
|
||||||
if (!method.isInherited) {
|
|
||||||
typedefs += method.generateTypedefs();
|
|
||||||
methodsOut += method.generate(false, false);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
out += typedefs;
|
|
||||||
out += `#ifndef ${BUILDING_SYMBOLS_GUARD}\n`;
|
|
||||||
out += methodsOut;
|
|
||||||
out += '#endif\n';
|
|
||||||
|
|
||||||
// Structure
|
// Structure
|
||||||
out += `struct ${this.name} final {\n`;
|
out += `struct ${this.#name} {\n`;
|
||||||
out += this.#generateProperties();
|
out += this.#generateProperties();
|
||||||
out += this.#generateMethods();
|
out += this.#generateMethods();
|
||||||
for (const property of this.#staticProperties) {
|
out += `};\n`;
|
||||||
// Static Property References
|
|
||||||
out += `${INDENT}static ${property.referenceDefinition(false)};\n`;
|
// Sanity Check Offsets
|
||||||
|
for (let i = 0; i < this.#properties.length; i++) {
|
||||||
|
const property = this.#properties[i]!;
|
||||||
|
const name = property.name();
|
||||||
|
const offset = property.offset;
|
||||||
|
out += `static_assert(offsetof(${this.#name}, ${name}) == ${toHex(offset)}, "Invalid Offset");\n`;
|
||||||
}
|
}
|
||||||
if (!this.#isSimple) {
|
|
||||||
// Disable Construction Of Complex Structures
|
// Sanity Check Size
|
||||||
out += preventConstruction(this.name);
|
if (this.#size !== null) {
|
||||||
|
out += assertSize(this.#name, this.#size);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allocation Function
|
||||||
|
if (this.#size !== null) {
|
||||||
|
out += `${this.#name} *alloc_${this.#name}();\n`;
|
||||||
}
|
}
|
||||||
out += '};\n';
|
|
||||||
|
|
||||||
// Return
|
// Return
|
||||||
return out;
|
return out;
|
||||||
@ -246,40 +247,41 @@ export class Struct {
|
|||||||
|
|
||||||
// Generate Compiled Code
|
// Generate Compiled Code
|
||||||
generateCode() {
|
generateCode() {
|
||||||
let out = '';
|
let declarations = '';
|
||||||
|
let init = '';
|
||||||
|
|
||||||
// Static Properties
|
// Static Properties
|
||||||
for (const property of this.#staticProperties) {
|
for (const property of this.#staticProperties) {
|
||||||
out += `${property.referenceDefinition(true)} = *(std::remove_reference_t<decltype(${property.prettyName()})> *) ${toHex(property.offset)};\n`;
|
init += `${INDENT}${property.fullName()}_pointer = (${property.type()} *) ${toHex(property.offset)};\n`;
|
||||||
|
declarations += property.globalPointerDefinition();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Methods
|
// Methods
|
||||||
for (const method of this.#methods) {
|
for (const method of this.#methods) {
|
||||||
if (!method.isInherited) {
|
if (!method.isInherited) {
|
||||||
out += method.generate(true, false);
|
init += `${INDENT}${method.getName()} = (${method.getType()}) ${toHex(method.address)};\n`;
|
||||||
|
declarations += method.generateDefinition();
|
||||||
|
init += `${INDENT}${method.getName()}_unedited = (${method.getType()}) ${toHex(method.address)};\n`;
|
||||||
|
declarations += method.generateDefinition('_unedited');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sanity Check Offsets
|
|
||||||
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`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sanity Check Size
|
|
||||||
if (this.#size !== null) {
|
|
||||||
out += assertSize(this.name, this.#size);
|
|
||||||
}
|
|
||||||
|
|
||||||
// VTable
|
// VTable
|
||||||
if (this.#vtable !== null) {
|
if (this.#vtable !== null) {
|
||||||
const vtable = this.#vtable.generateCode(this.#directParent);
|
const vtable = this.#vtable.generateCode();
|
||||||
out += vtable;
|
declarations += vtable.declarations;
|
||||||
|
init += vtable.init;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allocation Function
|
||||||
|
if (this.#size !== null) {
|
||||||
|
declarations += `${this.#name} *alloc_${this.#name}() {\n`;
|
||||||
|
declarations += `${INDENT}return new ${this.#name};\n`;
|
||||||
|
declarations += '}\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return
|
// Return
|
||||||
return out;
|
return {functions: declarations, init};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set Direct Parent (Used For "New Method" Testing)
|
// Set Direct Parent (Used For "New Method" Testing)
|
||||||
|
@ -1,44 +0,0 @@
|
|||||||
import { describe, it } from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { formatType, toHex, toUpperSnakeCase } from '../common';
|
|
||||||
|
|
||||||
describe('Upper-Snake-Case', () => {
|
|
||||||
const tests: [string, string, string][] = [
|
|
||||||
['One Word', 'Hello', 'HELLO'],
|
|
||||||
['Two Words', 'HelloWorld', 'HELLO_WORLD'],
|
|
||||||
['Empty', '', ''],
|
|
||||||
['All Uppercase', 'HELLO', 'HELLO'],
|
|
||||||
['All Lowercase', 'hello', 'HELLO']
|
|
||||||
];
|
|
||||||
for (const test of tests) {
|
|
||||||
it(test[0], () => {
|
|
||||||
assert.strictEqual(toUpperSnakeCase(test[1]), test[2]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('Formatting Types For Concatenation', () => {
|
|
||||||
const tests: [string, string, string][] = [
|
|
||||||
['Value', 'int', 'int '],
|
|
||||||
['Pointer', 'int *', 'int *'],
|
|
||||||
['Reference', 'int &', 'int &']
|
|
||||||
];
|
|
||||||
for (const test of tests) {
|
|
||||||
it(test[0], () => {
|
|
||||||
assert.strictEqual(formatType(test[1]), test[2]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('Hexadecimal', () => {
|
|
||||||
const tests: [string, number, string][] = [
|
|
||||||
['Zero', 0, '0x0'],
|
|
||||||
['Small Number', 10, '0xa'],
|
|
||||||
['Large Number', 100, '0x64']
|
|
||||||
];
|
|
||||||
for (const test of tests) {
|
|
||||||
it(test[0], () => {
|
|
||||||
assert.strictEqual(toHex(test[1]), test[2]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
@ -1,166 +0,0 @@
|
|||||||
import { describe, it } from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import { extractArrayInfo, forwardArguments, parseTypeAndName, prependArg, safeParseInt } from '../common';
|
|
||||||
import { parseMethod, parseProperty } from '../loader';
|
|
||||||
|
|
||||||
describe('Parsing Variable Declarations', () => {
|
|
||||||
const tests: { name: string, input: string, out: { type: string, name: string } }[] = [
|
|
||||||
{name: 'Simple', input: 'int x', out: {type: 'int', name: 'x'}},
|
|
||||||
{name: 'Pointer', input: 'int *y', out: {type: 'int *', name: 'y'}},
|
|
||||||
{name: 'Extra Space', input: ' float a ', out: {type: 'float', name: 'a'}},
|
|
||||||
{name: 'Ugly Pointer', input: 'int* z', out: {type: 'int*', name: 'z'}},
|
|
||||||
{name: 'Double Pointer', input: 'int **a', out: {type: 'int **', name: 'a'}},
|
|
||||||
{name: 'Ugly Double Pointer', input: 'int* *b', out: {type: 'int**', name: 'b'}},
|
|
||||||
{name: 'Reference', input: 'int &c', out: {type: 'int &', name: 'c'}},
|
|
||||||
{name: 'Reference-To-Pointer', input: 'int *&d', out: {type: 'int *&', name: 'd'}}
|
|
||||||
];
|
|
||||||
for (const test of tests) {
|
|
||||||
it(test.name, () => {
|
|
||||||
const obj = parseTypeAndName(test.input);
|
|
||||||
assert.strictEqual(obj.type, test.out.type);
|
|
||||||
assert.strictEqual(obj.name, test.out.name);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
it('Invalid', () => {
|
|
||||||
assert.throws(() => {
|
|
||||||
parseTypeAndName('abc');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('Prepending Arguments To Functions', () => {
|
|
||||||
const tests: { name: string, input: string, arg: string, out: string }[] = [
|
|
||||||
{name: 'Empty', input: '()', arg: 'int x', out: '(int x)'},
|
|
||||||
{name: 'Non-Empty', input: '(int x)', arg: 'int y', out: '(int y, int x)'}
|
|
||||||
];
|
|
||||||
for (const test of tests) {
|
|
||||||
it(test.name, () => {
|
|
||||||
assert.strictEqual(prependArg(test.input, test.arg), test.out);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('Parsing Integers', () => {
|
|
||||||
const tests: { name: string, input: string, out?: number }[] = [
|
|
||||||
{name: 'Zero', input: '0', out: 0},
|
|
||||||
{name: 'Negative', input: '-5', out: -5},
|
|
||||||
{name: 'Positive', input: '5', out: 5},
|
|
||||||
{name: 'Extra Space', input: ' 5 ', out: 5},
|
|
||||||
{name: 'Hexadecimal', input: '0x10', out: 16},
|
|
||||||
{name: 'Empty', input: ''},
|
|
||||||
{name: 'Text', input: 'abc'}
|
|
||||||
];
|
|
||||||
for (const test of tests) {
|
|
||||||
it(test.name, () => {
|
|
||||||
if (test.out !== undefined) {
|
|
||||||
assert.strictEqual(safeParseInt(test.input), test.out);
|
|
||||||
} else {
|
|
||||||
assert.throws(() => {
|
|
||||||
safeParseInt(test.input);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('Parsing Properties', () => {
|
|
||||||
const tests: { name: string, input: string, out?: { type: string, name: string, offset: number } }[] = [
|
|
||||||
{name: 'Basic', input: 'int x = 0x0', out: {type: 'int', name: 'x', offset: 0}},
|
|
||||||
{name: 'Extra Space', input: 'int z = 0x0', out: {type: 'int', name: 'z', offset: 0}},
|
|
||||||
{name: 'Pointer', input: 'float *y = 0x4', out: {type: 'float *', name: 'y', offset: 4}},
|
|
||||||
{name: 'Empty', input: ''},
|
|
||||||
{name: 'Malformed #1', input: 'int x'},
|
|
||||||
{name: 'Malformed #2', input: 'int x=2'},
|
|
||||||
{name: 'Malformed #3', input: 'int x = '}
|
|
||||||
];
|
|
||||||
for (const test of tests) {
|
|
||||||
it(test.name, () => {
|
|
||||||
if (test.out) {
|
|
||||||
const property = parseProperty(test.input);
|
|
||||||
assert.strictEqual(property.type, test.out.type);
|
|
||||||
assert.strictEqual(property.name, test.out.name);
|
|
||||||
assert.strictEqual(property.offset, test.out.offset);
|
|
||||||
} else {
|
|
||||||
assert.throws(() => {
|
|
||||||
parseProperty(test.input);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('Parsing Methods', () => {
|
|
||||||
const tests: { name: string, input: string, self: string, isStatic: boolean, out?: { name: string, returnType: string, args: string, address: number } }[] = [
|
|
||||||
{name: 'Basic', input: 'void func() = 0x10', self: 'Test', isStatic: false, out: {name: 'func', returnType: 'void', args: '(Test *self)', address: 16}},
|
|
||||||
{name: 'Advanced', input: 'int bar(int x, float y, std::vector<float> *arr) = 0x20', self: 'Foo', isStatic: false, out: {name: 'bar', returnType: 'int', args: '(Foo *self, int x, float y, std::vector<float> *arr)', address: 32}},
|
|
||||||
{name: 'Extra Space', input: 'int bar (int x) = 0x20', self: 'Foo', isStatic: false, out: {name: 'bar', returnType: 'int', args: '(Foo *self, int x)', address: 32}},
|
|
||||||
{name: 'Static', input: 'int thing(float x) = 0x30', self: 'Crazy', isStatic: true, out: {name: 'thing', returnType: 'int', args: '(float x)', address: 48}},
|
|
||||||
{name: 'Empty', input: '', self: 'Test', isStatic: false},
|
|
||||||
{name: 'Malformed #1', input: 'int broken', self: 'Test', isStatic: false},
|
|
||||||
{name: 'Malformed #2', input: 'int broken = 0x10', self: 'Test', isStatic: false},
|
|
||||||
{name: 'Malformed #3', input: 'int broken()', self: 'Test', isStatic: false},
|
|
||||||
{name: 'Malformed #4', input: 'int broken()=0x0', self: 'Test', isStatic: false},
|
|
||||||
{name: 'Malformed #5', input: 'int broken() = ', self: 'Test', isStatic: false},
|
|
||||||
{name: 'Malformed #6', input: 'abc', self: 'Test', isStatic: false}
|
|
||||||
];
|
|
||||||
for (const test of tests) {
|
|
||||||
it(test.name, () => {
|
|
||||||
if (test.out) {
|
|
||||||
const method = parseMethod(test.input, test.self, !test.isStatic, false);
|
|
||||||
assert.strictEqual(method.shortName, test.out.name);
|
|
||||||
assert.strictEqual(method.returnType, test.out.returnType);
|
|
||||||
assert.strictEqual(method.getArgs(), test.out.args);
|
|
||||||
assert.strictEqual(method.address, test.out.address);
|
|
||||||
} else {
|
|
||||||
assert.throws(() => {
|
|
||||||
parseMethod(test.input, test.self, !test.isStatic, false);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('Extracting Array Information', () => {
|
|
||||||
const tests: { name: string, input: string, out: { name: string, arrayInfo: string } }[] = [
|
|
||||||
{name: 'Basic', input: 'x', out: {name: 'x', arrayInfo: ''}},
|
|
||||||
{name: 'Array', input: 'x[10]', out: {name: 'x', arrayInfo: '[10]'}},
|
|
||||||
{name: 'Multi-Dimensional Array', input: 'x[10][10]', out: {name: 'x', arrayInfo: '[10][10]'}}
|
|
||||||
];
|
|
||||||
for (const test of tests) {
|
|
||||||
it(test.name, () => {
|
|
||||||
const out = extractArrayInfo(test.input);
|
|
||||||
assert.strictEqual(out.name, test.out.name);
|
|
||||||
assert.strictEqual(out.arrayInfo, test.out.arrayInfo);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('Forwarding Arguments', () => {
|
|
||||||
const tests: { name: string, input: string, extra?: string[], out?: string }[] = [
|
|
||||||
{name: 'No Arguments', input: '()', out: '()'},
|
|
||||||
{name: 'One Argument', input: '(int x)', out: '(x)'},
|
|
||||||
{name: 'Two Argument', input: '(int x, float y)', out: '(x, y)'},
|
|
||||||
{name: 'Arrays', input: '(int one[10], float two[20])', out: '(one, two)'},
|
|
||||||
{name: 'Generics #1', input: '(Obj<float> x, Obj2<int, int[10]> *y)', out: '(x, y)'},
|
|
||||||
{name: 'Generics #2', input: '(function<int(int, int)> &callback, void *data)', out: '(callback, data)'},
|
|
||||||
{name: 'Extra Arguments', input: '(int x)', extra: ['this'], out: '(this, x)'},
|
|
||||||
{name: 'Malformed #1', input: '(int)'},
|
|
||||||
{name: 'Malformed #2', input: '('},
|
|
||||||
{name: 'Malformed #3', input: ')'},
|
|
||||||
{name: 'Malformed #4', input: '(Obj<float x, int y)'},
|
|
||||||
{name: 'Malformed #5', input: '(int x, float y[5)'},
|
|
||||||
{name: 'Malformed #6', input: '(Obj<5] x)'}
|
|
||||||
];
|
|
||||||
for (const test of tests) {
|
|
||||||
it(test.name, () => {
|
|
||||||
if (test.out) {
|
|
||||||
const out = forwardArguments(test.input, test.extra ?? []);
|
|
||||||
assert.strictEqual(out, test.out);
|
|
||||||
} else {
|
|
||||||
assert.throws(() => {
|
|
||||||
forwardArguments(test.input, test.extra ?? []);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
153
src/vtable.ts
153
src/vtable.ts
@ -1,17 +1,14 @@
|
|||||||
import { BUILDING_SYMBOLS_GUARD, INDENT, INTERNAL, POINTER_SIZE, assertSize, preventConstruction, toHex } from './common';
|
import { INDENT, POINTER_SIZE, RTTI_SIZE, assertSize, getSelfArg, toHex } from './common';
|
||||||
import { Method } from './method';
|
import { Method } from './method';
|
||||||
import { Property } from './property';
|
import { Property } from './property';
|
||||||
|
|
||||||
// A VTable
|
|
||||||
const structuresWithVTableAddress: string[] = [];
|
|
||||||
export class VTable {
|
export class VTable {
|
||||||
readonly #self: string;
|
readonly #self: string;
|
||||||
#address: number | null;
|
#address: number | null;
|
||||||
#size: number | null;
|
#size: number | null;
|
||||||
readonly #methods: (Method | undefined)[];
|
readonly #methods: Method[];
|
||||||
readonly property: Property;
|
readonly property: Property;
|
||||||
#destructorOffset: number;
|
#destructorOffset: number;
|
||||||
readonly #destructors: Method[];
|
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
constructor(self: string) {
|
constructor(self: string) {
|
||||||
@ -20,7 +17,6 @@ export class VTable {
|
|||||||
this.#size = null;
|
this.#size = null;
|
||||||
this.#methods = [];
|
this.#methods = [];
|
||||||
this.#destructorOffset = 0;
|
this.#destructorOffset = 0;
|
||||||
this.#destructors = [];
|
|
||||||
// Create Property
|
// Create Property
|
||||||
this.property = new Property(0, this.#getName() + ' *', 'vtable', this.#self);
|
this.property = new Property(0, this.#getName() + ' *', 'vtable', this.#self);
|
||||||
}
|
}
|
||||||
@ -28,7 +24,6 @@ export class VTable {
|
|||||||
// Setters
|
// Setters
|
||||||
setAddress(address: number) {
|
setAddress(address: number) {
|
||||||
this.#address = address;
|
this.#address = address;
|
||||||
structuresWithVTableAddress.push(this.#self);
|
|
||||||
}
|
}
|
||||||
setSize(size: number) {
|
setSize(size: number) {
|
||||||
this.#size = size;
|
this.#size = size;
|
||||||
@ -38,7 +33,7 @@ export class VTable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add To VTable
|
// Add To VTable
|
||||||
#add(target: (Method | undefined)[], method: Method) {
|
#add(target: Method[], method: Method) {
|
||||||
// Check Offset
|
// Check Offset
|
||||||
const offset = method.address;
|
const offset = method.address;
|
||||||
if ((offset % POINTER_SIZE) !== 0) {
|
if ((offset % POINTER_SIZE) !== 0) {
|
||||||
@ -82,93 +77,78 @@ export class VTable {
|
|||||||
out.push(...this.#methods);
|
out.push(...this.#methods);
|
||||||
// Add Destructors (https://stackoverflow.com/a/17960941)
|
// Add Destructors (https://stackoverflow.com/a/17960941)
|
||||||
const destructor_return = `${this.#self} *`;
|
const destructor_return = `${this.#self} *`;
|
||||||
const destructor_args = '()';
|
const destructor_args = `(${getSelfArg(this.#self)})`;
|
||||||
if (this.#destructors.length === 0) {
|
this.#add(out, new Method(this.#self, 'destructor_complete', destructor_return, destructor_args, 0x0 + this.#destructorOffset, false, false));
|
||||||
this.#destructors.push(
|
this.#add(out, new Method(this.#self, 'destructor_deleting', destructor_return, destructor_args, 0x4 + this.#destructorOffset, false, false));
|
||||||
new Method(this.#self, 'destructor_complete', destructor_return, destructor_args, 0x0 + this.#destructorOffset, false, false),
|
|
||||||
new Method(this.#self, 'destructor_deleting', destructor_return, destructor_args, 0x4 + this.#destructorOffset, false, false)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
for (const destructor of this.#destructors) {
|
|
||||||
this.#add(out, destructor);
|
|
||||||
}
|
|
||||||
// Return
|
// Return
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get Parent Method
|
|
||||||
#getParentSelf(method: Method, parent: string | null) {
|
|
||||||
if (method.isInherited && parent) {
|
|
||||||
// Parent Exists
|
|
||||||
let out: string;
|
|
||||||
if (structuresWithVTableAddress.includes(parent)) {
|
|
||||||
out = parent;
|
|
||||||
} else {
|
|
||||||
// Unable To Determine
|
|
||||||
out = this.#self;
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
} else {
|
|
||||||
// Method Has No Parent
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate Header Code
|
// Generate Header Code
|
||||||
canGenerateWrappers() {
|
generate(directParent: string | null) {
|
||||||
return this.#address !== null;
|
|
||||||
}
|
|
||||||
generate() {
|
|
||||||
let out = '';
|
let out = '';
|
||||||
|
|
||||||
// Check
|
// Check
|
||||||
this.#check();
|
this.#check();
|
||||||
|
|
||||||
// Wrappers
|
// Method Prototypes
|
||||||
const methods = this.getMethods();
|
const methods = this.getMethods();
|
||||||
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 += `#ifndef ${BUILDING_SYMBOLS_GUARD}\n`;
|
|
||||||
out += methodsOut;
|
|
||||||
out += '#endif\n';
|
|
||||||
|
|
||||||
// Structure
|
|
||||||
out += `typedef struct ${this.#getName()} ${this.#getName()};\n`;
|
|
||||||
out += `struct ${this.#getName()} final {\n`;
|
|
||||||
for (let i = 0; i < methods.length; i++) {
|
for (let i = 0; i < methods.length; i++) {
|
||||||
const info = methods[i];
|
const info = methods[i];
|
||||||
if (info) {
|
if (info) {
|
||||||
out += info.getProperty();
|
out += info.generateTypedef();
|
||||||
} else {
|
|
||||||
out += `${INDENT}void *${INTERNAL}unknown${i.toString()};\n`;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (this.#size === null) {
|
|
||||||
// Prevent Construction
|
// Structure
|
||||||
out += preventConstruction(this.#getName());
|
out += `typedef struct ${this.#getName()} ${this.#getName()};\n`;
|
||||||
|
out += `struct ${this.#getName()} {\n`;
|
||||||
|
for (let i = 0; i < methods.length; i++) {
|
||||||
|
let name = `unknown${i}`;
|
||||||
|
let type = 'void *';
|
||||||
|
const info = methods[i];
|
||||||
|
if (info) {
|
||||||
|
name = info.shortName;
|
||||||
|
type = info.getType() + ' ';
|
||||||
|
}
|
||||||
|
out += `${INDENT}${type}${name};\n`;
|
||||||
}
|
}
|
||||||
|
out += `};\n`;
|
||||||
|
|
||||||
|
// Sanity Check Size
|
||||||
|
if (this.#size !== null) {
|
||||||
|
out += assertSize(this.#getName(), this.#size);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pointers
|
||||||
if (this.#address !== null) {
|
if (this.#address !== null) {
|
||||||
// Base
|
// Base
|
||||||
out += `${INDENT}static ${this.#getName()} *base;\n`;
|
out += `extern ${this.#getName()} *${this.#getName()}_base;\n`;
|
||||||
|
// Methods
|
||||||
|
for (let i = 0; i < methods.length; i++) {
|
||||||
|
const info = methods[i];
|
||||||
|
if (info) {
|
||||||
|
const type = `${info.getType()} *`;
|
||||||
|
out += `extern ${type}${info.getName()}_vtable_addr;\n`;
|
||||||
|
out += `extern ${info.generateDefinition('_non_virtual')}`;
|
||||||
|
out += info.generateNewMethodTest(directParent, '*', '_vtable_addr');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Duplication Method
|
||||||
|
if (this.#size !== null) {
|
||||||
|
out += `${this.#getName()} *dup_${this.#getName()}(${this.#getName()} *vtable);\n`;
|
||||||
}
|
}
|
||||||
out += '};\n';
|
|
||||||
|
|
||||||
// Return
|
// Return
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate Compiled Code
|
// Generate Compiled Code
|
||||||
generateCode(directParent: string | null) {
|
generateCode() {
|
||||||
let out = '';
|
let declarations = '';
|
||||||
|
let init = '';
|
||||||
|
|
||||||
// Check
|
// Check
|
||||||
this.#check();
|
this.#check();
|
||||||
@ -176,25 +156,40 @@ export class VTable {
|
|||||||
// Pointers
|
// Pointers
|
||||||
if (this.#address !== null) {
|
if (this.#address !== null) {
|
||||||
// Base
|
// Base
|
||||||
out += `${this.#getName()} *${this.#getName()}::base = (${this.#getName()} *) ${toHex(this.#address)};\n`;
|
init += `${INDENT}${this.#getName()}_base = (${this.#getName()} *) ${toHex(this.#address)};\n`;
|
||||||
}
|
declarations += `${this.#getName()} *${this.#getName()}_base;\n`;
|
||||||
|
// Methods
|
||||||
// Method Wrappers
|
|
||||||
if (this.canGenerateWrappers()) {
|
|
||||||
const methods = this.getMethods();
|
const methods = this.getMethods();
|
||||||
for (const info of methods) {
|
for (let i = 0; i < methods.length; i++) {
|
||||||
|
const info = methods[i];
|
||||||
if (info) {
|
if (info) {
|
||||||
out += info.generate(true, true, this.#getParentSelf(info, directParent));
|
const vtableAddress = this.#address + (i * POINTER_SIZE);
|
||||||
|
const type = `${info.getType()} *`;
|
||||||
|
init += `${INDENT}${info.getName()}_vtable_addr = (${type}) ${toHex(vtableAddress)};\n`;
|
||||||
|
declarations += `${type}${info.getName()}_vtable_addr;\n`;
|
||||||
|
init += `${INDENT}${info.getName()}_non_virtual = *${info.getName()}_vtable_addr;\n`;
|
||||||
|
declarations += info.generateDefinition('_non_virtual');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sanity Check Size
|
// Duplication Method
|
||||||
if (this.#size !== null) {
|
if (this.#size !== null) {
|
||||||
out += assertSize(this.#getName(), this.#size);
|
declarations += `${this.#getName()} *dup_${this.#getName()}(${this.#getName()} *vtable) {\n`;
|
||||||
|
declarations += `${INDENT}uchar *real_vtable = (uchar *) vtable;\n`;
|
||||||
|
declarations += `${INDENT}real_vtable -= ${RTTI_SIZE};\n`;
|
||||||
|
declarations += `${INDENT}size_t real_vtable_size = sizeof(${this.#getName()}) + ${RTTI_SIZE};\n`;
|
||||||
|
declarations += `${INDENT}uchar *new_vtable = (uchar *) ::operator new(real_vtable_size);\n`;
|
||||||
|
declarations += `${INDENT}if (new_vtable == NULL) {\n`;
|
||||||
|
declarations += `${INDENT}${INDENT}return NULL;\n`;
|
||||||
|
declarations += `${INDENT}}\n`;
|
||||||
|
declarations += `${INDENT}memcpy((void *) new_vtable, (void *) real_vtable, real_vtable_size);\n`;
|
||||||
|
declarations += `${INDENT}new_vtable += ${RTTI_SIZE};\n`;
|
||||||
|
declarations += `${INDENT}return (${this.#getName()} *) new_vtable;\n`;
|
||||||
|
declarations += '}\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return
|
// Return
|
||||||
return out;
|
return {declarations, init};
|
||||||
}
|
}
|
||||||
}
|
}
|
34
syntax-highlighting/def.nanorc
Normal file
34
syntax-highlighting/def.nanorc
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
syntax def "\.def$"
|
||||||
|
comment "//"
|
||||||
|
|
||||||
|
# Mistakes
|
||||||
|
# Missing semicolon
|
||||||
|
color red "[^;]$"
|
||||||
|
# Missing type
|
||||||
|
color red "^(((static|virtual)-)?method|property|static-property(-array)?) [a-zA-Z_][a-zA-Z0-9_]* ?(\(|=)"
|
||||||
|
# Missing prefix
|
||||||
|
color red "^[^ ]+"
|
||||||
|
# Missing vtable
|
||||||
|
color red "^(vtable(-size|-destructor-offset))? .+$"
|
||||||
|
|
||||||
|
# Reset
|
||||||
|
color normal "(\(|\))"
|
||||||
|
|
||||||
|
# Commands
|
||||||
|
color magenta "^(extends|size|vtable(-size|-destructor-offset)?|property|static-property|((static|virtual)-)?method|constructor)\>"
|
||||||
|
|
||||||
|
# Types
|
||||||
|
color green "\<((u?(char|short|int))|float|bool|void|std::(string|vector|map))\>"
|
||||||
|
|
||||||
|
# Numbers
|
||||||
|
color yellow "0x[a-f0-9]+"
|
||||||
|
# Non-hex numbers
|
||||||
|
color red " [0-9][a-f0-9]+;"
|
||||||
|
|
||||||
|
# Comments
|
||||||
|
color brightblue "//.*"
|
||||||
|
|
||||||
|
# Whitespace.
|
||||||
|
color normal "[[:space:]]+"
|
||||||
|
# Trailing whitespace.
|
||||||
|
color ,green "[[:space:]]+$"
|
@ -13,10 +13,8 @@
|
|||||||
<item>static-method</item>
|
<item>static-method</item>
|
||||||
<item>constructor</item>
|
<item>constructor</item>
|
||||||
<item>vtable-destructor-offset</item>
|
<item>vtable-destructor-offset</item>
|
||||||
<item>mark-as-simple</item>
|
|
||||||
</list>
|
</list>
|
||||||
<list name="types">
|
<list name="types">
|
||||||
<item>const</item>
|
|
||||||
<item>char</item>
|
<item>char</item>
|
||||||
<item>uchar</item>
|
<item>uchar</item>
|
||||||
<item>short</item>
|
<item>short</item>
|
@ -1,21 +0,0 @@
|
|||||||
syntax def "\.def$"
|
|
||||||
comment "//"
|
|
||||||
|
|
||||||
# Commands
|
|
||||||
color magenta "\<(extends|size|vtable(-size|-destructor-offset)?|property|static-property|((static|virtual)-)?method|constructor|mark-as-simple)\>"
|
|
||||||
|
|
||||||
# Types
|
|
||||||
color green "\<((u?(char|short|int))|float|bool|void|std::(string|vector|map))\>"
|
|
||||||
|
|
||||||
# Numbers
|
|
||||||
color yellow "0x[a-f0-9]+"
|
|
||||||
# Non-hex numbers
|
|
||||||
color red " [0-9][a-f0-9]+;"
|
|
||||||
|
|
||||||
# Comments
|
|
||||||
color brightblue "//.*"
|
|
||||||
|
|
||||||
# Whitespace.
|
|
||||||
color normal "[[:space:]]+"
|
|
||||||
# Trailing whitespace.
|
|
||||||
color ,green "[[:space:]]+$"
|
|
@ -1,24 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
||||||
<plist version="1.0">
|
|
||||||
<dict>
|
|
||||||
<key>name</key>
|
|
||||||
<string>Comments</string>
|
|
||||||
<key>scope</key>
|
|
||||||
<string>source.toml</string>
|
|
||||||
<key>settings</key>
|
|
||||||
<dict>
|
|
||||||
<key>shellVariables</key>
|
|
||||||
<array>
|
|
||||||
<dict>
|
|
||||||
<key>name</key>
|
|
||||||
<string>TM_COMMENT_START</string>
|
|
||||||
<key>value</key>
|
|
||||||
<string>//</string>
|
|
||||||
</dict>
|
|
||||||
</array>
|
|
||||||
</dict>
|
|
||||||
<key>uuid</key>
|
|
||||||
<string>C5C885D7-2733-4632-B709-B5B9DD518F90</string>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
@ -1,55 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
||||||
<plist version="1.0">
|
|
||||||
<dict>
|
|
||||||
<key>fileTypes</key>
|
|
||||||
<array>
|
|
||||||
<string>def</string>
|
|
||||||
</array>
|
|
||||||
<key>scopeName</key>
|
|
||||||
<string>source.symbol-processor</string>
|
|
||||||
<key>name</key>
|
|
||||||
<string>Symbol Processor Definition</string>
|
|
||||||
<key>patterns</key>
|
|
||||||
<array>
|
|
||||||
<dict>
|
|
||||||
<key>name</key>
|
|
||||||
<string>comment.line.double-slash.symbol-processor</string>
|
|
||||||
<key>match</key>
|
|
||||||
<string>//.*$</string>
|
|
||||||
</dict>
|
|
||||||
<dict>
|
|
||||||
<key>name</key>
|
|
||||||
<string>constant.numeric.symbol-processor.hex</string>
|
|
||||||
<key>match</key>
|
|
||||||
<string>\b0[xX][0-9a-fA-F]+</string>
|
|
||||||
</dict>
|
|
||||||
<dict>
|
|
||||||
<key>name</key>
|
|
||||||
<string>constant.numeric.symbol-processor.decimal</string>
|
|
||||||
<key>match</key>
|
|
||||||
<string>\b[0-9]+</string>
|
|
||||||
</dict>
|
|
||||||
<dict>
|
|
||||||
<key>name</key>
|
|
||||||
<string>keyword.control.symbol-processor</string>
|
|
||||||
<key>match</key>
|
|
||||||
<string>\b(extends|size|vtable-size|vtable-destructor-offset|vtable|property|static-property|method|virtual-method|static-method|constructor|mark-as-simple)\b</string>
|
|
||||||
</dict>
|
|
||||||
<dict>
|
|
||||||
<key>name</key>
|
|
||||||
<string>storage.type.symbol-processor</string>
|
|
||||||
<key>match</key>
|
|
||||||
<string>\b(const|char|uchar|short|ushort|int|uint|float|bool|void|std::string|std::vector|std::map|unsigned|long)\b</string>
|
|
||||||
</dict>
|
|
||||||
<dict>
|
|
||||||
<key>name</key>
|
|
||||||
<string>keyword.operator.symbol-processor</string>
|
|
||||||
<key>match</key>
|
|
||||||
<string>(=|;)</string>
|
|
||||||
</dict>
|
|
||||||
</array>
|
|
||||||
<key>uuid</key>
|
|
||||||
<string>D44198D4-5AEB-40E5-B4E4-0E11C69FFA42</string>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
@ -1,16 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
||||||
<plist version="1.0">
|
|
||||||
<dict>
|
|
||||||
<key>contactEmailRot13</key>
|
|
||||||
<string>connor24nolan@live.com</string>
|
|
||||||
<key>contactName</key>
|
|
||||||
<string>TheBrokenRail</string>
|
|
||||||
<key>description</key>
|
|
||||||
<string>Symbol Processor Definition File</string>
|
|
||||||
<key>name</key>
|
|
||||||
<string>Symbol Processor</string>
|
|
||||||
<key>uuid</key>
|
|
||||||
<string>8209EEB8-4193-4E63-BDBB-0407E47ADF50</string>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
@ -1,11 +1,11 @@
|
|||||||
{
|
{
|
||||||
"extends": [
|
"extends": [
|
||||||
"@tsconfig/strictest/tsconfig",
|
"@tsconfig/strictest/tsconfig",
|
||||||
"@tsconfig/node18/tsconfig"
|
"@tsconfig/node-lts/tsconfig"
|
||||||
],
|
],
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"outDir": "build",
|
"rootDir": "./src",
|
||||||
"rootDir": "src"
|
"outDir": "./build"
|
||||||
},
|
},
|
||||||
"include": [
|
"include": [
|
||||||
"src"
|
"src"
|
||||||
|
Loading…
x
Reference in New Issue
Block a user