Compare commits

..

33 Commits

Author SHA1 Message Date
WerWolv
a09aec032f Bump version to 1.6.1 2021-01-11 09:56:09 +01:00
WerWolv
7784fca0d4 Always display Pattern Data table header 2021-01-11 09:53:20 +01:00
WerWolv
68bd5569ce Don't show Plugin Views menu if there are no views 2021-01-11 09:50:51 +01:00
WerWolv
60e1c23a6b Fixed pattern format strings 2021-01-11 09:14:32 +01:00
WerWolv
77fbb54ebc Added dlsym to msys2 PKGBUILD 2021-01-11 08:54:23 +01:00
WerWolv
9b7b782020 Fixed cmake error when build type was left unset 2021-01-11 08:46:51 +01:00
WerWolv
bb3e0c126f CI steps naming consistency 2021-01-11 00:44:20 +01:00
WerWolv
3aeb9f31b0 Mark toEngineeringString inline to prevent linker errors 2021-01-11 00:36:24 +01:00
WerWolv
8b19f0c3c0 Improved UTF-8 display in data inspector 2021-01-11 00:34:50 +01:00
WerWolv
73e259d6e7 Added engineering display mode to calculator 2021-01-11 00:27:00 +01:00
WerWolv
f9039f4b34 Added hex editor view right click context menu 2021-01-10 23:59:36 +01:00
George Hopkins
5fb046ad1f Show commit on about page only if available (#132) 2021-01-10 22:57:57 +01:00
WerWolv
7b089a1f2f Fixed unions not advancing offset 2021-01-10 22:57:04 +01:00
WerWolv
867faef496 Fixed invalid applying of define replacements 2021-01-10 22:52:58 +01:00
WerWolv
557313ae1e Fixed boolean OR never being parsed 2021-01-10 22:52:28 +01:00
WerWolv
e4c2049975 Fixed off-by-one error for array bound check 2021-01-10 22:52:12 +01:00
WerWolv
b4ef19dac7 Fixed empty struct and union offset display 2021-01-10 19:43:21 +01:00
WerWolv
dc6c1fa622 Fixed issues with struct and union members when using conditionals 2021-01-10 19:40:44 +01:00
Nobutaka Mantani
d9db8401e2 Fix build on FreeBSD (#126)
* Fix build on FreeBSD

* Use more generic way to search libcrypto

* Integrate macro for FreeBSD
2021-01-10 18:52:00 +01:00
WerWolv
9fe8a0f491 Fixed enums not counting towards size of structs / enums 2021-01-10 18:24:58 +01:00
WerWolv
43d6b48cab Fixed rvalue endianess 2021-01-10 17:18:14 +01:00
WerWolv
ad40c53eb2 Fixed enum parse/evaluate error and crash 2021-01-10 17:14:38 +01:00
Robin Lambertz
c71c610eba Windows MSI Installer (#121)
* Create ImHex WIX Installer

* Build Windows Installer in github actions

* Have a single windows step handling MSI and ZIP.

* Properly copy dependencies to portable zip

* Add magicdb to zip/msi

* Use arial font and smaller text in license
2021-01-10 14:22:34 +01:00
WerWolv
cf1fe04431 Fixed invalid type name in bitfields 2021-01-10 13:50:34 +01:00
WerWolv
8f16a733b9 Fixed bitfields behaving like they have no size. Fixes #127 2021-01-10 13:40:07 +01:00
WerWolv
bc4991f915 Improved type consistency throughout the language 2021-01-10 00:40:57 +01:00
WerWolv
7a8e923b41 Added print & warnAssert functions and a colored console 2021-01-09 23:48:42 +01:00
WerWolv
e54dbcf574 Added assert function. Resolves #123 2021-01-09 21:47:52 +01:00
WerWolv
c5d023822d Added functions with string literals as parameter 2021-01-09 21:47:52 +01:00
WerWolv
e28d6e7451 Added string literals and improved character parsing 2021-01-09 21:47:52 +01:00
WerWolv
9f275cc84f Show evaluator errors in a console window instead of the first line 2021-01-09 21:47:52 +01:00
Philipp Kovalev
575903f921 fix(lang): fixes occurrence index in findSequnce built-in fucntion (#120) 2021-01-09 18:48:34 +01:00
WerWolv
02b3b94804 Increased ImHex to version 1.6.0 2021-01-08 22:09:08 +01:00
26 changed files with 834 additions and 312 deletions

View File

@@ -45,14 +45,13 @@ jobs:
CC=gcc-10 CXX=g++-10 cmake -DCMAKE_BUILD_TYPE=$BUILD_TYPE .. CC=gcc-10 CXX=g++-10 cmake -DCMAKE_BUILD_TYPE=$BUILD_TYPE ..
make -j 4 make -j 4
- name: 📦 Uploading artifact - name: 📦 Upload ELF
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v2
with: with:
name: Linux ELF name: Linux ELF
path: build/imhex path: build/imhex
win:
win-manual:
runs-on: windows-latest runs-on: windows-latest
strategy: strategy:
fail-fast: false fail-fast: false
@@ -97,18 +96,40 @@ jobs:
run: | run: |
mkdir build mkdir build
cd build cd build
ls -1 C:/hostedtoolcache/windows/Python/3.9.1/x64/python39.dll | xargs -L1 -I{} cp {} . # Get path to mingw python library
ls -1 D:/a/_temp/msys/msys64/mingw64/bin/libwinpthread-?.dll | xargs -L1 -I{} cp {} . PYTHON_LIB_NAME=$(pkg-config --libs-only-l python3 | sed 's/^-l//')
cmake -G "MinGW Makefiles" -DCMAKE_BUILD_TYPE=$BUILD_TYPE .. PYTHON_LIB_PATH=$(cygpath -m $(which lib${PYTHON_LIB_NAME}.dll))
mingw32-make -j 4
- name: 📦 Uploading artifact # Get path to magic db
MAGICDB_PATH=$(cygpath -m $(file --version | grep -oP "(?<=magic file from ).+"))
echo Python_LIBRARY: $PYTHON_LIB_PATH
echo MagicDB Path: $MAGICDB_PATH
cmake -G "MinGW Makefiles" \
-DCMAKE_BUILD_TYPE=$BUILD_TYPE \
-DCMAKE_INSTALL_PREFIX="$PWD/install" \
-DCREATE_PACKAGE=ON \
-DPython_LIBRARY="$PYTHON_LIB_PATH" \
-DEXTRA_MAGICDBS="$MAGICDB_PATH" \
..
mingw32-make -j4
mingw32-make install
cpack
- name: 📦 Upload Portable ZIP
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v2
with: with:
name: Windows EXE name: Windows Portable ZIP
path: | path: |
build/*.exe build/install/*
build/python39.dll
build/libwinpthread-?.dll - name: 📦 Upload Windows Installer
uses: actions/upload-artifact@v2
with:
name: Windows Installer
path: |
build/*.msi
macos-build: macos-build:
runs-on: macos-11.0 runs-on: macos-11.0
@@ -131,7 +152,7 @@ jobs:
CC=$(brew --prefix llvm)/bin/clang CXX=$(brew --prefix llvm)/bin/clang++ PKG_CONFIG_PATH="$(brew --prefix openssl)/lib/pkgconfig":"$(brew --prefix)/lib/pkgconfig" cmake -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCREATE_BUNDLE=ON -DCREATE_PACKAGE=ON .. CC=$(brew --prefix llvm)/bin/clang CXX=$(brew --prefix llvm)/bin/clang++ PKG_CONFIG_PATH="$(brew --prefix openssl)/lib/pkgconfig":"$(brew --prefix)/lib/pkgconfig" cmake -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCREATE_BUNDLE=ON -DCREATE_PACKAGE=ON ..
make -j 4 package make -j 4 package
- name: 📦 Uploading artifact - name: 📦 Upload DMG
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v2
with: with:
name: macOS DMG name: macOS DMG

View File

@@ -1,10 +1,17 @@
cmake_minimum_required(VERSION 3.16) cmake_minimum_required(VERSION 3.16)
project(imhex VERSION 1.5.0) project(imhex VERSION 1.6.1)
if(NOT CMAKE_BUILD_TYPE) if (WIN32)
set(CMAKE_BUILD_TYPE "Release" CACHE FORCE) set(EXTRA_MAGICDBS "" CACHE STRING "List of compiled magicdb files separated with a ;")
endif(NOT CMAKE_BUILD_TYPE) else()
set(EXTRA_MAGICDBS "" CACHE STRING "List of compiled magicdb files separated with a :")
endif()
if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Using Release build type as it was left unset" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release")
endif()
set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/modules") set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/modules")
@@ -23,7 +30,10 @@ set(Python_FIND_FRAMEWORK NEVER)
# Find packages # Find packages
find_package(PkgConfig REQUIRED) find_package(PkgConfig REQUIRED)
pkg_search_module(CRYPTO REQUIRED libcrypto) pkg_search_module(CRYPTO libcrypto)
if(NOT CRYPTO_FOUND)
find_library(CRYPTO crypto REQUIRED)
endif()
pkg_search_module(CAPSTONE REQUIRED capstone) pkg_search_module(CAPSTONE REQUIRED capstone)
find_package(OpenGL REQUIRED) find_package(OpenGL REQUIRED)
find_package(nlohmann_json REQUIRED) find_package(nlohmann_json REQUIRED)
@@ -72,24 +82,26 @@ elseif(CMAKE_SIZEOF_VOID_P EQUAL 4)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DARCH_32_BIT") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DARCH_32_BIT")
endif() endif()
# Get the current working branch if (IS_DIRECTORY "${CMAKE_SOURCE_DIR}/.git")
execute_process( # Get the current working branch
COMMAND git rev-parse --abbrev-ref HEAD execute_process(
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} COMMAND git rev-parse --abbrev-ref HEAD
OUTPUT_VARIABLE GIT_BRANCH WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE GIT_BRANCH
) OUTPUT_STRIP_TRAILING_WHITESPACE
)
# Get the latest abbreviated commit hash of the working branch # Get the latest abbreviated commit hash of the working branch
execute_process( execute_process(
COMMAND git log -1 --format=%h COMMAND git log -1 --format=%h
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_COMMIT_HASH OUTPUT_VARIABLE GIT_COMMIT_HASH
OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_STRIP_TRAILING_WHITESPACE
) )
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DGIT_COMMIT_HASH=\"\\\"${GIT_COMMIT_HASH}\"\\\"") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DGIT_COMMIT_HASH=\"\\\"${GIT_COMMIT_HASH}\"\\\"")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DGIT_BRANCH=\"\\\"${GIT_BRANCH}\"\\\"") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DGIT_BRANCH=\"\\\"${GIT_BRANCH}\"\\\"")
endif()
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -DRELEASE -DIMHEX_VERSION=\"\\\"${PROJECT_VERSION}\"\\\"") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -DRELEASE -DIMHEX_VERSION=\"\\\"${PROJECT_VERSION}\"\\\"")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG -DIMHEX_VERSION=\"\\\"${PROJECT_VERSION}-Debug\"\\\"") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG -DIMHEX_VERSION=\"\\\"${PROJECT_VERSION}-Debug\"\\\"")
@@ -97,6 +109,18 @@ set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG -DIMHEX_VERSION=\"\\
if (WIN32) if (WIN32)
set(application_type WIN32) set(application_type WIN32)
set(imhex_icon resource.rc) set(imhex_icon resource.rc)
if (CREATE_PACKAGE)
set(CPACK_GENERATOR "WIX")
set(CPACK_PACKAGE_NAME "ImHex")
set(CPACK_WIX_UPGRADE_GUID "05000E99-9659-42FD-A1CF-05C554B39285")
set(CPACK_WIX_PRODUCT_ICON "${PROJECT_SOURCE_DIR}/res/icon.ico")
set(CPACK_PACKAGE_INSTALL_DIRECTORY "ImHex")
set_property(INSTALL "$<TARGET_FILE_NAME:imhex>"
PROPERTY CPACK_START_MENU_SHORTCUTS "ImHex"
)
set(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/res/LICENSE.rtf")
endif()
elseif (APPLE) elseif (APPLE)
set (imhex_icon "${PROJECT_SOURCE_DIR}/res/mac/AppIcon.icns") set (imhex_icon "${PROJECT_SOURCE_DIR}/res/mac/AppIcon.icns")
@@ -166,6 +190,54 @@ elseif (UNIX)
target_link_libraries(imhex magic crypto ${CMAKE_DL_LIBS} capstone LLVMDemangle imgui libimhex ${Python_LIBRARIES} nlohmann_json::nlohmann_json dl) target_link_libraries(imhex magic crypto ${CMAKE_DL_LIBS} capstone LLVMDemangle imgui libimhex ${Python_LIBRARIES} nlohmann_json::nlohmann_json dl)
endif() endif()
if (WIN32)
# Install binaries directly in the prefix, usually C:\Program Files\ImHex.
set(CMAKE_INSTALL_BINDIR ".")
# Grab all dynamically linked dependencies.
INSTALL(CODE "set(CMAKE_INSTALL_BINDIR \"${CMAKE_INSTALL_BINDIR}\")")
INSTALL(CODE "get_filename_component(PY_PARENT ${Python_LIBRARIES} DIRECTORY)")
INSTALL(CODE "LIST(APPEND DEP_FOLDERS \${PY_PARENT})")
install(CODE [[
file(GET_RUNTIME_DEPENDENCIES
EXECUTABLES $<TARGET_FILE:imhex>
RESOLVED_DEPENDENCIES_VAR _r_deps
UNRESOLVED_DEPENDENCIES_VAR _u_deps
CONFLICTING_DEPENDENCIES_PREFIX _c_deps
DIRECTORIES ${DEP_FOLDERS}
POST_EXCLUDE_REGEXES ".*system32/.*\\.dll"
)
if(_u_deps)
message(WARNING "There were unresolved dependencies for binary $<TARGET_FILE:imhex>: \"${_u_deps}\"!")
endif()
if(_c_deps_FILENAMES)
message(WARNING "There were conflicting dependencies for library $<TARGET_FILE:imhex>: \"${_c_deps}\"!")
endif()
foreach(_file ${_r_deps})
file(INSTALL
DESTINATION "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_BINDIR}"
TYPE SHARED_LIBRARY
FOLLOW_SYMLINK_CHAIN
FILES "${_file}"
)
endforeach()
]])
endif()
# Compile the imhex-specific magicdb
add_custom_target(magic_dbs ALL
SOURCES magic_dbs/nintendo_magic
)
add_custom_command(TARGET magic_dbs
COMMAND file -C -m ${CMAKE_SOURCE_DIR}/magic_dbs
)
# Install the magicdb files.
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/magic_dbs.mgc DESTINATION magic/ RENAME imhex.mgc)
install(FILES ${EXTRA_MAGICDBS} DESTINATION magic/)
if (CREATE_BUNDLE) if (CREATE_BUNDLE)
include(PostprocessBundle) include(PostprocessBundle)

View File

@@ -1127,7 +1127,7 @@ void TextEditor::Render(const char* aTitle, const ImVec2& aSize, bool aBorder)
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::ColorConvertU32ToFloat4(mPalette[(int)PaletteIndex::Background])); ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::ColorConvertU32ToFloat4(mPalette[(int)PaletteIndex::Background]));
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f)); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f));
if (!mIgnoreImGuiChild) if (!mIgnoreImGuiChild)
ImGui::BeginChild(aTitle, aSize, aBorder, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NoMove); ImGui::BeginChild(aTitle, aSize, aBorder, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoMove);
if (mHandleKeyboardInputs) if (mHandleKeyboardInputs)
{ {

View File

@@ -333,7 +333,7 @@ namespace hex::lang {
[[nodiscard]] const std::unordered_map<std::string, ASTNode*>& getEntries() const { return this->m_entries; } [[nodiscard]] const std::unordered_map<std::string, ASTNode*>& getEntries() const { return this->m_entries; }
void addEntry(const std::string &name, ASTNode* expression) { this->m_entries.insert({ name, expression }); } void addEntry(const std::string &name, ASTNode* expression) { this->m_entries.insert({ name, expression }); }
[[nodiscard]] const ASTNode *getUnderlyingType() const { return this->m_underlyingType; } [[nodiscard]] ASTNode *getUnderlyingType() { return this->m_underlyingType; }
private: private:
std::unordered_map<std::string, ASTNode*> m_entries; std::unordered_map<std::string, ASTNode*> m_entries;
@@ -479,5 +479,27 @@ namespace hex::lang {
std::vector<ASTNode*> m_params; std::vector<ASTNode*> m_params;
}; };
class ASTNodeStringLiteral : public ASTNode {
public:
explicit ASTNodeStringLiteral(std::string_view string) : ASTNode(), m_string(string) { }
~ASTNodeStringLiteral() override { }
ASTNodeStringLiteral(const ASTNodeStringLiteral &other) : ASTNode(other) {
this->m_string = other.m_string;
}
ASTNode* clone() const override {
return new ASTNodeStringLiteral(*this);
}
[[nodiscard]] std::string_view getString() {
return this->m_string;
}
private:
std::string m_string;
};
} }

View File

@@ -3,6 +3,7 @@
#include <hex.hpp> #include <hex.hpp>
#include "providers/provider.hpp" #include "providers/provider.hpp"
#include "helpers/utils.hpp"
#include "lang/pattern_data.hpp" #include "lang/pattern_data.hpp"
#include "ast_node.hpp" #include "ast_node.hpp"
@@ -15,12 +16,12 @@ namespace hex::lang {
class Evaluator { class Evaluator {
public: public:
Evaluator(prv::Provider* &provider, std::endian defaultDataEndian); enum ConsoleLogLevel {
Debug,
std::optional<std::vector<PatternData*>> evaluate(const std::vector<ASTNode*>& ast); Info,
Warning,
const std::pair<u32, std::string>& getError() { return this->m_error; } Error
};
struct Function { struct Function {
constexpr static u32 UnlimitedParameters = 0xFFFF'FFFF; constexpr static u32 UnlimitedParameters = 0xFFFF'FFFF;
@@ -29,9 +30,14 @@ namespace hex::lang {
constexpr static u32 NoParameters = 0x0000'0000; constexpr static u32 NoParameters = 0x0000'0000;
u32 parameterCount; u32 parameterCount;
std::function<ASTNodeIntegerLiteral*(std::vector<ASTNodeIntegerLiteral*>)> func; std::function<ASTNodeIntegerLiteral*(std::vector<ASTNode*>)> func;
}; };
Evaluator(prv::Provider* &provider, std::endian defaultDataEndian);
std::optional<std::vector<PatternData*>> evaluate(const std::vector<ASTNode*>& ast);
const auto& getConsoleLog() { return this->m_consoleLog; }
private: private:
std::map<std::string, ASTNode*> m_types; std::map<std::string, ASTNode*> m_types;
prv::Provider* &m_provider; prv::Provider* &m_provider;
@@ -42,21 +48,33 @@ namespace hex::lang {
std::vector<std::vector<PatternData*>*> m_currMembers; std::vector<std::vector<PatternData*>*> m_currMembers;
std::map<std::string, Function> m_functions; std::map<std::string, Function> m_functions;
std::pair<u32, std::string> m_error; std::vector<std::pair<ConsoleLogLevel, std::string>> m_consoleLog;
using EvaluateError = std::pair<u32, std::string>; using EvaluateError = std::string;
[[noreturn]] static void throwEvaluateError(std::string_view error, u32 lineNumber) { void emmitDebugInfo(std::string_view message) {
throw EvaluateError(lineNumber, "Evaluator: " + std::string(error)); this->m_consoleLog.emplace_back(ConsoleLogLevel::Debug, "[-] " + std::string(message));
}
void emmitInfo(std::string_view message) {
this->m_consoleLog.emplace_back(ConsoleLogLevel::Info, "[i] " + std::string(message));
}
void emmitWaring(std::string_view message) {
this->m_consoleLog.emplace_back(ConsoleLogLevel::Warning, "[*] " + std::string(message));
}
[[noreturn]] static void throwEvaluateError(std::string_view message) {
throw EvaluateError("[!] " + std::string(message));
} }
[[nodiscard]] std::endian getCurrentEndian() const { [[nodiscard]] std::endian getCurrentEndian() const {
return this->m_endianStack.back(); return this->m_endianStack.back();
} }
void addFunction(std::string_view name, u32 parameterCount, std::function<ASTNodeIntegerLiteral*(std::vector<ASTNodeIntegerLiteral*>)> func) { void addFunction(std::string_view name, u32 parameterCount, std::function<ASTNodeIntegerLiteral*(std::vector<ASTNode*>)> func) {
if (this->m_functions.contains(name.data())) if (this->m_functions.contains(name.data()))
throwEvaluateError(hex::format("redefinition of function '%s'", name.data()), 1); throwEvaluateError(hex::format("redefinition of function '%s'", name.data()));
this->m_functions[name.data()] = { parameterCount, func }; this->m_functions[name.data()] = { parameterCount, func };
} }
@@ -70,7 +88,7 @@ namespace hex::lang {
ASTNodeIntegerLiteral* evaluateMathematicalExpression(ASTNodeNumericExpression *node); ASTNodeIntegerLiteral* evaluateMathematicalExpression(ASTNodeNumericExpression *node);
PatternData* evaluateBuiltinType(ASTNodeBuiltinType *node); PatternData* evaluateBuiltinType(ASTNodeBuiltinType *node);
std::vector<PatternData*> evaluateMember(ASTNode *node); void evaluateMember(ASTNode *node, std::vector<PatternData*> &currMembers, bool increaseOffset);
PatternData* evaluateStruct(ASTNodeStruct *node); PatternData* evaluateStruct(ASTNodeStruct *node);
PatternData* evaluateUnion(ASTNodeUnion *node); PatternData* evaluateUnion(ASTNodeUnion *node);
PatternData* evaluateEnum(ASTNodeEnum *node); PatternData* evaluateEnum(ASTNodeEnum *node);
@@ -81,12 +99,26 @@ namespace hex::lang {
PatternData* evaluatePointer(ASTNodePointerVariableDecl *node); PatternData* evaluatePointer(ASTNodePointerVariableDecl *node);
#define BUILTIN_FUNCTION(name) ASTNodeIntegerLiteral* name(std::vector<ASTNodeIntegerLiteral*> params) template<typename T>
T* asType(ASTNode *param) {
if (auto evaluatedParam = dynamic_cast<T*>(param); evaluatedParam != nullptr)
return evaluatedParam;
else
throwEvaluateError("function got wrong type of parameter");
}
#define BUILTIN_FUNCTION(name) ASTNodeIntegerLiteral* TOKEN_CONCAT(builtin_, name)(std::vector<ASTNode*> params)
BUILTIN_FUNCTION(findSequence); BUILTIN_FUNCTION(findSequence);
BUILTIN_FUNCTION(readUnsigned); BUILTIN_FUNCTION(readUnsigned);
BUILTIN_FUNCTION(readSigned); BUILTIN_FUNCTION(readSigned);
BUILTIN_FUNCTION(assert);
BUILTIN_FUNCTION(warnAssert);
BUILTIN_FUNCTION(print);
#undef BUILTIN_FUNCTION #undef BUILTIN_FUNCTION
}; };

View File

@@ -12,16 +12,15 @@ namespace hex::lang {
class Lexer { class Lexer {
public: public:
using LexerError = std::pair<u32, std::string>;
Lexer(); Lexer();
std::optional<std::vector<Token>> lex(const std::string& code); std::optional<std::vector<Token>> lex(const std::string& code);
const LexerError& getError() { return this->m_error; }
const std::pair<u32, std::string>& getError() { return this->m_error; }
private: private:
std::pair<u32, std::string> m_error; LexerError m_error;
using LexerError = std::pair<u32, std::string>;
[[noreturn]] void throwLexerError(std::string_view error, u32 lineNumber) const { [[noreturn]] void throwLexerError(std::string_view error, u32 lineNumber) const {
throw LexerError(lineNumber, "Lexer: " + std::string(error)); throw LexerError(lineNumber, "Lexer: " + std::string(error));

View File

@@ -16,18 +16,16 @@ namespace hex::lang {
class Parser { class Parser {
public: public:
using TokenIter = std::vector<Token>::const_iterator;
using ParseError = std::pair<u32, std::string>;
Parser() = default; Parser() = default;
~Parser() = default; ~Parser() = default;
using TokenIter = std::vector<Token>::const_iterator;
std::optional<std::vector<ASTNode*>> parse(const std::vector<Token> &tokens); std::optional<std::vector<ASTNode*>> parse(const std::vector<Token> &tokens);
const ParseError& getError() { return this->m_error; }
const std::pair<u32, std::string>& getError() { return this->m_error; }
private: private:
using ParseError = std::pair<u32, std::string>;
ParseError m_error; ParseError m_error;
TokenIter m_curr; TokenIter m_curr;
TokenIter m_originalPosition; TokenIter m_originalPosition;
@@ -54,6 +52,7 @@ namespace hex::lang {
} }
ASTNode* parseFunctionCall(); ASTNode* parseFunctionCall();
ASTNode* parseStringLiteral();
ASTNode* parseScopeResolution(std::vector<std::string> &path); ASTNode* parseScopeResolution(std::vector<std::string> &path);
ASTNode* parseRValue(std::vector<std::string> &path); ASTNode* parseRValue(std::vector<std::string> &path);
ASTNode* parseFactor(); ASTNode* parseFactor();

View File

@@ -159,9 +159,9 @@ namespace hex::lang {
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight())); ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight()));
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("0x%08llx : 0x%08llx", this->getOffset(), this->getOffset() + this->getSize() - 1); ImGui::Text("0x%08llX : 0x%08llX", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("0x%04llx", this->getSize()); ImGui::Text("0x%04llX", this->getSize());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextColored(ImColor(0xFF9BC64D), "%s", this->getFormattedName().c_str()); ImGui::TextColored(ImColor(0xFF9BC64D), "%s", this->getFormattedName().c_str());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
@@ -222,13 +222,13 @@ namespace hex::lang {
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight())); ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight()));
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("0x%08llx : 0x%08llx", this->getOffset(), this->getOffset() + this->getSize() - 1); ImGui::Text("0x%08llX : 0x%08llX", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("0x%04llx", this->getSize()); ImGui::Text("0x%04llX", this->getSize());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextColored(ImColor(0xFF9BC64D), "%s*", this->m_pointedAt->getFormattedName().c_str()); ImGui::TextColored(ImColor(0xFF9BC64D), "%s*", this->m_pointedAt->getFormattedName().c_str());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("*(0x%llx)", data); ImGui::Text("*(0x%llX)", data);
if (open) { if (open) {
this->m_pointedAt->createEntry(provider); this->m_pointedAt->createEntry(provider);
@@ -283,7 +283,7 @@ namespace hex::lang {
provider->read(this->getOffset(), &data, this->getSize()); provider->read(this->getOffset(), &data, this->getSize());
data = hex::changeEndianess(data, this->getSize(), this->getEndian()); data = hex::changeEndianess(data, this->getSize(), this->getEndian());
this->createDefaultEntry(hex::format("%lu (0x%0*lx)", data, this->getSize() * 2, data)); this->createDefaultEntry(hex::format("%llu (0x%0*llX)", data, this->getSize() * 2, data));
} }
[[nodiscard]] std::string getFormattedName() const override { [[nodiscard]] std::string getFormattedName() const override {
@@ -314,7 +314,7 @@ namespace hex::lang {
s64 signedData = hex::signExtend(data, this->getSize(), 64); s64 signedData = hex::signExtend(data, this->getSize(), 64);
this->createDefaultEntry(hex::format("%ld (0x%0*lx)", signedData, this->getSize() * 2, data)); this->createDefaultEntry(hex::format("%lld (0x%0*llX)", signedData, this->getSize() * 2, data));
} }
[[nodiscard]] std::string getFormattedName() const override { [[nodiscard]] std::string getFormattedName() const override {
@@ -350,7 +350,7 @@ namespace hex::lang {
provider->read(this->getOffset(), &data, 8); provider->read(this->getOffset(), &data, 8);
data = hex::changeEndianess(data, 8, this->getEndian()); data = hex::changeEndianess(data, 8, this->getEndian());
this->createDefaultEntry(hex::format("%e (0x%0*lX)", *reinterpret_cast<double*>(&data), this->getSize() * 2, data)); this->createDefaultEntry(hex::format("%e (0x%0*llX)", *reinterpret_cast<double*>(&data), this->getSize() * 2, data));
} }
} }
@@ -456,9 +456,9 @@ namespace hex::lang {
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight())); ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight()));
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("0x%08llx : 0x%08llx", this->getOffset(), this->getOffset() + this->getSize() - 1); ImGui::Text("0x%08llX : 0x%08llX", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("0x%04llx", this->getSize()); ImGui::Text("0x%04llX", this->getSize());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextColored(ImColor(0xFF9BC64D), "%s", this->m_entries[0]->getTypeName().c_str()); ImGui::TextColored(ImColor(0xFF9BC64D), "%s", this->m_entries[0]->getTypeName().c_str());
ImGui::SameLine(0, 0); ImGui::SameLine(0, 0);
@@ -526,9 +526,9 @@ namespace hex::lang {
bool open = ImGui::TreeNodeEx(this->getVariableName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth); bool open = ImGui::TreeNodeEx(this->getVariableName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("0x%08llx : 0x%08llx", this->getOffset(), this->getOffset() + this->getSize() - 1); ImGui::Text("0x%08llX : 0x%08llX", this->getOffset(), this->getOffset() + this->getSize() - (this->getSize() == 0 ? 0 : 1));
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("0x%04llx", this->getSize()); ImGui::Text("0x%04llX", this->getSize());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextColored(ImColor(0xFFD69C56), "struct"); ImGui::SameLine(); ImGui::Text("%s", this->getTypeName().c_str()); ImGui::TextColored(ImColor(0xFFD69C56), "struct"); ImGui::SameLine(); ImGui::Text("%s", this->getTypeName().c_str());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
@@ -606,9 +606,9 @@ namespace hex::lang {
bool open = ImGui::TreeNodeEx(this->getVariableName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth); bool open = ImGui::TreeNodeEx(this->getVariableName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("0x%08llx : 0x%08llx", this->getOffset(), this->getOffset() + this->getSize() - 1); ImGui::Text("0x%08llX : 0x%08llX", this->getOffset(), std::max(this->getOffset() + this->getSize() - (this->getSize() == 0 ? 0 : 1), u64(0)));
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("0x%04llx", this->getSize()); ImGui::Text("0x%04llX", this->getSize());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextColored(ImColor(0xFFD69C56), "union"); ImGui::SameLine(); ImGui::Text("%s", PatternData::getTypeName().c_str()); ImGui::TextColored(ImColor(0xFFD69C56), "union"); ImGui::SameLine(); ImGui::Text("%s", PatternData::getTypeName().c_str());
@@ -713,13 +713,13 @@ namespace hex::lang {
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight())); ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight()));
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("0x%08llx : 0x%08llx", this->getOffset(), this->getOffset() + this->getSize() - 1); ImGui::Text("0x%08llX : 0x%08llX", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("0x%04llx", this->getSize()); ImGui::Text("0x%04llX", this->getSize());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextColored(ImColor(0xFFD69C56), "enum"); ImGui::SameLine(); ImGui::Text("%s", PatternData::getTypeName().c_str()); ImGui::TextColored(ImColor(0xFFD69C56), "enum"); ImGui::SameLine(); ImGui::Text("%s", PatternData::getTypeName().c_str());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("%s", hex::format("%s (0x%0*lx)", valueString.c_str(), this->getSize() * 2, value).c_str()); ImGui::Text("%s", hex::format("%s (0x%0*llX)", valueString.c_str(), this->getSize() * 2, value).c_str());
} }
[[nodiscard]] std::string getFormattedName() const override { [[nodiscard]] std::string getFormattedName() const override {
@@ -755,9 +755,9 @@ namespace hex::lang {
bool open = ImGui::TreeNodeEx(this->getVariableName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth); bool open = ImGui::TreeNodeEx(this->getVariableName().c_str(), ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("0x%08llx : 0x%08llx", this->getOffset(), this->getOffset() + this->getSize() - 1); ImGui::Text("0x%08llX : 0x%08llX", this->getOffset(), this->getOffset() + this->getSize() - 1);
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("0x%04llx", this->getSize()); ImGui::Text("0x%04llX", this->getSize());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextColored(ImColor(0xFFD69C56), "bitfield"); ImGui::SameLine(); ImGui::Text("%s", PatternData::getTypeName().c_str()); ImGui::TextColored(ImColor(0xFFD69C56), "bitfield"); ImGui::SameLine(); ImGui::Text("%s", PatternData::getTypeName().c_str());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
@@ -779,19 +779,19 @@ namespace hex::lang {
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight())); ImGui::ColorButton("color", ImColor(this->getColor()), ImGuiColorEditFlags_NoTooltip, ImVec2(ImGui::GetColumnWidth(), ImGui::GetTextLineHeight()));
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("0x%08llx : 0x%08llx", this->getOffset() + (bitOffset >> 3), this->getOffset() + ((bitOffset + entrySize) >> 3)); ImGui::Text("0x%08llX : 0x%08llX", this->getOffset() + (bitOffset >> 3), this->getOffset() + ((bitOffset + entrySize) >> 3));
ImGui::TableNextColumn(); ImGui::TableNextColumn();
if (entrySize == 1) if (entrySize == 1)
ImGui::Text("%llu bit", entrySize); ImGui::Text("%llu bit", entrySize);
else else
ImGui::Text("%llu bits", entrySize); ImGui::Text("%llu bits", entrySize);
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::Text("%s", entryName.c_str()); ImGui::TextColored(ImColor(0xFF9BC64D), "bits");
ImGui::TableNextColumn(); ImGui::TableNextColumn();
{ {
u128 fieldValue = 0; u128 fieldValue = 0;
std::memcpy(&fieldValue, value.data() + (bitOffset / 8), (entrySize / 8) + 1); std::memcpy(&fieldValue, value.data() + (bitOffset / 8), (entrySize / 8) + 1);
ImGui::Text("%llx", hex::extract((bitOffset + entrySize) - 1 - ((bitOffset / 8) * 8), bitOffset - ((bitOffset / 8) * 8), fieldValue)); ImGui::Text("%llX", hex::extract((bitOffset + entrySize) - 1 - ((bitOffset / 8) * 8), bitOffset - ((bitOffset / 8) * 8), fieldValue));
} }
bitOffset += entrySize; bitOffset += entrySize;
} }

View File

@@ -17,6 +17,7 @@ namespace hex::lang {
ValueType, ValueType,
Operator, Operator,
Integer, Integer,
String,
Identifier, Identifier,
Separator Separator
}; };
@@ -142,7 +143,7 @@ namespace hex::lang {
} }
bool operator==(const ValueTypes &other) const { bool operator==(const ValueTypes &other) const {
if (this->type == Type::Integer || this->type == Type::Identifier) if (this->type == Type::Integer || this->type == Type::Identifier || this->type == Type::String)
return true; return true;
else if (this->type == Type::ValueType) { else if (this->type == Type::ValueType) {
auto otherValueType = std::get_if<ValueType>(&other); auto otherValueType = std::get_if<ValueType>(&other);
@@ -196,6 +197,7 @@ namespace hex::lang {
#define INTEGER hex::lang::Token::Type::Integer, hex::lang::Token::IntegerLiteral(hex::lang::Token::ValueType::Any, u64(0)) #define INTEGER hex::lang::Token::Type::Integer, hex::lang::Token::IntegerLiteral(hex::lang::Token::ValueType::Any, u64(0))
#define IDENTIFIER hex::lang::Token::Type::Identifier, "" #define IDENTIFIER hex::lang::Token::Type::Identifier, ""
#define STRING hex::lang::Token::Type::String, ""
#define OPERATOR_AT COMPONENT(Operator, AtDeclaration) #define OPERATOR_AT COMPONENT(Operator, AtDeclaration)
#define OPERATOR_ASSIGNMENT COMPONENT(Operator, Assignment) #define OPERATOR_ASSIGNMENT COMPONENT(Operator, Assignment)

View File

@@ -52,6 +52,7 @@ namespace hex {
void drawSearchPopup(); void drawSearchPopup();
void drawGotoPopup(); void drawGotoPopup();
void drawEditPopup();
void openFile(std::string path); void openFile(std::string path);
bool saveToFile(std::string path, const std::vector<u8>& data); bool saveToFile(std::string path, const std::vector<u8>& data);

View File

@@ -1,9 +1,8 @@
#pragma once #pragma once
#include "lang/ast_node.hpp"
#include "views/view.hpp" #include "views/view.hpp"
#include "lang/pattern_data.hpp" #include "lang/pattern_data.hpp"
#include "lang/evaluator.hpp"
#include "providers/provider.hpp" #include "providers/provider.hpp"
@@ -29,6 +28,7 @@ namespace hex {
std::filesystem::path m_possiblePatternFile; std::filesystem::path m_possiblePatternFile;
TextEditor m_textEditor; TextEditor m_textEditor;
std::vector<std::pair<lang::Evaluator::ConsoleLogLevel, std::string>> m_console;
imgui_addons::ImGuiFileBrowser m_fileBrowser; imgui_addons::ImGuiFileBrowser m_fileBrowser;
void loadPatternFile(std::string path); void loadPatternFile(std::string path);

View File

@@ -11,6 +11,7 @@ depends=("${MINGW_PACKAGE_PREFIX}-python")
makedepends=("${MINGW_PACKAGE_PREFIX}-gcc" makedepends=("${MINGW_PACKAGE_PREFIX}-gcc"
"${MINGW_PACKAGE_PREFIX}-cmake" "${MINGW_PACKAGE_PREFIX}-cmake"
"${MINGW_PACKAGE_PREFIX}-make" "${MINGW_PACKAGE_PREFIX}-make"
"${MINGW_PACKAGE_PREFIX}-dlsym"
"${MINGW_PACKAGE_PREFIX}-capstone" "${MINGW_PACKAGE_PREFIX}-capstone"
"${MINGW_PACKAGE_PREFIX}-glfw" "${MINGW_PACKAGE_PREFIX}-glfw"
"${MINGW_PACKAGE_PREFIX}-glm" "${MINGW_PACKAGE_PREFIX}-glm"

View File

@@ -17,7 +17,7 @@
#include <arpa/inet.h> #include <arpa/inet.h>
#endif #endif
#ifdef __APPLE__ #if defined(__APPLE__) || defined(__FreeBSD__)
#define off64_t off_t #define off64_t off_t
#define fopen64 fopen #define fopen64 fopen
#define fseeko64 fseek #define fseeko64 fseek
@@ -158,6 +158,24 @@ namespace hex {
return T(1) << bit_width(T(x - 1)); return T(1) << bit_width(T(x - 1));
} }
inline std::string toEngineeringString(double value) {
constexpr std::array prefixes = { "a", "f", "p", "n", "u", "m", "", "k", "M", "G", "T", "P", "E" };
int8_t prefixIndex = 6;
while (prefixIndex != 0 && prefixIndex != 12 && (value >= 1000 || value < 1) && value != 0) {
if (value >= 1000) {
value /= 1000;
prefixIndex++;
} else if (value < 1) {
value *= 1000;
prefixIndex--;
}
}
return std::to_string(value).substr(0, 5) + prefixes[prefixIndex];
}
std::vector<u8> readFile(std::string_view path); std::vector<u8> readFile(std::string_view path);
#define SCOPE_EXIT(func) ScopeExit TOKEN_CONCAT(scopeGuard, __COUNTER__)([&] { func }) #define SCOPE_EXIT(func) ScopeExit TOKEN_CONCAT(scopeGuard, __COUNTER__)([&] { func })

94
res/LICENSE.rtf Normal file
View File

@@ -0,0 +1,94 @@
{\rtf1\ansi\ansicpg1252\deff0\nouicompat{\fonttbl{\f0\fnil\fcharset0 Arial;}}
{\colortbl ;\red0\green0\blue255;\red0\green0\blue128;}
{\*\generator Riched20 10.0.19041}\viewkind4\uc1
\pard\nowidctlpar\sa180\kerning1\ul\b\fs24\lang1033 GNU GENERAL PUBLIC LICENSE\ulnone\b0\fs22\par
Version 2, June 1991\par
Copyright (C) 1989, 1991 Free Software Foundation, Inc. \line 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\line\line Everyone is permitted to copy and distribute verbatim copies\line of this license document, but changing it is not allowed.\par
\ul\b\fs24 Preamble\ulnone\b0\fs22\par
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.\par
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.\par
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.\par
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.\par
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.\par
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.\par
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.\par
The precise terms and conditions for copying, distribution and modification follow.\par
\ul\b\fs24 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\ulnone\b0\fs22\par
\par
\b 0.\b0 This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".\par
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.\par
\par
\b 1.\b0 You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.\par
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.\par
\par
\b 2.\b0 You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:\par
\pard\nowidctlpar\par
\pard\nowidctlpar\li360\b a)\b0 You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.\par
\pard\nowidctlpar\par
\pard\nowidctlpar\li360\b b)\b0 You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.\par
\pard\nowidctlpar\par
\pard\nowidctlpar\li360\b c)\b0 If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)\par
\pard\nowidctlpar\sa180 These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.\par
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.\par
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.\par
\par
\b 3.\b0 You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:\par
\pard\nowidctlpar\par
\pard\nowidctlpar\li360\b a)\b0 Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,\par
\pard\nowidctlpar\par
\pard\nowidctlpar\li360\b b)\b0 Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,\par
\pard\nowidctlpar\par
\pard\nowidctlpar\li360\b c)\b0 Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)\par
\pard\nowidctlpar\sa180 The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.\par
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.\par
\par
\b 4.\b0 You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.\par
\par
\b 5.\b0 You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.\par
\par
\b 6.\b0 Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.\par
\par
\b 7.\b0 If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.\par
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.\par
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.\par
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.\par
\par
\b 8.\b0 If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.\par
\par
\b 9.\b0 The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.\par
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.\par
\par
\b 10.\b0 If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.\par
\par
\b NO WARRANTY\b0\par
\b 11.\b0 BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\par
\par
\b 12.\b0 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\par
\b\fs24 END OF TERMS AND CONDITIONS\b0\fs22\par
\ul\b\fs24 How to Apply These Terms to Your New Programs\ulnone\b0\fs22\par
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.\par
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.\par
one line to give the program's name and an idea of what it does.\line Copyright (C) yyyy name of author\line\line This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.\line\line This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\line\line You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\par
Also add information on how to contact you by electronic and paper mail.\par
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:\par
Gnomovision version 69, Copyright (C) year name of author\line Gnomovision comes with ABSOLUTELY NO WARRANTY; for details\line type `show w'. This is free software, and you are welcome\line to redistribute it under certain conditions; type `show c' \line for details.\par
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.\par
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:\par
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.\line\line signature of Ty Coon, 1 April 1989\line Ty Coon, President of Vice\par
This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the {{\field{\*\fldinst{HYPERLINK "https://www.gnu.org/licenses/lgpl.html" }}{\fldrslt{\ul\cf1\cf2\ul\lang255 GNU Lesser General Public License}}}}\f0\fs22 instead of this License.\par
}

View File

@@ -2,20 +2,20 @@
namespace hex::lang { namespace hex::lang {
#define BUILTIN_FUNCTION(name) ASTNodeIntegerLiteral* Evaluator::name(std::vector<ASTNodeIntegerLiteral*> params) #define BUILTIN_FUNCTION(name) ASTNodeIntegerLiteral* Evaluator::TOKEN_CONCAT(builtin_, name)(std::vector<ASTNode*> params)
#define LITERAL_COMPARE(literal, cond) std::visit([&, this](auto &&literal) { return (cond) != 0; }, literal) #define LITERAL_COMPARE(literal, cond) std::visit([&, this](auto &&literal) { return (cond) != 0; }, literal)
BUILTIN_FUNCTION(findSequence) { BUILTIN_FUNCTION(findSequence) {
auto& occurrenceIndex = params[0]->getValue(); auto& occurrenceIndex = asType<ASTNodeIntegerLiteral>(params[0])->getValue();
std::vector<u8> sequence; std::vector<u8> sequence;
for (u32 i = 1; i < params.size(); i++) { for (u32 i = 1; i < params.size(); i++) {
sequence.push_back(std::visit([](auto &&value) -> u8 { sequence.push_back(std::visit([](auto &&value) -> u8 {
if (value <= 0xFF) if (value <= 0xFF)
return value; return value;
else else
throwEvaluateError("sequence bytes need to fit into 1 byte", 1); throwEvaluateError("sequence bytes need to fit into 1 byte");
}, params[i]->getValue())); }, asType<ASTNodeIntegerLiteral>(params[i])->getValue()));
} }
std::vector<u8> bytes(sequence.size(), 0x00); std::vector<u8> bytes(sequence.size(), 0x00);
@@ -24,7 +24,7 @@ namespace hex::lang {
this->m_provider->read(offset, bytes.data(), bytes.size()); this->m_provider->read(offset, bytes.data(), bytes.size());
if (bytes == sequence) { if (bytes == sequence) {
if (LITERAL_COMPARE(occurrenceIndex, occurrenceIndex < occurrences)) { if (LITERAL_COMPARE(occurrenceIndex, occurrences < occurrenceIndex)) {
occurrences++; occurrences++;
continue; continue;
} }
@@ -33,19 +33,19 @@ namespace hex::lang {
} }
} }
throwEvaluateError("failed to find sequence", 1); throwEvaluateError("failed to find sequence");
} }
BUILTIN_FUNCTION(readUnsigned) { BUILTIN_FUNCTION(readUnsigned) {
auto address = params[0]->getValue(); auto address = asType<ASTNodeIntegerLiteral>(params[0])->getValue();
auto size = params[1]->getValue(); auto size = asType<ASTNodeIntegerLiteral>(params[1])->getValue();
if (LITERAL_COMPARE(address, address >= this->m_provider->getActualSize())) if (LITERAL_COMPARE(address, address >= this->m_provider->getActualSize()))
throwEvaluateError("address out of range", 1); throwEvaluateError("address out of range");
return std::visit([this](auto &&address, auto &&size) { return std::visit([this](auto &&address, auto &&size) {
if (size <= 0 || size > 16) if (size <= 0 || size > 16)
throwEvaluateError("invalid read size", 1); throwEvaluateError("invalid read size");
u8 value[(u8)size]; u8 value[(u8)size];
this->m_provider->read(address, value, size); this->m_provider->read(address, value, size);
@@ -56,36 +56,88 @@ namespace hex::lang {
case 4: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned32Bit, hex::changeEndianess(*reinterpret_cast<u32*>(value), 4, this->getCurrentEndian()) }); case 4: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned32Bit, hex::changeEndianess(*reinterpret_cast<u32*>(value), 4, this->getCurrentEndian()) });
case 8: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned64Bit, hex::changeEndianess(*reinterpret_cast<u64*>(value), 8, this->getCurrentEndian()) }); case 8: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned64Bit, hex::changeEndianess(*reinterpret_cast<u64*>(value), 8, this->getCurrentEndian()) });
case 16: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned128Bit, hex::changeEndianess(*reinterpret_cast<u128*>(value), 16, this->getCurrentEndian()) }); case 16: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned128Bit, hex::changeEndianess(*reinterpret_cast<u128*>(value), 16, this->getCurrentEndian()) });
default: throwEvaluateError("invalid read size", 1); default: throwEvaluateError("invalid read size");
} }
}, address, size); }, address, size);
} }
BUILTIN_FUNCTION(readSigned) { BUILTIN_FUNCTION(readSigned) {
auto address = params[0]->getValue(); auto address = asType<ASTNodeIntegerLiteral>(params[0])->getValue();
auto size = params[1]->getValue(); auto size = asType<ASTNodeIntegerLiteral>(params[1])->getValue();
if (LITERAL_COMPARE(address, address >= this->m_provider->getActualSize())) if (LITERAL_COMPARE(address, address >= this->m_provider->getActualSize()))
throwEvaluateError("address out of range", 1); throwEvaluateError("address out of range");
return std::visit([this](auto &&address, auto &&size) { return std::visit([this](auto &&address, auto &&size) {
if (size <= 0 || size > 16) if (size <= 0 || size > 16)
throwEvaluateError("invalid read size", 1); throwEvaluateError("invalid read size");
u8 value[(u8)size]; u8 value[(u8)size];
this->m_provider->read(address, value, size); this->m_provider->read(address, value, size);
switch ((u8)size) { switch ((u8)size) {
case 1: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed8Bit, hex::changeEndianess(*reinterpret_cast<s8*>(value), 1, this->getCurrentEndian()) }); case 1: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed8Bit, hex::changeEndianess(*reinterpret_cast<s8*>(value), 1, this->getCurrentEndian()) });
case 2: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed16Bit, hex::changeEndianess(*reinterpret_cast<s16*>(value), 2, this->getCurrentEndian()) }); case 2: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed16Bit, hex::changeEndianess(*reinterpret_cast<s16*>(value), 2, this->getCurrentEndian()) });
case 4: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed32Bit, hex::changeEndianess(*reinterpret_cast<s32*>(value), 4, this->getCurrentEndian()) }); case 4: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed32Bit, hex::changeEndianess(*reinterpret_cast<s32*>(value), 4, this->getCurrentEndian()) });
case 8: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed64Bit, hex::changeEndianess(*reinterpret_cast<s64*>(value), 8, this->getCurrentEndian()) }); case 8: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed64Bit, hex::changeEndianess(*reinterpret_cast<s64*>(value), 8, this->getCurrentEndian()) });
case 16: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed128Bit, hex::changeEndianess(*reinterpret_cast<s128*>(value), 16, this->getCurrentEndian()) }); case 16: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed128Bit, hex::changeEndianess(*reinterpret_cast<s128*>(value), 16, this->getCurrentEndian()) });
default: throwEvaluateError("invalid read size", 1); default: throwEvaluateError("invalid read size");
} }
}, address, size); }, address, size);
} }
BUILTIN_FUNCTION(assert) {
auto condition = asType<ASTNodeIntegerLiteral>(params[0])->getValue();
auto message = asType<ASTNodeStringLiteral>(params[1])->getString();
if (LITERAL_COMPARE(condition, condition == 0))
throwEvaluateError(hex::format("assert failed \"%s\"", message.data()));
return nullptr;
}
BUILTIN_FUNCTION(warnAssert) {
auto condition = asType<ASTNodeIntegerLiteral>(params[0])->getValue();
auto message = asType<ASTNodeStringLiteral>(params[1])->getString();
if (LITERAL_COMPARE(condition, condition == 0))
this->emmitWaring(hex::format("assert failed \"%s\"", message.data()));
return nullptr;
}
BUILTIN_FUNCTION(print) {
std::string message;
for (auto& param : params) {
if (auto integerLiteral = dynamic_cast<ASTNodeIntegerLiteral*>(param); integerLiteral != nullptr) {
switch (integerLiteral->getType()) {
case Token::ValueType::Character: message += std::get<s8>(integerLiteral->getValue()); break;
case Token::ValueType::Unsigned8Bit: message += std::to_string(std::get<u8>(integerLiteral->getValue())); break;
case Token::ValueType::Signed8Bit: message += std::to_string(std::get<s8>(integerLiteral->getValue())); break;
case Token::ValueType::Unsigned16Bit: message += std::to_string(std::get<u16>(integerLiteral->getValue())); break;
case Token::ValueType::Signed16Bit: message += std::to_string(std::get<s16>(integerLiteral->getValue())); break;
case Token::ValueType::Unsigned32Bit: message += std::to_string(std::get<u32>(integerLiteral->getValue())); break;
case Token::ValueType::Signed32Bit: message += std::to_string(std::get<s32>(integerLiteral->getValue())); break;
case Token::ValueType::Unsigned64Bit: message += std::to_string(std::get<u64>(integerLiteral->getValue())); break;
case Token::ValueType::Signed64Bit: message += std::to_string(std::get<s64>(integerLiteral->getValue())); break;
case Token::ValueType::Unsigned128Bit: message += "A lot"; break; // TODO: Implement u128 to_string
case Token::ValueType::Signed128Bit: message += "A lot"; break; // TODO: Implement s128 to_string
case Token::ValueType::Float: message += std::to_string(std::get<float>(integerLiteral->getValue())); break;
case Token::ValueType::Double: message += std::to_string(std::get<double>(integerLiteral->getValue())); break;
case Token::ValueType::Boolean: message += std::get<s32>(integerLiteral->getValue()) ? "true" : "false"; break;
case Token::ValueType::CustomType: message += "< Custom Type >"; break;
}
}
else if (auto stringLiteral = dynamic_cast<ASTNodeStringLiteral*>(param); stringLiteral != nullptr)
message += stringLiteral->getString();
}
this->emmitInfo(message);
return nullptr;
}
#undef BUILTIN_FUNCTION #undef BUILTIN_FUNCTION

View File

@@ -14,15 +14,27 @@ namespace hex::lang {
: m_provider(provider), m_defaultDataEndian(defaultDataEndian) { : m_provider(provider), m_defaultDataEndian(defaultDataEndian) {
this->addFunction("findSequence", Function::MoreParametersThan | 1, [this](auto params) { this->addFunction("findSequence", Function::MoreParametersThan | 1, [this](auto params) {
return this->findSequence(params); return this->builtin_findSequence(params);
}); });
this->addFunction("readUnsigned", 2, [this](auto params) { this->addFunction("readUnsigned", 2, [this](auto params) {
return this->readUnsigned(params); return this->builtin_readUnsigned(params);
}); });
this->addFunction("readSigned", 2, [this](auto params) { this->addFunction("readSigned", 2, [this](auto params) {
return this->readSigned(params); return this->builtin_readSigned(params);
});
this->addFunction("assert", 2, [this](auto params) {
return this->builtin_assert(params);
});
this->addFunction("warnAssert", 2, [this](auto params) {
return this->builtin_warnAssert(params);
});
this->addFunction("print", Function::MoreParametersThan | 0, [this](auto params) {
return this->builtin_print(params);
}); });
} }
@@ -42,12 +54,12 @@ namespace hex::lang {
} }
} }
throwEvaluateError("failed to find identifier", node->getLineNumber()); throwEvaluateError("failed to find identifier");
} }
ASTNodeIntegerLiteral* Evaluator::evaluateRValue(ASTNodeRValue *node) { ASTNodeIntegerLiteral* Evaluator::evaluateRValue(ASTNodeRValue *node) {
if (this->m_currMembers.empty() && this->m_globalMembers.empty()) if (this->m_currMembers.empty() && this->m_globalMembers.empty())
throwEvaluateError("no variables available", node->getLineNumber()); throwEvaluateError("no variables available");
std::vector<PatternData*> currMembers; std::vector<PatternData*> currMembers;
@@ -70,7 +82,7 @@ namespace hex::lang {
continue; continue;
} }
else if (currPattern != nullptr) else if (currPattern != nullptr)
throwEvaluateError("tried to access member of a non-struct/union type", node->getLineNumber()); throwEvaluateError("tried to access member of a non-struct/union type");
auto candidate = std::find_if(currMembers.begin(), currMembers.end(), [&](auto member) { auto candidate = std::find_if(currMembers.begin(), currMembers.end(), [&](auto member) {
return member->getVariableName() == identifier; return member->getVariableName() == identifier;
@@ -79,7 +91,7 @@ namespace hex::lang {
if (candidate != currMembers.end()) if (candidate != currMembers.end())
currPattern = *candidate; currPattern = *candidate;
else else
throwEvaluateError(hex::format("could not find identifier '%s'", identifier.c_str()), node->getLineNumber()); throwEvaluateError(hex::format("could not find identifier '%s'", identifier.c_str()));
} }
if (auto pointerPattern = dynamic_cast<PatternDataPointer*>(currPattern); pointerPattern != nullptr) if (auto pointerPattern = dynamic_cast<PatternDataPointer*>(currPattern); pointerPattern != nullptr)
@@ -90,53 +102,57 @@ namespace hex::lang {
this->m_provider->read(unsignedPattern->getOffset(), value, unsignedPattern->getSize()); this->m_provider->read(unsignedPattern->getOffset(), value, unsignedPattern->getSize());
switch (unsignedPattern->getSize()) { switch (unsignedPattern->getSize()) {
case 1: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned8Bit, hex::changeEndianess(*reinterpret_cast<u8*>(value), 1, this->getCurrentEndian()) }); case 1: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned8Bit, hex::changeEndianess(*reinterpret_cast<u8*>(value), 1, unsignedPattern->getEndian()) });
case 2: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned16Bit, hex::changeEndianess(*reinterpret_cast<u16*>(value), 2, this->getCurrentEndian()) }); case 2: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned16Bit, hex::changeEndianess(*reinterpret_cast<u16*>(value), 2, unsignedPattern->getEndian()) });
case 4: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned32Bit, hex::changeEndianess(*reinterpret_cast<u32*>(value), 4, this->getCurrentEndian()) }); case 4: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned32Bit, hex::changeEndianess(*reinterpret_cast<u32*>(value), 4, unsignedPattern->getEndian()) });
case 8: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned64Bit, hex::changeEndianess(*reinterpret_cast<u64*>(value), 8, this->getCurrentEndian()) }); case 8: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned64Bit, hex::changeEndianess(*reinterpret_cast<u64*>(value), 8, unsignedPattern->getEndian()) });
case 16: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned128Bit, hex::changeEndianess(*reinterpret_cast<u128*>(value), 16, this->getCurrentEndian()) }); case 16: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned128Bit, hex::changeEndianess(*reinterpret_cast<u128*>(value), 16, unsignedPattern->getEndian()) });
default: throwEvaluateError("invalid rvalue size", node->getLineNumber()); default: throwEvaluateError("invalid rvalue size");
} }
} else if (auto signedPattern = dynamic_cast<PatternDataSigned*>(currPattern); signedPattern != nullptr) { } else if (auto signedPattern = dynamic_cast<PatternDataSigned*>(currPattern); signedPattern != nullptr) {
u8 value[unsignedPattern->getSize()]; u8 value[unsignedPattern->getSize()];
this->m_provider->read(signedPattern->getOffset(), value, signedPattern->getSize()); this->m_provider->read(signedPattern->getOffset(), value, signedPattern->getSize());
switch (unsignedPattern->getSize()) { switch (unsignedPattern->getSize()) {
case 1: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed8Bit, hex::changeEndianess(*reinterpret_cast<s8*>(value), 1, this->getCurrentEndian()) }); case 1: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed8Bit, hex::changeEndianess(*reinterpret_cast<s8*>(value), 1, signedPattern->getEndian()) });
case 2: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed16Bit, hex::changeEndianess(*reinterpret_cast<s16*>(value), 2, this->getCurrentEndian()) }); case 2: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed16Bit, hex::changeEndianess(*reinterpret_cast<s16*>(value), 2, signedPattern->getEndian()) });
case 4: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed32Bit, hex::changeEndianess(*reinterpret_cast<s32*>(value), 4, this->getCurrentEndian()) }); case 4: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed32Bit, hex::changeEndianess(*reinterpret_cast<s32*>(value), 4, signedPattern->getEndian()) });
case 8: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed64Bit, hex::changeEndianess(*reinterpret_cast<s64*>(value), 8, this->getCurrentEndian()) }); case 8: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed64Bit, hex::changeEndianess(*reinterpret_cast<s64*>(value), 8, signedPattern->getEndian()) });
case 16: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed128Bit, hex::changeEndianess(*reinterpret_cast<s128*>(value), 16, this->getCurrentEndian()) }); case 16: return new ASTNodeIntegerLiteral({ Token::ValueType::Signed128Bit, hex::changeEndianess(*reinterpret_cast<s128*>(value), 16, signedPattern->getEndian()) });
default: throwEvaluateError("invalid rvalue size", node->getLineNumber()); default: throwEvaluateError("invalid rvalue size");
} }
} else if (auto enumPattern = dynamic_cast<PatternDataEnum*>(currPattern); enumPattern != nullptr) { } else if (auto enumPattern = dynamic_cast<PatternDataEnum*>(currPattern); enumPattern != nullptr) {
u8 value[enumPattern->getSize()]; u8 value[enumPattern->getSize()];
this->m_provider->read(enumPattern->getOffset(), value, enumPattern->getSize()); this->m_provider->read(enumPattern->getOffset(), value, enumPattern->getSize());
switch (enumPattern->getSize()) { switch (enumPattern->getSize()) {
case 1: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned8Bit, hex::changeEndianess(*reinterpret_cast<u8*>(value), 1, this->getCurrentEndian()) }); case 1: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned8Bit, hex::changeEndianess(*reinterpret_cast<u8*>(value), 1, enumPattern->getEndian()) });
case 2: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned16Bit, hex::changeEndianess(*reinterpret_cast<u16*>(value), 2, this->getCurrentEndian()) }); case 2: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned16Bit, hex::changeEndianess(*reinterpret_cast<u16*>(value), 2, enumPattern->getEndian()) });
case 4: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned32Bit, hex::changeEndianess(*reinterpret_cast<u32*>(value), 4, this->getCurrentEndian()) }); case 4: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned32Bit, hex::changeEndianess(*reinterpret_cast<u32*>(value), 4, enumPattern->getEndian()) });
case 8: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned64Bit, hex::changeEndianess(*reinterpret_cast<u64*>(value), 8, this->getCurrentEndian()) }); case 8: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned64Bit, hex::changeEndianess(*reinterpret_cast<u64*>(value), 8, enumPattern->getEndian()) });
case 16: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned128Bit, hex::changeEndianess(*reinterpret_cast<u128*>(value), 16, this->getCurrentEndian()) }); case 16: return new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned128Bit, hex::changeEndianess(*reinterpret_cast<u128*>(value), 16, enumPattern->getEndian()) });
default: throwEvaluateError("invalid rvalue size", node->getLineNumber()); default: throwEvaluateError("invalid rvalue size");
} }
} else } else
throwEvaluateError("tried to use non-integer value in numeric expression", node->getLineNumber()); throwEvaluateError("tried to use non-integer value in numeric expression");
} }
ASTNodeIntegerLiteral* Evaluator::evaluateFunctionCall(ASTNodeFunctionCall *node) { ASTNodeIntegerLiteral* Evaluator::evaluateFunctionCall(ASTNodeFunctionCall *node) {
std::vector<ASTNodeIntegerLiteral*> evaluatedParams; std::vector<ASTNode*> evaluatedParams;
ScopeExit paramCleanup([&] { ScopeExit paramCleanup([&] {
for (auto &param : evaluatedParams) for (auto &param : evaluatedParams)
delete param; delete param;
}); });
for (auto &param : node->getParams()) for (auto &param : node->getParams()) {
evaluatedParams.push_back(this->evaluateMathematicalExpression(static_cast<ASTNodeNumericExpression*>(param))); if (auto numericExpression = dynamic_cast<ASTNodeNumericExpression*>(param); numericExpression != nullptr)
evaluatedParams.push_back(this->evaluateMathematicalExpression(numericExpression));
else if (auto stringLiteral = dynamic_cast<ASTNodeStringLiteral*>(param); stringLiteral != nullptr)
evaluatedParams.push_back(stringLiteral->clone());
}
if (!this->m_functions.contains(node->getFunctionName().data())) if (!this->m_functions.contains(node->getFunctionName().data()))
throwEvaluateError(hex::format("no function named '%s' found", node->getFunctionName().data()), node->getLineNumber()); throwEvaluateError(hex::format("no function named '%s' found", node->getFunctionName().data()));
auto &function = this->m_functions[node->getFunctionName().data()]; auto &function = this->m_functions[node->getFunctionName().data()];
@@ -145,12 +161,12 @@ namespace hex::lang {
} }
else if (function.parameterCount & Function::LessParametersThan) { else if (function.parameterCount & Function::LessParametersThan) {
if (evaluatedParams.size() >= (function.parameterCount & ~Function::LessParametersThan)) if (evaluatedParams.size() >= (function.parameterCount & ~Function::LessParametersThan))
throwEvaluateError(hex::format("too many parameters for function '%s'. Expected %d", node->getFunctionName().data(), function.parameterCount & ~Function::LessParametersThan), node->getLineNumber()); throwEvaluateError(hex::format("too many parameters for function '%s'. Expected %d", node->getFunctionName().data(), function.parameterCount & ~Function::LessParametersThan));
} else if (function.parameterCount & Function::MoreParametersThan) { } else if (function.parameterCount & Function::MoreParametersThan) {
if (evaluatedParams.size() <= (function.parameterCount & ~Function::MoreParametersThan)) if (evaluatedParams.size() <= (function.parameterCount & ~Function::MoreParametersThan))
throwEvaluateError(hex::format("too few parameters for function '%s'. Expected %d", node->getFunctionName().data(), function.parameterCount & ~Function::MoreParametersThan), node->getLineNumber()); throwEvaluateError(hex::format("too few parameters for function '%s'. Expected %d", node->getFunctionName().data(), function.parameterCount & ~Function::MoreParametersThan));
} else if (function.parameterCount != evaluatedParams.size()) { } else if (function.parameterCount != evaluatedParams.size()) {
throwEvaluateError(hex::format("invalid number of parameters for function '%s'. Expected %d", node->getFunctionName().data(), function.parameterCount), node->getLineNumber()); throwEvaluateError(hex::format("invalid number of parameters for function '%s'. Expected %d", node->getFunctionName().data(), function.parameterCount));
} }
return function.func(evaluatedParams); return function.func(evaluatedParams);
@@ -195,6 +211,11 @@ namespace hex::lang {
#define CHECK_TYPE(type) if (left->getType() == (type) || right->getType() == (type)) return (type) #define CHECK_TYPE(type) if (left->getType() == (type) || right->getType() == (type)) return (type)
#define DEFAULT_TYPE(type) return (type) #define DEFAULT_TYPE(type) return (type)
if (left->getType() == Token::ValueType::Any && right->getType() != Token::ValueType::Any)
return right->getType();
if (left->getType() != Token::ValueType::Any && right->getType() == Token::ValueType::Any)
return left->getType();
CHECK_TYPE(Token::ValueType::Double); CHECK_TYPE(Token::ValueType::Double);
CHECK_TYPE(Token::ValueType::Float); CHECK_TYPE(Token::ValueType::Float);
CHECK_TYPE(Token::ValueType::Unsigned128Bit); CHECK_TYPE(Token::ValueType::Unsigned128Bit);
@@ -208,6 +229,7 @@ namespace hex::lang {
CHECK_TYPE(Token::ValueType::Unsigned8Bit); CHECK_TYPE(Token::ValueType::Unsigned8Bit);
CHECK_TYPE(Token::ValueType::Signed8Bit); CHECK_TYPE(Token::ValueType::Signed8Bit);
CHECK_TYPE(Token::ValueType::Character); CHECK_TYPE(Token::ValueType::Character);
CHECK_TYPE(Token::ValueType::Boolean);
DEFAULT_TYPE(Token::ValueType::Signed32Bit); DEFAULT_TYPE(Token::ValueType::Signed32Bit);
#undef CHECK_TYPE #undef CHECK_TYPE
@@ -258,12 +280,12 @@ namespace hex::lang {
case Token::Operator::BoolNot: case Token::Operator::BoolNot:
return new ASTNodeIntegerLiteral({ newType, !rightValue }); return new ASTNodeIntegerLiteral({ newType, !rightValue });
default: default:
throwEvaluateError("invalid operator used in mathematical expression", left->getLineNumber()); throwEvaluateError("invalid operator used in mathematical expression");
} }
}, left->getValue(), right->getValue()); }, left->getValue(), right->getValue());
} catch (std::runtime_error &e) { } catch (std::runtime_error &e) {
throwEvaluateError("bitwise operations on floating point numbers are forbidden", left->getLineNumber()); throwEvaluateError("bitwise operations on floating point numbers are forbidden");
} }
} }
@@ -278,10 +300,16 @@ namespace hex::lang {
return evaluateScopeResolution(exprScopeResolution); return evaluateScopeResolution(exprScopeResolution);
else if (auto exprTernary = dynamic_cast<ASTNodeTernaryExpression*>(node); exprTernary != nullptr) else if (auto exprTernary = dynamic_cast<ASTNodeTernaryExpression*>(node); exprTernary != nullptr)
return evaluateTernaryExpression(exprTernary); return evaluateTernaryExpression(exprTernary);
else if (auto exprFunctionCall = dynamic_cast<ASTNodeFunctionCall*>(node); exprFunctionCall != nullptr) else if (auto exprFunctionCall = dynamic_cast<ASTNodeFunctionCall*>(node); exprFunctionCall != nullptr) {
return evaluateFunctionCall(exprFunctionCall); auto returnValue = evaluateFunctionCall(exprFunctionCall);
if (returnValue == nullptr)
throwEvaluateError("function returning void used in expression");
else
return returnValue;
}
else else
throwEvaluateError("invalid operand", node->getLineNumber()); throwEvaluateError("invalid operand");
} }
ASTNodeIntegerLiteral* Evaluator::evaluateTernaryExpression(ASTNodeTernaryExpression *node) { ASTNodeIntegerLiteral* Evaluator::evaluateTernaryExpression(ASTNodeTernaryExpression *node) {
@@ -296,7 +324,7 @@ namespace hex::lang {
return this->evaluateOperand(node->getThirdOperand()); return this->evaluateOperand(node->getThirdOperand());
} }
default: default:
throwEvaluateError("invalid operator used in ternary expression", node->getLineNumber()); throwEvaluateError("invalid operator used in ternary expression");
} }
} }
@@ -324,7 +352,7 @@ namespace hex::lang {
else if (Token::isFloatingPoint(type)) else if (Token::isFloatingPoint(type))
pattern = new PatternDataFloat(this->m_currOffset, typeSize); pattern = new PatternDataFloat(this->m_currOffset, typeSize);
else else
throwEvaluateError("invalid builtin type", node->getLineNumber()); throwEvaluateError("invalid builtin type");
this->m_currOffset += typeSize; this->m_currOffset += typeSize;
@@ -334,35 +362,35 @@ namespace hex::lang {
return pattern; return pattern;
} }
std::vector<PatternData*> Evaluator::evaluateMember(ASTNode *node) { void Evaluator::evaluateMember(ASTNode *node, std::vector<PatternData*> &currMembers, bool increaseOffset) {
auto startOffset = this->m_currOffset;
if (auto memberVariableNode = dynamic_cast<ASTNodeVariableDecl*>(node); memberVariableNode != nullptr) if (auto memberVariableNode = dynamic_cast<ASTNodeVariableDecl*>(node); memberVariableNode != nullptr)
return { this->evaluateVariable(memberVariableNode) }; currMembers.push_back(this->evaluateVariable(memberVariableNode));
else if (auto memberArrayNode = dynamic_cast<ASTNodeArrayVariableDecl*>(node); memberArrayNode != nullptr) else if (auto memberArrayNode = dynamic_cast<ASTNodeArrayVariableDecl*>(node); memberArrayNode != nullptr)
return { this->evaluateArray(memberArrayNode) }; currMembers.push_back(this->evaluateArray(memberArrayNode));
else if (auto memberPointerNode = dynamic_cast<ASTNodePointerVariableDecl*>(node); memberPointerNode != nullptr) else if (auto memberPointerNode = dynamic_cast<ASTNodePointerVariableDecl*>(node); memberPointerNode != nullptr)
return { this->evaluatePointer(memberPointerNode) }; currMembers.push_back(this->evaluatePointer(memberPointerNode));
else if (auto conditionalNode = dynamic_cast<ASTNodeConditionalStatement*>(node); conditionalNode != nullptr) { else if (auto conditionalNode = dynamic_cast<ASTNodeConditionalStatement*>(node); conditionalNode != nullptr) {
auto condition = this->evaluateMathematicalExpression(static_cast<ASTNodeNumericExpression*>(conditionalNode->getCondition())); auto condition = this->evaluateMathematicalExpression(static_cast<ASTNodeNumericExpression*>(conditionalNode->getCondition()));
std::vector<PatternData*> patterns;
if (std::visit([](auto &&value) { return value != 0; }, condition->getValue())) { if (std::visit([](auto &&value) { return value != 0; }, condition->getValue())) {
for (auto &statement : conditionalNode->getTrueBody()) { for (auto &statement : conditionalNode->getTrueBody()) {
auto statementPatterns = this->evaluateMember(statement); this->evaluateMember(statement, currMembers, increaseOffset);
std::copy(statementPatterns.begin(), statementPatterns.end(), std::back_inserter(patterns));
} }
} else { } else {
for (auto &statement : conditionalNode->getFalseBody()) { for (auto &statement : conditionalNode->getFalseBody()) {
auto statementPatterns = this->evaluateMember(statement); this->evaluateMember(statement, currMembers, increaseOffset);
std::copy(statementPatterns.begin(), statementPatterns.end(), std::back_inserter(patterns));
} }
} }
delete condition; delete condition;
return patterns;
} }
else else
throwEvaluateError("invalid struct member", node->getLineNumber()); throwEvaluateError("invalid struct member");
if (!increaseOffset)
this->m_currOffset = startOffset;
} }
PatternData* Evaluator::evaluateStruct(ASTNodeStruct *node) { PatternData* Evaluator::evaluateStruct(ASTNodeStruct *node) {
@@ -373,8 +401,7 @@ namespace hex::lang {
auto startOffset = this->m_currOffset; auto startOffset = this->m_currOffset;
for (auto &member : node->getMembers()) { for (auto &member : node->getMembers()) {
auto newMembers = this->evaluateMember(member); this->evaluateMember(member, memberPatterns, true);
std::copy(newMembers.begin(), newMembers.end(), std::back_inserter(memberPatterns));
} }
return new PatternDataStruct(startOffset, this->m_currOffset - startOffset, memberPatterns); return new PatternDataStruct(startOffset, this->m_currOffset - startOffset, memberPatterns);
@@ -387,14 +414,18 @@ namespace hex::lang {
SCOPE_EXIT( this->m_currMembers.pop_back(); ); SCOPE_EXIT( this->m_currMembers.pop_back(); );
auto startOffset = this->m_currOffset; auto startOffset = this->m_currOffset;
for (auto &member : node->getMembers()) {
auto newMembers = this->evaluateMember(member);
std::copy(newMembers.begin(), newMembers.end(), std::back_inserter(memberPatterns));
this->m_currOffset = startOffset; for (auto &member : node->getMembers()) {
this->evaluateMember(member, memberPatterns, false);
} }
return new PatternDataUnion(startOffset, this->m_currOffset - startOffset, memberPatterns); size_t size = 0;
for (const auto &pattern : memberPatterns)
size = std::max(size, pattern->getSize());
this->m_currOffset += size;
return new PatternDataUnion(startOffset, size, memberPatterns);
} }
PatternData* Evaluator::evaluateEnum(ASTNodeEnum *node) { PatternData* Evaluator::evaluateEnum(ASTNodeEnum *node) {
@@ -404,7 +435,7 @@ namespace hex::lang {
for (auto &[name, value] : node->getEntries()) { for (auto &[name, value] : node->getEntries()) {
auto expression = dynamic_cast<ASTNodeNumericExpression*>(value); auto expression = dynamic_cast<ASTNodeNumericExpression*>(value);
if (expression == nullptr) if (expression == nullptr)
throwEvaluateError("invalid expression in enum value", value->getLineNumber()); throwEvaluateError("invalid expression in enum value");
auto valueNode = evaluateMathematicalExpression(expression); auto valueNode = evaluateMathematicalExpression(expression);
SCOPE_EXIT( delete valueNode; ); SCOPE_EXIT( delete valueNode; );
@@ -412,13 +443,19 @@ namespace hex::lang {
entryPatterns.push_back({{ valueNode->getType(), valueNode->getValue() }, name }); entryPatterns.push_back({{ valueNode->getType(), valueNode->getValue() }, name });
} }
size_t size; auto underlyingType = dynamic_cast<ASTNodeTypeDecl*>(node->getUnderlyingType());
if (auto underlyingType = dynamic_cast<const ASTNodeBuiltinType*>(node->getUnderlyingType()); underlyingType != nullptr) if (underlyingType == nullptr)
size = Token::getTypeSize(underlyingType->getType()); throwEvaluateError("enum underlying type was not ASTNodeTypeDecl. This is a bug");
else
throwEvaluateError("invalid enum underlying type", node->getLineNumber());
return new PatternDataEnum(startOffset, size, entryPatterns); size_t size;
if (auto builtinType = dynamic_cast<ASTNodeBuiltinType*>(underlyingType->getType()); builtinType != nullptr)
size = Token::getTypeSize(builtinType->getType());
else
throwEvaluateError("invalid enum underlying type");
this->m_currOffset += size;
return new PatternDataEnum(startOffset, size, entryPatterns);;
} }
PatternData* Evaluator::evaluateBitfield(ASTNodeBitfield *node) { PatternData* Evaluator::evaluateBitfield(ASTNodeBitfield *node) {
@@ -429,26 +466,29 @@ namespace hex::lang {
for (auto &[name, value] : node->getEntries()) { for (auto &[name, value] : node->getEntries()) {
auto expression = dynamic_cast<ASTNodeNumericExpression*>(value); auto expression = dynamic_cast<ASTNodeNumericExpression*>(value);
if (expression == nullptr) if (expression == nullptr)
throwEvaluateError("invalid expression in bitfield field size", value->getLineNumber()); throwEvaluateError("invalid expression in bitfield field size");
auto valueNode = evaluateMathematicalExpression(expression); auto valueNode = evaluateMathematicalExpression(expression);
SCOPE_EXIT( delete valueNode; ); SCOPE_EXIT( delete valueNode; );
auto fieldBits = std::visit([node, type = valueNode->getType()] (auto &&value) { auto fieldBits = std::visit([node, type = valueNode->getType()] (auto &&value) {
if (Token::isFloatingPoint(type)) if (Token::isFloatingPoint(type))
throwEvaluateError("bitfield entry size must be an integer value", node->getLineNumber()); throwEvaluateError("bitfield entry size must be an integer value");
return static_cast<s128>(value); return static_cast<s128>(value);
}, valueNode->getValue()); }, valueNode->getValue());
if (fieldBits > 64 || fieldBits <= 0) if (fieldBits > 64 || fieldBits <= 0)
throwEvaluateError("bitfield entry must occupy between 1 and 64 bits", value->getLineNumber()); throwEvaluateError("bitfield entry must occupy between 1 and 64 bits");
bits += fieldBits; bits += fieldBits;
entryPatterns.emplace_back(name, fieldBits); entryPatterns.emplace_back(name, fieldBits);
} }
return new PatternDataBitfield(startOffset, (bits / 8) + 1, entryPatterns); size_t size = (bits + 7) / 8;
this->m_currOffset += size;
return new PatternDataBitfield(startOffset, size, entryPatterns);
} }
PatternData* Evaluator::evaluateType(ASTNodeTypeDecl *node) { PatternData* Evaluator::evaluateType(ASTNodeTypeDecl *node) {
@@ -471,7 +511,7 @@ namespace hex::lang {
else if (auto bitfieldNode = dynamic_cast<ASTNodeBitfield*>(type); bitfieldNode != nullptr) else if (auto bitfieldNode = dynamic_cast<ASTNodeBitfield*>(type); bitfieldNode != nullptr)
pattern = this->evaluateBitfield(bitfieldNode); pattern = this->evaluateBitfield(bitfieldNode);
else else
throwEvaluateError("type could not be evaluated", node->getLineNumber()); throwEvaluateError("type could not be evaluated");
if (!node->getName().empty()) if (!node->getName().empty())
pattern->setTypeName(node->getName().data()); pattern->setTypeName(node->getName().data());
@@ -491,12 +531,12 @@ namespace hex::lang {
this->m_currOffset = std::visit([node, type = valueNode->getType()] (auto &&value) { this->m_currOffset = std::visit([node, type = valueNode->getType()] (auto &&value) {
if (Token::isFloatingPoint(type)) if (Token::isFloatingPoint(type))
throwEvaluateError("placement offset must be an integer value", node->getLineNumber()); throwEvaluateError("placement offset must be an integer value");
return static_cast<u64>(value); return static_cast<u64>(value);
}, valueNode->getValue()); }, valueNode->getValue());
} }
if (this->m_currOffset >= this->m_provider->getActualSize()) if (this->m_currOffset >= this->m_provider->getActualSize())
throwEvaluateError("variable placed out of range", node->getLineNumber()); throwEvaluateError("variable placed out of range");
PatternData *pattern; PatternData *pattern;
if (auto typeDecl = dynamic_cast<ASTNodeTypeDecl*>(node->getType()); typeDecl != nullptr) if (auto typeDecl = dynamic_cast<ASTNodeTypeDecl*>(node->getType()); typeDecl != nullptr)
@@ -504,7 +544,7 @@ namespace hex::lang {
else if (auto builtinTypeDecl = dynamic_cast<ASTNodeBuiltinType*>(node->getType()); builtinTypeDecl != nullptr) else if (auto builtinTypeDecl = dynamic_cast<ASTNodeBuiltinType*>(node->getType()); builtinTypeDecl != nullptr)
pattern = this->evaluateBuiltinType(builtinTypeDecl); pattern = this->evaluateBuiltinType(builtinTypeDecl);
else else
throwEvaluateError("ASTNodeVariableDecl had an invalid type. This is a bug!", 1); throwEvaluateError("ASTNodeVariableDecl had an invalid type. This is a bug!");
pattern->setVariableName(node->getName().data()); pattern->setVariableName(node->getName().data());
@@ -519,7 +559,7 @@ namespace hex::lang {
this->m_currOffset = std::visit([node, type = valueNode->getType()] (auto &&value) { this->m_currOffset = std::visit([node, type = valueNode->getType()] (auto &&value) {
if (Token::isFloatingPoint(type)) if (Token::isFloatingPoint(type))
throwEvaluateError("placement offset must be an integer value", node->getLineNumber()); throwEvaluateError("placement offset must be an integer value");
return static_cast<u64>(value); return static_cast<u64>(value);
}, valueNode->getValue()); }, valueNode->getValue());
} }
@@ -533,13 +573,13 @@ namespace hex::lang {
if (auto sizeNumericExpression = dynamic_cast<ASTNodeNumericExpression*>(node->getSize()); sizeNumericExpression != nullptr) if (auto sizeNumericExpression = dynamic_cast<ASTNodeNumericExpression*>(node->getSize()); sizeNumericExpression != nullptr)
valueNode = evaluateMathematicalExpression(sizeNumericExpression); valueNode = evaluateMathematicalExpression(sizeNumericExpression);
else else
throwEvaluateError("array size not a numeric expression", node->getLineNumber()); throwEvaluateError("array size not a numeric expression");
SCOPE_EXIT( delete valueNode; ); SCOPE_EXIT( delete valueNode; );
arraySize = std::visit([node, type = valueNode->getType()] (auto &&value) { arraySize = std::visit([node, type = valueNode->getType()] (auto &&value) {
if (Token::isFloatingPoint(type)) if (Token::isFloatingPoint(type))
throwEvaluateError("array size must be an integer value", node->getLineNumber()); throwEvaluateError("array size must be an integer value");
return static_cast<u64>(value); return static_cast<u64>(value);
}, valueNode->getValue()); }, valueNode->getValue());
@@ -572,7 +612,7 @@ namespace hex::lang {
entry = this->evaluateBuiltinType(builtinTypeDecl); entry = this->evaluateBuiltinType(builtinTypeDecl);
} }
else else
throwEvaluateError("ASTNodeVariableDecl had an invalid type. This is a bug!", 1); throwEvaluateError("ASTNodeVariableDecl had an invalid type. This is a bug!");
entry->setVariableName(hex::format("[%llu]", (u64)i)); entry->setVariableName(hex::format("[%llu]", (u64)i));
entry->setEndian(this->getCurrentEndian()); entry->setEndian(this->getCurrentEndian());
@@ -583,8 +623,8 @@ namespace hex::lang {
entries.push_back(entry); entries.push_back(entry);
if (this->m_currOffset >= this->m_provider->getActualSize()) if (this->m_currOffset > this->m_provider->getActualSize())
throwEvaluateError("array exceeds size of file", node->getLineNumber()); throwEvaluateError("array exceeds size of file");
} }
PatternData *pattern; PatternData *pattern;
@@ -595,7 +635,7 @@ namespace hex::lang {
pattern = new PatternDataString(startOffset, (this->m_currOffset - startOffset), color.value_or(0)); pattern = new PatternDataString(startOffset, (this->m_currOffset - startOffset), color.value_or(0));
else { else {
if (node->getSize() == nullptr) if (node->getSize() == nullptr)
throwEvaluateError("no bounds provided for array", node->getLineNumber()); throwEvaluateError("no bounds provided for array");
pattern = new PatternDataArray(startOffset, (this->m_currOffset - startOffset), entries, color.value_or(0)); pattern = new PatternDataArray(startOffset, (this->m_currOffset - startOffset), entries, color.value_or(0));
} }
@@ -612,7 +652,7 @@ namespace hex::lang {
pointerOffset = std::visit([node, type = valueNode->getType()] (auto &&value) { pointerOffset = std::visit([node, type = valueNode->getType()] (auto &&value) {
if (Token::isFloatingPoint(type)) if (Token::isFloatingPoint(type))
throwEvaluateError("pointer offset must be an integer value", node->getLineNumber()); throwEvaluateError("pointer offset must be an integer value");
return static_cast<s128>(value); return static_cast<s128>(value);
}, valueNode->getValue()); }, valueNode->getValue());
this->m_currOffset = pointerOffset; this->m_currOffset = pointerOffset;
@@ -624,12 +664,12 @@ namespace hex::lang {
auto underlyingType = dynamic_cast<ASTNodeTypeDecl*>(node->getSizeType()); auto underlyingType = dynamic_cast<ASTNodeTypeDecl*>(node->getSizeType());
if (underlyingType == nullptr) if (underlyingType == nullptr)
throwEvaluateError("underlying type is not ASTNodeTypeDecl. This is a bug", node->getLineNumber()); throwEvaluateError("underlying type is not ASTNodeTypeDecl. This is a bug");
if (auto builtinTypeNode = dynamic_cast<ASTNodeBuiltinType*>(underlyingType->getType()); builtinTypeNode != nullptr) { if (auto builtinTypeNode = dynamic_cast<ASTNodeBuiltinType*>(underlyingType->getType()); builtinTypeNode != nullptr) {
sizeType = evaluateBuiltinType(builtinTypeNode); sizeType = evaluateBuiltinType(builtinTypeNode);
} else } else
throwEvaluateError("pointer size is not a builtin type", node->getLineNumber()); throwEvaluateError("pointer size is not a builtin type");
size_t pointerSize = sizeType->getSize(); size_t pointerSize = sizeType->getSize();
@@ -641,7 +681,7 @@ namespace hex::lang {
if (this->m_currOffset > this->m_provider->getActualSize()) if (this->m_currOffset > this->m_provider->getActualSize())
throwEvaluateError("pointer points past the end of the data", 1); throwEvaluateError("pointer points past the end of the data");
PatternData *pointedAt; PatternData *pointedAt;
if (auto typeDecl = dynamic_cast<ASTNodeTypeDecl*>(node->getType()); typeDecl != nullptr) if (auto typeDecl = dynamic_cast<ASTNodeTypeDecl*>(node->getType()); typeDecl != nullptr)
@@ -649,7 +689,7 @@ namespace hex::lang {
else if (auto builtinTypeDecl = dynamic_cast<ASTNodeBuiltinType*>(node->getType()); builtinTypeDecl != nullptr) else if (auto builtinTypeDecl = dynamic_cast<ASTNodeBuiltinType*>(node->getType()); builtinTypeDecl != nullptr)
pointedAt = this->evaluateBuiltinType(builtinTypeDecl); pointedAt = this->evaluateBuiltinType(builtinTypeDecl);
else else
throwEvaluateError("ASTNodeVariableDecl had an invalid type. This is a bug!", 1); throwEvaluateError("ASTNodeVariableDecl had an invalid type. This is a bug!");
this->m_currOffset = pointerOffset + pointerSize; this->m_currOffset = pointerOffset + pointerSize;
@@ -675,12 +715,15 @@ namespace hex::lang {
this->m_globalMembers.push_back(this->evaluatePointer(pointerDeclNode)); this->m_globalMembers.push_back(this->evaluatePointer(pointerDeclNode));
} else if (auto typeDeclNode = dynamic_cast<ASTNodeTypeDecl*>(node); typeDeclNode != nullptr) { } else if (auto typeDeclNode = dynamic_cast<ASTNodeTypeDecl*>(node); typeDeclNode != nullptr) {
this->m_types[typeDeclNode->getName().data()] = typeDeclNode->getType(); this->m_types[typeDeclNode->getName().data()] = typeDeclNode->getType();
} else if (auto functionCallNode = dynamic_cast<ASTNodeFunctionCall*>(node); functionCallNode != nullptr) {
auto result = this->evaluateFunctionCall(functionCallNode);
delete result;
} }
this->m_endianStack.pop_back(); this->m_endianStack.clear();
} }
} catch (EvaluateError &e) { } catch (EvaluateError &e) {
this->m_error = e; this->m_consoleLog.emplace_back(ConsoleLogLevel::Error, e);
this->m_endianStack.clear(); this->m_endianStack.clear();
return { }; return { };

View File

@@ -143,6 +143,103 @@ namespace hex::lang {
return { }; return { };
} }
std::optional<std::pair<char, size_t>> getCharacter(std::string_view string) {
if (string.length() < 1)
return { };
// Escape sequences
if (string[0] == '\\') {
if (string.length() < 2)
return { };
// Handle simple escape sequences
switch (string[1]) {
case 'a': return {{ '\a', 2 }};
case 'b': return {{ '\b', 2 }};
case 'f': return {{ '\f', 2 }};
case 'n': return {{ '\n', 2 }};
case 'r': return {{ '\r', 2 }};
case 't': return {{ '\t', 2 }};
case 'v': return {{ '\v', 2 }};
case '\\': return {{ '\\', 2 }};
case '\'': return {{ '\'', 2 }};
case '\"': return {{ '\"', 2 }};
}
// Hexadecimal number
if (string[1] == 'x') {
if (string.length() != 4)
return { };
if (!isxdigit(string[2]) || !isxdigit(string[3]))
return { };
return {{ std::strtoul(&string[2], nullptr, 16), 4 }};
}
// Octal number
if (string[1] == 'o') {
if (string.length() != 5)
return { };
if (string[2] < '0' || string[2] > '7' || string[3] < '0' || string[3] > '7' || string[4] < '0' || string[4] > '7')
return { };
return {{ std::strtoul(&string[2], nullptr, 8), 5 }};
}
return { };
} else return {{ string[0], 1 }};
}
std::optional<std::pair<std::string, size_t>> getStringLiteral(std::string_view string) {
if (!string.starts_with('\"'))
return { };
size_t size = 1;
std::string result;
while (string[size] != '\"') {
auto character = getCharacter(string.substr(size));
if (!character.has_value())
return { };
auto &[c, charSize] = character.value();
result += c;
size += charSize;
if (size >= string.length())
return { };
}
return {{ result, size + 1 }};
}
std::optional<std::pair<char, size_t>> getCharacterLiteral(std::string_view string) {
if (string.empty())
return { };
if (!string[0] != '\'')
return { };
auto character = getCharacter(string.substr(1));
if (!character.has_value())
return { };
auto &[c, charSize] = character.value();
if (string.length() >= charSize || string[charSize] != '\'')
return { };
return {{ c, charSize + 2 }};
}
std::optional<std::vector<Token>> Lexer::lex(const std::string& code) { std::optional<std::vector<Token>> Lexer::lex(const std::string& code) {
std::vector<Token> tokens; std::vector<Token> tokens;
u32 offset = 0; u32 offset = 0;
@@ -263,38 +360,25 @@ namespace hex::lang {
tokens.emplace_back(TOKEN(Operator, TernaryConditional)); tokens.emplace_back(TOKEN(Operator, TernaryConditional));
offset += 1; offset += 1;
} else if (c == '\'') { } else if (c == '\'') {
offset += 1; auto character = getCharacterLiteral(code.substr(offset));
if (offset >= code.length()) if (!character.has_value())
throwLexerError("invalid character literal", lineNumber); throwLexerError("invalid character literal", lineNumber);
char character = code[offset]; auto [c, charSize] = character.value();
if (character == '\\') { tokens.emplace_back(VALUE_TOKEN(Integer, Token::IntegerLiteral(Token::ValueType::Character, c) ));
offset += 1; offset += charSize;
} else if (c == '\"') {
auto string = getStringLiteral(code.substr(offset));
if (offset >= code.length()) if (!string.has_value())
throwLexerError("invalid character literal", lineNumber); throwLexerError("invalid string literal", lineNumber);
if (code[offset] != '\\' && code[offset] != '\'') auto [s, stringSize] = string.value();
throwLexerError("invalid escape sequence", lineNumber);
character = code[offset];
} else {
if (code[offset] == '\\' || code[offset] == '\'' || character == '\n' || character == '\r')
throwLexerError("invalid character literal", lineNumber);
}
offset += 1;
if (offset >= code.length() || code[offset] != '\'')
throwLexerError("missing terminating ' after character literal", lineNumber);
tokens.emplace_back(VALUE_TOKEN(Integer, Token::IntegerLiteral(Token::ValueType::Character, character) ));
offset += 1;
tokens.emplace_back(VALUE_TOKEN(String, s));
offset += stringSize;
} else if (std::isalpha(c)) { } else if (std::isalpha(c)) {
std::string identifier = matchTillInvalid(&code[offset], [](char c) -> bool { return std::isalnum(c) || c == '_'; }); std::string identifier = matchTillInvalid(&code[offset], [](char c) -> bool { return std::isalnum(c) || c == '_'; });
@@ -319,9 +403,9 @@ namespace hex::lang {
else if (identifier == "else") else if (identifier == "else")
tokens.emplace_back(TOKEN(Keyword, Else)); tokens.emplace_back(TOKEN(Keyword, Else));
else if (identifier == "false") else if (identifier == "false")
tokens.emplace_back(VALUE_TOKEN(Integer, Token::IntegerLiteral(Token::ValueType::Unsigned8Bit, u8(0)))); tokens.emplace_back(VALUE_TOKEN(Integer, Token::IntegerLiteral(Token::ValueType::Boolean, s32(0))));
else if (identifier == "true") else if (identifier == "true")
tokens.emplace_back(VALUE_TOKEN(Integer, Token::IntegerLiteral(Token::ValueType::Unsigned8Bit, u8(1)))); tokens.emplace_back(VALUE_TOKEN(Integer, Token::IntegerLiteral(Token::ValueType::Boolean, s32(1))));
// Check for built-in types // Check for built-in types
else if (identifier == "u8") else if (identifier == "u8")

View File

@@ -5,7 +5,7 @@
#define MATCHES(x) (begin() && x) #define MATCHES(x) (begin() && x)
#define TO_NUMERIC_EXPRESSION(node) new ASTNodeNumericExpression((node), new ASTNodeIntegerLiteral({ Token::ValueType::Signed32Bit, s32(0) }), Token::Operator::Plus) #define TO_NUMERIC_EXPRESSION(node) new ASTNodeNumericExpression((node), new ASTNodeIntegerLiteral({ Token::ValueType::Any, s32(0) }), Token::Operator::Plus)
// Definition syntax: // Definition syntax:
// [A] : Either A or no token // [A] : Either A or no token
@@ -28,7 +28,10 @@ namespace hex::lang {
}); });
while (!MATCHES(sequence(SEPARATOR_ROUNDBRACKETCLOSE))) { while (!MATCHES(sequence(SEPARATOR_ROUNDBRACKETCLOSE))) {
params.push_back(parseMathematicalExpression()); if (MATCHES(sequence(STRING)))
params.push_back(parseStringLiteral());
else
params.push_back(parseMathematicalExpression());
if (MATCHES(sequence(SEPARATOR_COMMA, SEPARATOR_ROUNDBRACKETCLOSE))) if (MATCHES(sequence(SEPARATOR_COMMA, SEPARATOR_ROUNDBRACKETCLOSE)))
throwParseError("unexpected ',' at end of function parameter list", -1); throwParseError("unexpected ',' at end of function parameter list", -1);
@@ -41,7 +44,11 @@ namespace hex::lang {
paramCleanup.release(); paramCleanup.release();
return TO_NUMERIC_EXPRESSION(new ASTNodeFunctionCall(functionName, params)); return new ASTNodeFunctionCall(functionName, params);
}
ASTNode* Parser::parseStringLiteral() {
return new ASTNodeStringLiteral(getValue<std::string>(-1));
} }
// Identifier::<Identifier[::]...> // Identifier::<Identifier[::]...>
@@ -86,7 +93,7 @@ namespace hex::lang {
this->m_curr--; this->m_curr--;
return this->parseScopeResolution(path); return this->parseScopeResolution(path);
} else if (MATCHES(sequence(IDENTIFIER, SEPARATOR_ROUNDBRACKETOPEN))) { } else if (MATCHES(sequence(IDENTIFIER, SEPARATOR_ROUNDBRACKETOPEN))) {
return this->parseFunctionCall(); return TO_NUMERIC_EXPRESSION(this->parseFunctionCall());
} else if (MATCHES(sequence(IDENTIFIER))) { } else if (MATCHES(sequence(IDENTIFIER))) {
std::vector<std::string> path; std::vector<std::string> path;
return this->parseRValue(path); return this->parseRValue(path);
@@ -99,7 +106,7 @@ namespace hex::lang {
if (MATCHES(sequence(OPERATOR_PLUS) || sequence(OPERATOR_MINUS) || sequence(OPERATOR_BOOLNOT) || sequence(OPERATOR_BITNOT))) { if (MATCHES(sequence(OPERATOR_PLUS) || sequence(OPERATOR_MINUS) || sequence(OPERATOR_BOOLNOT) || sequence(OPERATOR_BITNOT))) {
auto op = getValue<Token::Operator>(-1); auto op = getValue<Token::Operator>(-1);
return new ASTNodeNumericExpression(new ASTNodeIntegerLiteral({ Token::ValueType::Signed32Bit, 0}), this->parseFactor(), op); return new ASTNodeNumericExpression(new ASTNodeIntegerLiteral({ Token::ValueType::Any, 0 }), this->parseFactor(), op);
} }
return this->parseFactor(); return this->parseFactor();
@@ -233,15 +240,15 @@ namespace hex::lang {
// (parseBooleanOr) ? (parseBooleanOr) : (parseBooleanOr) // (parseBooleanOr) ? (parseBooleanOr) : (parseBooleanOr)
ASTNode* Parser::parseTernaryConditional() { ASTNode* Parser::parseTernaryConditional() {
auto node = this->parseBooleanXor(); auto node = this->parseBooleanOr();
while (MATCHES(sequence(OPERATOR_TERNARYCONDITIONAL))) { while (MATCHES(sequence(OPERATOR_TERNARYCONDITIONAL))) {
auto second = this->parseBooleanXor(); auto second = this->parseBooleanOr();
if (!MATCHES(sequence(OPERATOR_INHERIT))) if (!MATCHES(sequence(OPERATOR_INHERIT)))
throwParseError("expected ':' in ternary expression"); throwParseError("expected ':' in ternary expression");
auto third = this->parseBooleanXor(); auto third = this->parseBooleanOr();
node = new ASTNodeTernaryExpression(node, second, third, Token::Operator::TernaryConditional); node = new ASTNodeTernaryExpression(node, second, third, Token::Operator::TernaryConditional);
} }
@@ -447,6 +454,7 @@ namespace hex::lang {
auto underlyingType = dynamic_cast<ASTNodeTypeDecl*>(parseType(-2)); auto underlyingType = dynamic_cast<ASTNodeTypeDecl*>(parseType(-2));
if (underlyingType == nullptr) throwParseError("failed to parse type", -2); if (underlyingType == nullptr) throwParseError("failed to parse type", -2);
if (underlyingType->getEndian().has_value()) throwParseError("underlying type may not have an endian specification", -2);
const auto enumNode = new ASTNodeEnum(underlyingType); const auto enumNode = new ASTNodeEnum(underlyingType);
ScopeExit enumGuard([&]{ delete enumNode; }); ScopeExit enumGuard([&]{ delete enumNode; });
@@ -464,22 +472,22 @@ namespace hex::lang {
ASTNode *valueExpr; ASTNode *valueExpr;
auto name = getValue<std::string>(-1); auto name = getValue<std::string>(-1);
if (enumNode->getEntries().empty()) if (enumNode->getEntries().empty())
lastEntry = TO_NUMERIC_EXPRESSION(new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned8Bit, u8(0) })); valueExpr = lastEntry = TO_NUMERIC_EXPRESSION(new ASTNodeIntegerLiteral({ Token::ValueType::Unsigned8Bit, u8(0) }));
else else
valueExpr = new ASTNodeNumericExpression(lastEntry->clone(), new ASTNodeIntegerLiteral({ Token::ValueType::Signed32Bit, s32(1) }), Token::Operator::Plus); valueExpr = new ASTNodeNumericExpression(lastEntry->clone(), new ASTNodeIntegerLiteral({ Token::ValueType::Any, s32(1) }), Token::Operator::Plus);
enumNode->addEntry(name, valueExpr); enumNode->addEntry(name, valueExpr);
} }
else if (MATCHES(sequence(SEPARATOR_ENDOFPROGRAM))) else if (MATCHES(sequence(SEPARATOR_ENDOFPROGRAM)))
throwParseError("unexpected end of program", -2); throwParseError("unexpected end of program", -2);
else else
throwParseError("invalid union member", 0); throwParseError("invalid enum entry", -1);
if (!MATCHES(sequence(SEPARATOR_COMMA))) { if (!MATCHES(sequence(SEPARATOR_COMMA))) {
if (MATCHES(sequence(SEPARATOR_CURLYBRACKETCLOSE))) if (MATCHES(sequence(SEPARATOR_CURLYBRACKETCLOSE)))
break; break;
else else
throwParseError("missing ',' between enum entries", 0); throwParseError("missing ',' between enum entries", -1);
} }
} }
@@ -591,6 +599,8 @@ namespace hex::lang {
statement = parseEnum(); statement = parseEnum();
else if (MATCHES(sequence(KEYWORD_BITFIELD, IDENTIFIER, SEPARATOR_CURLYBRACKETOPEN))) else if (MATCHES(sequence(KEYWORD_BITFIELD, IDENTIFIER, SEPARATOR_CURLYBRACKETOPEN)))
statement = parseBitfield(); statement = parseBitfield();
else if (MATCHES(sequence(IDENTIFIER, SEPARATOR_ROUNDBRACKETOPEN)))
statement = parseFunctionCall();
else throwParseError("invalid sequence", 0); else throwParseError("invalid sequence", 0);
if (!MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))) if (!MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION)))

View File

@@ -172,7 +172,13 @@ namespace hex::lang {
if (initialRun) { if (initialRun) {
// Apply defines // Apply defines
for (const auto &[define, value] : this->m_defines) { std::vector<std::pair<std::string, std::string>> sortedDefines;
std::copy(this->m_defines.begin(), this->m_defines.end(), std::back_inserter(sortedDefines));
std::sort(sortedDefines.begin(), sortedDefines.end(), [](const auto &left, const auto &right) {
return left.first.size() > right.first.size();
});
for (const auto &[define, value] : sortedDefines) {
s32 index = 0; s32 index = 0;
while((index = output.find(define, index)) != std::string::npos) { while((index = output.find(define, index)) != std::string::npos) {
output.replace(index, define.length(), value); output.replace(index, define.length(), value);

View File

@@ -87,7 +87,11 @@ namespace hex {
u8 codepointSize = ImTextCharFromUtf8(&codepoint, buffer, buffer + 4); u8 codepointSize = ImTextCharFromUtf8(&codepoint, buffer, buffer + 4);
std::memcpy(codepointString, &codepoint, std::min(codepointSize, u8(4))); std::memcpy(codepointString, &codepoint, std::min(codepointSize, u8(4)));
this->m_cachedData.emplace_back("UTF-8 code point", hex::format("'%s' (U+%04lx)", codepoint == 0xFFFD ? "Invalid" : codepointString, codepoint), sizeof(char8_t)); this->m_cachedData.emplace_back("UTF-8 code point", hex::format("'%s' (U+%04lx)",
codepoint == 0xFFFD ? "Invalid" :
codepoint < 0xFF ? makePrintable(codepoint).c_str() :
codepointString
, codepoint), sizeof(char8_t));
} }
this->m_cachedData.emplace_back("float (32 bit)", hex::format("%e", hex::changeEndianess(this->m_previewData.float32, this->m_endian)), sizeof(float)); this->m_cachedData.emplace_back("float (32 bit)", hex::format("%e", hex::changeEndianess(this->m_previewData.float32, this->m_endian)), sizeof(float));

View File

@@ -30,7 +30,9 @@ namespace hex {
void ViewHelp::drawAboutPopup() { void ViewHelp::drawAboutPopup() {
if (ImGui::BeginPopupModal("About", &this->m_aboutWindowOpen, ImGuiWindowFlags_AlwaysAutoResize)) { if (ImGui::BeginPopupModal("About", &this->m_aboutWindowOpen, ImGuiWindowFlags_AlwaysAutoResize)) {
ImGui::Text("ImHex Hex Editor v%s by WerWolv", IMHEX_VERSION); ImGui::Text("ImHex Hex Editor v%s by WerWolv", IMHEX_VERSION);
#if defined(GIT_BRANCH) && defined(GIT_COMMIT_HASH)
ImGui::Text("%s@%s", GIT_BRANCH, GIT_COMMIT_HASH); ImGui::Text("%s@%s", GIT_BRANCH, GIT_COMMIT_HASH);
#endif
ImGui::NewLine(); ImGui::NewLine();
ImGui::Text("Source code available on GitHub:"); ImGui::SameLine(); ImGui::Text("Source code available on GitHub:"); ImGui::SameLine();
ImGui::TextColored(ImVec4(0.4F, 0.4F, 0.8F, 1.0F), "WerWolv/ImHex "); ImGui::TextColored(ImVec4(0.4F, 0.4F, 0.8F, 1.0F), "WerWolv/ImHex ");

View File

@@ -117,29 +117,38 @@ namespace hex {
this->m_memoryEditor.DrawWindow("Hex Editor", &this->getWindowOpenState(), this, dataSize, dataSize == 0 ? 0x00 : provider->getBaseAddress()); this->m_memoryEditor.DrawWindow("Hex Editor", &this->getWindowOpenState(), this, dataSize, dataSize == 0 ? 0x00 : provider->getBaseAddress());
if (dataSize != 0x00) { if (dataSize != 0x00) {
ImGui::Begin("Hex Editor"); if (ImGui::Begin("Hex Editor")) {
ImGui::SameLine();
ImGui::Spacing();
ImGui::SameLine();
ImGui::Text("Page %d / %d", provider->getCurrentPage() + 1, provider->getPageCount());
ImGui::SameLine();
if (ImGui::ArrowButton("prevPage", ImGuiDir_Left)) { if (ImGui::IsMouseClicked(ImGuiMouseButton_Right) && ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows))
provider->setCurrentPage(provider->getCurrentPage() - 1); ImGui::OpenPopup("Edit");
Region dataPreview = { std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd), 1 }; if (ImGui::BeginPopup("Edit")) {
View::postEvent(Events::RegionSelected, &dataPreview); this->drawEditPopup();
ImGui::EndPopup();
}
ImGui::SameLine();
ImGui::Spacing();
ImGui::SameLine();
ImGui::Text("Page %d / %d", provider->getCurrentPage() + 1, provider->getPageCount());
ImGui::SameLine();
if (ImGui::ArrowButton("prevPage", ImGuiDir_Left)) {
provider->setCurrentPage(provider->getCurrentPage() - 1);
Region dataPreview = { std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd), 1 };
View::postEvent(Events::RegionSelected, &dataPreview);
}
ImGui::SameLine();
if (ImGui::ArrowButton("nextPage", ImGuiDir_Right)) {
provider->setCurrentPage(provider->getCurrentPage() + 1);
Region dataPreview = { std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd), 1 };
View::postEvent(Events::RegionSelected, &dataPreview);
}
} }
ImGui::SameLine();
if (ImGui::ArrowButton("nextPage", ImGuiDir_Right)) {
provider->setCurrentPage(provider->getCurrentPage() + 1);
Region dataPreview = { std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd), 1 };
View::postEvent(Events::RegionSelected, &dataPreview);
}
ImGui::End(); ImGui::End();
this->drawSearchPopup(); this->drawSearchPopup();
@@ -385,47 +394,7 @@ namespace hex {
} }
if (ImGui::BeginMenu("Edit")) { if (ImGui::BeginMenu("Edit")) {
if (ImGui::BeginMenu("Copy as...", this->m_memoryEditor.DataPreviewAddr != -1 && this->m_memoryEditor.DataPreviewAddrEnd != -1)) { this->drawEditPopup();
if (ImGui::MenuItem("Bytes", "CTRL + ALT + C"))
this->copyBytes();
if (ImGui::MenuItem("Hex String", "CTRL + SHIFT + C"))
this->copyString();
ImGui::Separator();
if (ImGui::MenuItem("C Array"))
this->copyLanguageArray(Language::C);
if (ImGui::MenuItem("C++ Array"))
this->copyLanguageArray(Language::Cpp);
if (ImGui::MenuItem("C# Array"))
this->copyLanguageArray(Language::CSharp);
if (ImGui::MenuItem("Rust Array"))
this->copyLanguageArray(Language::Rust);
if (ImGui::MenuItem("Python Array"))
this->copyLanguageArray(Language::Python);
if (ImGui::MenuItem("Java Array"))
this->copyLanguageArray(Language::Java);
if (ImGui::MenuItem("JavaScript Array"))
this->copyLanguageArray(Language::JavaScript);
ImGui::Separator();
if (ImGui::MenuItem("Editor View"))
this->copyHexView();
if (ImGui::MenuItem("HTML"))
this->copyHexViewHTML();
ImGui::EndMenu();
}
if (ImGui::MenuItem("Create bookmark", nullptr, false, this->m_memoryEditor.DataPreviewAddr != -1 && this->m_memoryEditor.DataPreviewAddrEnd != -1)) {
size_t start = std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
size_t end = std::max(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
Bookmark bookmark = { start, end - start + 1, { }, { } };
View::postEvent(Events::AddBookmark, &bookmark);
}
ImGui::EndMenu(); ImGui::EndMenu();
} }
} }
@@ -978,4 +947,47 @@ R"(
} }
} }
void ViewHexEditor::drawEditPopup() {
if (ImGui::BeginMenu("Copy as...", this->m_memoryEditor.DataPreviewAddr != -1 && this->m_memoryEditor.DataPreviewAddrEnd != -1)) {
if (ImGui::MenuItem("Bytes", "CTRL + ALT + C"))
this->copyBytes();
if (ImGui::MenuItem("Hex String", "CTRL + SHIFT + C"))
this->copyString();
ImGui::Separator();
if (ImGui::MenuItem("C Array"))
this->copyLanguageArray(Language::C);
if (ImGui::MenuItem("C++ Array"))
this->copyLanguageArray(Language::Cpp);
if (ImGui::MenuItem("C# Array"))
this->copyLanguageArray(Language::CSharp);
if (ImGui::MenuItem("Rust Array"))
this->copyLanguageArray(Language::Rust);
if (ImGui::MenuItem("Python Array"))
this->copyLanguageArray(Language::Python);
if (ImGui::MenuItem("Java Array"))
this->copyLanguageArray(Language::Java);
if (ImGui::MenuItem("JavaScript Array"))
this->copyLanguageArray(Language::JavaScript);
ImGui::Separator();
if (ImGui::MenuItem("Editor View"))
this->copyHexView();
if (ImGui::MenuItem("HTML"))
this->copyHexViewHTML();
ImGui::EndMenu();
}
if (ImGui::MenuItem("Create bookmark", nullptr, false, this->m_memoryEditor.DataPreviewAddr != -1 && this->m_memoryEditor.DataPreviewAddrEnd != -1)) {
size_t start = std::min(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
size_t end = std::max(this->m_memoryEditor.DataPreviewAddr, this->m_memoryEditor.DataPreviewAddrEnd);
Bookmark bookmark = { start, end - start + 1, { }, { } };
View::postEvent(Events::AddBookmark, &bookmark);
}
}
} }

View File

@@ -28,6 +28,7 @@ namespace hex {
{ "s8", 1 }, { "s16", 2 }, { "s32", 4 }, { "s64", 8 }, { "s128", 16 }, { "s8", 1 }, { "s16", 2 }, { "s32", 4 }, { "s64", 8 }, { "s128", 16 },
{ "float", 4 }, { "double", 8 }, { "char", 1 }, { "bool", 1 }, { "padding", 1 } { "float", 4 }, { "double", 8 }, { "char", 1 }, { "bool", 1 }, { "padding", 1 }
}; };
for (const auto &[name, size] : builtInTypes) { for (const auto &[name, size] : builtInTypes) {
TextEditor::Identifier id; TextEditor::Identifier id;
id.mDeclaration = std::to_string(size); id.mDeclaration = std::to_string(size);
@@ -52,6 +53,8 @@ namespace hex {
paletteIndex = TextEditor::PaletteIndex::Number; paletteIndex = TextEditor::PaletteIndex::Number;
else if (TokenizeCStyleCharacterLiteral(inBegin, inEnd, outBegin, outEnd)) else if (TokenizeCStyleCharacterLiteral(inBegin, inEnd, outBegin, outEnd))
paletteIndex = TextEditor::PaletteIndex::CharLiteral; paletteIndex = TextEditor::PaletteIndex::CharLiteral;
else if (TokenizeCStyleString(inBegin, inEnd, outBegin, outEnd))
paletteIndex = TextEditor::PaletteIndex::String;
return paletteIndex != TextEditor::PaletteIndex::Max; return paletteIndex != TextEditor::PaletteIndex::Max;
}; };
@@ -185,7 +188,39 @@ namespace hex {
auto provider = *SharedData::get().currentProvider; auto provider = *SharedData::get().currentProvider;
if (provider != nullptr && provider->isAvailable()) { if (provider != nullptr && provider->isAvailable()) {
this->m_textEditor.Render("Pattern"); auto textEditorSize = ImGui::GetContentRegionAvail();
textEditorSize.y *= 4.0/5.0;
this->m_textEditor.Render("Pattern", textEditorSize, true);
auto consoleSize = ImGui::GetContentRegionAvail();
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.0, 0.0, 0.0, 1.0));
if (ImGui::BeginChild("##console", consoleSize, true, ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
for (auto &[level, message] : this->m_console) {
switch (level) {
case lang::Evaluator::ConsoleLogLevel::Debug:
ImGui::PushStyleColor(ImGuiCol_Text, ImColor(0x1F, 0xA9, 0x49, 0xFF).Value);
break;
case lang::Evaluator::ConsoleLogLevel::Info:
ImGui::PushStyleColor(ImGuiCol_Text, ImColor(0x00, 0x70, 0xB4, 0xFF).Value);
break;
case lang::Evaluator::ConsoleLogLevel::Warning:
ImGui::PushStyleColor(ImGuiCol_Text, ImColor(0xFF, 0xC8, 0x01, 0xFF).Value);
break;
case lang::Evaluator::ConsoleLogLevel::Error:
ImGui::PushStyleColor(ImGuiCol_Text, ImColor(0xAE, 0x0C, 0x00, 0xFF).Value);
break;
default: continue;
}
ImGui::TextUnformatted(message.c_str());
ImGui::PopStyleColor();
}
}
ImGui::EndChild();
ImGui::PopStyleColor(1);
if (this->m_textEditor.IsTextChanged()) { if (this->m_textEditor.IsTextChanged()) {
this->parsePattern(this->m_textEditor.GetText().data()); this->parsePattern(this->m_textEditor.GetText().data());
@@ -254,6 +289,7 @@ namespace hex {
void ViewPattern::parsePattern(char *buffer) { void ViewPattern::parsePattern(char *buffer) {
this->clearPatternData(); this->clearPatternData();
this->m_textEditor.SetErrorMarkers({ }); this->m_textEditor.SetErrorMarkers({ });
this->m_console.clear();
this->postEvent(Events::PatternChanged); this->postEvent(Events::PatternChanged);
hex::lang::Preprocessor preprocessor; hex::lang::Preprocessor preprocessor;
@@ -305,11 +341,11 @@ namespace hex {
auto provider = *SharedData::get().currentProvider; auto provider = *SharedData::get().currentProvider;
hex::lang::Evaluator evaluator(provider, defaultDataEndianess); hex::lang::Evaluator evaluator(provider, defaultDataEndianess);
auto patternData = evaluator.evaluate(ast.value()); auto patternData = evaluator.evaluate(ast.value());
if (!patternData.has_value()) { this->m_console = evaluator.getConsoleLog();
this->m_textEditor.SetErrorMarkers({ evaluator.getError() }); if (!patternData.has_value())
return; return;
}
this->m_patternData = patternData.value(); this->m_patternData = patternData.value();
this->postEvent(Events::PatternChanged); this->postEvent(Events::PatternChanged);

View File

@@ -54,8 +54,8 @@ namespace hex {
if (provider != nullptr && provider->isReadable()) { if (provider != nullptr && provider->isReadable()) {
if (beginPatternDataTable(provider, this->m_patternData, this->m_sortedPatternData)) { if (beginPatternDataTable(provider, this->m_patternData, this->m_sortedPatternData)) {
ImGui::TableHeadersRow();
if (this->m_sortedPatternData.size() > 0) { if (this->m_sortedPatternData.size() > 0) {
ImGui::TableHeadersRow();
for (auto &patternData : this->m_sortedPatternData) for (auto &patternData : this->m_sortedPatternData)
patternData->createEntry(provider); patternData->createEntry(provider);

View File

@@ -195,7 +195,7 @@ namespace hex {
else else
ImGui::NewLine(); ImGui::NewLine();
enum class MathDisplayType { Standard, Scientific, Programmer } mathDisplayType; enum class MathDisplayType { Standard, Scientific, Engineering, Programmer } mathDisplayType;
if (ImGui::BeginTabBar("##mathFormatTabBar")) { if (ImGui::BeginTabBar("##mathFormatTabBar")) {
if (ImGui::BeginTabItem("Standard")) { if (ImGui::BeginTabItem("Standard")) {
mathDisplayType = MathDisplayType::Standard; mathDisplayType = MathDisplayType::Standard;
@@ -205,6 +205,10 @@ namespace hex {
mathDisplayType = MathDisplayType::Scientific; mathDisplayType = MathDisplayType::Scientific;
ImGui::EndTabItem(); ImGui::EndTabItem();
} }
if (ImGui::BeginTabItem("Engineering")) {
mathDisplayType = MathDisplayType::Engineering;
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Programmer")) { if (ImGui::BeginTabItem("Programmer")) {
mathDisplayType = MathDisplayType::Programmer; mathDisplayType = MathDisplayType::Programmer;
ImGui::EndTabItem(); ImGui::EndTabItem();
@@ -242,6 +246,9 @@ namespace hex {
case MathDisplayType::Scientific: case MathDisplayType::Scientific:
ImGui::Text("%.6Le", this->m_mathHistory[(this->m_mathHistory.size() - 1) - i]); ImGui::Text("%.6Le", this->m_mathHistory[(this->m_mathHistory.size() - 1) - i]);
break; break;
case MathDisplayType::Engineering:
ImGui::Text("%s", hex::toEngineeringString(this->m_mathHistory[(this->m_mathHistory.size() - 1) - i]).c_str());
break;
case MathDisplayType::Programmer: case MathDisplayType::Programmer:
ImGui::Text("0x%llX (%llu)", ImGui::Text("0x%llX (%llu)",
u64(this->m_mathHistory[(this->m_mathHistory.size() - 1) - i]), u64(this->m_mathHistory[(this->m_mathHistory.size() - 1) - i]),
@@ -279,6 +286,9 @@ namespace hex {
case MathDisplayType::Scientific: case MathDisplayType::Scientific:
ImGui::Text("%.6Le", value); ImGui::Text("%.6Le", value);
break; break;
case MathDisplayType::Engineering:
ImGui::Text("%s", hex::toEngineeringString(value).c_str());
break;
case MathDisplayType::Programmer: case MathDisplayType::Programmer:
ImGui::Text("0x%llX (%llu)", u64(value), u64(value)); ImGui::Text("0x%llX (%llu)", u64(value), u64(value));
break; break;

View File

@@ -161,13 +161,15 @@ namespace hex {
ImGui::MenuItem((view->getName() + " View").c_str(), "", &view->getWindowOpenState()); ImGui::MenuItem((view->getName() + " View").c_str(), "", &view->getWindowOpenState());
} }
if (ImGui::BeginMenu("Plugin Views")) { if (!this->m_pluginViews.empty()) {
for (auto &view : this->m_pluginViews) { if (ImGui::BeginMenu("Plugin Views")) {
if (view->hasViewMenuItemEntry()) for (auto &view : this->m_pluginViews) {
ImGui::MenuItem((view->getName() + " View").c_str(), "", &view->getWindowOpenState()); if (view->hasViewMenuItemEntry())
} ImGui::MenuItem((view->getName() + " View").c_str(), "", &view->getWindowOpenState());
}
ImGui::EndMenu(); ImGui::EndMenu();
}
} }
ImGui::EndMenu(); ImGui::EndMenu();