Compare commits

...

2 Commits

Author SHA1 Message Date
4d64fd2190 Improve Tests
All checks were successful
CI / Build (push) Successful in 15s
2025-02-24 06:25:48 -05:00
8dc7b17251 Refactor Generated Code 2025-02-24 05:23:00 -05:00
14 changed files with 434 additions and 258 deletions

116
data/function.h Normal file
View File

@ -0,0 +1,116 @@
#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;
};
// 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<discriminator, Ret(Args...)> *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;
}
}
};

10
data/internal.h Normal file
View File

@ -0,0 +1,10 @@
#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

View File

@ -1,10 +1,66 @@
#define LEAN_SYMBOLS_HEADER
#define {{ BUILDING_SYMBOLS_GUARD }}
#include "{{ headerPath }}"
// Thunk Template
template <auto *const *func>
decltype(auto) __thunk(auto... args) {
return (*func)->get_thunk_target()(std::forward<decltype(args)>(args)...);
}
// 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
{{ main }}

View File

@ -5,153 +5,19 @@
#error "Symbols Are ARM-Only"
#endif
// Internal Macros
{{ include internal.h }}
// Function Object
{{ include function.h }}
// Headers
#include <variant>
#include <functional>
#include <cstddef>
#include <string>
#include <vector>
#include <map>
#include <type_traits>
#include <cstring>
// Internal Macros
#define __PREVENT_DESTRUCTION(self) \
~self() = delete
#define __PREVENT_CONSTRUCTION(self) \
self() = delete; \
__PREVENT_DESTRUCTION(self)
#define __PREVENT_COPY(self) \
self(const self &) = delete; \
self &operator=(const self &) = delete
// Virtual Function Information
struct __VirtualFunctionInfo {
// Constructors
template <typename Ret, typename Self, typename Super, typename... Args>
__VirtualFunctionInfo(Ret (**const addr_)(Self, Args...), Ret (*const parent_)(Super, Args...)):
addr((void **) addr_),
parent((void *) parent_) {}
template <typename T>
__VirtualFunctionInfo(T **const addr_, const std::nullptr_t parent_):
__VirtualFunctionInfo(addr_, (T *) parent_) {}
// Method
[[nodiscard]] bool can_overwrite() const {
return *addr != parent;
}
// Properties
void **const addr;
void *const parent;
};
// Thunks
typedef void *(*thunk_enabler_t)(void *target, void *thunk);
extern thunk_enabler_t thunk_enabler;
// Function Information
template <typename T>
class __Function;
template <typename Ret, typename... Args>
class __Function<Ret(Args...)> {
// Prevent Copying
__PREVENT_COPY(__Function);
__PREVENT_DESTRUCTION(__Function);
public:
// Types
typedef Ret (*ptr_type)(Args...);
typedef std::function<Ret(Args...)> type;
typedef std::function<Ret(const type &, Args...)> overwrite_type;
// Normal Function
__Function(const std::string name_, const ptr_type thunk_, const ptr_type func_):
func(func_),
enabled(true),
name(name_),
backup(func_),
thunk(thunk_) {}
// Virtual Function
template <typename Parent>
__Function(const std::string name_, const ptr_type thunk_, ptr_type *const func_, const Parent parent):
func(__VirtualFunctionInfo(func_, parent)),
enabled(std::get<__VirtualFunctionInfo>(func).can_overwrite()),
name(name_),
backup(*get_vtable_addr()),
thunk(thunk_) {}
// Overwrite Function
[[nodiscard]] bool overwrite(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(bool result_will_be_stored) {
if (!enabled) {
return nullptr;
} else {
if (result_will_be_stored) {
enable_thunk();
}
if (is_virtual()) {
return *get_vtable_addr();
} else {
return std::get<ptr_type>(func);
}
}
}
[[nodiscard]] ptr_type *get_vtable_addr() const {
return (ptr_type *) std::get<__VirtualFunctionInfo>(func).addr;
}
[[nodiscard]] type get_thunk_target() const {
if (thunk_target) {
return thunk_target;
} else {
return backup;
}
}
private:
// Current Function
std::variant<ptr_type, __VirtualFunctionInfo> func;
[[nodiscard]] bool is_virtual() const {
return func.index() == 1;
}
public:
// State
const bool enabled;
const std::string name;
// Backup Of Original Function Pointer
const ptr_type backup;
private:
// Thunk
const ptr_type 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);
if (!is_virtual()) {
func = real_thunk;
}
thunk_enabled = true;
}
}
};
// Shortcuts
typedef unsigned char uchar;
typedef unsigned short ushort;

