Compare commits

...

19 commits
v0.5.3 ... main

Author SHA1 Message Date
Vaxry
557241780c
version: bump to 0.6.3
Some checks failed
Build & Test / nix (hyprlang) (push) Has been cancelled
Build & Test / nix (hyprlang-with-tests) (push) Has been cancelled
Build & Test (Arch) / gcc build / ASan tests (push) Has been cancelled
Build & Test (Arch) / gcc build / UBSan tests (push) Has been cancelled
Build & Test (Arch) / gcc build / MSan tests (push) Has been cancelled
Build & Test (Arch) / clang build / gcc test (push) Has been cancelled
Build & Test (Arch) / Deploy docs (push) Has been cancelled
2025-05-07 23:03:32 +01:00
Vaxry
a59e86a3da
parser: change expression syntax to avoid bash clashes
changes from $() to {{}} to avoid clashing with bash syntax
2025-05-07 23:03:03 +01:00
Vaxry
a15e7ba78a
version: bump to 0.6.2 2025-05-07 19:46:08 +01:00
Mihai Fufezan
e863ebcee9
flake.lock: update
Some checks are pending
Build & Test (Arch) / gcc build / ASan tests (push) Waiting to run
Build & Test (Arch) / gcc build / UBSan tests (push) Waiting to run
Build & Test (Arch) / gcc build / MSan tests (push) Waiting to run
Build & Test (Arch) / clang build / gcc test (push) Waiting to run
Build & Test (Arch) / Deploy docs (push) Waiting to run
Build & Test / nix (hyprlang) (push) Waiting to run
Build & Test / nix (hyprlang-with-tests) (push) Waiting to run
2025-05-07 20:11:54 +03:00
Vaxry
6726cfd54b
parser: add support for basic arithmetic
Adds support for  expressions that take left and right hand side and an operation (+-*/) -> e.g.

