diff options
author | Robin Haberkorn <robin.haberkorn@googlemail.com> | 2021-05-30 02:38:43 +0200 |
---|---|---|
committer | Robin Haberkorn <robin.haberkorn@googlemail.com> | 2021-05-30 03:12:56 +0200 |
commit | 432ad24e382681f1c13b07e8486e91063dd96e2e (patch) | |
tree | 51838adac822767bd5884b9383cd4c72f29d3840 /src/undo.h | |
parent | 524bc3960e6a6e5645ce904e20f72479e24e0a23 (diff) | |
download | sciteco-432ad24e382681f1c13b07e8486e91063dd96e2e.tar.gz |
THE GREAT CEEIFICATION EVENT
This is a total conversion of SciTECO to plain C (GNU C11).
The chance was taken to improve a lot of internal datastructures,
fix fundamental bugs and lay the foundations of future features.
The GTK user interface is now in an useable state!
All changes have been squashed together.
The language itself has almost not changed at all, except for:
* Detection of string terminators (usually Escape) now takes
the string building characters into account.
A string is only terminated outside of string building characters.
In other words, you can now for instance write
I^EQ[Hello$world]$
This removes one of the last bits of shellisms which is out of
place in SciTECO where no tokenization/lexing is performed.
Consequently, the current termination character can also be
escaped using ^Q/^R.
This is used by auto completions to make sure that strings
are inserted verbatim and without unwanted sideeffects.
* All strings can now safely contain null-characters
(see also: 8-bit cleanliness).
The null-character itself (^@) is not (yet) a valid SciTECO
command, though.
An incomplete list of changes:
* We got rid of the BSD headers for RB trees and lists/queues.
The problem with them was that they used a form of metaprogramming
only to gain a bit of type safety. It also resulted in less
readble code. This was a C++ desease.
The new code avoids metaprogramming only to gain type safety.
The BSD tree.h has been replaced by rb3ptr by Jens Stimpfle
(https://github.com/jstimpfle/rb3ptr).
This implementation is also more memory efficient than BSD's.
The BSD list.h and queue.h has been replaced with a custom
src/list.h.
* Fixed crashes, performance issues and compatibility issues with
the Gtk 3 User Interface.
It is now more or less ready for general use.
The GDK lock is no longer used to avoid using deprecated functions.
On the downside, the new implementation (driving the Gtk event loop
stepwise) is even slower than the old one.
A few glitches remain (see TODO), but it is hoped that they will
be resolved by the Scintilla update which will be performed soon.
* A lot of program units have been split up, so they are shorter
and easier to maintain: core-commands.c, qreg-commands.c,
goto-commands.c, file-utils.h.
* Parser states are simply structs of callbacks now.
They still use a kind of polymorphy using a preprocessor trick.
TECO_DEFINE_STATE() takes an initializer list that will be
merged with the default list of field initializers.
To "subclass" states, you can simply define new macros that add
initializers to existing macros.
* Parsers no longer have a "transitions" table but the input_cb()
may use switch-case statements.
There are also teco_machine_main_transition_t now which can
be used to implement simple transitions. Additionally, you
can specify functions to execute during transitions.
This largely avoids long switch-case-statements.
* Parsers are embeddable/reusable now, at least in parse-only mode.
This does not currently bring any advantages but may later
be used to write a Scintilla lexer for TECO syntax highlighting.
Once parsers are fully embeddable, it will also be possible
to run TECO macros in a kind of coroutine which would allow
them to process string arguments in real time.
* undo.[ch] still uses metaprogramming extensively but via
the C preprocessor of course. On the downside, most undo
token generators must be initiated explicitly (theoretically
we could have used embedded functions / trampolines to
instantiate automatically but this has turned out to be
dangereous).
There is a TECO_DEFINE_UNDO_CALL() to generate closures for
arbitrary functions now (ie. to call an arbitrary function
at undo-time). This simplified a lot of code and is much
shorter than manually pushing undo tokens in many cases.
* Instead of the ridiculous C++ Curiously Recurring Template
Pattern to achieve static polymorphy for user interface
implementations, we now simply declare all functions to
implement in interface.h and link in the implementations.
This is possible since we no longer hace to define
interface subclasses (all state is static variables in
the interface's *.c files).
* Headers are now significantly shorter than in C++ since
we can often hide more of our "class" implementations.
* Memory counting is based on dlmalloc for most platforms now.
Unfortunately, there is no malloc implementation that
provides an efficient constant-time memory counter that
is guaranteed to decrease when freeing memory.
But since we use a defined malloc implementation now,
malloc_usable_size() can be used safely for tracking memory use.
malloc() replacement is very tricky on Windows, so we
use a poll thread on Windows. This can also be enabled
on other supported platforms using --disable-malloc-replacement.
All in all, I'm still not pleased with the state of memory
limiting. It is a mess.
* Error handling uses GError now. This has the advantage that
the GError codes can be reused once we support error catching
in the SciTECO language.
* Added a few more test suite cases.
* Haiku is no longer supported as builds are instable and
I did not manage to debug them - quite possibly Haiku bugs
were responsible.
* Glib v2.44 or later are now required.
The GTK UI requires Gtk+ v3.12 or later now.
The GtkFlowBox fallback and sciteco-wrapper workaround are
no longer required.
* We now extensively use the GCC/Clang-specific g_auto
feature (automatic deallocations when leaving the current
code block).
* Updated copyright to 2021.
SciTECO has been in continuous development, even though there
have been no commits since 2018.
* Since these changes are so significant, the target release has
been set to v2.0.
It is planned that beginning with v3.0, the language will be
kept stable.
Diffstat (limited to 'src/undo.h')
-rw-r--r-- | src/undo.h | 399 |
1 files changed, 203 insertions, 196 deletions
@@ -1,5 +1,5 @@ /* - * Copyright (C) 2012-2017 Robin Haberkorn + * Copyright (C) 2012-2021 Robin Haberkorn * * 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 @@ -14,227 +14,234 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ - -#ifndef __UNDO_H -#define __UNDO_H - -#include <string.h> - -#include <bsd/sys/queue.h> +#pragma once #include <glib.h> -#include <glib/gprintf.h> -#include "memory.h" +#include "sciteco.h" -#ifdef DEBUG -#include "parser.h" -#endif - -namespace SciTECO { +extern gboolean teco_undo_enabled; /** - * Undo tokens are generated to revert any - * changes to the editor state, ie. they - * define an action to take upon rubout. + * A callback to be invoked when an undo token gets executed or cleaned up. + * + * @note Unless you want to cast user_data in every callback implementation, + * you may want to cast your callback type instead to teco_undo_action_t. + * Casting to functions of different signature is theoretically undefined behavior, + * but works on all major platforms including Emscripten, as long as they differ only + * in pointer types. * - * Undo tokens are organized into an undo - * stack. + * @param user_data + * The data allocated by teco_undo_push_size() (usually a context structure). + * You are supposed to free any external resources (heap pointers etc.) referenced + * from it till the end of the callback. + * @param run + * Whether the operation should actually be performed instead of merely freeing + * the associated memory. */ -class UndoToken : public Object { -public: - SLIST_ENTRY(UndoToken) tokens; - - virtual ~UndoToken() {} - - virtual void run(void) = 0; -}; - -template <typename Type> -class UndoTokenVariable : public UndoToken { - Type *ptr; - Type value; - -public: - UndoTokenVariable(Type &variable, Type _value) - : ptr(&variable), value(_value) {} - - void - run(void) - { -#ifdef DEBUG - if ((State **)ptr == &States::current) - g_printf("undo state -> %p\n", (void *)value); -#endif - *ptr = value; - } -}; +typedef void (*teco_undo_action_t)(gpointer user_data, gboolean run); -class UndoTokenString : public UndoToken { - gchar **ptr; - gchar *str; +gpointer teco_undo_push_size(teco_undo_action_t action_cb, gsize size) + G_GNUC_ALLOC_SIZE(2); -public: - UndoTokenString(gchar *&variable, gchar *_str) - : ptr(&variable) - { - str = _str ? g_strdup(_str) : NULL; - } +#define teco_undo_push(NAME) \ + ((NAME##_t *)teco_undo_push_size((teco_undo_action_t)NAME##_action, \ + sizeof(NAME##_t))) - ~UndoTokenString() - { - g_free(str); +/** + * @defgroup undo_objects Undo objects + * + * @note + * The general meta programming approach here is similar to C++ explicit template + * instantiation. + * A macro is expanded for every object type into some compilation unit and a declaration + * into the corresponding header. + * The object's type is mangled into the generated "push"-function's name. + * In case of scalars, C11 Generics and some macro magic is then used to hide the + * type names and for "reference" style passing. + * + * Explicit instantiation could be theoretically avoided using GCC compound expressions + * and nested functions. However, GCC will inevitably generate trampolines which + * are unportable and induce a runtime penalty. + * Furthermore, nested functions are not supported by Clang, where the Blocks extension + * would have to be used instead. + * Another alternative for implicit instantiation would be preprocessing of all source + * files with some custom M4 macros. + */ +/* + * FIXME: Due to the requirements on the variable, we could be tempted to inline + * references to it directly into the action()-function, saving the `ptr` + * in the undo token. This is however often practically not possible. + * We could however add a variant for true global variables. + * + * FIXME: Sometimes, the push-function is used only in a single compilation unit, + * so it should be declared `static` or `static inline`. + * Is it worth complicating our APIs in order to support that? + * + * FIXME: Perhaps better split this into TECO_DEFINE_UNDO_OBJECT() and TECO_DEFINE_UNDO_OBJECT_OWN() + */ +#define __TECO_DEFINE_UNDO_OBJECT(NAME, TYPE, COPY, DELETE, DELETE_IF_DISABLED, DELETE_ON_RUN) \ + typedef struct { \ + TYPE *ptr; \ + TYPE value; \ + } teco_undo_object_##NAME##_t; \ + \ + static void \ + teco_undo_object_##NAME##_action(teco_undo_object_##NAME##_t *ctx, gboolean run) \ + { \ + if (run) { \ + DELETE_ON_RUN(*ctx->ptr); \ + *ctx->ptr = ctx->value; \ + } else { \ + DELETE(ctx->value); \ + } \ + } \ + \ + /** @ingroup undo_objects */ \ + TYPE * \ + teco_undo_object_##NAME##_push(TYPE *ptr) \ + { \ + teco_undo_object_##NAME##_t *ctx = teco_undo_push(teco_undo_object_##NAME); \ + if (ctx) { \ + ctx->ptr = ptr; \ + ctx->value = COPY(*ptr); \ + } else { \ + DELETE_IF_DISABLED(*ptr); \ + } \ + return ptr; \ } - void - run(void) - { - g_free(*ptr); - *ptr = str; - str = NULL; - } -}; +/** + * Defines an undo token push function that when executed restores + * the value/state of a variable of TYPE to the value it had when this + * was called. + * + * This can be used to undo changes to arbitrary variables, either + * requiring explicit memory handling or to scalars. + * + * The lifetime of the variable must be global - a pointer to it must be valid + * until the undo token could be executed. + * This will usually exclude stack-allocated variables or objects. + * + * @param NAME C identifier used for name mangling. + * @param TYPE Type of variable to restore. + * @param COPY A global function/expression to execute in order to copy VAR. + * If left empty, this is an identity operation and ownership + * of the variable is passed to the undo token. + * @param DELETE A global function/expression to execute in order to destruct + * objects of TYPE. Leave empty if destruction is not necessary. + * + * @ingroup undo_objects + */ +#define TECO_DEFINE_UNDO_OBJECT(NAME, TYPE, COPY, DELETE) \ + __TECO_DEFINE_UNDO_OBJECT(NAME, TYPE, COPY, DELETE, /* don't delete if disabled */, DELETE) +/** + * @fixme _OWN variants will invalidate the variable pointer, so perhaps + * it will be clearer to have _SET variants instead. + * + * @ingroup undo_objects + */ +#define TECO_DEFINE_UNDO_OBJECT_OWN(NAME, TYPE, DELETE) \ + __TECO_DEFINE_UNDO_OBJECT(NAME, TYPE, /* pass ownership */, DELETE, DELETE, /* don't delete if run */) -template <class Type> -class UndoTokenObject : public UndoToken { - Type **ptr; - Type *obj; +/** @ingroup undo_objects */ +#define TECO_DECLARE_UNDO_OBJECT(NAME, TYPE) \ + TYPE *teco_undo_object_##NAME##_push(TYPE *ptr) -public: - UndoTokenObject(Type *&variable, Type *_obj) - : ptr(&variable), obj(_obj) {} +/** @ingroup undo_objects */ +#define TECO_DEFINE_UNDO_SCALAR(TYPE) \ + TECO_DEFINE_UNDO_OBJECT_OWN(TYPE, TYPE, /* don't delete */) - ~UndoTokenObject() - { - delete obj; - } +/** @ingroup undo_objects */ +#define TECO_DECLARE_UNDO_SCALAR(TYPE) \ + TECO_DECLARE_UNDO_OBJECT(TYPE, TYPE) - void - run(void) - { - delete *ptr; - *ptr = obj; - obj = NULL; - } -}; - -extern class UndoStack : public Object { - /** - * Stack of UndoToken lists. - * - * Each stack element represents - * a command line character (the UndoTokens - * generated by that character), so it's OK - * to use a data structure that may need - * reallocation but is space efficient. - * This data structure allows us to omit the - * command line program counter from the UndoTokens - * but wastes a few bytes for input characters - * that produce no UndoToken (e.g. NOPs like space). - */ - GPtrArray *heads; - - void push(UndoToken *token); - -public: - bool enabled; - - UndoStack(bool _enabled = false) - : heads(g_ptr_array_new()), enabled(_enabled) {} - ~UndoStack() - { - clear(); - g_ptr_array_free(heads, TRUE); - } +/* + * FIXME: We had to add -Wno-unused-value to surpress warnings. + * Perhaps it's clearer to sacrifice the lvalue feature. + * + * TODO: Check whether generating an additional check on teco_undo_enabled here + * significantly improves batch-mode performance. + */ +TECO_DECLARE_UNDO_SCALAR(gchar); +#define teco_undo_gchar(VAR) (*teco_undo_object_gchar_push(&(VAR))) - /** - * Allocate and push undo token. - * - * This does nothing if undo is disabled and should - * not be used when ownership of some data is to be - * passed to the undo token. - */ - template <class TokenType, typename... Params> - inline void - push(Params && ... params) - { - if (enabled) - push(new TokenType(params...)); - } +TECO_DECLARE_UNDO_SCALAR(gint); +#define teco_undo_gint(VAR) (*teco_undo_object_gint_push(&(VAR))) - /** - * Allocate and push undo token, passing ownership. - * - * This creates and deletes the undo token cheaply - * if undo is disabled, so that data whose ownership - * is passed to the undo token is correctly reclaimed. - * - * @bug We must know which version of push to call - * depending on the token type. This could be hidden - * if UndoTokens had static push methods that take care - * of reclaiming memory. - */ - template <class TokenType, typename... Params> - inline void - push_own(Params && ... params) - { - if (enabled) { - push(new TokenType(params...)); - } else { - /* ensures that all memory is reclaimed */ - TokenType dummy(params...); - } - } +TECO_DECLARE_UNDO_SCALAR(guint); +#define teco_undo_guint(VAR) (*teco_undo_object_guint_push(&(VAR))) - template <typename Type> - inline Type & - push_var(Type &variable, Type value) - { - push<UndoTokenVariable<Type>>(variable, value); - return variable; - } +TECO_DECLARE_UNDO_SCALAR(gsize); +#define teco_undo_gsize(VAR) (*teco_undo_object_gsize_push(&(VAR))) - template <typename Type> - inline Type & - push_var(Type &variable) - { - return push_var<Type>(variable, variable); - } +TECO_DECLARE_UNDO_SCALAR(teco_int_t); +#define teco_undo_int(VAR) (*teco_undo_object_teco_int_t_push(&(VAR))) - inline gchar *& - push_str(gchar *&variable, gchar *str) - { - push<UndoTokenString>(variable, str); - return variable; - } - inline gchar *& - push_str(gchar *&variable) - { - return push_str(variable, variable); - } +TECO_DECLARE_UNDO_SCALAR(gboolean); +#define teco_undo_gboolean(VAR) (*teco_undo_object_gboolean_push(&(VAR))) - template <class Type> - inline Type *& - push_obj(Type *&variable, Type *obj) - { - /* pass ownership of original object */ - push_own<UndoTokenObject<Type>>(variable, obj); - return variable; - } +TECO_DECLARE_UNDO_SCALAR(gconstpointer); +#define teco_undo_ptr(VAR) \ + (*(typeof(VAR) *)teco_undo_object_gconstpointer_push((gconstpointer *)&(VAR))) - template <class Type> - inline Type *& - push_obj(Type *&variable) - { - return push_obj<Type>(variable, variable); - } +#define __TECO_GEN_STRUCT(ID, X) X arg_##ID; +//#define __TECO_GEN_ARG(ID, X) X arg_##ID, +//#define __TECO_GEN_ARG_LAST(ID, X) X arg_##ID +#define __TECO_GEN_CALL(ID, X) ctx->arg_##ID, +#define __TECO_GEN_CALL_LAST(ID, X) ctx->arg_##ID +#define __TECO_GEN_INIT(ID, X) ctx->arg_##ID = arg_##ID; - void pop(gint pc); +/** + * @defgroup undo_calls Function calls on rubout. + * @{ + */ - void clear(void); -} undo; +/** + * Create an undo token that calls FNC with arbitrary scalar parameters + * (maximum 5, captured at the time of the call). + * It defines a function undo__FNC() for actually creating the closure. + * + * All arguments must be constants or expressions evaluating to scalars though, + * since no memory management (copying/freeing) is performed. + * + * Tipp: In order to save memory in the undo token structures, it is + * often trivial to define a static inline function that calls FNC and binds + * "constant" parameters. + * + * @param FNC Name of a global function or macro to execute. + * It must be a plain C identifier. + * @param ... The parameter types of FNC (signature). + * Only the types without any variable names must be specified. + * + * @fixme Sometimes, the push-function is used only in a single compilation unit, + * so it should be declared `static` or `static inline`. + * Is it worth complicating our APIs in order to support that? + */ +#define TECO_DEFINE_UNDO_CALL(FNC, ...) \ + typedef struct { \ + TECO_FOR_EACH(__TECO_GEN_STRUCT, __TECO_GEN_STRUCT, ##__VA_ARGS__) \ + } teco_undo_call_##FNC##_t; \ + \ + static void \ + teco_undo_call_##FNC##_action(teco_undo_call_##FNC##_t *ctx, gboolean run) \ + { \ + if (run) \ + FNC(TECO_FOR_EACH(__TECO_GEN_CALL, __TECO_GEN_CALL_LAST, ##__VA_ARGS__)); \ + } \ + \ + /** @ingroup undo_calls */ \ + void \ + undo__##FNC(TECO_FOR_EACH(__TECO_GEN_ARG, __TECO_GEN_ARG_LAST, ##__VA_ARGS__)) \ + { \ + teco_undo_call_##FNC##_t *ctx = teco_undo_push(teco_undo_call_##FNC); \ + if (ctx) { \ + TECO_FOR_EACH(__TECO_GEN_INIT, __TECO_GEN_INIT, ##__VA_ARGS__) \ + } \ + } -} /* namespace SciTECO */ +/** @} */ -#endif +void teco_undo_pop(gint pc); +void teco_undo_clear(void); |