View File

@ -9,7 +9,7 @@ export const EXTENSION = '.def';
export const STRUCTURE_FILES: Record<string, string> = {};
export const COMMENT = '//';
export const INTERNAL = '__';
export const LEAN_HEADER_GUARD = '#ifndef LEAN_SYMBOLS_HEADER\n';
export const BUILDING_SYMBOLS_GUARD = 'BUILDING_SYMBOLS_LIB';
// Read Definition File
export function readDefinition(name: string) {
if (!STRUCTURE_FILES[name]) {
@ -36,6 +36,7 @@ export function syntaxError(message?: string): never {
// Convert 'int x' Into {type: 'int', name: 'x'}
const POINTER_TOKENS = ['*', '&'];
export function parseTypeAndName(piece: string) {
piece = piece.trim();
// Split On Last Space
const index = piece.lastIndexOf(' ');
if (index === -1) {
@ -52,6 +53,9 @@ export function parseTypeAndName(piece: string) {
}
type += x;
}
// Trim
name = name.trim();
type = type.trim();
// Return
return {type, name};
}
@ -95,6 +99,7 @@ export function assertSize(name: string, size: number) {
}
// Parse Integer With Error Checking
export function safeParseInt(str: string) {
str = str.trim();
const x = parseInt(str);
if (isNaN(x)) {
throw new Error('Invalid Integer: ' + str);
@ -117,20 +122,23 @@ export function getDataDir() {
return path.join(__dirname, '..', 'data');
}
// Format File From Data Directory
export function formatFile(file: string, options: Record<string, string>) {
// Include Other Files
export function formatFile(file: string, options: Record<string, string>, includeOtherFiles = true) {
const newOptions = Object.assign({}, options);
const dataDir = getDataDir();
const otherFiles = fs.readdirSync(dataDir);
for (let otherFile of otherFiles) {
otherFile = path.join(dataDir, otherFile);
options[`include ${otherFile}`] = fs.readFileSync(otherFile, 'utf8');
// Include Other Files
if (includeOtherFiles) {
const otherFiles = fs.readdirSync(dataDir);
for (const otherFile of otherFiles) {
newOptions[`include ${otherFile}`] = formatFile(otherFile, options, false);
}
}
// Format
file = path.join(dataDir, file);
let data = fs.readFileSync(file, 'utf8');
for (const key in options) {
const value = options[key];
for (const key in newOptions) {
let value = newOptions[key];
if (value) {
value = value.trim();
data = data.replace(`{{ ${key} }}`, value);
}
}

View File

@ -1,6 +1,6 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import { STRUCTURE_FILES, EXTENSION, formatFile, getDataDir, extendErrorMessage } from './common';
import { STRUCTURE_FILES, EXTENSION, formatFile, getDataDir, extendErrorMessage, BUILDING_SYMBOLS_GUARD } from './common';
import { getStructure } from './map';
import { Struct } from './struct';
@ -41,7 +41,7 @@ while (process.argv.length > 0) {
const fullName = file.base;
const name = file.name;
// Store
if (name in STRUCTURE_FILES) {
if (STRUCTURE_FILES[name]) {
throw new Error(`Multiple Definition Files Provided: ${fullName}`);
}
STRUCTURE_FILES[name] = filePath;
@ -129,7 +129,7 @@ function makeHeaderPart() {
try {
structures += structure.generate();
} catch (e) {
throw new Error(extendErrorMessage(e, 'Error Generating Header: ' + name));
throw new Error(extendErrorMessage(e, 'Generating Header: ' + name));
}
structures += '\n';
}
@ -155,7 +155,7 @@ function makeMainHeader(output: string) {
// Main
const main = makeHeaderPart().trim();
// Write
const result = formatFile('out.h', {forwardDeclarations, extraHeaders, main, data: getDataDir()});
const result = formatFile('out.h', {BUILDING_SYMBOLS_GUARD, forwardDeclarations, extraHeaders, main, data: getDataDir()});
fs.writeFileSync(output, result);
}
makeMainHeader(headerOutput);
@ -182,14 +182,14 @@ function makeCompiledCode(outputDir: string) {
try {
declarations += structure.generateCode().trim();
} catch (e) {
throw new Error(extendErrorMessage(e, 'Error Generating Code: ' + name));
throw new Error(extendErrorMessage(e, 'Generating Code: ' + name));
}
declarations += '\n';
// Write
const headerPath = fs.realpathSync(headerOutput);
const main = declarations.trim();
const result = formatFile('out.cpp', {headerPath, main, data: getDataDir()});
const result = formatFile('out.cpp', {BUILDING_SYMBOLS_GUARD, headerPath, main, data: getDataDir()});
const output = path.join(outputDir, name + '.cpp');
fs.writeFileSync(output, result);
}

View File

@ -4,7 +4,7 @@ import { Property, StaticProperty } from './property';
import { Struct } from './struct';
// Error Handling
export class ErrorOnLine extends Error {
class ErrorOnLine extends Error {
constructor (e: unknown, file: string, line: number) {
// Get Message
let message: string;
@ -20,8 +20,9 @@ export class ErrorOnLine extends Error {
}
// Parse Property
function parseProperty(args: string) {
const [a, b] = args.split(' = ');
export const OFFSET_SEPARATOR = ' = ';
export function parseProperty(args: string) {
const [a, b] = args.split(OFFSET_SEPARATOR);
if (!a || !b) {
syntaxError('Invalid Piece Count');
}
@ -31,18 +32,18 @@ function parseProperty(args: string) {
}
// Parse Method
function parseMethod(args: string, self: string, insertSelfArg: boolean, isInherited: boolean) {
export function parseMethod(args: string, self: string, insertSelfArg: boolean, isInherited: boolean) {
const argsStart = args.indexOf('(');
if (argsStart === -1) {
syntaxError('Cannot Find Arguments');
}
const start = args.substring(0, argsStart).trim();
const {type, name} = parseTypeAndName(start);
const end = args.substring(argsStart).trim().split(' = ');
const end = args.substring(argsStart).trim().split(OFFSET_SEPARATOR);
if (!end[0] || !end[1]) {
syntaxError('Invalid Piece Count');
}
let methodArgs = end[0];
let methodArgs = end[0].trim();
if (!methodArgs.startsWith('(') || !methodArgs.endsWith(')')) {
syntaxError('Invalid Method Arguments');
}
@ -172,7 +173,6 @@ export function load(target: Struct, name: string, isExtended: boolean) {
let data = `${target.name} *constructor`;
if (args.startsWith('(')) {
// No Custom Name
data += ' ';
} else {
// Use Custom Name
data += '_';

View File

@ -1,6 +1,11 @@
import { INDENT, INTERNAL, formatType, toHex } from './common';
// A Template Parameter So Each Template Instantiation Is Unique
let nextDiscriminator = 0;
// An Individual Method
export class Method {
readonly #discriminator: number;
readonly self: string;
readonly shortName: string;
readonly returnType: string;
@ -11,6 +16,7 @@ export class Method {
// Constructor
constructor(self: string, name: string, returnType: string, args: string, address: number, isInherited: boolean, isStatic: boolean) {
this.#discriminator = nextDiscriminator++;
this.self = self;
this.shortName = name;
this.returnType = returnType;
@ -34,7 +40,7 @@ export class Method {
return `${INDENT}${this.#getRawType()} *${this.shortName};\n`;
}
#getFullType() {
return `${INTERNAL}Function<${this.#getRawType()}>`;
return `${INTERNAL}Function<${this.#discriminator.toString()}, ${this.#getRawType()}>`;
}
// Typedefs
@ -52,16 +58,14 @@ export class Method {
generate(code: boolean, isVirtual: boolean, parentSelf?: string) {
let out = '';
out += 'extern ';
const type = this.#getFullType();
out += `${type} *const ${this.getName()}`;
out += `${this.#getFullType()} *const ${this.getName()}`;
if (code) {
out += ` = new ${type}(${JSON.stringify(this.getName('::'))}, `;
out += `${INTERNAL}thunk<&${this.getName()}>, `;
out += ` = new ${this.#getFullType()}(${JSON.stringify(this.getName('::'))}, `;
if (isVirtual) {
const parentMethod = parentSelf ? this.#getVirtualCall(parentSelf) : 'nullptr';
out += `&${this.#getVirtualCall()}, ${parentMethod}`;
out += `new ${INTERNAL}VirtualFunctionInfo(&${this.#getVirtualCall()}, (void *) ${parentMethod})`;
} else {
out += `(${this.#getRawType()} *) ${toHex(this.address)}`;
out += `new ${INTERNAL}NormalFunctionInfo((${this.#getRawType()} *) ${toHex(this.address)})`;
}
out += ')';
}

View File

@ -1,5 +1,6 @@
import { INTERNAL, formatType } from './common';
// A Single Property
export class Property {
readonly offset: number;
readonly #type: string;

View File

@ -1,8 +1,9 @@
import { INDENT, STRUCTURE_FILES, toHex, assertSize, INTERNAL, preventConstruction, LEAN_HEADER_GUARD } from './common';
import { INDENT, STRUCTURE_FILES, toHex, assertSize, INTERNAL, preventConstruction, BUILDING_SYMBOLS_GUARD } from './common';
import { Method } from './method';
import { Property, StaticProperty } from './property';
import { VTable } from './vtable';
// A Structure/Class
export class Struct {
readonly name: string;
#vtable: VTable | null;
@ -71,7 +72,7 @@ export class Struct {
this.#properties.push(property);
// Add Dependency If Needed
const type = property.rawType();
if (type in STRUCTURE_FILES) {
if (STRUCTURE_FILES[type]) {
this.#addDependency(type);
}
}
@ -165,7 +166,7 @@ export class Struct {
}
#generateMethods() {
let out = '';
out += LEAN_HEADER_GUARD;
out += `#ifndef ${BUILDING_SYMBOLS_GUARD}\n`;
// Normal Methods
for (const method of this.#methods) {
out += this.#generateMethod(method, false);
@ -174,7 +175,9 @@ export class Struct {
if (this.#vtable !== null) {
const virtualMethods = this.#vtable.getMethods();
for (const method of virtualMethods) {
out += this.#generateMethod(method, true);
if (method) {
out += this.#generateMethod(method, true);
}
}
}
// Allocation Method
@ -223,7 +226,7 @@ export class Struct {
}
}
out += typedefs;
out += LEAN_HEADER_GUARD;
out += `#ifndef ${BUILDING_SYMBOLS_GUARD}\n`;
out += methodsOut;
out += '#endif\n';

View File

@ -1,67 +0,0 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { formatType, parseTypeAndName, prependArg, toUpperSnakeCase } from '../common';
describe('Parsing Variable Declarations', () => {
const tests: [string, string, string, string][] = [
['Simple', 'int x', 'int', 'x'],
['Pointer', 'int *y', 'int *', 'y'],
['Ugly Pointer', 'int* z', 'int*', 'z'],
['Double Pointer', 'int **a', 'int **', 'a'],
['Ugly Double Pointer', 'int* *b', 'int**', 'b'],
['Reference', 'int &c', 'int &', 'c'],
['Reference-To-Pointer', 'int *&d', 'int *&', 'd']
];
for (const test of tests) {
it(test[0], () => {
const obj = parseTypeAndName(test[1]);
assert.strictEqual(obj.type, test[2]);
assert.strictEqual(obj.name, test[3]);
});
}
it('Invalid', () => {
assert.throws(() => {
parseTypeAndName('abc');
});
});
});
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('Prepending Arguments To Functions', () => {
const tests: [string, string, string, string][] = [
['Empty', '()', 'int x', '(int x)'],
['Non-Empty', '(int x)', 'int y', '(int y, int x)']
];
for (const test of tests) {
it(test[0], () => {
assert.strictEqual(prependArg(test[1], test[2]), test[3]);
});
}
});

44
src/test/formatting.ts Normal file
View File

@ -0,0 +1,44 @@
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]);
});
}
});

121
src/test/parsing.ts Normal file
View File

@ -0,0 +1,121 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { 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.args, test.out.args);
assert.strictEqual(method.address, test.out.address);
} else {
assert.throws(() => {
parseMethod(test.input, test.self, !test.isStatic, false);
});
}
});
}
});

View File

@ -1,15 +1,17 @@
import { INDENT, LEAN_HEADER_GUARD, POINTER_SIZE, assertSize, getSelfArg, preventConstruction, toHex } from './common';
import { BUILDING_SYMBOLS_GUARD, INDENT, POINTER_SIZE, assertSize, getSelfArg, preventConstruction, toHex } from './common';
import { Method } from './method';
import { Property } from './property';
// A VTable
const structuresWithVTableAddress: string[] = [];
export class VTable {
readonly #self: string;
#address: number | null;
#size: number | null;
readonly #methods: Method[];
readonly #methods: (Method | undefined)[];
readonly property: Property;
#destructorOffset: number;
readonly #destructors: Method[];
// Constructor
constructor(self: string) {
@ -18,6 +20,7 @@ export class VTable {
this.#size = null;
this.#methods = [];
this.#destructorOffset = 0;
this.#destructors = [];
// Create Property
this.property = new Property(0, this.#getName() + ' *', 'vtable', this.#self);
}
@ -35,7 +38,7 @@ export class VTable {
}
// Add To VTable
#add(target: Method[], method: Method) {
#add(target: (Method | undefined)[], method: Method) {
// Check Offset
const offset = method.address;
if ((offset % POINTER_SIZE) !== 0) {
@ -43,7 +46,7 @@ export class VTable {
}
// Add
const index = offset / POINTER_SIZE;
if (index in target) {
if (target[index]) {
throw new Error(`Duplicate Virtual Method At Offset: ${toHex(offset)}`);
}
target[index] = method;
@ -80,8 +83,15 @@ export class VTable {
// Add Destructors (https://stackoverflow.com/a/17960941)
const destructor_return = `${this.#self} *`;
const destructor_args = `(${getSelfArg(this.#self)})`;
this.#add(out, new Method(this.#self, 'destructor_complete', destructor_return, destructor_args, 0x0 + this.#destructorOffset, false, false));
this.#add(out, new Method(this.#self, 'destructor_deleting', destructor_return, destructor_args, 0x4 + this.#destructorOffset, false, false));
if (this.#destructors.length === 0) {
this.#destructors.push(
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 out;
}
@ -119,13 +129,15 @@ export class VTable {
let typedefs = '';
let methodsOut = '';
for (const info of methods) {
typedefs += info.generateTypedefs();
if (this.canGenerateWrappers()) {
methodsOut += info.generate(false, true);
if (info) {
typedefs += info.generateTypedefs();
if (this.canGenerateWrappers()) {
methodsOut += info.generate(false, true);
}
}
}
out += typedefs;
out += LEAN_HEADER_GUARD;
out += `#ifndef ${BUILDING_SYMBOLS_GUARD}\n`;
out += methodsOut;
out += '#endif\n';
@ -176,7 +188,9 @@ export class VTable {
if (this.canGenerateWrappers()) {
const methods = this.getMethods();
for (const info of methods) {
out += info.generate(true, true, this.#getParentSelf(info, directParent));
if (info) {
out += info.generate(true, true, this.#getParentSelf(info, directParent));
}
}
}