fixes #67
2025-05-07 17:50:22 +01:00
Honkazel
397600c42b
clang-tidy: fix some errors (#70) 2025-04-22 23:23:39 +02:00
Vaxry
f1000c54d2 version: bump to 0.6.1 2025-04-12 15:35:25 +01:00
Lukas
72df3861f1
README: fix typo (#65) 2025-03-05 18:18:47 +02:00
Vaxry
1d7d96a278 docs: fix incorrect doc about getValue type 2025-02-25 17:18:11 +00:00
Mihai Fufezan
a7334904d5
CI: remove deprecated magic-nix-cache-action 2025-02-08 23:08:34 +02:00
Honkazel
7a59f2de3f
core: clang-tidy and comp fixes (#63) 2025-02-08 01:44:54 +01:00
Mihai Fufezan
f41271d35c
flake.lock: update 2025-01-23 14:16:46 +02:00
Joshua Baker
55608efdaa
core: add multiline support (#58)
Adds support for multi-line commands with a backslash
2024-12-28 13:36:59 +00:00
Mihai Fufezan
0404833ea1
flake.lock: update 2024-12-23 00:24:19 +02:00
Mihai Fufezan
16e59c1eb1
flake.lock: update 2024-12-16 17:57:08 +02:00
Vaxry
9441266c89 cmakelists: remove clang-specific config
closes #59
2024-12-14 23:34:04 +00:00
Mihai Fufezan
f7acd5dabb
flake.nix: use gcc14Stdenv, update 2024-12-14 13:01:16 +02:00
Vaxry
1b0c595731 version: bump to 0.6.0 2024-12-13 20:48:31 +00:00
Vaxry
058fcf84c9 API: add a templated config value wrapper
This is basically a copy of the Hyprland config wrapper. It's much more straightforward to use, and much harder to fuck up.
2024-12-13 20:48:06 +00:00
16 changed files with 486 additions and 127 deletions

101
.clang-tidy Normal file
View file

@ -0,0 +1,101 @@
WarningsAsErrors: '*'
HeaderFilterRegex: '.*\.hpp'
FormatStyle: 'file'
Checks: >
-*,
bugprone-*,
-bugprone-easily-swappable-parameters,
-bugprone-forward-declaration-namespace,
-bugprone-forward-declaration-namespace,
-bugprone-macro-parentheses,
-bugprone-narrowing-conversions,
-bugprone-branch-clone,
-bugprone-assignment-in-if-condition,
concurrency-*,
-concurrency-mt-unsafe,
cppcoreguidelines-*,
-cppcoreguidelines-owning-memory,
-cppcoreguidelines-avoid-magic-numbers,
-cppcoreguidelines-pro-bounds-constant-array-index,
-cppcoreguidelines-avoid-const-or-ref-data-members,
-cppcoreguidelines-non-private-member-variables-in-classes,
-cppcoreguidelines-avoid-goto,
-cppcoreguidelines-pro-bounds-array-to-pointer-decay,
-cppcoreguidelines-avoid-do-while,
-cppcoreguidelines-avoid-non-const-global-variables,
-cppcoreguidelines-special-member-functions,
-cppcoreguidelines-explicit-virtual-functions,
-cppcoreguidelines-avoid-c-arrays,
-cppcoreguidelines-pro-bounds-pointer-arithmetic,
-cppcoreguidelines-narrowing-conversions,
-cppcoreguidelines-pro-type-union-access,
-cppcoreguidelines-pro-type-member-init,
-cppcoreguidelines-macro-usage,
-cppcoreguidelines-macro-to-enum,
-cppcoreguidelines-init-variables,
-cppcoreguidelines-pro-type-cstyle-cast,
-cppcoreguidelines-pro-type-vararg,
-cppcoreguidelines-pro-type-reinterpret-cast,
google-global-names-in-headers,
-google-readability-casting,
google-runtime-operator,
misc-*,
-misc-unused-parameters,
-misc-no-recursion,
-misc-non-private-member-variables-in-classes,
-misc-include-cleaner,
-misc-use-anonymous-namespace,
-misc-const-correctness,
modernize-*,
-modernize-return-braced-init-list,
-modernize-use-trailing-return-type,
-modernize-use-using,
-modernize-use-override,
-modernize-avoid-c-arrays,
-modernize-macro-to-enum,
-modernize-loop-convert,
-modernize-use-nodiscard,
-modernize-pass-by-value,
-modernize-use-auto,
performance-*,
-performance-avoid-endl,
-performance-unnecessary-value-param,
portability-std-allocator-const,
readability-*,
-readability-function-cognitive-complexity,
-readability-function-size,
-readability-identifier-length,
-readability-magic-numbers,
-readability-uppercase-literal-suffix,
-readability-braces-around-statements,
-readability-redundant-access-specifiers,
-readability-else-after-return,
-readability-container-data-pointer,
-readability-implicit-bool-conversion,
-readability-avoid-nested-conditional-operator,
-readability-redundant-member-init,
-readability-redundant-string-init,
-readability-avoid-const-params-in-decls,
-readability-named-parameter,
-readability-convert-member-functions-to-static,
-readability-qualified-auto,
-readability-make-member-function-const,
-readability-isolate-declaration,
-readability-inconsistent-declaration-parameter-name,
-clang-diagnostic-error,
CheckOptions:
performance-for-range-copy.WarnOnAllAutoCopies: true
performance-inefficient-string-concatenation.StrictMode: true
readability-braces-around-statements.ShortStatementLines: 0
readability-identifier-naming.ClassCase: CamelCase
readability-identifier-naming.ClassIgnoredRegexp: I.*
readability-identifier-naming.ClassPrefix: C # We can't use regex here?!?!?!?
readability-identifier-naming.EnumCase: CamelCase
readability-identifier-naming.EnumPrefix: e
readability-identifier-naming.EnumConstantCase: UPPER_CASE
readability-identifier-naming.FunctionCase: camelBack
readability-identifier-naming.NamespaceCase: CamelCase
readability-identifier-naming.NamespacePrefix: N
readability-identifier-naming.StructPrefix: S
readability-identifier-naming.StructCase: CamelCase

View file

@ -14,7 +14,6 @@ jobs:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- uses: DeterminateSystems/nix-installer-action@main - uses: DeterminateSystems/nix-installer-action@main
- uses: DeterminateSystems/magic-nix-cache-action@main
# not needed (yet) # not needed (yet)
# - uses: cachix/cachix-action@v12 # - uses: cachix/cachix-action@v12

3
.gitignore vendored
View file

@ -12,4 +12,5 @@ _deps
.vscode .vscode
build/ build/
doxygen/ doxygen/
doxygen-awesome-css/ doxygen-awesome-css/
.cache/

View file

@ -28,9 +28,16 @@ endif()
add_compile_definitions(HYPRLANG_INTERNAL) add_compile_definitions(HYPRLANG_INTERNAL)
set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD 23)
add_compile_options(
-Wall
-Wextra
-Wpedantic
-Wno-unused-parameter
-Wno-missing-field-initializers)
set(CMAKE_EXPORT_COMPILE_COMMANDS TRUE)
find_package(PkgConfig REQUIRED) find_package(PkgConfig REQUIRED)
pkg_check_modules(deps REQUIRED IMPORTED_TARGET hyprutils>=0.1.1) pkg_check_modules(deps REQUIRED IMPORTED_TARGET hyprutils>=0.7.1)
file(GLOB_RECURSE SRCFILES CONFIGURE_DEPENDS "src/*.cpp" "include/hyprlang.hpp") file(GLOB_RECURSE SRCFILES CONFIGURE_DEPENDS "src/*.cpp" "include/hyprlang.hpp")
@ -47,15 +54,6 @@ set_target_properties(
target_link_libraries(hyprlang PkgConfig::deps) target_link_libraries(hyprlang PkgConfig::deps)
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
# for std::expected. probably evil. Arch's clang is very outdated tho...
target_compile_options(hyprlang PUBLIC -std=gnu++2b -D__cpp_concepts=202002L
-Wno-macro-redefined)
add_compile_options(-stdlib=libc++)
add_link_options(-stdlib=libc++)
message(STATUS "Using clang++ to compile hyprlang")
endif()
add_library(hypr::hyprlang ALIAS hyprlang) add_library(hypr::hyprlang ALIAS hyprlang)
install(TARGETS hyprlang) install(TARGETS hyprlang)

View file

@ -54,4 +54,4 @@ Visit [hyprland.org/hyprlang](https://hyprland.org/hyprlang) to see the document
### Example implementation ### Example implementation
For an example implmentation, take a look at the `tests/` directory. For an example implementation, take a look at the `tests/` directory.

View file

@ -1 +1 @@
0.5.3 0.6.3

View file

@ -10,11 +10,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1721324102, "lastModified": 1746635225,
"narHash": "sha256-WAZ0X6yJW1hFG6otkHBfyJDKRpNP5stsRqdEuHrFRpk=", "narHash": "sha256-W9G9bb0zRYDBRseHbVez0J8qVpD5QbizX67H/vsudhM=",
"owner": "hyprwm", "owner": "hyprwm",
"repo": "hyprutils", "repo": "hyprutils",
"rev": "962582a090bc233c4de9d9897f46794280288989", "rev": "674ea57373f08b7609ce93baff131117a0dfe70d",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -25,11 +25,11 @@
}, },
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1721138476, "lastModified": 1746461020,
"narHash": "sha256-+W5eZOhhemLQxelojLxETfbFbc19NWawsXBlapYpqIA=", "narHash": "sha256-7+pG1I9jvxNlmln4YgnlW4o+w0TZX24k688mibiFDUE=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "ad0b5eed1b6031efaed382844806550c3dcb4206", "rev": "3730d8a308f94996a9ba7c7138ede69c1b9ac4ae",
"type": "github" "type": "github"
}, },
"original": { "original": {

View file

@ -39,7 +39,7 @@
inputs.hyprutils.overlays.default inputs.hyprutils.overlays.default
(final: prev: { (final: prev: {
hyprlang = final.callPackage ./nix/default.nix { hyprlang = final.callPackage ./nix/default.nix {
stdenv = final.gcc13Stdenv; stdenv = final.gcc14Stdenv;
version = version + "+date=" + (mkDate (self.lastModifiedDate or "19700101")) + "_" + (self.shortRev or "dirty"); version = version + "+date=" + (mkDate (self.lastModifiedDate or "19700101")) + "_" + (self.shortRev or "dirty");
}; };
hyprlang-with-tests = final.hyprlang.override {doCheck = true;}; hyprlang-with-tests = final.hyprlang.override {doCheck = true;};

View file

@ -3,11 +3,13 @@
#ifndef HYPRLANG_HPP #ifndef HYPRLANG_HPP
#define HYPRLANG_HPP #define HYPRLANG_HPP
#include <typeindex>
#include <any> #include <any>
#include <memory>
#include <string> #include <string>
#include <fstream> #include <ostream>
#include <vector> #include <vector>
#include <print>
#include <cstdlib>
class CConfigImpl; class CConfigImpl;
struct SConfigDefaultValue; struct SConfigDefaultValue;
@ -48,7 +50,7 @@ namespace Hyprlang {
typedef CConfigCustomValueType CUSTOMTYPE; typedef CConfigCustomValueType CUSTOMTYPE;
/*! /*!
A very simple vector type A very simple vector type
*/ */
struct SVector2D { struct SVector2D {
float x = 0, y = 0; float x = 0, y = 0;
@ -93,12 +95,12 @@ namespace Hyprlang {
Generic struct for options for the config parser Generic struct for options for the config parser
*/ */
struct SConfigOptions { struct SConfigOptions {
/*! /*!
Don't throw errors on missing values. Don't throw errors on missing values.
*/ */
int verifyOnly = false; int verifyOnly = false;
/*! /*!
Return all errors instead of just the first Return all errors instead of just the first
*/ */
int throwAllErrors = false; int throwAllErrors = false;
@ -173,11 +175,11 @@ namespace Hyprlang {
typedef void (*PCONFIGCUSTOMVALUEDESTRUCTOR)(void** data); typedef void (*PCONFIGCUSTOMVALUEDESTRUCTOR)(void** data);
/*! /*!
Container for a custom config value type Container for a custom config value type
When creating, pass your handler. When creating, pass your handler.
Handler will receive a void** that points to a void* that you can set to your own Handler will receive a void** that points to a void* that you can set to your own
thing. Pass a dtor to free whatever you allocated when the custom value type is being released. thing. Pass a dtor to free whatever you allocated when the custom value type is being released.
data may always be pointing to a nullptr. data may always be pointing to a nullptr.
*/ */
class CConfigCustomValueType { class CConfigCustomValueType {
public: public:
@ -252,7 +254,7 @@ namespace Hyprlang {
/*! /*!
Get the contained value as an std::any. Get the contained value as an std::any.
For strings, this is a const char*. For strings, this is a const char*.
For custom data types, this is a CConfigCustomValueType*. For custom data types, this is a void* representing the data ptr stored by it.
*/ */
std::any getValue() const { std::any getValue() const {
switch (m_eType) { switch (m_eType) {
@ -269,7 +271,7 @@ namespace Hyprlang {
/*! /*!
\since 0.3.0 \since 0.3.0
a flag to notify whether this value has been set explicitly by the user, a flag to notify whether this value has been set explicitly by the user,
or not. or not.
*/ */
@ -303,7 +305,7 @@ namespace Hyprlang {
~CConfig(); ~CConfig();
/*! /*!
Add a config value, for example myCategory:myValue. Add a config value, for example myCategory:myValue.
This has to be done before commence() This has to be done before commence()
Value provided becomes default. Value provided becomes default.
*/ */
@ -317,8 +319,8 @@ namespace Hyprlang {
/*! /*!
\since 0.3.0 \since 0.3.0
Unregister a handler. Unregister a handler.
*/ */
void unregisterHandler(const char* name); void unregisterHandler(const char* name);
@ -360,14 +362,14 @@ namespace Hyprlang {
CParseResult parse(); CParseResult parse();
/*! /*!
Same as parse(), but parse a specific file, without any refreshing. Same as parse(), but parse a specific file, without any refreshing.
recommended to use for stuff like source = path.conf recommended to use for stuff like source = path.conf
*/ */
CParseResult parseFile(const char* file); CParseResult parseFile(const char* file);
/*! /*!
Parse a single "line", dynamically. Parse a single "line", dynamically.
Values set by this are temporary and will be overwritten Values set by this are temporary and will be overwritten
by default / config on the next parse() by default / config on the next parse()
*/ */
CParseResult parseDynamic(const char* line); CParseResult parseDynamic(const char* line);
@ -375,14 +377,14 @@ namespace Hyprlang {
/*! /*!
Get a config's value ptr. These are static. Get a config's value ptr. These are static.
nullptr on fail nullptr on fail
*/ */
CConfigValue* getConfigValuePtr(const char* name); CConfigValue* getConfigValuePtr(const char* name);
/*! /*!
Get a special category's config value ptr. These are only static for static (key-less) Get a special category's config value ptr. These are only static for static (key-less)
categories. categories.
key can be nullptr for static categories. Cannot be nullptr for id-based categories. key can be nullptr for static categories. Cannot be nullptr for id-based categories.
nullptr on fail. nullptr on fail.
*/ */
CConfigValue* getSpecialConfigValuePtr(const char* category, const char* name, const char* key = nullptr); CConfigValue* getSpecialConfigValuePtr(const char* category, const char* name, const char* key = nullptr);
@ -452,10 +454,91 @@ namespace Hyprlang {
void retrieveKeysForCat(const char* category, const char*** out, size_t* len); void retrieveKeysForCat(const char* category, const char*** out, size_t* len);
CParseResult parseRawStream(const std::string& stream); CParseResult parseRawStream(const std::string& stream);
}; };
/*!
Templated wrapper for Hyprlang values. Much more straightforward to use.
\since 0.6.0
*/
template <typename T>
class CSimpleConfigValue {
public:
CSimpleConfigValue(CConfig* const pConfig, const char* val) {
const auto VAL = pConfig->getConfigValuePtr(val);
if (!VAL) {
std::println("CSimpleConfigValue: value not found");
abort();
}
// NOLINTNEXTLINE
p_ = VAL->getDataStaticPtr();
#ifdef HYPRLAND_DEBUG
// verify type
const auto ANY = VAL->getValue();
const auto TYPE = std::type_index(ANY.type());
// exceptions
const bool STRINGEX = (typeid(T) == typeid(std::string) && TYPE == typeid(Hyprlang::STRING));
const bool CUSTOMEX = (typeid(T) == typeid(Hyprlang::CUSTOMTYPE) && (TYPE == typeid(Hyprlang::CUSTOMTYPE*) || TYPE == typeid(void*) /* dunno why it does this? */));
if (typeid(T) != TYPE && !STRINGEX && !CUSTOMEX) {
std::println("CSimpleConfigValue: Mismatched type in CConfigValue<T>, got {} but has {}", typeid(T).name(), TYPE.name());
abort();
}
#endif
}
T* ptr() const {
return *(T* const*)p_;
}
T operator*() const {
return *ptr();
}
private:
void* const* p_ = nullptr;
};
template <>
inline std::string* CSimpleConfigValue<std::string>::ptr() const {
std::print("Impossible to implement ptr() of CConfigValue<std::string>");
abort();
return nullptr;
}
template <>
inline std::string CSimpleConfigValue<std::string>::operator*() const {
return std::string{*(Hyprlang::STRING*)p_};
}
template <>
inline Hyprlang::STRING* CSimpleConfigValue<Hyprlang::STRING>::ptr() const {
return (Hyprlang::STRING*)p_;
}
template <>
inline Hyprlang::STRING CSimpleConfigValue<Hyprlang::STRING>::operator*() const {
return *(Hyprlang::STRING*)p_;
}
template <>
inline Hyprlang::CUSTOMTYPE* CSimpleConfigValue<Hyprlang::CUSTOMTYPE>::ptr() const {
return *(Hyprlang::CUSTOMTYPE* const*)p_;
}
template <>
inline Hyprlang::CUSTOMTYPE CSimpleConfigValue<Hyprlang::CUSTOMTYPE>::operator*() const {
std::print("Impossible to implement operator* of CConfigValue<Hyprlang::CUSTOMTYPE>, use ptr()");
abort();
return *ptr();
}
}; };
#ifndef HYPRLANG_INTERNAL #ifndef HYPRLANG_INTERNAL
#undef HYPRLANG_END_MAGIC #undef HYPRLANG_END_MAGIC
#endif #endif
#endif #endif

View file

@ -1,6 +1,6 @@
#include "public.hpp" #include "public.hpp"
#include "config.hpp" #include "config.hpp"
#include <string.h> #include <cstring>
using namespace Hyprlang; using namespace Hyprlang;
@ -30,38 +30,28 @@ CConfigValue::~CConfigValue() {
} }
} }
CConfigValue::CConfigValue(const int64_t value) { CConfigValue::CConfigValue(const int64_t value) : m_eType(CONFIGDATATYPE_INT), m_pData(new int64_t) {
m_pData = new int64_t;
*reinterpret_cast<int64_t*>(m_pData) = value; *reinterpret_cast<int64_t*>(m_pData) = value;
m_eType = CONFIGDATATYPE_INT;
} }
CConfigValue::CConfigValue(const float value) { CConfigValue::CConfigValue(const float value) : m_eType(CONFIGDATATYPE_FLOAT), m_pData(new float) {
m_pData = new float;
*reinterpret_cast<float*>(m_pData) = value; *reinterpret_cast<float*>(m_pData) = value;
m_eType = CONFIGDATATYPE_FLOAT;
} }
CConfigValue::CConfigValue(const SVector2D value) { CConfigValue::CConfigValue(const SVector2D value) : m_eType(CONFIGDATATYPE_VEC2), m_pData(new SVector2D) {
m_pData = new SVector2D;
*reinterpret_cast<SVector2D*>(m_pData) = value; *reinterpret_cast<SVector2D*>(m_pData) = value;
m_eType = CONFIGDATATYPE_VEC2;
} }
CConfigValue::CConfigValue(const char* value) { CConfigValue::CConfigValue(const char* value) : m_eType(CONFIGDATATYPE_STR), m_pData(new char[strlen(value) + 1]) {
m_pData = new char[strlen(value) + 1];
strncpy((char*)m_pData, value, strlen(value)); strncpy((char*)m_pData, value, strlen(value));
((char*)m_pData)[strlen(value)] = '\0'; ((char*)m_pData)[strlen(value)] = '\0';
m_eType = CONFIGDATATYPE_STR;
} }
CConfigValue::CConfigValue(CConfigCustomValueType&& value) { CConfigValue::CConfigValue(CConfigCustomValueType&& value) : m_eType(CONFIGDATATYPE_CUSTOM), m_pData(new CConfigCustomValueType(value)) {
m_pData = new CConfigCustomValueType(value); ;
m_eType = CONFIGDATATYPE_CUSTOM;
} }
CConfigValue::CConfigValue(const CConfigValue& other) { CConfigValue::CConfigValue(const CConfigValue& other) : m_eType(other.m_eType) {
m_eType = other.m_eType;
setFrom(&other); setFrom(&other);
} }
@ -77,11 +67,9 @@ void* const* CConfigValue::getDataStaticPtr() const {
return &m_pData; return &m_pData;
} }
CConfigCustomValueType::CConfigCustomValueType(PCONFIGCUSTOMVALUEHANDLERFUNC handler_, PCONFIGCUSTOMVALUEDESTRUCTOR dtor_, const char* def) { CConfigCustomValueType::CConfigCustomValueType(PCONFIGCUSTOMVALUEHANDLERFUNC handler_, PCONFIGCUSTOMVALUEDESTRUCTOR dtor_, const char* def) :
handler = handler_; handler(handler_), dtor(dtor_), defaultVal(def), lastVal(def) {
dtor = dtor_; ;
defaultVal = def;
lastVal = def;
} }
CConfigCustomValueType::~CConfigCustomValueType() { CConfigCustomValueType::~CConfigCustomValueType() {
@ -216,4 +204,4 @@ void CConfigValue::setFrom(std::any ref) {
throw "bad defaultFrom type"; throw "bad defaultFrom type";
} }
} }
} }

View file

@ -12,6 +12,7 @@
#include <cstring> #include <cstring>
#include <hyprutils/string/VarList.hpp> #include <hyprutils/string/VarList.hpp>
#include <hyprutils/string/String.hpp> #include <hyprutils/string/String.hpp>
#include <hyprutils/string/ConstVarList.hpp>
using namespace Hyprlang; using namespace Hyprlang;
using namespace Hyprutils::String; using namespace Hyprutils::String;
@ -20,28 +21,51 @@ using namespace Hyprutils::String;
#include <crt_externs.h> #include <crt_externs.h>
#define environ (*_NSGetEnviron()) #define environ (*_NSGetEnviron())
#else #else
// NOLINTNEXTLINE
extern "C" char** environ; extern "C" char** environ;
#endif #endif
// defines // defines
inline constexpr const char* ANONYMOUS_KEY = "__hyprlang_internal_anonymous_key"; inline constexpr const char* ANONYMOUS_KEY = "__hyprlang_internal_anonymous_key";
inline constexpr const char* MULTILINE_SPACE_CHARSET = " \t";
// //
static size_t seekABIStructSize(const void* begin, size_t startOffset, size_t maxSize) { static size_t seekABIStructSize(const void* begin, size_t startOffset, size_t maxSize) {
for (size_t off = startOffset; off < maxSize; off += 4) { for (size_t off = startOffset; off < maxSize; off += 4) {
if (*(int*)((unsigned char*)begin + off) == int{HYPRLANG_END_MAGIC}) if (*(int*)((unsigned char*)begin + off) == HYPRLANG_END_MAGIC)
return off; return off;
} }
return 0; return 0;
} }
CConfig::CConfig(const char* path, const Hyprlang::SConfigOptions& options_) { static std::expected<std::string, eGetNextLineFailure> getNextLine(std::istream& str, int& rawLineNum, int& lineNum) {
std::string line = "";
std::string nextLine = "";
if (!std::getline(str, line))
return std::unexpected(GETNEXTLINEFAILURE_EOF);
lineNum = ++rawLineNum;
while (line.length() > 0 && line.at(line.length() - 1) == '\\') {
const auto lastNonSpace = line.length() < 2 ? -1 : line.find_last_not_of(MULTILINE_SPACE_CHARSET, line.length() - 2);
line = line.substr(0, lastNonSpace + 1);
if (!std::getline(str, nextLine))
return std::unexpected(GETNEXTLINEFAILURE_BACKSLASH);
++rawLineNum;
line += nextLine;
}
return line;
}
CConfig::CConfig(const char* path, const Hyprlang::SConfigOptions& options_) : impl(new CConfigImpl) {
SConfigOptions options; SConfigOptions options;
std::memcpy(&options, &options_, seekABIStructSize(&options_, 16, sizeof(SConfigOptions))); std::memcpy(&options, &options_, seekABIStructSize(&options_, 16, sizeof(SConfigOptions)));
impl = new CConfigImpl;
if (options.pathIsStream) if (options.pathIsStream)
impl->rawConfigString = path; impl->rawConfigString = path;
else else
@ -60,7 +84,7 @@ CConfig::CConfig(const char* path, const Hyprlang::SConfigOptions& options_) {
impl->envVariables.push_back({VARIABLE, VALUE}); impl->envVariables.push_back({VARIABLE, VALUE});
} }
std::sort(impl->envVariables.begin(), impl->envVariables.end(), [&](const auto& a, const auto& b) { return a.name.length() > b.name.length(); }); std::ranges::sort(impl->envVariables, [&](const auto& a, const auto& b) { return a.name.length() > b.name.length(); });
impl->configOptions = options; impl->configOptions = options;
} }
@ -74,40 +98,42 @@ void CConfig::addConfigValue(const char* name, const CConfigValue& value) {
throw "Cannot addConfigValue after commence()"; throw "Cannot addConfigValue after commence()";
if ((eDataType)value.m_eType != CONFIGDATATYPE_CUSTOM && (eDataType)value.m_eType != CONFIGDATATYPE_STR) if ((eDataType)value.m_eType != CONFIGDATATYPE_CUSTOM && (eDataType)value.m_eType != CONFIGDATATYPE_STR)
impl->defaultValues.emplace(name, SConfigDefaultValue{value.getValue(), (eDataType)value.m_eType}); impl->defaultValues.emplace(name, SConfigDefaultValue{.data = value.getValue(), .type = (eDataType)value.m_eType});
else if ((eDataType)value.m_eType == CONFIGDATATYPE_STR) else if ((eDataType)value.m_eType == CONFIGDATATYPE_STR)
impl->defaultValues.emplace(name, SConfigDefaultValue{std::string{std::any_cast<const char*>(value.getValue())}, (eDataType)value.m_eType}); impl->defaultValues.emplace(name, SConfigDefaultValue{.data = std::string{std::any_cast<const char*>(value.getValue())}, .type = (eDataType)value.m_eType});
else else
impl->defaultValues.emplace(name, impl->defaultValues.emplace(name,
SConfigDefaultValue{reinterpret_cast<CConfigCustomValueType*>(value.m_pData)->defaultVal, (eDataType)value.m_eType, SConfigDefaultValue{.data = reinterpret_cast<CConfigCustomValueType*>(value.m_pData)->defaultVal,
reinterpret_cast<CConfigCustomValueType*>(value.m_pData)->handler, .type = (eDataType)value.m_eType,
reinterpret_cast<CConfigCustomValueType*>(value.m_pData)->dtor}); .handler = reinterpret_cast<CConfigCustomValueType*>(value.m_pData)->handler,
.dtor = reinterpret_cast<CConfigCustomValueType*>(value.m_pData)->dtor});
} }
void CConfig::addSpecialConfigValue(const char* cat, const char* name, const CConfigValue& value) { void CConfig::addSpecialConfigValue(const char* cat, const char* name, const CConfigValue& value) {
const auto IT = std::find_if(impl->specialCategoryDescriptors.begin(), impl->specialCategoryDescriptors.end(), [&](const auto& other) { return other->name == cat; }); const auto IT = std::ranges::find_if(impl->specialCategoryDescriptors, [&](const auto& other) { return other->name == cat; });
if (IT == impl->specialCategoryDescriptors.end()) if (IT == impl->specialCategoryDescriptors.end())
throw "No such category"; throw "No such category";
if ((eDataType)value.m_eType != CONFIGDATATYPE_CUSTOM && (eDataType)value.m_eType != CONFIGDATATYPE_STR) if ((eDataType)value.m_eType != CONFIGDATATYPE_CUSTOM && (eDataType)value.m_eType != CONFIGDATATYPE_STR)
IT->get()->defaultValues.emplace(name, SConfigDefaultValue{value.getValue(), (eDataType)value.m_eType}); IT->get()->defaultValues.emplace(name, SConfigDefaultValue{.data = value.getValue(), .type = (eDataType)value.m_eType});
else if ((eDataType)value.m_eType == CONFIGDATATYPE_STR) else if ((eDataType)value.m_eType == CONFIGDATATYPE_STR)
IT->get()->defaultValues.emplace(name, SConfigDefaultValue{std::string{std::any_cast<const char*>(value.getValue())}, (eDataType)value.m_eType}); IT->get()->defaultValues.emplace(name, SConfigDefaultValue{.data = std::string{std::any_cast<const char*>(value.getValue())}, .type = (eDataType)value.m_eType});
else else
IT->get()->defaultValues.emplace(name, IT->get()->defaultValues.emplace(name,
SConfigDefaultValue{reinterpret_cast<CConfigCustomValueType*>(value.m_pData)->defaultVal, (eDataType)value.m_eType, SConfigDefaultValue{.data = reinterpret_cast<CConfigCustomValueType*>(value.m_pData)->defaultVal,
reinterpret_cast<CConfigCustomValueType*>(value.m_pData)->handler, .type = (eDataType)value.m_eType,
reinterpret_cast<CConfigCustomValueType*>(value.m_pData)->dtor}); .handler = reinterpret_cast<CConfigCustomValueType*>(value.m_pData)->handler,
.dtor = reinterpret_cast<CConfigCustomValueType*>(value.m_pData)->dtor});
const auto CAT = std::find_if(impl->specialCategories.begin(), impl->specialCategories.end(), [cat, name](const auto& other) { return other->name == cat && other->isStatic; }); const auto CAT = std::ranges::find_if(impl->specialCategories, [cat](const auto& other) { return other->name == cat && other->isStatic; });
if (CAT != impl->specialCategories.end()) if (CAT != impl->specialCategories.end())
CAT->get()->values[name].defaultFrom(IT->get()->defaultValues[name]); CAT->get()->values[name].defaultFrom(IT->get()->defaultValues[name]);
} }
void CConfig::removeSpecialConfigValue(const char* cat, const char* name) { void CConfig::removeSpecialConfigValue(const char* cat, const char* name) {
const auto IT = std::find_if(impl->specialCategoryDescriptors.begin(), impl->specialCategoryDescriptors.end(), [&](const auto& other) { return other->name == cat; }); const auto IT = std::ranges::find_if(impl->specialCategoryDescriptors, [&](const auto& other) { return other->name == cat; });
if (IT == impl->specialCategoryDescriptors.end()) if (IT == impl->specialCategoryDescriptors.end())
throw "No such category"; throw "No such category";
@ -138,9 +164,8 @@ void CConfig::addSpecialCategory(const char* name, SSpecialCategoryOptions optio
} }
// sort longest to shortest // sort longest to shortest
std::sort(impl->specialCategories.begin(), impl->specialCategories.end(), [](const auto& a, const auto& b) -> int { return a->name.length() > b->name.length(); }); std::ranges::sort(impl->specialCategories, [](const auto& a, const auto& b) -> int { return a->name.length() > b->name.length(); });
std::sort(impl->specialCategoryDescriptors.begin(), impl->specialCategoryDescriptors.end(), std::ranges::sort(impl->specialCategoryDescriptors, [](const auto& a, const auto& b) -> int { return a->name.length() > b->name.length(); });
[](const auto& a, const auto& b) -> int { return a->name.length() > b->name.length(); });
} }
void CConfig::removeSpecialCategory(const char* name) { void CConfig::removeSpecialCategory(const char* name) {
@ -195,7 +220,7 @@ static std::expected<int64_t, std::string> configStringToInt(const std::string&
if (!r.has_value() || !g.has_value() || !b.has_value()) if (!r.has_value() || !g.has_value() || !b.has_value())
return std::unexpected("failed parsing " + VALUEWITHOUTFUNC); return std::unexpected("failed parsing " + VALUEWITHOUTFUNC);
return a * (Hyprlang::INT)0x1000000 + r.value() * (Hyprlang::INT)0x10000 + g.value() * (Hyprlang::INT)0x100 + b.value(); return (a * (Hyprlang::INT)0x1000000) + (r.value() * (Hyprlang::INT)0x10000) + (g.value() * (Hyprlang::INT)0x100) + b.value();
} else if (VALUEWITHOUTFUNC.length() == 8) { } else if (VALUEWITHOUTFUNC.length() == 8) {
const auto RGBA = parseHex(VALUEWITHOUTFUNC); const auto RGBA = parseHex(VALUEWITHOUTFUNC);
@ -203,7 +228,7 @@ static std::expected<int64_t, std::string> configStringToInt(const std::string&
return RGBA; return RGBA;
// now we need to RGBA -> ARGB. The config holds ARGB only. // now we need to RGBA -> ARGB. The config holds ARGB only.
return (RGBA.value() >> 8) + 0x1000000 * (RGBA.value() & 0xFF); return (RGBA.value() >> 8) + (0x1000000 * (RGBA.value() & 0xFF));
} }
return std::unexpected("rgba() expects length of 8 characters (4 bytes) or 4 comma separated values"); return std::unexpected("rgba() expects length of 8 characters (4 bytes) or 4 comma separated values");
@ -224,7 +249,7 @@ static std::expected<int64_t, std::string> configStringToInt(const std::string&
if (!r.has_value() || !g.has_value() || !b.has_value()) if (!r.has_value() || !g.has_value() || !b.has_value())
return std::unexpected("failed parsing " + VALUEWITHOUTFUNC); return std::unexpected("failed parsing " + VALUEWITHOUTFUNC);
return (Hyprlang::INT)0xFF000000 + r.value() * (Hyprlang::INT)0x10000 + g.value() * (Hyprlang::INT)0x100 + b.value(); return (Hyprlang::INT)0xFF000000 + (r.value() * (Hyprlang::INT)0x10000) + (g.value() * (Hyprlang::INT)0x100) + b.value();
} else if (VALUEWITHOUTFUNC.length() == 6) { } else if (VALUEWITHOUTFUNC.length() == 6) {
const auto RGB = parseHex(VALUEWITHOUTFUNC); const auto RGB = parseHex(VALUEWITHOUTFUNC);
@ -357,8 +382,7 @@ CParseResult CConfig::configSetValueSafe(const std::string& command, const std::
// find suitable key // find suitable key
size_t biggest = 0; size_t biggest = 0;
for (auto& catt : impl->specialCategories) { for (auto& catt : impl->specialCategories) {
if (catt->anonymousID > biggest) biggest = std::max(catt->anonymousID, biggest);
biggest = catt->anonymousID;
} }
biggest++; biggest++;
@ -417,7 +441,7 @@ CParseResult CConfig::configSetValueSafe(const std::string& command, const std::
if (LHS.contains(" ") || RHS.contains(" ")) if (LHS.contains(" ") || RHS.contains(" "))
throw std::runtime_error("too many args"); throw std::runtime_error("too many args");
VALUEIT->second.setFrom(SVector2D{std::stof(LHS), std::stof(RHS)}); VALUEIT->second.setFrom(SVector2D{.x = std::stof(LHS), .y = std::stof(RHS)});
} catch (std::exception& e) { } catch (std::exception& e) {
result.setError(std::format("failed parsing a vec2: {}", e.what())); result.setError(std::format("failed parsing a vec2: {}", e.what()));
return result; return result;
@ -451,14 +475,14 @@ CParseResult CConfig::configSetValueSafe(const std::string& command, const std::
} }
CParseResult CConfig::parseVariable(const std::string& lhs, const std::string& rhs, bool dynamic) { CParseResult CConfig::parseVariable(const std::string& lhs, const std::string& rhs, bool dynamic) {
auto IT = std::find_if(impl->variables.begin(), impl->variables.end(), [&](const auto& v) { return v.name == lhs.substr(1); }); auto IT = std::ranges::find_if(impl->variables, [&](const auto& v) { return v.name == lhs.substr(1); });
if (IT != impl->variables.end()) if (IT != impl->variables.end())
IT->value = rhs; IT->value = rhs;
else { else {
impl->variables.push_back({lhs.substr(1), rhs}); impl->variables.push_back({lhs.substr(1), rhs});
std::sort(impl->variables.begin(), impl->variables.end(), [](const auto& lhs, const auto& rhs) { return lhs.name.length() > rhs.name.length(); }); std::ranges::sort(impl->variables, [](const auto& lhs, const auto& rhs) { return lhs.name.length() > rhs.name.length(); });
IT = std::find_if(impl->variables.begin(), impl->variables.end(), [&](const auto& v) { return v.name == lhs.substr(1); }); IT = std::ranges::find_if(impl->variables, [&](const auto& v) { return v.name == lhs.substr(1); });
} }
if (dynamic) { if (dynamic) {
@ -487,6 +511,56 @@ void CConfigImpl::parseComment(const std::string& comment) {
currentFlags.noError = args[2] == "true" || args[2] == "yes" || args[2] == "enable" || args[2] == "enabled" || args[2] == "set"; currentFlags.noError = args[2] == "true" || args[2] == "yes" || args[2] == "enable" || args[2] == "enabled" || args[2] == "set";
} }
std::expected<float, std::string> CConfigImpl::parseExpression(const std::string& s) {
// for now, we only support very basic expressions.
// + - * / and only one per $()
// TODO: something better
if (s.empty())
return std::unexpected("Expression is empty");
CConstVarList args(s, 0, 's', true);
if (args[1] != "+" && args[1] != "-" && args[1] != "*" && args[1] != "/")
return std::unexpected("Invalid expression type: supported +, -, *, /");
auto LHS_VAR = std::ranges::find_if(variables, [&](const auto& v) { return v.name == args[0]; });
auto RHS_VAR = std::ranges::find_if(variables, [&](const auto& v) { return v.name == args[2]; });
float left = 0;
float right = 0;
if (LHS_VAR != variables.end()) {
try {
left = std::stof(LHS_VAR->value);
} catch (...) { return std::unexpected("Failed to parse expression: value 1 holds a variable that does not look like a number"); }
} else {
try {
left = std::stof(std::string{args[0]});
} catch (...) { return std::unexpected("Failed to parse expression: value 1 does not look like a number or the variable doesn't exist"); }
}
if (RHS_VAR != variables.end()) {
try {
right = std::stof(RHS_VAR->value);
} catch (...) { return std::unexpected("Failed to parse expression: value 1 holds a variable that does not look like a number"); }
} else {
try {
right = std::stof(std::string{args[2]});
} catch (...) { return std::unexpected("Failed to parse expression: value 1 does not look like a number or the variable doesn't exist"); }
}
switch (args[1][0]) {
case '+': return left + right;
case '-': return left - right;
case '*': return left * right;
case '/': return left / right;
default: break;
}
return std::unexpected("Unknown error while parsing expression");
}
CParseResult CConfig::parseLine(std::string line, bool dynamic) { CParseResult CConfig::parseLine(std::string line, bool dynamic) {
CParseResult result; CParseResult result;
@ -548,6 +622,8 @@ CParseResult CConfig::parseLine(std::string line, bool dynamic) {
// limit unwrapping iterations to 100. if exceeds, raise error // limit unwrapping iterations to 100. if exceeds, raise error
for (size_t i = 0; i < 100; ++i) { for (size_t i = 0; i < 100; ++i) {
bool anyMatch = false; bool anyMatch = false;
// parse variables
for (auto& var : impl->variables) { for (auto& var : impl->variables) {
// don't parse LHS variables if this is a variable... // don't parse LHS variables if this is a variable...
const auto LHSIT = ISVARIABLE ? std::string::npos : LHS.find("$" + var.name); const auto LHSIT = ISVARIABLE ? std::string::npos : LHS.find("$" + var.name);
@ -566,6 +642,24 @@ CParseResult CConfig::parseLine(std::string line, bool dynamic) {
anyMatch = true; anyMatch = true;
} }
// parse expressions $(somevar + 2)
// We only support single expressions for now
while (RHS.contains("{{")) {
const auto BEGIN_EXPR = RHS.find("{{");
const auto END_EXPR = RHS.find("}}", BEGIN_EXPR + 2);
if (END_EXPR != std::string::npos) {
// try to parse the expression
const auto RESULT = impl->parseExpression(RHS.substr(BEGIN_EXPR + 2, END_EXPR - BEGIN_EXPR - 2));
if (!RESULT.has_value()) {
result.setError(RESULT.error());
return result;
}
RHS = RHS.substr(0, BEGIN_EXPR) + std::format("{}", RESULT.value()) + RHS.substr(END_EXPR + 2);
} else
break;
}
if (!anyMatch) if (!anyMatch)
break; break;
@ -593,7 +687,7 @@ CParseResult CConfig::parseLine(std::string line, bool dynamic) {
size_t idx = 0; size_t idx = 0;
size_t depth = 0; size_t depth = 0;
while ((colon = HANDLERNAME.find(":", idx)) != std::string::npos && impl->categories.size() > depth) { while ((colon = HANDLERNAME.find(':', idx)) != std::string::npos && impl->categories.size() > depth) {
auto actual = HANDLERNAME.substr(idx, colon - idx); auto actual = HANDLERNAME.substr(idx, colon - idx);
if (actual != impl->categories[depth]) if (actual != impl->categories[depth])
@ -695,22 +789,35 @@ CParseResult CConfig::parse() {
CParseResult CConfig::parseRawStream(const std::string& stream) { CParseResult CConfig::parseRawStream(const std::string& stream) {
CParseResult result; CParseResult result;
std::string line = ""; int rawLineNum = 0;
int linenum = 1; int lineNum = 0;
std::stringstream str(stream); std::stringstream str(stream);
while (std::getline(str, line)) { while (true) {
const auto RET = parseLine(line); const auto line = getNextLine(str, rawLineNum, lineNum);
if (!line) {
switch (line.error()) {
case GETNEXTLINEFAILURE_EOF: break;
case GETNEXTLINEFAILURE_BACKSLASH:
if (!impl->parseError.empty())
impl->parseError += "\n";
impl->parseError += std::format("Config error: Last line ends with backslash");
result.setError(impl->parseError);
break;
}
break;
}
const auto RET = parseLine(line.value());
if (RET.error && (impl->parseError.empty() || impl->configOptions.throwAllErrors)) { if (RET.error && (impl->parseError.empty() || impl->configOptions.throwAllErrors)) {
if (!impl->parseError.empty()) if (!impl->parseError.empty())
impl->parseError += "\n"; impl->parseError += "\n";
impl->parseError += std::format("Config error at line {}: {}", linenum, RET.errorStdString); impl->parseError += std::format("Config error at line {}: {}", lineNum, RET.errorStdString);
result.setError(impl->parseError); result.setError(impl->parseError);
} }
++linenum;
} }
if (!impl->categories.empty()) { if (!impl->categories.empty()) {
@ -736,21 +843,33 @@ CParseResult CConfig::parseFile(const char* file) {
return result; return result;
} }
std::string line = ""; int rawLineNum = 0;
int linenum = 1; int lineNum = 0;
while (std::getline(iffile, line)) { while (true) {
const auto line = getNextLine(iffile, rawLineNum, lineNum);
const auto RET = parseLine(line); if (!line) {
switch (line.error()) {
case GETNEXTLINEFAILURE_EOF: break;
case GETNEXTLINEFAILURE_BACKSLASH:
if (!impl->parseError.empty())
impl->parseError += "\n";
impl->parseError += std::format("Config error in file {}: Last line ends with backslash", file);
result.setError(impl->parseError);
break;
}
break;
}
const auto RET = parseLine(line.value());
if (!impl->currentFlags.noError && RET.error && (impl->parseError.empty() || impl->configOptions.throwAllErrors)) { if (!impl->currentFlags.noError && RET.error && (impl->parseError.empty() || impl->configOptions.throwAllErrors)) {
if (!impl->parseError.empty()) if (!impl->parseError.empty())
impl->parseError += "\n"; impl->parseError += "\n";
impl->parseError += std::format("Config error in file {} at line {}: {}", file, linenum, RET.errorStdString); impl->parseError += std::format("Config error in file {} at line {}: {}", file, lineNum, RET.errorStdString);
result.setError(impl->parseError); result.setError(impl->parseError);
} }
++linenum;
} }
iffile.close(); iffile.close();
@ -811,7 +930,7 @@ CConfigValue* CConfig::getSpecialConfigValuePtr(const char* category, const char
void CConfig::registerHandler(PCONFIGHANDLERFUNC func, const char* name, SHandlerOptions options_) { void CConfig::registerHandler(PCONFIGHANDLERFUNC func, const char* name, SHandlerOptions options_) {
SHandlerOptions options; SHandlerOptions options;
std::memcpy(&options, &options_, seekABIStructSize(&options_, 0, sizeof(SHandlerOptions))); std::memcpy(&options, &options_, seekABIStructSize(&options_, 0, sizeof(SHandlerOptions)));
impl->handlers.push_back(SHandler{name, options, func}); impl->handlers.push_back(SHandler{.name = name, .options = options, .func = func});
} }
void CConfig::unregisterHandler(const char* name) { void CConfig::unregisterHandler(const char* name) {

View file

@ -3,6 +3,8 @@
#include <unordered_map> #include <unordered_map>
#include <string> #include <string>
#include <vector> #include <vector>
#include <memory>
#include <expected>
struct SHandler { struct SHandler {
std::string name = ""; std::string name = "";
@ -64,6 +66,11 @@ struct SSpecialCategory {
size_t anonymousID = 0; size_t anonymousID = 0;
}; };
enum eGetNextLineFailure : uint8_t {
GETNEXTLINEFAILURE_EOF = 0,
GETNEXTLINEFAILURE_BACKSLASH,
};
class CConfigImpl { class CConfigImpl {
public: public:
std::string path = ""; std::string path = "";
@ -89,8 +96,9 @@ class CConfigImpl {
Hyprlang::SConfigOptions configOptions; Hyprlang::SConfigOptions configOptions;
void parseComment(const std::string& comment); void parseComment(const std::string& comment);
std::expected<float, std::string> parseExpression(const std::string& s);
struct { struct {
bool noError = false; bool noError = false;
} currentFlags; } currentFlags;
}; };

View file

@ -14,6 +14,9 @@ $MY_VAR = 1337
$MY_VAR_2 = $MY_VAR $MY_VAR_2 = $MY_VAR
testVar = $MY_VAR$MY_VAR_2 testVar = $MY_VAR$MY_VAR_2
$EXPR_VAR = {{MY_VAR + 2}}
testExpr = {{EXPR_VAR - 4}}
testEnv = $SHELL testEnv = $SHELL
source = ./colors.conf source = ./colors.conf
@ -90,6 +93,11 @@ flagsStuff {
value = 2 value = 2
} }
multiline = \
very \
long \
command
testCategory:testValueHex = 0xFFfFaAbB testCategory:testValueHex = 0xFFfFaAbB
$RECURSIVE1 = a $RECURSIVE1 = a
@ -103,4 +111,3 @@ doABarrelRoll = woohoo, some, params # Funny!
flagsabc = test flagsabc = test
#doSomethingFunny = 1, 2, 3, 4 # Funnier! #doSomethingFunny = 1, 2, 3, 4 # Funnier!
#testSpaces = abc , def # many spaces, should be trimmed #testSpaces = abc , def # many spaces, should be trimmed

View file

@ -0,0 +1,20 @@
# Careful when modifying this file. Line numbers are part of the test.
multiline = \
one \
two \
three
# Line numbers reported in errors should match the actual line numbers of the source file
# even after multi-line configs. Any errors reported should use the line number of the
# first line of any multi-line config.
this \
should \
cause \
error \
on \
line \
12
# A config file cannot end with a bashslash because we are expecting another line! Even in a comment! \

View file

@ -11,7 +11,7 @@ std::string garbage() {
std::string chars; std::string chars;
for (int i = 0; i < len; ++i) { for (int i = 0; i < len; ++i) {
chars += rand() % 254 + 1; chars += std::to_string((rand() % 254) + 1);
} }
return chars; return chars;

63
tests/parse/main.cpp Executable file → Normal file
View file

@ -48,7 +48,7 @@ static Hyprlang::CParseResult handleFlagsTest(const char* COMMAND, const char* V
} }
static Hyprlang::CParseResult handleCategoryKeyword(const char* COMMAND, const char* VALUE) { static Hyprlang::CParseResult handleCategoryKeyword(const char* COMMAND, const char* VALUE) {
categoryKeywordActualValues.push_back(VALUE); categoryKeywordActualValues.emplace_back(VALUE);
return Hyprlang::CParseResult(); return Hyprlang::CParseResult();
} }
@ -107,8 +107,9 @@ int main(int argc, char** argv, char** envp) {
// setup config // setup config
config.addConfigValue("testInt", (Hyprlang::INT)0); config.addConfigValue("testInt", (Hyprlang::INT)0);
config.addConfigValue("testExpr", (Hyprlang::INT)0);
config.addConfigValue("testFloat", 0.F); config.addConfigValue("testFloat", 0.F);
config.addConfigValue("testVec", Hyprlang::SVector2D{69, 420}); config.addConfigValue("testVec", Hyprlang::SVector2D{.x = 69, .y = 420});
config.addConfigValue("testString", ""); config.addConfigValue("testString", "");
config.addConfigValue("testStringColon", ""); config.addConfigValue("testStringColon", "");
config.addConfigValue("testEnv", ""); config.addConfigValue("testEnv", "");
@ -131,25 +132,27 @@ int main(int argc, char** argv, char** envp) {
config.addConfigValue("myColors:random", (Hyprlang::INT)0); config.addConfigValue("myColors:random", (Hyprlang::INT)0);
config.addConfigValue("customType", {Hyprlang::CConfigCustomValueType{&handleCustomValueSet, &handleCustomValueDestroy, "def"}}); config.addConfigValue("customType", {Hyprlang::CConfigCustomValueType{&handleCustomValueSet, &handleCustomValueDestroy, "def"}});
config.registerHandler(&handleDoABarrelRoll, "doABarrelRoll", {false}); config.registerHandler(&handleDoABarrelRoll, "doABarrelRoll", {.allowFlags = false});
config.registerHandler(&handleFlagsTest, "flags", {true}); config.registerHandler(&handleFlagsTest, "flags", {.allowFlags = true});
config.registerHandler(&handleSource, "source", {false}); config.registerHandler(&handleSource, "source", {.allowFlags = false});
config.registerHandler(&handleTestIgnoreKeyword, "testIgnoreKeyword", {false}); config.registerHandler(&handleTestIgnoreKeyword, "testIgnoreKeyword", {.allowFlags = false});
config.registerHandler(&handleTestUseKeyword, ":testUseKeyword", {false}); config.registerHandler(&handleTestUseKeyword, ":testUseKeyword", {.allowFlags = false});
config.registerHandler(&handleNoop, "testCategory:testUseKeyword", {false}); config.registerHandler(&handleNoop, "testCategory:testUseKeyword", {.allowFlags = false});
config.registerHandler(&handleCategoryKeyword, "testCategory:categoryKeyword", {false}); config.registerHandler(&handleCategoryKeyword, "testCategory:categoryKeyword", {.allowFlags = false});
config.addSpecialCategory("special", {"key"}); config.addSpecialCategory("special", {.key = "key"});
config.addSpecialConfigValue("special", "value", (Hyprlang::INT)0); config.addSpecialConfigValue("special", "value", (Hyprlang::INT)0);
config.addSpecialCategory("specialAnonymous", {nullptr, false, true}); config.addSpecialCategory("specialAnonymous", {.key = nullptr, .ignoreMissing = false, .anonymousKeyBased = true});
config.addSpecialConfigValue("specialAnonymous", "value", (Hyprlang::INT)0); config.addSpecialConfigValue("specialAnonymous", "value", (Hyprlang::INT)0);
config.addConfigValue("multiline", "");
config.commence(); config.commence();
config.addSpecialCategory("specialGeneric:one", {nullptr, true}); config.addSpecialCategory("specialGeneric:one", {.key = nullptr, .ignoreMissing = true});
config.addSpecialConfigValue("specialGeneric:one", "value", (Hyprlang::INT)0); config.addSpecialConfigValue("specialGeneric:one", "value", (Hyprlang::INT)0);
config.addSpecialCategory("specialGeneric:two", {nullptr, true}); config.addSpecialCategory("specialGeneric:two", {.key = nullptr, .ignoreMissing = true});
config.addSpecialConfigValue("specialGeneric:two", "value", (Hyprlang::INT)0); config.addSpecialConfigValue("specialGeneric:two", "value", (Hyprlang::INT)0);
const Hyprlang::CConfigValue copyTest = {(Hyprlang::INT)1}; const Hyprlang::CConfigValue copyTest = {(Hyprlang::INT)1};
@ -167,7 +170,7 @@ int main(int argc, char** argv, char** envp) {
std::cout << " → Testing values\n"; std::cout << " → Testing values\n";
EXPECT(std::any_cast<int64_t>(config.getConfigValue("testInt")), 123); EXPECT(std::any_cast<int64_t>(config.getConfigValue("testInt")), 123);
EXPECT(std::any_cast<float>(config.getConfigValue("testFloat")), 123.456f); EXPECT(std::any_cast<float>(config.getConfigValue("testFloat")), 123.456f);
auto EXP = Hyprlang::SVector2D{69, 420}; auto EXP = Hyprlang::SVector2D{.x = 69, .y = 420};
EXPECT(std::any_cast<Hyprlang::SVector2D>(config.getConfigValue("testVec")), EXP); EXPECT(std::any_cast<Hyprlang::SVector2D>(config.getConfigValue("testVec")), EXP);
EXPECT(std::any_cast<const char*>(config.getConfigValue("testString")), std::string{"Hello World! # This is not a comment!"}); EXPECT(std::any_cast<const char*>(config.getConfigValue("testString")), std::string{"Hello World! # This is not a comment!"});
EXPECT(std::any_cast<const char*>(config.getConfigValue("testStringQuotes")), std::string{"\"Hello World!\""}); EXPECT(std::any_cast<const char*>(config.getConfigValue("testStringQuotes")), std::string{"\"Hello World!\""});
@ -185,6 +188,20 @@ int main(int argc, char** argv, char** envp) {
EXPECT(ignoreKeyword, "aaa"); EXPECT(ignoreKeyword, "aaa");
EXPECT(useKeyword, "yes"); EXPECT(useKeyword, "yes");
// Test templated wrapper
auto T1 = Hyprlang::CSimpleConfigValue<Hyprlang::INT>(&config, "testInt");
auto T2 = Hyprlang::CSimpleConfigValue<Hyprlang::FLOAT>(&config, "testFloat");
auto T3 = Hyprlang::CSimpleConfigValue<Hyprlang::SVector2D>(&config, "testVec");
auto T4 = Hyprlang::CSimpleConfigValue<std::string>(&config, "testString");
EXPECT(*T1, 123);
EXPECT(*T2, 123.456F);
EXPECT(*T3, EXP);
EXPECT(*T4, "Hello World! # This is not a comment!");
// test expressions
std::cout << " → Testing expressions\n";
EXPECT(std::any_cast<int64_t>(config.getConfigValue("testExpr")), 1335);
// test static values // test static values
std::cout << " → Testing static values\n"; std::cout << " → Testing static values\n";
static auto* const PTESTINT = config.getConfigValuePtr("testInt")->getDataStaticPtr(); static auto* const PTESTINT = config.getConfigValuePtr("testInt")->getDataStaticPtr();
@ -231,6 +248,10 @@ int main(int argc, char** argv, char** envp) {
EXPECT(config.parseDynamic("$RECURSIVE1 = d").error, false); EXPECT(config.parseDynamic("$RECURSIVE1 = d").error, false);
EXPECT(std::any_cast<const char*>(config.getConfigValue("testStringRecursive")), std::string{"dbc"}); EXPECT(std::any_cast<const char*>(config.getConfigValue("testStringRecursive")), std::string{"dbc"});
// test dynamic exprs
EXPECT(config.parseDynamic("testExpr = {{EXPR_VAR * 2}}").error, false);
EXPECT(std::any_cast<int64_t>(config.getConfigValue("testExpr")), 1339L * 2);
// test env variables // test env variables
std::cout << " → Testing env variables\n"; std::cout << " → Testing env variables\n";
EXPECT(std::any_cast<const char*>(config.getConfigValue("testEnv")), std::string{getenv("SHELL")}); EXPECT(std::any_cast<const char*>(config.getConfigValue("testEnv")), std::string{getenv("SHELL")});
@ -269,6 +290,9 @@ int main(int argc, char** argv, char** envp) {
std::cout << " → Testing custom types\n"; std::cout << " → Testing custom types\n";
EXPECT(*reinterpret_cast<int64_t*>(std::any_cast<void*>(config.getConfigValue("customType"))), (Hyprlang::INT)1); EXPECT(*reinterpret_cast<int64_t*>(std::any_cast<void*>(config.getConfigValue("customType"))), (Hyprlang::INT)1);
// test multiline config
EXPECT(std::any_cast<const char*>(config.getConfigValue("multiline")), std::string{"very long command"});
std::cout << " → Testing error.conf\n"; std::cout << " → Testing error.conf\n";
Hyprlang::CConfig errorConfig("./config/error.conf", {.verifyOnly = true, .throwAllErrors = true}); Hyprlang::CConfig errorConfig("./config/error.conf", {.verifyOnly = true, .throwAllErrors = true});
@ -297,6 +321,17 @@ int main(int argc, char** argv, char** envp) {
EXPECT(ERRORS2.error, true); EXPECT(ERRORS2.error, true);
const auto ERRORSTR2 = std::string{ERRORS2.getError()}; const auto ERRORSTR2 = std::string{ERRORS2.getError()};
EXPECT(std::count(ERRORSTR2.begin(), ERRORSTR2.end(), '\n'), 9 - 1); EXPECT(std::count(ERRORSTR2.begin(), ERRORSTR2.end(), '\n'), 9 - 1);
Hyprlang::CConfig multilineErrorConfig("./config/multiline-errors.conf", {.verifyOnly = true, .throwAllErrors = true});
multilineErrorConfig.commence();
const auto ERRORS3 = multilineErrorConfig.parse();
EXPECT(ERRORS3.error, true);
const auto ERRORSTR3 = std::string{ERRORS3.getError()};
// Error on line 12
EXPECT(ERRORSTR3.contains("12"), true);
// Backslash at end of file
EXPECT(ERRORSTR3.contains("backslash"), true);
} catch (const char* e) { } catch (const char* e) {
std::cout << Colors::RED << "Error: " << Colors::RESET << e << "\n"; std::cout << Colors::RED << "Error: " << Colors::RESET << e << "\n";
return 1; return 1;