summaryrefslogtreecommitdiff
path: root/source/luametatex
diff options
context:
space:
mode:
authorHans Hagen <pragma@wxs.nl>2026-11-22 22:35:18 +0000
committerContext Git Mirror Bot <phg@phi-gamma.net>2026-11-22 22:35:18 +0000
commite5337a5d9bf6eb951599ed4f3b86a41514236704 (patch)
treeae0cbdfd99014fa35eccd08dd700a2953d5c37e6 /source/luametatex
parent8d460b764f99b306461189a66cb22bbb319db454 (diff)
2026-10-31 00:18:07HEADbeta
Diffstat (limited to 'source/luametatex')
-rw-r--r--source/luametatex/CMakeLists.txt210
-rw-r--r--source/luametatex/build.cmd2
-rw-r--r--source/luametatex/build.sh2
-rw-r--r--source/luametatex/cmake/arm64.cmake4
-rw-r--r--source/luametatex/cmake/lua.cmake11
-rw-r--r--source/luametatex/cmake/luametatex.cmake29
-rw-r--r--source/luametatex/cmake/luaoptional.cmake8
-rw-r--r--source/luametatex/cmake/luarest.cmake74
-rw-r--r--source/luametatex/cmake/luasocket.cmake4
-rw-r--r--source/luametatex/cmake/mimalloc.cmake6
-rw-r--r--source/luametatex/cmake/mp.cmake32
-rw-r--r--source/luametatex/cmake/softposit.cmake2
-rw-r--r--source/luametatex/cmake/tex.cmake73
-rw-r--r--source/luametatex/cmake/utilities.cmake31
-rw-r--r--source/luametatex/cmake/xzembedded.cmake25
-rw-r--r--source/luametatex/profile-generic.sh12
-rw-r--r--source/luametatex/profile-hans-linux.sh6
-rw-r--r--source/luametatex/profile-hans-mingw.sh6
-rw-r--r--source/luametatex/profile-hans-native.sh6
-rw-r--r--source/luametatex/profile-hans-rpi.sh6
-rw-r--r--source/luametatex/profile-math.sh9
-rw-r--r--source/luametatex/source/libraries/avl/readme.txt44
-rw-r--r--source/luametatex/source/libraries/pplib/ppcrypt.c3
-rw-r--r--source/luametatex/source/libraries/softposit/build/Linux-x86_64-GCC/Makefile245
-rw-r--r--source/luametatex/source/libraries/softposit/build/Linux-x86_64-GCC/softposit_test.abin129840 -> 0 bytes
-rw-r--r--source/luametatex/source/libraries/softposit/source/include/platform.h (renamed from source/luametatex/source/libraries/softposit/build/Linux-x86_64-GCC/platform.h)0
-rw-r--r--source/luametatex/source/libraries/xzembedded/AUTHORS11
-rw-r--r--source/luametatex/source/libraries/xzembedded/COPYING13
-rw-r--r--source/luametatex/source/libraries/xzembedded/MAINTAINERS12
-rw-r--r--source/luametatex/source/libraries/xzembedded/README167
-rw-r--r--source/luametatex/source/libraries/xzembedded/notused/Kconfig81
-rw-r--r--source/luametatex/source/libraries/xzembedded/notused/Makefile5
-rw-r--r--source/luametatex/source/libraries/xzembedded/notused/xz_dec_test.c214
-rw-r--r--source/luametatex/source/libraries/xzembedded/xz.h448
-rw-r--r--source/luametatex/source/libraries/xzembedded/xz_config.h145
-rw-r--r--source/luametatex/source/libraries/xzembedded/xz_crc32.c58
-rw-r--r--source/luametatex/source/libraries/xzembedded/xz_crc64.c53
-rw-r--r--source/luametatex/source/libraries/xzembedded/xz_dec_bcj.c738
-rw-r--r--source/luametatex/source/libraries/xzembedded/xz_dec_lzma2.c1345
-rw-r--r--source/luametatex/source/libraries/xzembedded/xz_dec_stream.c984
-rw-r--r--source/luametatex/source/libraries/xzembedded/xz_dec_syms.c27
-rw-r--r--source/luametatex/source/libraries/xzembedded/xz_lzma2.h203
-rw-r--r--source/luametatex/source/libraries/xzembedded/xz_private.h189
-rw-r--r--source/luametatex/source/libraries/xzembedded/xz_sha256.c182
-rw-r--r--source/luametatex/source/libraries/xzembedded/xz_stream.h61
-rw-r--r--source/luametatex/source/lua/lmtenginelib.c100
-rw-r--r--source/luametatex/source/lua/lmtenginelib.h2
-rw-r--r--source/luametatex/source/lua/lmtfontlib.c4
-rw-r--r--source/luametatex/source/lua/lmthelperlib.c35
-rw-r--r--source/luametatex/source/lua/lmtinterface.c1
-rw-r--r--source/luametatex/source/lua/lmtinterface.h45
-rw-r--r--source/luametatex/source/lua/lmtmplib.c21
-rw-r--r--source/luametatex/source/lua/lmtnodelib.c347
-rw-r--r--source/luametatex/source/lua/lmtnodelib.h2
-rw-r--r--source/luametatex/source/lua/lmtsecuritylib.c34
-rw-r--r--source/luametatex/source/lua/lmtstatuslib.c251
-rw-r--r--source/luametatex/source/lua/lmttexiolib.c6
-rw-r--r--source/luametatex/source/lua/lmttexlib.c632
-rw-r--r--source/luametatex/source/lua/lmttokenlib.c11
-rw-r--r--source/luametatex/source/luacore/lua55/src/lcode.c6
-rw-r--r--source/luametatex/source/luacore/lua55/src/lcorolib.c3
-rw-r--r--source/luametatex/source/luacore/lua55/src/ldebug.c6
-rw-r--r--source/luametatex/source/luacore/lua55/src/lfunc.c2
-rw-r--r--source/luametatex/source/luacore/lua55/src/lfunc.h4
-rw-r--r--source/luametatex/source/luacore/lua55/src/lstate.c22
-rw-r--r--source/luametatex/source/luacore/lua55/src/lua.c3
-rw-r--r--source/luametatex/source/luacore/lua55/src/lundump.c23
-rw-r--r--source/luametatex/source/luacore/lua55/src/lvm.c7
-rw-r--r--source/luametatex/source/luametatex.c10
-rw-r--r--source/luametatex/source/luametatex.h24
-rw-r--r--source/luametatex/source/luaoptional/cmake/mujs/CMakeLists.txt214
-rw-r--r--source/luametatex/source/luaoptional/cmake/mujs/CMakeSettings.json2
-rw-r--r--source/luametatex/source/luaoptional/lmtcurl.c108
-rw-r--r--source/luametatex/source/luaoptional/readme.txt60
-rw-r--r--source/luametatex/source/luarest/lmtclientlib.c869
-rw-r--r--source/luametatex/source/luarest/lmteffectslib.c2
-rw-r--r--source/luametatex/source/luarest/lmtfilelib.c508
-rw-r--r--source/luametatex/source/luarest/lmtiolibext.c1145
-rw-r--r--source/luametatex/source/luarest/lmtoslibext.c234
-rw-r--r--source/luametatex/source/luarest/lmtprocesslib.c365
-rw-r--r--source/luametatex/source/luarest/lmtserverlib.c1012
-rw-r--r--source/luametatex/source/luarest/lmtstrlibext.c5417
-rw-r--r--source/luametatex/source/luarest/lmttimerlib.c2
-rw-r--r--source/luametatex/source/luarest/lmtxmathlib.c211
-rw-r--r--source/luametatex/source/luarest/lmtxzlib.c278
-rw-r--r--source/luametatex/source/luarest/lmtziplib.c3
-rw-r--r--source/luametatex/source/mp/mp.c63
-rw-r--r--source/luametatex/source/mp/mp.h4
-rw-r--r--source/luametatex/source/mp/mpmathdecimal.c6
-rw-r--r--source/luametatex/source/mp/mpmathdouble.c8
-rw-r--r--source/luametatex/source/mp/mpmathexperiment.c6
-rw-r--r--source/luametatex/source/mp/mpmathposit.c6
-rw-r--r--source/luametatex/source/mp/mpmathscaled.c6
-rw-r--r--source/luametatex/source/mp/readme.txt86
-rw-r--r--source/luametatex/source/tex/texalign.c91
-rw-r--r--source/luametatex/source/tex/texarithmetic.c70
-rw-r--r--source/luametatex/source/tex/texarithmetic.h42
-rw-r--r--source/luametatex/source/tex/texbalance.c64
-rw-r--r--source/luametatex/source/tex/texbuildpage.c146
-rw-r--r--source/luametatex/source/tex/texcommands.c10
-rw-r--r--source/luametatex/source/tex/texcommands.h5
-rw-r--r--source/luametatex/source/tex/texconditional.c46
-rw-r--r--source/luametatex/source/tex/texdiscretionaries.c3
-rw-r--r--source/luametatex/source/tex/texdumpdata.c2
-rw-r--r--source/luametatex/source/tex/texdumpdata.h2
-rw-r--r--source/luametatex/source/tex/texequivalents.c116
-rw-r--r--source/luametatex/source/tex/texequivalents.h7
-rw-r--r--source/luametatex/source/tex/texexpand.c13
-rw-r--r--source/luametatex/source/tex/texfont.c186
-rw-r--r--source/luametatex/source/tex/texinserts.c17
-rw-r--r--source/luametatex/source/tex/texinserts.h10
-rw-r--r--source/luametatex/source/tex/texlanguage.c17
-rw-r--r--source/luametatex/source/tex/texlinebreak.c305
-rw-r--r--source/luametatex/source/tex/texlocalboxes.c2
-rw-r--r--source/luametatex/source/tex/texmaincontrol.c83
-rw-r--r--source/luametatex/source/tex/texmarks.c20
-rw-r--r--source/luametatex/source/tex/texmath.c410
-rw-r--r--source/luametatex/source/tex/texmath.h11
-rw-r--r--source/luametatex/source/tex/texmlist.c707
-rw-r--r--source/luametatex/source/tex/texmlist.h4
-rw-r--r--source/luametatex/source/tex/texnesting.c34
-rw-r--r--source/luametatex/source/tex/texnesting.h2
-rw-r--r--source/luametatex/source/tex/texnodes.c157
-rw-r--r--source/luametatex/source/tex/texnodes.h15
-rw-r--r--source/luametatex/source/tex/texpackaging.c131
-rw-r--r--source/luametatex/source/tex/texpackaging.h6
-rw-r--r--source/luametatex/source/tex/texprinting.c22
-rw-r--r--source/luametatex/source/tex/texscanning.c324
-rw-r--r--source/luametatex/source/tex/texscanning.h6
-rw-r--r--source/luametatex/source/tex/texsnapping.c2
-rw-r--r--source/luametatex/source/tex/texstringpool.c4
-rw-r--r--source/luametatex/source/tex/textoken.c39
-rw-r--r--source/luametatex/source/tex/textoken.h6
-rw-r--r--source/luametatex/source/tex/textypes.h3
-rw-r--r--source/luametatex/source/utilities/auxarithmetic.h127
-rw-r--r--source/luametatex/source/utilities/auxcompiler.h43
-rw-r--r--source/luametatex/source/utilities/auxfile.h4
-rw-r--r--source/luametatex/source/utilities/auxserialize.c562
-rw-r--r--source/luametatex/source/utilities/auxserialize.h19
-rw-r--r--source/luametatex/source/utilities/auxunistring.c278
-rw-r--r--source/luametatex/source/utilities/auxunistring.h22
141 files changed, 18170 insertions, 4027 deletions
diff --git a/source/luametatex/CMakeLists.txt b/source/luametatex/CMakeLists.txt
index 4ea8f79ec..5d51b520c 100644
--- a/source/luametatex/CMakeLists.txt
+++ b/source/luametatex/CMakeLists.txt
@@ -5,10 +5,18 @@
# Don't use -ffast-math as we depend on sign bit nilling in mp.
+# -fno-fast-math -ffp-contract=off -fno-associative-math -fno-reciprocal-math
+
+# /fp:strict
+
cmake_minimum_required(VERSION 3.10..3.28)
project(luametatex VERSION 2.11 LANGUAGES C)
+if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
+ set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose the type of build." FORCE)
+endif()
+
# I need to check with Mojca of the compile farm can handle this. It currently is not that
# critical because CMake will use a lower version if needed. But we do need to enable the
# extensions.
@@ -39,8 +47,9 @@ include(GNUInstallDirs)
# possible to Lua. We will *not* add interfaces with many bindings because that will introduce
# dependencies (and looking at e.g. LuaTeX build updates shows that clearly: a no-go).
-set(LMT_KPSE_TOO 1) # In case we want to manage MKII scripts (etc) with mtxrun.
-set(LMT_HB_TOO 1) # Maybe handy for Idris' font development (old converted ffi stuff)
+set(LMT_KPSE_TOO 1) # In case we want to manage MKII scripts (etc) with mtxrun.
+set(LMT_HB_TOO 1) # Maybe handy for Idris' font development (old converted ffi stuff).
+set(LMT_SOCKET_TOO 0) # Only when we transition.
# Options:
@@ -151,7 +160,7 @@ endif()
if (CMAKE_C_COMPILER MATCHES "musl-gcc")
add_compile_options(-std=gnu11 -Wno-cpp)
- add_definitions(-D_GNU_SOURCE)
+ add_compile_definitions(_GNU_SOURCE)
endif()
if (LMT_DEBUG)
@@ -173,7 +182,7 @@ endif()
# This is for Mikael, Keith and Hans to play with. We use less memory but not that much compared
# to what this mechanism used anyway. This will likely become the default.
-# add_definitions(-DLMT_ZBUFFER_FLOAT_RGB=1)
+# add_compile_definitions(LMT_ZBUFFER_FLOAT_RGB=1)
# When one wants to use Lua libraries, this is needed. But keep in mind that it's not supported,
# so we won't look into issues that could result from that. Getting a matching library is upto
@@ -185,23 +194,25 @@ endif()
if (DEFINED LMT_PERMIT_LUA_LIBRARIES)
unset(LMT_STRIP)
unset(LMT_OPTIMIZE)
- add_definitions(-DLMT_PERMIT_LUA_LIBRARIES="yes")
+ add_compile_definitions(LMT_PERMIT_LUA_LIBRARIES="yes")
endif ()
if (MSVC)
+ # Apply universally to all MSVC toolchains to suppress unsafe function warnings
+
+ add_compile_definitions(_CRT_SECURE_NO_WARNINGS)
+
if (CMAKE_C_COMPILER_ID MATCHES "Clang")
if (LMT_DEBUG)
add_compile_options(
- -Wall
-g
-O0
)
else()
add_compile_options(
- -Wall
- -O2
+ -O3
)
endif()
@@ -218,56 +229,12 @@ if (MSVC)
-Wno-shadow
)
- add_definitions(-D_CRT_SECURE_NO_WARNINGS)
-
- add_definitions(-DLMT_COMPILER_USED="clang")
+ add_compile_definitions(LMT_COMPILER_USED="clang")
else()
add_compile_options(
- /Wall
-
- /wd4127 # constant conditional expression
- /wd4131 # old style declarator
- /wd4152 # function pointer cast
- /wd4201 # nonstandard extension used: nameless struct/union
- /wd4244 # assignment in conditional expression
- /wd4456 # local vars with same name as outer variable
- /wd4457 # local vars with same function parameter
- /wd4464 # relative include path
- /wd4668 # missing defines
- /wd4702 # unreachable code
- /wd4710 # inlining
- /wd4711 # inlining
- /wd4774 # sprint argument 2 warning
- /wd4777 # format argument 2 warning
- /wd4820 # local vars with same name as outer variable
- /wd4996 # strdup etc warnings
- /wd5045 # spectre
-
- # /GL # whole program link optimization
- # /Gw # whole program data optimization (a little smaller bin)
-
- # /Ob3 # more agressive inline, much larger bin, no gain
-
- /wd4061 # enumerator * in switch * is not explicitly handled (mp)
- /wd4701 # potentially unitialized local variable (lua)
- /wd4255 # no function prototype given
-
- /wd5105 # macro expansion producing 'defined' has undefined behavior
-
- /wd4548 # expression before comma has no effect; expected expression with side-effect
-
- # indeed a bit faster but also a much larger binary:
-
- # /fp:fast
-
- # okay for amd processors too but no difference in size so probably no gain:
-
- # /favor:INTEL64
- # /fsanitize:address
- # /std:c17
-
+ /W4
)
# We always optimize ... symbols are not in the binary anyway so there is no advantage
@@ -277,20 +244,35 @@ if (MSVC)
if (NOT LMT_DEBUG)
add_compile_options(
- /GL # whole program link optimization
- /Gw # whole program data optimization (a little smaller bin)
+ /O2 # maximize speed
+ /Oi # enable intrinsic functions
+ /Ot # favor fast code over small size
+ /Ob2 # aggressive inlining
+ /GL # whole program link optimization
+ /Gw # whole program data optimization (a little smaller bin)
)
endif()
- add_definitions(-DLMT_COMPILER_USED="msvc")
+ add_compile_definitions(LMT_COMPILER_USED="msvc")
add_compile_options(
+ /W4
/utf-8
+ /wd4201 # Nonstandard extension: nameless struct/union
+ /wd4310 # Cast truncates constant value
+ /wd4100 # Unreferenced formal parameter
+ /wd4244 # Conversion loss of data (e.g. int to short)
+ /wd4267 # Conversion loss of data (size_t to int)
+ /wd4018 # Signed/unsigned mismatch
+ /wd4127 # Conditional expression is constant
+ /wd4706 # Assignment within conditional expression
+ /wd4456 # Declaration hides previous local declaration
+ /wd4709 # Comma operator within a subscript expression
)
endif()
- else()
+else()
if (CMAKE_C_COMPILER_ID MATCHES "Clang")
@@ -301,11 +283,11 @@ if (MSVC)
)
else()
add_compile_options(
- -O2
+ -O3
)
endif()
- add_definitions(-DLMT_COMPILER_USED="clang")
+ add_compile_definitions(LMT_COMPILER_USED="clang")
else()
@@ -317,12 +299,10 @@ if (MSVC)
else()
add_compile_options(
-O3
- # -g0
- # -mtune=nocona # fails on arm so more testing needed
)
endif()
- add_definitions(-DLMT_COMPILER_USED="gcc")
+ add_compile_definitions(LMT_COMPILER_USED="gcc")
# add_compile_options(-pg)
# add_link_options(-pg)
@@ -347,12 +327,6 @@ if (MSVC)
-Wcast-align
-Wcast-qual
- # we need to check for zeros anyway as not all compiles have this
-
- # -fno-signed-zeros
- # -fno-trapping-math
- # -fno-math-errno
-
-Wno-unknown-pragmas
-Wno-unused-result
-fno-strict-aliasing
@@ -360,7 +334,7 @@ if (MSVC)
# for c17
#
- # add_definitions(-D__STDC_WANT_LIB_EXT2__=1)
+ # add_compile_definitions(__STDC_WANT_LIB_EXT2__=1)
if (((DEFINED LMT_OPTIMIZE) OR (DEFINED LMT_STRIP)) AND NOT LMT_DEBUG)
if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
@@ -377,41 +351,75 @@ endif()
if (CMAKE_C_COMPILER_ID MATCHES "Clang")
add_compile_options(
+ # prevent unknown flag errors across different Clang compiler versions
-Wno-unknown-warning-option
+
+ # silence pedantic checks on standard C headers and pointer math
+ -Wno-reserved-identifier
+ -Wno-reserved-id-macro
+ -Wno-unsafe-buffer-usage # Clang 16+ pointer arithmetic warnings
+
+ # cross-platform header inclusion & format flexibility
-Wno-nonportable-include-path
- -Wno-nonportable-system-include-path
- -Wno-newline-eof
- -Wno-extra-semi-stmt
+ -Wno-format-nonliteral
+
+ # noisy type conversions & shadow suppressions
-Wno-sign-conversion
- -Wno-unused-macros
- -Wno-reserved-id-macro
- -Wno-comma
- -Wno-switch-enum
-Wno-shadow
- -Wno-missing-noreturn
-Wno-implicit-fallthrough
- # -Wno-format
- -Wno-reserved-identifier
- -Wno-date-time
- -Wno-format-nonliteral
- -Wno-float-equal
- # too noisy, we just look at what gcc reports
- -Wno-unsafe-buffer-usage
- -Wno-macro-redefined
- -Wno-undef
- -Wno-switch-default
- -Wno-class-varargs
)
endif()
+if (MSVC)
+ # Remove runtime checks (/RTC1) which conflict with optimizations (/O2)
+ foreach(flag_var
+ CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE
+ CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO)
+ if(${flag_var} MATCHES "/RTC1")
+ string(REGEX REPLACE "/RTC1" "" ${flag_var} "${${flag_var}}")
+ endif()
+ endforeach()
+endif()
+
+if (MSVC)
+ # Remove runtime checks (/RTC1) and clean up conflicting default flags to avoid D9025 warnings
+ foreach(flag_var
+ CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE
+ CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO)
+
+ if(${flag_var} MATCHES "/W3")
+ string(REGEX REPLACE "/W3" "/W4" ${flag_var} "${${flag_var}}")
+ endif()
+
+ if(${flag_var} MATCHES "/Od")
+ string(REGEX REPLACE "/Od" "/O2" ${flag_var} "${${flag_var}}")
+ endif()
+
+ # Strip out /Ob0 so it doesn't clash with your /Ob2
+ if(${flag_var} MATCHES "/Ob0")
+ string(REGEX REPLACE "/Ob0" "" ${flag_var} "${${flag_var}}")
+ endif()
+
+ if(${flag_var} MATCHES "/MDd")
+ string(REGEX REPLACE "/MDd" "/MD" ${flag_var} "${${flag_var}}")
+ endif()
+
+ string(REGEX REPLACE "/RTC1" "" ${flag_var} "${${flag_var}}")
+ endforeach()
+endif()
+
+
# Not that tested (converted ffi originals):
-if ((DEFINED LMT_KPSE_TOO))
- add_definitions(-DLMT_KPSE_TOO=1)
+if (LMT_KPSE_TOO)
+ add_compile_definitions(LMT_KPSE_TOO=1)
+endif()
+if (LMT_HB_TOO)
+ add_compile_definitions(LMT_HB_TOO=1)
endif()
-if ((DEFINED LMT_HB_TOO))
- add_definitions(-DLMT_HB_TOO=1)
+if (LMT_SOCKET_TOO)
+ add_compile_definitions(LMT_SOCKET_TOO=1)
endif()
# This needs cmake >= 3.9 and produces a 60K smaller mingw binary but it take quite a bit of
@@ -496,19 +504,24 @@ endif()
include_directories(${CMAKE_ROOT}/source)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/source)
-if ((DEFINED luametatex_use_mimalloc))
- add_definitions(-DLUAMETATEX_USE_MIMALLOC=1)
- # add_definitions(-DMIMALLOC_RESET_DELAY=250)
+if (DEFINED luametatex_use_mimalloc)
+ add_compile_definitions(LUAMETATEX_USE_MIMALLOC=1)
+ # add_compile_definitions(MIMALLOC_RESET_DELAY=250)
# set(luametatex_use_mimalloc 1)
include(cmake/mimalloc.cmake)
endif()
+include(cmake/utilities.cmake)
include(cmake/tex.cmake)
include(cmake/lua.cmake)
include(cmake/mp.cmake)
include(cmake/luarest.cmake)
-include(cmake/luasocket.cmake)
+
+if (LMT_SOCKET_TOO)
+ include(cmake/luasocket.cmake)
+endif()
+
include(cmake/luaoptional.cmake)
include(cmake/pplib.cmake)
@@ -519,7 +532,8 @@ include(cmake/potrace.cmake)
include(cmake/qrcodegen.cmake)
include(cmake/nanojpeg.cmake)
include(cmake/triangles.cmake)
+include(cmake/xzembedded.cmake)
# include(cmake/qhull.cmake)
-include(cmake/luametatex.cmake) \ No newline at end of file
+include(cmake/luametatex.cmake)
diff --git a/source/luametatex/build.cmd b/source/luametatex/build.cmd
index 17f06e185..d05bef582 100644
--- a/source/luametatex/build.cmd
+++ b/source/luametatex/build.cmd
@@ -73,7 +73,7 @@ dir build\%luametatexbuildpath%\Release\luametatex.exe
@echo .
@echo binaries:
@echo .
-@echo tex/texmf-win64/bin/luametatex.exe : the compiled binary (some 2-3MB)
+@echo tex/texmf-win64/bin/luametatex.exe : the compiled binary (some 4-5MB)
@echo tex/texmf-win64/bin/mtxrun.exe : copy of or link to luametatex.exe
@echo tex/texmf-win64/bin/context.exe : copy of or link to luametatex.exe
@echo tex/texmf-win64/bin/mtxrun.lua : copy of tex/texmf-context/scripts/context/lua/mtxrun.lua
diff --git a/source/luametatex/build.sh b/source/luametatex/build.sh
index 36af9398a..b7f9c9878 100644
--- a/source/luametatex/build.sh
+++ b/source/luametatex/build.sh
@@ -496,7 +496,7 @@ echo "styles made by the user : tex/texmf-projects/tex/context/user/...."
echo ""
echo "binaries:"
echo ""
-echo "tex/texmf-<your platform>/bin/luametatex$SUFFIX : the compiled binary (some 3-4MB)"
+echo "tex/texmf-<your platform>/bin/luametatex$SUFFIX : the compiled binary (some 4-5MB)"
echo "tex/texmf-<your platform>/bin/mtxrun$SUFFIX : copy of or link to luametatex"
echo "tex/texmf-<your platform>/bin/context$SUFFIX : copy of or link to luametatex"
echo ""
diff --git a/source/luametatex/cmake/arm64.cmake b/source/luametatex/cmake/arm64.cmake
index 3c0a754ac..113fefb4a 100644
--- a/source/luametatex/cmake/arm64.cmake
+++ b/source/luametatex/cmake/arm64.cmake
@@ -4,7 +4,7 @@ set(CMAKE_SYSTEM_NAME ARM64)
set(TOOLCHAIN_PREFIX aarch64-linux-gnu)
set(CMAKE_C_COMPILER ${TOOLCHAIN_PREFIX}-gcc)
-add_definitions(-DLUA_USE_LINUX=1)
-add_definitions(-DLUA_USE_MKSTEMP=1)
+add_compile_definitions(LUA_USE_LINUX=1)
+add_compile_definitions(LUA_USE_MKSTEMP=1)
# set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc")
diff --git a/source/luametatex/cmake/lua.cmake b/source/luametatex/cmake/lua.cmake
index 4521b1ce4..c17396c7b 100644
--- a/source/luametatex/cmake/lua.cmake
+++ b/source/luametatex/cmake/lua.cmake
@@ -70,7 +70,7 @@ target_compile_definitions(lua PUBLIC
# LUAI_ASSERT
# LUA_STRFTIMEOPTIONS="aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%"
# MINSTRTABSIZE=65536
- NDEBUG=0
+ # NDEBUG=0
)
if (UNIX)
@@ -106,3 +106,12 @@ endif (NOT MSVC)
if (DEFINED LMT_PERMIT_LUA_LIBRARIES)
set_property(TARGET lua PROPERTY POSITION_INDEPENDENT_CODE ON)
endif ()
+
+if (NOT MSVC)
+ target_compile_options(lua PRIVATE
+ -O3
+ -fomit-frame-pointer
+ -fno-stack-protector
+ )
+endif()
+
diff --git a/source/luametatex/cmake/luametatex.cmake b/source/luametatex/cmake/luametatex.cmake
index 38b4a2a11..253b49e78 100644
--- a/source/luametatex/cmake/luametatex.cmake
+++ b/source/luametatex/cmake/luametatex.cmake
@@ -12,15 +12,20 @@ target_include_directories(luametatex PRIVATE
source/luacore/lua55/src
)
+target_link_libraries(tex PRIVATE luaoptional)
+target_link_libraries(luaoptional PRIVATE tex)
+
target_link_libraries(luametatex
+
+ # $<LINK_GROUP:REDEF,tex,luarest,utilities,luaoptional,mp>
+
+ luaoptional
tex
+ luarest
+ utilities
lua
mp
- luarest
- luasocket
- luaoptional
-
pplib
miniz
softposit
@@ -29,10 +34,24 @@ target_link_libraries(luametatex
triangles
nanojpeg
filib
+ xzembedded
# qhull
)
+if (LMT_SOCKET_TOO)
+ target_link_libraries(luametatex
+ luasocket
+ )
+else()
+ if (WIN32)
+ target_link_libraries(luametatex
+ wsock32
+ ws2_32
+ )
+ endif()
+endif()
+
if (LUAMETATEX_NOLDL)
# mingw ucrt
else()
@@ -81,7 +100,7 @@ if (${CMAKE_HOST_SOLARIS})
socket
nsl
resolv
-)
+ )
endif()
if (DEFINED LMT_OPTIMIZE)
diff --git a/source/luametatex/cmake/luaoptional.cmake b/source/luametatex/cmake/luaoptional.cmake
index 8fe339fd5..35516b305 100644
--- a/source/luametatex/cmake/luaoptional.cmake
+++ b/source/luametatex/cmake/luaoptional.cmake
@@ -1,5 +1,7 @@
set(luaoptional_sources
+ source/luaoptional/lmtoptional.c
+
source/luaoptional/lmtsqlite.c
source/luaoptional/lmtmysql.c
source/luaoptional/lmtpostgress.c
@@ -29,3 +31,9 @@ target_include_directories(luaoptional PRIVATE
source/libraries/mimalloc/include
)
+if (NOT MSVC)
+ target_compile_options(luaoptional PRIVATE
+ -O3
+ -Wno-unused-parameter # FFI/Binding layers often have unused wrapper params
+ )
+endif() \ No newline at end of file
diff --git a/source/luametatex/cmake/luarest.cmake b/source/luametatex/cmake/luarest.cmake
index 003bc0815..fc81d7d20 100644
--- a/source/luametatex/cmake/luarest.cmake
+++ b/source/luametatex/cmake/luarest.cmake
@@ -2,29 +2,72 @@
# rest because the complex interfaces are different per platform. There is
# not that much code involved. But, anyway, at some point it might become
# a real optional module in which case the following will change.
+# cmake/luarest.cmake
set(luarest_sources
-
source/luaoptional/lmtcerflib.c
-
source/libraries/libcerf/erfcx.c
source/libraries/libcerf/err_fcts.c
source/libraries/libcerf/im_w_of_x.c
source/libraries/libcerf/w_of_z.c
source/libraries/libcerf/width.c
- # source/libraries/hull/libhull.c
+ source/luarest/lmtfilelib.c
+ source/luarest/lmtpdfelib.c
+ source/luarest/lmtiolibext.c
+ source/luarest/lmtoslibext.c
+ source/luarest/lmtstrlibext.c
+ source/luarest/lmtdecodelib.c
+ source/luarest/lmtsha2lib.c
+ source/luarest/lmtmd5lib.c
+ source/luarest/lmtaeslib.c
+ source/luarest/lmtbasexxlib.c
+ source/luarest/lmtxmathlib.c
+ source/luarest/lmtxcomplexlib.c
+ source/luarest/lmtxdecimallib.c
+ source/luarest/lmtxintervallib.c
+ source/luarest/lmtziplib.c
+ source/luarest/lmtsparselib.c
+ source/luarest/lmtbitsetlib.c
+ source/luarest/lmtposit.c
+ source/luarest/lmtpotrace.c
+ source/luarest/lmtqrcodegen.c
+ source/luarest/lmtnanojpeg.c
+ source/luarest/lmtseriallib.c
+ source/luarest/lmtprocesslib.c
+ source/luarest/lmttimerlib.c
+ source/luarest/lmtvectorlib.c
+ source/luarest/lmtbytemaplib.c
+ source/luarest/lmteffectslib.c
+ source/luarest/lmtzbufferlib.c
+ source/luarest/lmtkdtreelib.c
+ source/luarest/lmtclientlib.c
+ source/luarest/lmtserverlib.c
+ source/luarest/lmtxzlib.c
)
add_library(luarest STATIC ${luarest_sources})
+target_compile_definitions(luarest PUBLIC
+ DECUSE64=1
+ # DECCHECK=1
+ # DECBUFFER=512
+ DECNUMDIGITS=1000
+)
+
target_include_directories(luarest PRIVATE
source/libraries/libcerf
source/luacore/lua55/src
+ source/libraries/mimalloc/include
+ source/libraries/potrace/src
+ source/libraries/qrcodegen
+ source/libraries/nanojpeg
+ source/libraries/pplib
+ source/libraries/pplib/util
+ source/libraries/decnumber
+ source/libraries/filib
)
-# only when all ok, to avoid messages
-
include(CheckCCompilerFlag)
CHECK_C_COMPILER_FLAG("-Wno-discarded-qualifiers" limited_support)
@@ -32,3 +75,24 @@ CHECK_C_COMPILER_FLAG("-Wno-discarded-qualifiers" limited_support)
if (limited_support)
target_compile_options(luarest PRIVATE -Wno-discarded-qualifiers)
endif()
+
+if (NOT MSVC)
+ target_compile_options(luarest PRIVATE
+ -O3
+ -fstrict-aliasing
+ )
+endif()
+
+# File-specific compilation rule for vector math speedup
+
+set_source_files_properties(
+ source/luarest/lmtvectorlib.c
+ source/luarest/lmteffectslib.c
+ source/luarest/lmtzbufferlib.c
+ PROPERTIES
+ COMPILE_FLAGS "-O3 -ffp-contract=fast -ftree-vectorize"
+)
+
+if (WIN32)
+ target_link_libraries(luarest PRIVATE winhttp)
+endif() \ No newline at end of file
diff --git a/source/luametatex/cmake/luasocket.cmake b/source/luametatex/cmake/luasocket.cmake
index f32e02e0d..1b6abacc8 100644
--- a/source/luametatex/cmake/luasocket.cmake
+++ b/source/luametatex/cmake/luasocket.cmake
@@ -64,7 +64,3 @@ if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
LUASOCKET_INET_PTON
)
endif()
-
-
-
-
diff --git a/source/luametatex/cmake/mimalloc.cmake b/source/luametatex/cmake/mimalloc.cmake
index 1d759e437..bfd86c761 100644
--- a/source/luametatex/cmake/mimalloc.cmake
+++ b/source/luametatex/cmake/mimalloc.cmake
@@ -21,8 +21,8 @@ set(mimalloc_sources
# if (MI_OSX_ZONE)
# list(APPEND mimalloc_sources source/libraries/mimalloc/src/prim/osx/alloc-override-zone.c)
-# add_definitions(-DMI_OSX_ZONE=1)
-# add_definitions(-DMI_OSX_INTERPOSE=1)
+# add_compile_definitions(MI_OSX_ZONE=1)
+# add_compile_definitions(MI_OSX_INTERPOSE=1)
# endif()
set(MI_OPT_ARCH_FLAGS "")
@@ -67,7 +67,7 @@ target_compile_definitions(mimalloc PRIVATE
# MIMALLOC_ALLOW_THP=1
MI_DEBUG=0
MI_SECURE=0
- NDEBUG=0
+ # NDEBUG=0
# MI_DEBUG=3
# MI_SHOW_ERRORS=1
# MI_PADDING=1
diff --git a/source/luametatex/cmake/mp.cmake b/source/luametatex/cmake/mp.cmake
index cf0c44707..660737520 100644
--- a/source/luametatex/cmake/mp.cmake
+++ b/source/luametatex/cmake/mp.cmake
@@ -1,5 +1,4 @@
set(mp_sources
-
source/mp/mp.c
source/mp/mpstrings.c
source/mp/mpmathscaled.c
@@ -14,16 +13,14 @@ set(mp_sources
source/libraries/avl/avl.c
- source/utilities/auxbytemaps.c
-
source/lua/lmtmplib.c
-
- source/luarest/lmtxdecimallib.c
- source/luarest/lmtxintervallib.c
)
add_library(mp STATIC ${mp_sources})
+# Ensure target dependencies for circular symbol resolution
+target_link_libraries(mp PRIVATE utilities luarest lua)
+
target_include_directories(mp PRIVATE
.
source/.
@@ -44,19 +41,28 @@ target_compile_definitions(mp PUBLIC
DECNUMDIGITS=1000
)
-if (CMAKE_C_COMPILER_ID STREQUAL "Clang")
+# Floating-point precision rules for MetaPost path solving
+if (MSVC)
target_compile_options(mp PRIVATE
- -Wno-unreachable-code-break
+ # /O2 /Oi /Ot
+ /fp:precise
)
-endif()
-
-if (NOT MSVC)
+else()
target_compile_options(mp PRIVATE
+ -O3
+ -fno-fast-math
+ -ffp-contract=off
+ -fno-associative-math
+ -fno-strict-aliasing
-Wno-unused-parameter
-Wno-sign-compare
-Wno-cast-qual
-Wno-cast-align
- # for decnumber with lto
- -fno-strict-aliasing
)
endif()
+
+if (CMAKE_C_COMPILER_ID STREQUAL "Clang")
+ target_compile_options(mp PRIVATE
+ -Wno-unreachable-code-break
+ )
+endif() \ No newline at end of file
diff --git a/source/luametatex/cmake/softposit.cmake b/source/luametatex/cmake/softposit.cmake
index 45f10564b..8b5a53759 100644
--- a/source/luametatex/cmake/softposit.cmake
+++ b/source/luametatex/cmake/softposit.cmake
@@ -118,7 +118,7 @@ add_library(softposit STATIC ${softposit_sources})
target_include_directories(softposit PRIVATE
source/libraries/softposit/source
source/libraries/softposit/source/include
- source/libraries/softposit/build/Linux-x86_64-GCC
+ # source/libraries/softposit/build/Linux-x86_64-GCC
)
target_compile_options(softposit PRIVATE
diff --git a/source/luametatex/cmake/tex.cmake b/source/luametatex/cmake/tex.cmake
index 74f1c5f90..75f552ddb 100644
--- a/source/luametatex/cmake/tex.cmake
+++ b/source/luametatex/cmake/tex.cmake
@@ -1,28 +1,16 @@
+# cmake/tex.cmake
+
if (DEFINED luametatex_use_helpers)
set(tex_sources_helpers source/lua/lmthelperlib.c)
endif()
set(tex_sources
-
- source/utilities/auxmemory.c
- source/utilities/auxzlib.c
- source/utilities/auxsparsearray.c
- source/utilities/auxsystem.c
- source/utilities/auxunistring.c
- source/utilities/auxfile.c
- source/utilities/auxposit.c
- source/utilities/auxbytemaps.c
- source/utilities/auxkdtree2d.c
- source/utilities/auxkdtree3d.c
-
- source/libraries/hnj/hnjhyphen.c
-
+ # Lua engine interface
source/lua/lmtinterface.c
source/lua/lmtlibrary.c
source/lua/lmtcallbacklib.c
source/lua/lmtlanguagelib.c
source/lua/lmtlualib.c
- # source/lua/lmtluaclib.c
source/lua/lmttexiolib.c
source/lua/lmttexlib.c
source/lua/lmttokenlib.c
@@ -31,40 +19,9 @@ set(tex_sources
source/lua/lmtenginelib.c
source/lua/lmtfontlib.c
source/lua/lmtstatuslib.c
-
source/lua/lmthelperlib.c
- source/luaoptional/lmtoptional.c
-
- source/luarest/lmtfilelib.c
- source/luarest/lmtpdfelib.c
- source/luarest/lmtiolibext.c
- source/luarest/lmtoslibext.c
- source/luarest/lmtstrlibext.c
- source/luarest/lmtdecodelib.c
- source/luarest/lmtsha2lib.c
- source/luarest/lmtmd5lib.c
- source/luarest/lmtaeslib.c
- source/luarest/lmtbasexxlib.c
- source/luarest/lmtxmathlib.c
- source/luarest/lmtxcomplexlib.c
- source/luarest/lmtziplib.c
- source/luarest/lmtsparselib.c
- source/luarest/lmtbitsetlib.c
- source/luarest/lmtposit.c
- source/luarest/lmtpotrace.c
- source/luarest/lmtqrcodegen.c
- source/luarest/lmtnanojpeg.c
- source/luarest/lmtseriallib.c
- source/luarest/lmtprocesslib.c
- source/luarest/lmttimerlib.c
- source/luarest/lmtvectorlib.c
- source/luarest/lmtbytemaplib.c
- source/luarest/lmteffectslib.c
- source/luarest/lmtzbufferlib.c
- source/luarest/lmtkdtreelib.c
- # source/luarest/lmtspecificlib.c
-
+ # Core TeX engine routines
source/tex/texalign.c
source/tex/texarithmetic.c
source/tex/texbuildpage.c
@@ -104,13 +61,27 @@ set(tex_sources
source/tex/textoken.c
source/tex/texrules.c
source/tex/texbalance.c
-
)
add_library(tex STATIC ${tex_sources})
+if (MSVC)
+ target_compile_options(tex PRIVATE
+ /fp:strict # Strict floating-point model
+ /W4 # High warning level
+ )
+else()
+ target_compile_options(tex PRIVATE
+ -O3
+ -fomit-frame-pointer
+ -ffp-contract=off
+ -fno-fast-math
+ -fno-strict-aliasing
+ -Wall -Wextra
+ )
+endif()
+
target_compile_definitions(tex PUBLIC
- # LUAI_HASHLIMIT=6 # obsolete
ZLIB_CONST=1
MINIZ_NO_ARCHIVE_APIS=1
MINIZ_NO_STDIO=1
@@ -130,6 +101,4 @@ target_include_directories(tex PRIVATE
source/libraries/qrcodegen
source/libraries/nanojpeg
source/libraries/triangles
-
- # source/libraries/qhull/src/libqhull_r
-)
+) \ No newline at end of file
diff --git a/source/luametatex/cmake/utilities.cmake b/source/luametatex/cmake/utilities.cmake
new file mode 100644
index 000000000..15dbef0ba
--- /dev/null
+++ b/source/luametatex/cmake/utilities.cmake
@@ -0,0 +1,31 @@
+# cmake/utilities.cmake
+
+set(utilities_sources
+ source/utilities/auxmemory.c
+ source/utilities/auxzlib.c
+ source/utilities/auxsparsearray.c
+ source/utilities/auxsystem.c
+ source/utilities/auxunistring.c
+ source/utilities/auxfile.c
+ source/utilities/auxposit.c
+ source/utilities/auxbytemaps.c
+ source/utilities/auxkdtree2d.c
+ source/utilities/auxkdtree3d.c
+ source/utilities/auxserialize.c
+
+ source/libraries/hnj/hnjhyphen.c
+)
+
+add_library(utilities STATIC ${utilities_sources})
+
+target_include_directories(utilities PRIVATE
+ source/.
+ source/luacore/lua55/src
+)
+
+if (NOT MSVC)
+ target_compile_options(utilities PRIVATE
+ -O3
+ -fomit-frame-pointer
+ )
+endif() \ No newline at end of file
diff --git a/source/luametatex/cmake/xzembedded.cmake b/source/luametatex/cmake/xzembedded.cmake
new file mode 100644
index 000000000..ab49d7d97
--- /dev/null
+++ b/source/luametatex/cmake/xzembedded.cmake
@@ -0,0 +1,25 @@
+set(xzembedded_sources
+ source/libraries/xzembedded/xz_crc32.c
+ source/libraries/xzembedded/xz_crc64.c
+ source/libraries/xzembedded/xz_dec_lzma2.c
+ source/libraries/xzembedded/xz_dec_stream.c
+)
+
+add_library(xzembedded STATIC ${xzembedded_sources})
+
+target_include_directories(xzembedded PUBLIC
+ utilities
+ source/libraries/xzembedded
+)
+
+# target_compile_definitions(xzembedded PUBLIC
+# XZ_USE_CRC64
+# XZ_DEC_CONCATENATED
+# )
+
+if (NOT MSVC)
+ target_compile_options(xzembedded PRIVATE
+ -Wno-cast-align
+ -Wno-cast-qual
+ )
+endif (NOT MSVC) \ No newline at end of file
diff --git a/source/luametatex/profile-generic.sh b/source/luametatex/profile-generic.sh
index ba298cee3..fd036da4d 100644
--- a/source/luametatex/profile-generic.sh
+++ b/source/luametatex/profile-generic.sh
@@ -1,10 +1,10 @@
# This setup is a generic one.
-export LMT_SETUP_CMD=
-export LMT_CONTEXT_BIN=~/context/tex/texmf-linux-64/bin
-export LMT_MANUAL_LUAMETATEX=~/context/tex/texmf-context/doc/context/sources/general/manuals/luametatex/luametatex.tex
-export LMT_MANUAL_LUAMETAFUN=~/context/tex/texmf-context/doc/context/sources/general/manuals/luametafun/luametafun.tex
-export LMT_MANUAL_MATHINCONTEXT=~/context/tex/texmf-context/doc/context/sources/general/manuals/mathincontext/mathincontext.tex
-export LMT_PROFILE_RUNTIME_DIR=
+export LMT_SETUP_CMD=
+export LMT_CONTEXT_BIN=~/context/tex/texmf-linux-64/bin
+export LMT_MANUAL_LUAMETATEX=~/context/tex/texmf-context/doc/context/sources/documents/general/manuals/mkxl/luametatex/luametatex.tex
+export LMT_MANUAL_LUAMETAFUN=~/context/tex/texmf-context/doc/context/sources/documents/general/manuals/mkxl/luametafun/luametafun.tex
+export LMT_MANUAL_MATHINCONTEXT=~/context/tex/texmf-context/doc/context/sources/documents/general/manuals/mkxl/mathincontext/mathincontext.tex
+export LMT_PROFILE_RUNTIME_DIR=
printenv | grep LMT \ No newline at end of file
diff --git a/source/luametatex/profile-hans-linux.sh b/source/luametatex/profile-hans-linux.sh
index 19caddf72..2e4495559 100644
--- a/source/luametatex/profile-hans-linux.sh
+++ b/source/luametatex/profile-hans-linux.sh
@@ -19,8 +19,8 @@ export LMT_CONTEXT_BIN=$CONTEXTROOT/tex-context/tex/texmf-linux-64/bin
# Here is where the latest manuals are.
-export LMT_MANUAL_LUAMETATEX=$CONTEXTROOT/manuals/mkiv/external/luametatex/luametatex.tex
-export LMT_MANUAL_LUAMETAFUN=$CONTEXTROOT/manuals/mkiv/external/luametafun/luametafun.tex
-export LMT_MANUAL_MATHINCONTEXT=$CONTEXTROOT/manuals/mkiv/external/mathincontext/mathincontext.tex
+export LMT_MANUAL_LUAMETATEX=$CONTEXTROOT/manuals/mkxl/external/luametatex/luametatex.tex
+export LMT_MANUAL_LUAMETAFUN=$CONTEXTROOT/manuals/mkxl/external/luametafun/luametafun.tex
+export LMT_MANUAL_MATHINCONTEXT=$CONTEXTROOT/manuals/mkxl/external/mathincontext/mathincontext.tex
printenv | grep LMT \ No newline at end of file
diff --git a/source/luametatex/profile-hans-mingw.sh b/source/luametatex/profile-hans-mingw.sh
index cd8066481..671e0d05b 100644
--- a/source/luametatex/profile-hans-mingw.sh
+++ b/source/luametatex/profile-hans-mingw.sh
@@ -20,8 +20,8 @@ export LMT_CONTEXT_BIN=/mnt/c/data/develop/tex-context/tex/texmf-win64/bin
# Here is where the latest manuals are.
-export LMT_MANUAL_LUAMETATEX=$CONTEXTROOT/manuals/mkiv/external/luametatex/luametatex.tex
-export LMT_MANUAL_LUAMETAFUN=$CONTEXTROOT/manuals/mkiv/external/luametafun/luametafun.tex
-export LMT_MANUAL_MATHINCONTEXT=$CONTEXTROOT/manuals/mkiv/external/mathincontext/mathincontext.tex
+export LMT_MANUAL_LUAMETATEX=$CONTEXTROOT/manuals/mkxl/external/luametatex/luametatex.tex
+export LMT_MANUAL_LUAMETAFUN=$CONTEXTROOT/manuals/mkxl/external/luametafun/luametafun.tex
+export LMT_MANUAL_MATHINCONTEXT=$CONTEXTROOT/manuals/mkxl/external/mathincontext/mathincontext.tex
printenv | grep LMT \ No newline at end of file
diff --git a/source/luametatex/profile-hans-native.sh b/source/luametatex/profile-hans-native.sh
index 22a6ef1c5..3f738c69a 100644
--- a/source/luametatex/profile-hans-native.sh
+++ b/source/luametatex/profile-hans-native.sh
@@ -20,8 +20,8 @@ export LMT_CONTEXT_BIN=/mnt/c/data/develop/tex-context/tex/texmf-linux-64/bin
# Here is where the latest manuals are.
-export LMT_MANUAL_LUAMETATEX=$CONTEXTROOT/manuals/mkiv/external/luametatex/luametatex.tex
-export LMT_MANUAL_LUAMETAFUN=$CONTEXTROOT/manuals/mkiv/external/luametafun/luametafun.tex
-export LMT_MANUAL_MATHINCONTEXT=$CONTEXTROOT/manuals/mkiv/external/mathincontext/mathincontext.tex
+export LMT_MANUAL_LUAMETATEX=$CONTEXTROOT/manuals/mkxl/external/luametatex/luametatex.tex
+export LMT_MANUAL_LUAMETAFUN=$CONTEXTROOT/manuals/mkxl/external/luametafun/luametafun.tex
+export LMT_MANUAL_MATHINCONTEXT=$CONTEXTROOT/manuals/mkxl/external/mathincontext/mathincontext.tex
printenv | grep LMT \ No newline at end of file
diff --git a/source/luametatex/profile-hans-rpi.sh b/source/luametatex/profile-hans-rpi.sh
index 4c98b2925..8704c3d07 100644
--- a/source/luametatex/profile-hans-rpi.sh
+++ b/source/luametatex/profile-hans-rpi.sh
@@ -5,9 +5,9 @@ export LMT_SETUP_CMD=
export CONTEXTROOT=/data/context
export LMT_CONTEXT_BIN=$CONTEXTROOT/tex/texmf-linux-aarch64/bin
-export LMT_MANUAL_LUAMETATEX=$CONTEXTROOT/tex/texmf-context/doc/context/sources/general/manuals/luametatex/luametatex.tex
-export LMT_MANUAL_LUAMETAFUN=$CONTEXTROOT/tex/texmf-context/doc/context/sources/general/manuals/luametafun/luametafun.tex
-export LMT_MANUAL_MATHINCONTEXT=$CONTEXTROOT/tex/texmf-context/doc/context/sources/general/manuals/mathincontext/mathincontext.tex
+export LMT_MANUAL_LUAMETATEX=$CONTEXTROOT/tex/texmf-context/doc/context/sources/documents/general/manuals/mkxl/luametatex/luametatex.tex
+export LMT_MANUAL_LUAMETAFUN=$CONTEXTROOT/tex/texmf-context/doc/context/sources/documents/general/manuals/mkxl/luametafun/luametafun.tex
+export LMT_MANUAL_MATHINCONTEXT=$CONTEXTROOT/tex/texmf-context/doc/context/sources/documents/general/manuals/mkxl/mathincontext/mathincontext.tex
export LMT_PROFILE_RUNTIME_DIR=
printenv | grep LMT \ No newline at end of file
diff --git a/source/luametatex/profile-math.sh b/source/luametatex/profile-math.sh
deleted file mode 100644
index 76eecfce7..000000000
--- a/source/luametatex/profile-math.sh
+++ /dev/null
@@ -1,9 +0,0 @@
-# This setup is a generic one.
-
-export LMT_SETUP_CMD=
-export LMT_CONTEXT_BIN=~/ConTeXt/tex/texmf-linux-64/bin
-export LMT_MANUAL_LUAMETATEX=~/ConTeXt/tex/texmf-context/doc/context/sources/general/manuals/luametatex/luametatex.tex
-export LMT_MANUAL_LUAMETAFUN=~/ConTeXt/tex/texmf-context/doc/context/sources/general/manuals/luametafun/luametafun.tex
-export LMT_MANUAL_MATHINCONTEXT=~/lubox/projekt/mathincontext/mathincontext.tex
-
-printenv | grep LMT
diff --git a/source/luametatex/source/libraries/avl/readme.txt b/source/luametatex/source/libraries/avl/readme.txt
index 9b4708248..90ff0949b 100644
--- a/source/luametatex/source/libraries/avl/readme.txt
+++ b/source/luametatex/source/libraries/avl/readme.txt
@@ -1,23 +1,23 @@
-Remark
-
-Usage of the avl library (irr) showed up in pdfTeX when Hartmut added some functionality. It therefore
-also ended up in being used in LuaTeX. The two files avl.c and avl.h come from pyavl and are in the
-public domain:
-
- license: this package, pyavl, is donated to the public domain
- author : Richard McGraw
- email : dasnar@fastmail.fm
-
-In the pdfTeX/LuaTeX the files were just there but I could track them down to
-
- https://github.com/pankajp/pyavl
-
-where the dates indicate that nothing has changed in the meantime. In the copies used here I added the
-information mentioned above. The files had some (experimental) code as well as optional testing on NULL
-values. As I don't expect updates (the code has been okay for quite a while) I made the tests mandate
-and removed the experimental code.
-
-We can strip this library and save some 10K on the binary because we don't need that much of it. That
-might happen at some point.
-
+Remark
+
+Usage of the avl library (irr) showed up in pdfTeX when Hartmut added some functionality. It therefore
+also ended up in being used in LuaTeX. The two files avl.c and avl.h come from pyavl and are in the
+public domain:
+
+ license: this package, pyavl, is donated to the public domain
+ author : Richard McGraw
+ email : dasnar@fastmail.fm
+
+In the pdfTeX/LuaTeX the files were just there but I could track them down to
+
+ https://github.com/pankajp/pyavl
+
+where the dates indicate that nothing has changed in the meantime. In the copies used here I added the
+information mentioned above. The files had some (experimental) code as well as optional testing on NULL
+values. As I don't expect updates (the code has been okay for quite a while) I made the tests mandate
+and removed the experimental code.
+
+We can strip this library and save some 10K on the binary because we don't need that much of it. That
+might happen at some point.
+
Hans Hagen \ No newline at end of file
diff --git a/source/luametatex/source/libraries/pplib/ppcrypt.c b/source/luametatex/source/libraries/pplib/ppcrypt.c
index 832e8c327..c22889b51 100644
--- a/source/luametatex/source/libraries/pplib/ppcrypt.c
+++ b/source/luametatex/source/libraries/pplib/ppcrypt.c
@@ -609,7 +609,8 @@ ppcrypt_status ppdoc_crypt_init (ppdoc *pdf, const void *userpass, size_t userpa
default:
return PPCRYPT_FAIL;
}
-
+ if (crypt->filekeylength > PPCRYPT_MAX_KEY)
+ return PPCRYPT_FAIL;
/* setup passwords */
if (userpass != NULL)
ppcrypt_set_user_password(crypt, userpass, userpasslength);
diff --git a/source/luametatex/source/libraries/softposit/build/Linux-x86_64-GCC/Makefile b/source/luametatex/source/libraries/softposit/build/Linux-x86_64-GCC/Makefile
deleted file mode 100644
index d8e76b157..000000000
--- a/source/luametatex/source/libraries/softposit/build/Linux-x86_64-GCC/Makefile
+++ /dev/null
@@ -1,245 +0,0 @@
-#============================================================================
-#
-#This C source file is part of the SoftPosit Posit Arithmetic Package
-#by S. H. Leong (Cerlane).
-#
-#Copyright 2017, 2018 A*STAR. All rights reserved.
-#
-#This C source file was based on SoftFloat IEEE Floating-Point Arithmetic
-#Package, Release 3d, by John R. Hauser.
-#
-#
-# Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the
-# University of California. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# 1. Redistributions of source code must retain the above copyright notice,
-# this list of conditions, and the following disclaimer.
-#
-# 2. Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions, and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-#
-# 3. Neither the name of the University nor the names of its contributors
-# may be used to endorse or promote products derived from this software
-# without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
-# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
-# DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
-# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-#=============================================================================
-
-SOURCE_DIR ?= ../../source
-PYTHON_DIR ?= ../../python
-SPECIALIZE_TYPE ?= 8086-SSE
-COMPILER ?= gcc
-
-SOFTPOSIT_OPTS ?= \
- -DINLINE_LEVEL=5 #\
- -DSOFTPOSIT_QUAD -lquadmath
-
-COMPILE_PYTHON = \
- $(COMPILER) -fPIC -c $(PYTHON_DIR)/softposit_python_wrap.c \
- -I/usr/include/python \
- -I$(SOURCE_DIR)/include -I.
-COMPILE_PYTHON3 = \
- $(COMPILER) -fPIC -c $(PYTHON_DIR)/softposit_python_wrap.c \
- -I/usr/include/python3 \
- -I$(SOURCE_DIR)/include -I.
-LINK_PYTHON = \
- ld -shared *.o -o $(PYTHON_DIR)/_softposit.so
-
-
-ifeq ($(OS),Windows_NT)
- DELETE = del /Q /F
-else
- DELETE = rm -f
-endif
-
-C_INCLUDES = -I. -I$(SOURCE_DIR)/$(SPECIALIZE_TYPE) -I$(SOURCE_DIR)/include
-OPTIMISATION = -O2 #-march=core-avx2
-COMPILE_C = \
- $(COMPILER) -c -Werror-implicit-function-declaration -DSOFTPOSIT_FAST_INT64 \
- $(SOFTPOSIT_OPTS) $(C_INCLUDES) $(OPTIMISATION) \
- -o $@
-MAKELIB = ar crs $@
-MAKESLIB = $(COMPILER) -shared $^
-
-OBJ = .o
-LIB = .a
-SLIB = .so
-
-.PHONY: all
-all: softposit$(LIB)
-
-quad: SOFTPOSIT_OPTS+= -DSOFTPOSIT_QUAD -lquadmath
-quad: all
-
-python2: SOFTPOSIT_OPTS+= -fPIC
-python2: all
- $(COMPILE_PYTHON)
- $(LINK_PYTHON)
-
-python3: SOFTPOSIT_OPTS+= -fPIC
-python3: all
- $(COMPILE_PYTHON3)
- $(LINK_PYTHON)
-
-julia: SOFTPOSIT_OPTS+= -fPIC
-julia: softposit$(SLIB)
-
-
-
-OBJS_PRIMITIVES =
-
-OBJS_SPECIALIZE =
-
-OBJS_OTHERS = \
- s_addMagsP8$(OBJ) \
- s_subMagsP8$(OBJ) \
- s_mulAddP8$(OBJ) \
- p8_add$(OBJ) \
- p8_sub$(OBJ) \
- p8_mul$(OBJ) \
- p8_div$(OBJ) \
- p8_sqrt$(OBJ) \
- p8_to_p16$(OBJ) \
- p8_to_p32$(OBJ) \
- p8_to_pX2$(OBJ) \
- p8_to_i32$(OBJ) \
- p8_to_i64$(OBJ) \
- p8_to_ui32$(OBJ) \
- p8_to_ui64$(OBJ) \
- p8_roundToInt$(OBJ) \
- p8_mulAdd$(OBJ) \
- p8_eq$(OBJ) \
- p8_le$(OBJ) \
- p8_lt$(OBJ) \
- quire8_fdp_add$(OBJ) \
- quire8_fdp_sub$(OBJ) \
- ui32_to_p8$(OBJ) \
- ui64_to_p8$(OBJ) \
- i32_to_p8$(OBJ) \
- i64_to_p8$(OBJ) \
- s_addMagsP16$(OBJ) \
- s_subMagsP16$(OBJ) \
- s_mulAddP16$(OBJ) \
- p16_to_ui32$(OBJ) \
- p16_to_ui64$(OBJ) \
- p16_to_i32$(OBJ) \
- p16_to_i64$(OBJ) \
- p16_to_p8$(OBJ) \
- p16_to_p32$(OBJ) \
- p16_to_pX2$(OBJ) \
- p16_roundToInt$(OBJ) \
- p16_add$(OBJ) \
- p16_sub$(OBJ) \
- p16_mul$(OBJ) \
- p16_mulAdd$(OBJ) \
- p16_div$(OBJ) \
- p16_eq$(OBJ) \
- p16_le$(OBJ) \
- p16_lt$(OBJ) \
- p16_sqrt$(OBJ) \
- quire16_fdp_add$(OBJ) \
- quire16_fdp_sub$(OBJ) \
- quire_helper$(OBJ) \
- ui32_to_p16$(OBJ) \
- ui64_to_p16$(OBJ) \
- i32_to_p16$(OBJ) \
- i64_to_p16$(OBJ) \
- s_addMagsP32$(OBJ) \
- s_subMagsP32$(OBJ) \
- s_mulAddP32$(OBJ) \
- p32_to_ui32$(OBJ) \
- p32_to_ui64$(OBJ) \
- p32_to_i32$(OBJ) \
- p32_to_i64$(OBJ) \
- p32_to_p8$(OBJ) \
- p32_to_p16$(OBJ) \
- p32_to_pX2$(OBJ) \
- p32_roundToInt$(OBJ) \
- p32_add$(OBJ) \
- p32_sub$(OBJ) \
- p32_mul$(OBJ) \
- p32_mulAdd$(OBJ) \
- p32_div$(OBJ) \
- p32_eq$(OBJ) \
- p32_le$(OBJ) \
- p32_lt$(OBJ) \
- p32_sqrt$(OBJ) \
- quire32_fdp_add$(OBJ) \
- quire32_fdp_sub$(OBJ) \
- ui32_to_p32$(OBJ) \
- ui64_to_p32$(OBJ) \
- i32_to_p32$(OBJ) \
- i64_to_p32$(OBJ) \
- s_approxRecipSqrt_1Ks$(OBJ) \
- c_convertDecToPosit8$(OBJ) \
- c_convertPosit8ToDec$(OBJ) \
- c_convertDecToPosit16$(OBJ) \
- c_convertPosit16ToDec$(OBJ) \
- c_convertQuire8ToPosit8$(OBJ) \
- c_convertQuire16ToPosit16$(OBJ) \
- c_convertQuire32ToPosit32$(OBJ) \
- c_convertDecToPosit32$(OBJ) \
- c_convertPosit32ToDec$(OBJ) \
- c_int$(OBJ) \
- s_addMagsPX2$(OBJ) \
- s_subMagsPX2$(OBJ) \
- s_mulAddPX2$(OBJ) \
- pX2_add$(OBJ) \
- pX2_sub$(OBJ) \
- pX2_mul$(OBJ) \
- pX2_div$(OBJ) \
- pX2_mulAdd$(OBJ) \
- pX2_roundToInt$(OBJ) \
- pX2_sqrt$(OBJ) \
- pX2_eq$(OBJ) \
- pX2_le$(OBJ) \
- pX2_lt$(OBJ) \
- ui32_to_pX2$(OBJ) \
- ui64_to_pX2$(OBJ) \
- i32_to_pX2$(OBJ) \
- i64_to_pX2$(OBJ) \
- c_convertQuireX2ToPositX2$(OBJ)
-
-
-OBJS_ALL := $(OBJS_PRIMITIVES) $(OBJS_SPECIALIZE) $(OBJS_OTHERS)
-
-$(OBJS_ALL): \
- platform.h \
- $(SOURCE_DIR)/include/primitives.h
-
-$(OBJS_SPECIALIZE) $(OBJS_OTHERS): \
- $(SOURCE_DIR)/include/softposit_types.h $(SOURCE_DIR)/include/internals.h \
- $(SOURCE_DIR)/$(SPECIALIZE_TYPE)/specialize.h \
- $(SOURCE_DIR)/include/softposit.h
-
-$(OBJS_PRIMITIVES) $(OBJS_OTHERS): %$(OBJ): $(SOURCE_DIR)/%.c
- $(COMPILE_C) $(SOURCE_DIR)/$*.c
-
-$(OBJS_SPECIALIZE): %$(OBJ): $(SOURCE_DIR)/$(SPECIALIZE_TYPE)/%.c
- $(COMPILE_C) $(SOURCE_DIR)/$(SPECIALIZE_TYPE)/$*.c
-
-softposit$(LIB): $(OBJS_ALL)
- $(MAKELIB) $^
-
-softposit$(SLIB): $(OBJS_ALL)
- $(MAKESLIB) -o $@
-
-
-.PHONY: clean
-clean:
- $(DELETE) $(OBJS_ALL) softposit_python_wrap.o softposit$(LIB) softposit$(SLIB)
-
diff --git a/source/luametatex/source/libraries/softposit/build/Linux-x86_64-GCC/softposit_test.a b/source/luametatex/source/libraries/softposit/build/Linux-x86_64-GCC/softposit_test.a
deleted file mode 100644
index 7bab40bc7..000000000
--- a/source/luametatex/source/libraries/softposit/build/Linux-x86_64-GCC/softposit_test.a
+++ /dev/null
Binary files differ
diff --git a/source/luametatex/source/libraries/softposit/build/Linux-x86_64-GCC/platform.h b/source/luametatex/source/libraries/softposit/source/include/platform.h
index c6c752ffc..c6c752ffc 100644
--- a/source/luametatex/source/libraries/softposit/build/Linux-x86_64-GCC/platform.h
+++ b/source/luametatex/source/libraries/softposit/source/include/platform.h
diff --git a/source/luametatex/source/libraries/xzembedded/AUTHORS b/source/luametatex/source/libraries/xzembedded/AUTHORS
new file mode 100644
index 000000000..23afcf11d
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/AUTHORS
@@ -0,0 +1,11 @@
+
+Authors of XZ Embedded
+======================
+
+ XZ Embedded is developed and maintained by
+ Lasse Collin <lasse.collin@tukaani.org>.
+
+ Major parts of XZ Embedded are based on code written by Igor Pavlov,
+ specifically the LZMA SDK <https://7-zip.org/sdk.html>. Without this
+ code, XZ Embedded wouldn't exist.
+
diff --git a/source/luametatex/source/libraries/xzembedded/COPYING b/source/luametatex/source/libraries/xzembedded/COPYING
new file mode 100644
index 000000000..f0c316128
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/COPYING
@@ -0,0 +1,13 @@
+Copyright (C) The XZ Embedded authors and contributors
+
+Permission to use, copy, modify, and/or distribute this
+software for any purpose with or without fee is hereby granted.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
+WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
+THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
+CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/source/luametatex/source/libraries/xzembedded/MAINTAINERS b/source/luametatex/source/libraries/xzembedded/MAINTAINERS
new file mode 100644
index 000000000..4d84f3847
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/MAINTAINERS
@@ -0,0 +1,12 @@
+XZ EMBEDDED
+M: Lasse Collin <lasse.collin@tukaani.org>
+S: Maintained
+W: https://tukaani.org/xz/embedded.html
+B: https://github.com/tukaani-project/xz-embedded/issues
+C: irc://irc.libera.chat/tukaani
+F: Documentation/staging/xz.rst
+F: include/linux/decompress/unxz.h
+F: include/linux/xz.h
+F: lib/decompress_unxz.c
+F: lib/xz/
+F: scripts/xz_wrap.sh
diff --git a/source/luametatex/source/libraries/xzembedded/README b/source/luametatex/source/libraries/xzembedded/README
new file mode 100644
index 000000000..cdb2fd873
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/README
@@ -0,0 +1,167 @@
+
+XZ Embedded
+===========
+
+ XZ Embedded is a relatively small, limited implementation of the .xz
+ file format. Currently only decoding is implemented.
+
+ XZ Embedded was written for use in the Linux kernel, but the code can
+ be easily used in other environments too, including regular userspace
+ applications. See userspace/xzminidec.c for an example program.
+
+ NOTE: The version of XZ Embedded in the Linux kernel lacks a few
+ build-time-selectable optional features that are present in the
+ upstream XZ Embedded project: support for concatated .xz files,
+ CRC64, and ignoring unsupported check. These aren't in Linux
+ because they don't seem useful there but they would add to the
+ code size.
+
+ This README contains information that is useful only when the copy
+ of XZ Embedded isn't part of the Linux kernel tree. You should also
+ read linux/Documentation/staging/xz.rst even if you aren't using
+ XZ Embedded as part of Linux; information in that file is not
+ repeated in this README.
+
+Conformance to the .xz file format specification
+
+ As of the .xz file format specification version 1.2.0, this
+ decompressor implementation has the following limitations:
+
+ - Delta filter is not included.
+
+ - BCJ filters don't support non-default start offset.
+
+ - LZMA2 supports at most 3 GiB dictionary.
+
+ There are a couple of corner cases where things have been simplified
+ at expense of detecting errors as early as possible. These should not
+ matter in practice at all since they don't cause security issues. But
+ it is good to know this if testing the code with the test files from
+ XZ Utils.
+
+Compiler requirements
+
+ XZ Embedded should compile with any C99 or C11 compiler. The code
+ should also be GNU-C89 compatible still. GNU-C89 was used in the
+ Linux kernel until 2022. GNU-C89 support likely will be dropped
+ at some point.
+
+Embedding into userspace applications
+
+ To embed the XZ decoder, copy the following files into a single
+ directory in your source code tree:
+
+ linux/include/linux/xz.h
+ linux/lib/xz/xz_crc32.c
+ linux/lib/xz/xz_dec_lzma2.c
+ linux/lib/xz/xz_dec_stream.c
+ linux/lib/xz/xz_lzma2.h
+ linux/lib/xz/xz_private.h
+ linux/lib/xz/xz_stream.h
+ userspace/xz_config.h
+
+ Alternatively, xz.h may be placed into a different directory but then
+ that directory must be in the compiler include path when compiling
+ the .c files.
+
+ Your code should use only the functions declared in xz.h. The rest of
+ the .h files are meant only for internal use in XZ Embedded.
+
+ You may want to modify xz_config.h to be more suitable for your build
+ environment. Probably you should at least skim through it even if the
+ default file works as is.
+
+Supporting concatenated .xz files
+
+ Regular .xz files can be concatenated as is and the xz command line
+ tool will decompress all streams from a concatenated file (a few
+ other popular formats and tools support this too). This kind of .xz
+ files are more common than one might think because pxz, an early
+ threaded XZ compressor, created this kind of .xz files.
+
+ The xz_dec_run() function will stop after decompressing one stream.
+ This is good when XZ data is stored inside some other file format.
+ However, if one is decompressing regular standalone .xz files, one
+ will want to decompress all streams in the file. This is easy with
+ xz_dec_catrun(). To include support for xz_dec_catrun(), you need
+ to #define XZ_DEC_CONCATENATED in xz_config.h or in compiler flags.
+
+Integrity check support
+
+ XZ Embedded always supports the integrity check types None and
+ CRC32. Support for CRC64 and SHA-256 is optional. The xz tool
+ from XZ Utils uses CRC64 by default, but CRC32 is usually
+ enough in embedded systems to keep the code size smaller.
+
+ If you want support for CRC64, you need to copy linux/lib/xz/xz_crc64.c
+ into your application, and #define XZ_USE_CRC64 in xz_config.h or in
+ compiler flags.
+
+ When using the internal CRC32 or CRC64, their lookup tables need to be
+ initialized with xz_crc32_init() and xz_crc64_init(), respectively.
+ See xz.h for details.
+
+ To use external CRC32 or CRC64 code instead of the code from
+ xz_crc32.c or xz_crc64.c, the following #defines may be used
+ in xz_config.h or in compiler flags:
+
+ #define XZ_INTERNAL_CRC32 0
+ #define XZ_INTERNAL_CRC64 0
+
+ Then it is up to you to provide compatible xz_crc32() or xz_crc64()
+ functions.
+
+ If the .xz file being decompressed uses an integrity check type that
+ isn't supported by XZ Embedded, it is treated as an error and the
+ file cannot be decompressed. For multi-call mode, this can be modified
+ by #defining XZ_DEC_ANY_CHECK. Then xz_dec_run() will return
+ XZ_UNSUPPORTED_CHECK when unsupported check type is detected. After
+ that decompression can be continued normally except that the
+ integrity check won't be verified. In single-call mode there's
+ no way to continue decoding, so XZ_DEC_ANY_CHECK is almost useless
+ in single-call mode.
+
+BCJ filter support
+
+ If you want support for one or more BCJ filters, you need to copy
+ linux/lib/xz/xz_dec_bcj.c into your application, and use appropriate
+ #defines in xz_config.h or in compiler flags. You don't need these
+ #defines in the code that just uses XZ Embedded via xz.h, but having
+ them always #defined doesn't hurt either.
+
+ #define Instruction set BCJ filter endianness
+ XZ_DEC_X86 x86-32 or x86-64 Little endian only
+ XZ_DEC_POWERPC PowerPC Big endian only
+ XZ_DEC_IA64 Itanium (IA-64) Big or little endian
+ XZ_DEC_ARM ARM Little endian instructions
+ XZ_DEC_ARMTHUMB ARM-Thumb Big or little endian
+ XZ_DEC_ARM64 ARM64 Big or little endian
+ XZ_DEC_SPARC SPARC Big or little endian
+ XZ_DEC_RISCV RISC-V Big or little endian
+
+ While some architectures are (partially) bi-endian, the endianness
+ setting doesn't change the endianness of the instructions on all
+ architectures. That's why many filters work for both big and little
+ endian executables (Itanium and ARM based architectures have little
+ endian instructions and SPARC has big endian instructions).
+
+Notes about shared libraries
+
+ If you are including XZ Embedded into a shared library, you should
+ rename the xz_* functions to prevent symbol conflicts in case your
+ library is linked against some other library or application that
+ also has XZ Embedded in it (which may even be a different version
+ of XZ Embedded).
+
+ Please don't create a shared library of XZ Embedded itself unless
+ it is fine to rebuild everything depending on that shared library
+ every time you upgrade to a newer version of XZ Embedded. There are
+ no API or ABI stability guarantees between different versions of
+ XZ Embedded.
+
+Contact information
+
+ Email: Lasse Collin <lasse.collin@tukaani.org>
+ IRC: Larhzu on #tukaani on Libera Chat
+ GitHub: https://github.com/tukaani-project/xz-embedded
+
diff --git a/source/luametatex/source/libraries/xzembedded/notused/Kconfig b/source/luametatex/source/libraries/xzembedded/notused/Kconfig
new file mode 100644
index 000000000..f5141f475
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/notused/Kconfig
@@ -0,0 +1,81 @@
+config XZ_DEC
+ tristate "XZ decompression support"
+ select CRC32
+ help
+ LZMA2 compression algorithm and BCJ filters are supported using
+ the .xz file format as the container. For integrity checking,
+ CRC32 is supported. See Documentation/staging/xz.rst for more
+ information.
+
+if XZ_DEC
+
+config XZ_DEC_X86
+ bool "x86 BCJ filter decoder" if EXPERT
+ default y
+ select XZ_DEC_BCJ
+
+config XZ_DEC_POWERPC
+ bool "PowerPC BCJ filter decoder" if EXPERT
+ default y
+ select XZ_DEC_BCJ
+
+config XZ_DEC_IA64
+ bool "IA-64 BCJ filter decoder" if EXPERT
+ default y
+ select XZ_DEC_BCJ
+
+config XZ_DEC_ARM
+ bool "ARM BCJ filter decoder" if EXPERT
+ default y
+ select XZ_DEC_BCJ
+
+config XZ_DEC_ARMTHUMB
+ bool "ARM-Thumb BCJ filter decoder" if EXPERT
+ default y
+ select XZ_DEC_BCJ
+
+config XZ_DEC_ARM64
+ bool "ARM64 BCJ filter decoder" if EXPERT
+ default y
+ select XZ_DEC_BCJ
+
+config XZ_DEC_SPARC
+ bool "SPARC BCJ filter decoder" if EXPERT
+ default y
+ select XZ_DEC_BCJ
+
+config XZ_DEC_RISCV
+ bool "RISC-V BCJ filter decoder" if EXPERT
+ default y
+ select XZ_DEC_BCJ
+
+config XZ_DEC_MICROLZMA
+ bool "MicroLZMA decoder"
+ default n
+ help
+ MicroLZMA is a header format variant where the first byte
+ of a raw LZMA stream (without the end of stream marker) has
+ been replaced with a bitwise-negation of the lc/lp/pb
+ properties byte. MicroLZMA was created to be used in EROFS
+ but can be used by other things too where wasting minimal
+ amount of space for headers is important.
+
+ Unless you know that you need this, say N.
+
+endif
+
+config XZ_DEC_BCJ
+ bool
+ default n
+
+config XZ_DEC_TEST
+ tristate "XZ decompressor tester"
+ default n
+ depends on XZ_DEC
+ help
+ This allows passing .xz files to the in-kernel XZ decoder via
+ a character special file. It calculates CRC32 of the decompressed
+ data and writes diagnostics to the system log.
+
+ Unless you are developing the XZ decoder, you don't need this
+ and should say N.
diff --git a/source/luametatex/source/libraries/xzembedded/notused/Makefile b/source/luametatex/source/libraries/xzembedded/notused/Makefile
new file mode 100644
index 000000000..a7fa7693f
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/notused/Makefile
@@ -0,0 +1,5 @@
+obj-$(CONFIG_XZ_DEC) += xz_dec.o
+xz_dec-y := xz_dec_syms.o xz_dec_stream.o xz_dec_lzma2.o
+xz_dec-$(CONFIG_XZ_DEC_BCJ) += xz_dec_bcj.o
+
+obj-$(CONFIG_XZ_DEC_TEST) += xz_dec_test.o
diff --git a/source/luametatex/source/libraries/xzembedded/notused/xz_dec_test.c b/source/luametatex/source/libraries/xzembedded/notused/xz_dec_test.c
new file mode 100644
index 000000000..53d3600f2
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/notused/xz_dec_test.c
@@ -0,0 +1,214 @@
+// SPDX-License-Identifier: 0BSD
+
+/*
+ * XZ decoder tester
+ *
+ * Author: Lasse Collin <lasse.collin@tukaani.org>
+ */
+
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/fs.h>
+#include <linux/uaccess.h>
+#include <linux/crc32.h>
+#include <linux/xz.h>
+
+/* Maximum supported dictionary size */
+#define DICT_MAX (1 << 20)
+
+/* Device name to pass to register_chrdev(). */
+#define DEVICE_NAME "xz_dec_test"
+
+/* Dynamically allocated device major number */
+static int device_major;
+
+/*
+ * We reuse the same decoder state, and thus can decode only one
+ * file at a time.
+ */
+static bool device_is_open;
+
+/* XZ decoder state */
+static struct xz_dec *state;
+
+/*
+ * Return value of xz_dec_run(). We need to avoid calling xz_dec_run() after
+ * it has returned XZ_STREAM_END, so we make this static.
+ */
+static enum xz_ret ret;
+
+/*
+ * Input and output buffers. The input buffer is used as a temporary safe
+ * place for the data coming from the userspace.
+ */
+static uint8_t buffer_in[1024];
+static uint8_t buffer_out[1024];
+
+/*
+ * Structure to pass the input and output buffers to the XZ decoder.
+ * A few of the fields are never modified so we initialize them here.
+ */
+static struct xz_buf buffers = {
+ .in = buffer_in,
+ .out = buffer_out,
+ .out_size = sizeof(buffer_out)
+};
+
+/*
+ * CRC32 of uncompressed data. This is used to give the user a simple way
+ * to check that the decoder produces correct output.
+ */
+static uint32_t crc;
+
+static int xz_dec_test_open(struct inode *i, struct file *f)
+{
+ if (device_is_open)
+ return -EBUSY;
+
+ device_is_open = true;
+
+ xz_dec_reset(state);
+ ret = XZ_OK;
+ crc = 0xFFFFFFFF;
+
+ buffers.in_pos = 0;
+ buffers.in_size = 0;
+ buffers.out_pos = 0;
+
+ printk(KERN_INFO DEVICE_NAME ": opened\n");
+ return 0;
+}
+
+static int xz_dec_test_release(struct inode *i, struct file *f)
+{
+ device_is_open = false;
+
+ if (ret == XZ_OK)
+ printk(KERN_INFO DEVICE_NAME ": input was truncated\n");
+
+ printk(KERN_INFO DEVICE_NAME ": closed\n");
+ return 0;
+}
+
+/*
+ * Decode the data given to us from the userspace. CRC32 of the uncompressed
+ * data is calculated and is printed at the end of successful decoding. The
+ * uncompressed data isn't stored anywhere for further use.
+ *
+ * The .xz file must have exactly one Stream and no Stream Padding. The data
+ * after the first Stream is considered to be garbage.
+ */
+static ssize_t xz_dec_test_write(struct file *file, const char __user *buf,
+ size_t size, loff_t *pos)
+{
+ size_t remaining;
+
+ if (ret != XZ_OK) {
+ if (size > 0)
+ printk(KERN_INFO DEVICE_NAME ": %zu bytes of "
+ "garbage at the end of the file\n",
+ size);
+
+ return -ENOSPC;
+ }
+
+ printk(KERN_INFO DEVICE_NAME ": decoding %zu bytes of input\n",
+ size);
+
+ remaining = size;
+ while ((remaining > 0 || buffers.out_pos == buffers.out_size)
+ && ret == XZ_OK) {
+ if (buffers.in_pos == buffers.in_size) {
+ buffers.in_pos = 0;
+ buffers.in_size = min(remaining, sizeof(buffer_in));
+ if (copy_from_user(buffer_in, buf, buffers.in_size))
+ return -EFAULT;
+
+ buf += buffers.in_size;
+ remaining -= buffers.in_size;
+ }
+
+ buffers.out_pos = 0;
+ ret = xz_dec_run(state, &buffers);
+ crc = crc32(crc, buffer_out, buffers.out_pos);
+ }
+
+ switch (ret) {
+ case XZ_OK:
+ printk(KERN_INFO DEVICE_NAME ": XZ_OK\n");
+ return size;
+
+ case XZ_STREAM_END:
+ printk(KERN_INFO DEVICE_NAME ": XZ_STREAM_END, "
+ "CRC32 = 0x%08X\n", ~crc);
+ return size - remaining - (buffers.in_size - buffers.in_pos);
+
+ case XZ_MEMLIMIT_ERROR:
+ printk(KERN_INFO DEVICE_NAME ": XZ_MEMLIMIT_ERROR\n");
+ break;
+
+ case XZ_FORMAT_ERROR:
+ printk(KERN_INFO DEVICE_NAME ": XZ_FORMAT_ERROR\n");
+ break;
+
+ case XZ_OPTIONS_ERROR:
+ printk(KERN_INFO DEVICE_NAME ": XZ_OPTIONS_ERROR\n");
+ break;
+
+ case XZ_DATA_ERROR:
+ printk(KERN_INFO DEVICE_NAME ": XZ_DATA_ERROR\n");
+ break;
+
+ case XZ_BUF_ERROR:
+ printk(KERN_INFO DEVICE_NAME ": XZ_BUF_ERROR\n");
+ break;
+
+ default:
+ printk(KERN_INFO DEVICE_NAME ": Bug detected!\n");
+ break;
+ }
+
+ return -EIO;
+}
+
+/* Allocate the XZ decoder state and register the character device. */
+static int __init xz_dec_test_init(void)
+{
+ static const struct file_operations fileops = {
+ .owner = THIS_MODULE,
+ .open = &xz_dec_test_open,
+ .release = &xz_dec_test_release,
+ .write = &xz_dec_test_write
+ };
+
+ state = xz_dec_init(XZ_PREALLOC, DICT_MAX);
+ if (state == NULL)
+ return -ENOMEM;
+
+ device_major = register_chrdev(0, DEVICE_NAME, &fileops);
+ if (device_major < 0) {
+ xz_dec_end(state);
+ return device_major;
+ }
+
+ printk(KERN_INFO DEVICE_NAME ": module loaded\n");
+ printk(KERN_INFO DEVICE_NAME ": Create a device node with "
+ "'mknod " DEVICE_NAME " c %d 0' and write .xz files "
+ "to it.\n", device_major);
+ return 0;
+}
+
+static void __exit xz_dec_test_exit(void)
+{
+ unregister_chrdev(device_major, DEVICE_NAME);
+ xz_dec_end(state);
+ printk(KERN_INFO DEVICE_NAME ": module unloaded\n");
+}
+
+module_init(xz_dec_test_init);
+module_exit(xz_dec_test_exit);
+
+MODULE_DESCRIPTION("XZ decompressor tester");
+MODULE_VERSION("1.0");
+MODULE_AUTHOR("Lasse Collin <lasse.collin@tukaani.org>");
+MODULE_LICENSE("Dual BSD/GPL");
diff --git a/source/luametatex/source/libraries/xzembedded/xz.h b/source/luametatex/source/libraries/xzembedded/xz.h
new file mode 100644
index 000000000..c317c4941
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/xz.h
@@ -0,0 +1,448 @@
+/* SPDX-License-Identifier: 0BSD */
+
+/*
+ * XZ decompressor
+ *
+ * Authors: Lasse Collin <lasse.collin@tukaani.org>
+ * Igor Pavlov <https://7-zip.org/>
+ */
+
+#ifndef XZ_H
+#define XZ_H
+
+#ifdef __KERNEL__
+# include <linux/stddef.h>
+# include <linux/types.h>
+#else
+# include <stddef.h>
+# include <stdint.h>
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* "#define XZ_EXTERN static" can be used to make extern functions static. */
+#ifndef XZ_EXTERN
+# define XZ_EXTERN extern
+#endif
+
+/**
+ * enum xz_mode - Operation mode
+ *
+ * @XZ_SINGLE: Single-call mode. This uses less RAM than
+ * multi-call modes, because the LZMA2
+ * dictionary doesn't need to be allocated as
+ * part of the decoder state. All required data
+ * structures are allocated at initialization,
+ * so xz_dec_run() cannot return XZ_MEM_ERROR.
+ * @XZ_PREALLOC: Multi-call mode with preallocated LZMA2
+ * dictionary buffer. All data structures are
+ * allocated at initialization, so xz_dec_run()
+ * cannot return XZ_MEM_ERROR.
+ * @XZ_DYNALLOC: Multi-call mode. The LZMA2 dictionary is
+ * allocated once the required size has been
+ * parsed from the stream headers. If the
+ * allocation fails, xz_dec_run() will return
+ * XZ_MEM_ERROR.
+ *
+ * It is possible to enable support only for a subset of the above
+ * modes at compile time by defining XZ_DEC_SINGLE, XZ_DEC_PREALLOC,
+ * or XZ_DEC_DYNALLOC. The xz_dec kernel module is always compiled
+ * with support for all operation modes, but the preboot code may
+ * be built with fewer features to minimize code size.
+ */
+enum xz_mode {
+ XZ_SINGLE,
+ XZ_PREALLOC,
+ XZ_DYNALLOC
+};
+
+/**
+ * enum xz_ret - Return codes
+ * @XZ_OK: Everything is OK so far. More input or more
+ * output space is required to continue. This
+ * return code is possible only in multi-call mode
+ * (XZ_PREALLOC or XZ_DYNALLOC).
+ * @XZ_STREAM_END: Operation finished successfully.
+ * @XZ_UNSUPPORTED_CHECK: Integrity check type is not supported. Decoding
+ * is still possible in multi-call mode by simply
+ * calling xz_dec_run() again.
+ * Note that this return value is used only if
+ * XZ_DEC_ANY_CHECK was defined at build time,
+ * which is not used in the kernel. Unsupported
+ * check types return XZ_OPTIONS_ERROR if
+ * XZ_DEC_ANY_CHECK was not defined at build time.
+ * @XZ_MEM_ERROR: Allocating memory failed. This return code is
+ * possible only if the decoder was initialized
+ * with XZ_DYNALLOC. The amount of memory that was
+ * tried to be allocated was no more than the
+ * dict_max argument given to xz_dec_init().
+ * @XZ_MEMLIMIT_ERROR: A bigger LZMA2 dictionary would be needed than
+ * allowed by the dict_max argument given to
+ * xz_dec_init(). This return value is possible
+ * only in multi-call mode (XZ_PREALLOC or
+ * XZ_DYNALLOC); the single-call mode (XZ_SINGLE)
+ * ignores the dict_max argument.
+ * @XZ_FORMAT_ERROR: File format was not recognized (wrong magic
+ * bytes).
+ * @XZ_OPTIONS_ERROR: This implementation doesn't support the requested
+ * compression options. In the decoder this means
+ * that the header CRC32 matches, but the header
+ * itself specifies something that we don't support.
+ * @XZ_DATA_ERROR: Compressed data is corrupt.
+ * @XZ_BUF_ERROR: Cannot make any progress. Details are slightly
+ * different between multi-call and single-call
+ * mode; more information below.
+ *
+ * In multi-call mode, XZ_BUF_ERROR is returned when two consecutive calls
+ * to XZ code cannot consume any input and cannot produce any new output.
+ * This happens when there is no new input available, or the output buffer
+ * is full while at least one output byte is still pending. Assuming your
+ * code is not buggy, you can get this error only when decoding a compressed
+ * stream that is truncated or otherwise corrupt.
+ *
+ * In single-call mode, XZ_BUF_ERROR is returned only when the output buffer
+ * is too small or the compressed input is corrupt in a way that makes the
+ * decoder produce more output than the caller expected. When it is
+ * (relatively) clear that the compressed input is truncated, XZ_DATA_ERROR
+ * is used instead of XZ_BUF_ERROR.
+ */
+enum xz_ret {
+ XZ_OK,
+ XZ_STREAM_END,
+ XZ_UNSUPPORTED_CHECK,
+ XZ_MEM_ERROR,
+ XZ_MEMLIMIT_ERROR,
+ XZ_FORMAT_ERROR,
+ XZ_OPTIONS_ERROR,
+ XZ_DATA_ERROR,
+ XZ_BUF_ERROR
+};
+
+/**
+ * struct xz_buf - Passing input and output buffers to XZ code
+ * @in: Beginning of the input buffer. This may be NULL if and only
+ * if in_pos is equal to in_size.
+ * @in_pos: Current position in the input buffer. This must not exceed
+ * in_size.
+ * @in_size: Size of the input buffer
+ * @out: Beginning of the output buffer. This may be NULL if and only
+ * if out_pos is equal to out_size.
+ * @out_pos: Current position in the output buffer. This must not exceed
+ * out_size.
+ * @out_size: Size of the output buffer
+ *
+ * Only the contents of the output buffer from out[out_pos] onward, and
+ * the variables in_pos and out_pos are modified by the XZ code.
+ */
+struct xz_buf {
+ const uint8_t *in;
+ size_t in_pos;
+ size_t in_size;
+
+ uint8_t *out;
+ size_t out_pos;
+ size_t out_size;
+};
+
+/*
+ * struct xz_dec - Opaque type to hold the XZ decoder state
+ */
+struct xz_dec;
+
+/**
+ * xz_dec_init() - Allocate and initialize a XZ decoder state
+ * @mode: Operation mode
+ * @dict_max: Maximum size of the LZMA2 dictionary (history buffer) for
+ * multi-call decoding. This is ignored in single-call mode
+ * (mode == XZ_SINGLE). LZMA2 dictionary is always 2^n bytes
+ * or 2^n + 2^(n-1) bytes (the latter sizes are less common
+ * in practice), so other values for dict_max don't make sense.
+ * In the kernel, dictionary sizes of 64 KiB, 128 KiB, 256 KiB,
+ * 512 KiB, and 1 MiB are probably the only reasonable values,
+ * except for kernel and initramfs images where a bigger
+ * dictionary can be fine and useful.
+ *
+ * Single-call mode (XZ_SINGLE): xz_dec_run() decodes the whole stream at
+ * once. The caller must provide enough output space or the decoding will
+ * fail. The output space is used as the dictionary buffer, which is why
+ * there is no need to allocate the dictionary as part of the decoder's
+ * internal state.
+ *
+ * Because the output buffer is used as the workspace, streams encoded using
+ * a big dictionary are not a problem in single-call mode. It is enough that
+ * the output buffer is big enough to hold the actual uncompressed data; it
+ * can be smaller than the dictionary size stored in the stream headers.
+ *
+ * Multi-call mode with preallocated dictionary (XZ_PREALLOC): dict_max bytes
+ * of memory is preallocated for the LZMA2 dictionary. This way there is no
+ * risk that xz_dec_run() could run out of memory, since xz_dec_run() will
+ * never allocate any memory. Instead, if the preallocated dictionary is too
+ * small for decoding the given input stream, xz_dec_run() will return
+ * XZ_MEMLIMIT_ERROR. Thus, it is important to know what kind of data will be
+ * decoded to avoid allocating excessive amount of memory for the dictionary.
+ *
+ * Multi-call mode with dynamically allocated dictionary (XZ_DYNALLOC):
+ * dict_max specifies the maximum allowed dictionary size that xz_dec_run()
+ * may allocate once it has parsed the dictionary size from the stream
+ * headers. This way excessive allocations can be avoided while still
+ * limiting the maximum memory usage to a sane value to prevent running the
+ * system out of memory when decompressing streams from untrusted sources.
+ *
+ * On success, xz_dec_init() returns a pointer to struct xz_dec, which is
+ * ready to be used with xz_dec_run(). If memory allocation fails,
+ * xz_dec_init() returns NULL.
+ */
+XZ_EXTERN struct xz_dec *xz_dec_init(enum xz_mode mode, uint32_t dict_max);
+
+/**
+ * xz_dec_run() - Run the XZ decoder for a single XZ stream
+ * @s: Decoder state allocated using xz_dec_init()
+ * @b: Input and output buffers
+ *
+ * The possible return values depend on build options and operation mode.
+ * See enum xz_ret for details.
+ *
+ * Note that if an error occurs in single-call mode (return value is not
+ * XZ_STREAM_END), b->in_pos and b->out_pos are not modified and the
+ * contents of the output buffer from b->out[b->out_pos] onward are
+ * undefined. This is true even after XZ_BUF_ERROR, because with some filter
+ * chains, there may be a second pass over the output buffer, and this pass
+ * cannot be properly done if the output buffer is truncated. Thus, you
+ * cannot give the single-call decoder a too small buffer and then expect to
+ * get that amount valid data from the beginning of the stream. You must use
+ * the multi-call decoder if you don't want to uncompress the whole stream.
+ *
+ * Use xz_dec_run() when XZ data is stored inside some other file format.
+ * The decoding will stop after one XZ stream has been decompressed. To
+ * decompress regular .xz files which might have multiple concatenated
+ * streams, use xz_dec_catrun() instead.
+ */
+XZ_EXTERN enum xz_ret xz_dec_run(struct xz_dec *s, struct xz_buf *b);
+
+/**
+ * xz_dec_catrun() - Run the XZ decoder with support for concatenated streams
+ * @s: Decoder state allocated using xz_dec_init()
+ * @b: Input and output buffers
+ * @finish: This is an int instead of bool to avoid requiring stdbool.h.
+ * As long as more input might be coming, finish must be false.
+ * When the caller knows that it has provided all the input to
+ * the decoder (some possibly still in b->in), it must set finish
+ * to true. Only when finish is true can this function return
+ * XZ_STREAM_END to indicate successful decompression of the
+ * file. In single-call mode (XZ_SINGLE) finish is assumed to
+ * always be true; the caller-provided value is ignored.
+ *
+ * This is like xz_dec_run() except that this makes it easy to decode .xz
+ * files with multiple streams (multiple .xz files concatenated as is).
+ * The rarely-used Stream Padding feature is supported too, that is, there
+ * can be null bytes after or between the streams. The number of null bytes
+ * must be a multiple of four.
+ *
+ * When finish is false and b->in_pos == b->in_size, it is possible that
+ * XZ_BUF_ERROR isn't returned even when no progress is possible (XZ_OK is
+ * returned instead). This shouldn't matter because in this situation a
+ * reasonable caller will attempt to provide more input or set finish to
+ * true for the next xz_dec_catrun() call anyway.
+ *
+ * For any struct xz_dec that has been initialized for multi-call mode:
+ * Once decoding has been started with xz_dec_run() or xz_dec_catrun(),
+ * the same function must be used until xz_dec_reset() or xz_dec_end().
+ * Switching between the two decoding functions without resetting results
+ * in undefined behavior.
+ *
+ * xz_dec_catrun() is only available if XZ_DEC_CONCATENATED was defined
+ * at compile time.
+ */
+XZ_EXTERN enum xz_ret xz_dec_catrun(struct xz_dec *s, struct xz_buf *b,
+ int finish);
+
+/**
+ * xz_dec_reset() - Reset an already allocated decoder state
+ * @s: Decoder state allocated using xz_dec_init()
+ *
+ * This function can be used to reset the multi-call decoder state without
+ * freeing and reallocating memory with xz_dec_end() and xz_dec_init().
+ *
+ * In single-call mode, xz_dec_reset() is always called in the beginning of
+ * xz_dec_run(). Thus, explicit call to xz_dec_reset() is useful only in
+ * multi-call mode.
+ */
+XZ_EXTERN void xz_dec_reset(struct xz_dec *s);
+
+/**
+ * xz_dec_end() - Free the memory allocated for the decoder state
+ * @s: Decoder state allocated using xz_dec_init(). If s is NULL,
+ * this function does nothing.
+ */
+XZ_EXTERN void xz_dec_end(struct xz_dec *s);
+
+/**
+ * DOC: MicroLZMA decompressor
+ *
+ * This MicroLZMA header format was created for use in EROFS but may be used
+ * by others too. **In most cases one needs the XZ APIs above instead.**
+ *
+ * The compressed format supported by this decoder is a raw LZMA stream
+ * whose first byte (always 0x00) has been replaced with bitwise-negation
+ * of the LZMA properties (lc/lp/pb) byte. For example, if lc/lp/pb is
+ * 3/0/2, the first byte is 0xA2. This way the first byte can never be 0x00.
+ * Just like with LZMA2, lc + lp <= 4 must be true. The LZMA end-of-stream
+ * marker must not be used. The unused values are reserved for future use.
+ */
+
+/*
+ * struct xz_dec_microlzma - Opaque type to hold the MicroLZMA decoder state
+ */
+struct xz_dec_microlzma;
+
+/**
+ * xz_dec_microlzma_alloc() - Allocate memory for the MicroLZMA decoder
+ * @mode: XZ_SINGLE or XZ_PREALLOC
+ * @dict_size: LZMA dictionary size. This must be at least 4 KiB and
+ * at most 3 GiB.
+ *
+ * In contrast to xz_dec_init(), this function only allocates the memory
+ * and remembers the dictionary size. xz_dec_microlzma_reset() must be used
+ * before calling xz_dec_microlzma_run().
+ *
+ * The amount of allocated memory is a little less than 30 KiB with XZ_SINGLE.
+ * With XZ_PREALLOC also a dictionary buffer of dict_size bytes is allocated.
+ *
+ * On success, xz_dec_microlzma_alloc() returns a pointer to
+ * struct xz_dec_microlzma. If memory allocation fails or
+ * dict_size is invalid, NULL is returned.
+ */
+XZ_EXTERN struct xz_dec_microlzma *xz_dec_microlzma_alloc(enum xz_mode mode,
+ uint32_t dict_size);
+
+/**
+ * xz_dec_microlzma_reset() - Reset the MicroLZMA decoder state
+ * @s: Decoder state allocated using xz_dec_microlzma_alloc()
+ * @comp_size: Compressed size of the input stream
+ * @uncomp_size: Uncompressed size of the input stream. A value smaller
+ * than the real uncompressed size of the input stream can
+ * be specified if uncomp_size_is_exact is set to false.
+ * uncomp_size can never be set to a value larger than the
+ * expected real uncompressed size because it would eventually
+ * result in XZ_DATA_ERROR.
+ * @uncomp_size_is_exact: This is an int instead of bool to avoid
+ * requiring stdbool.h. This should normally be set to true.
+ * When this is set to false, error detection is weaker.
+ */
+XZ_EXTERN void xz_dec_microlzma_reset(struct xz_dec_microlzma *s,
+ uint32_t comp_size, uint32_t uncomp_size,
+ int uncomp_size_is_exact);
+
+/**
+ * xz_dec_microlzma_run() - Run the MicroLZMA decoder
+ * @s: Decoder state initialized using xz_dec_microlzma_reset()
+ * @b: Input and output buffers
+ *
+ * This works similarly to xz_dec_run() with a few important differences.
+ * Only the differences are documented here.
+ *
+ * The only possible return values are XZ_OK, XZ_STREAM_END, and
+ * XZ_DATA_ERROR. This function cannot return XZ_BUF_ERROR: if no progress
+ * is possible due to lack of input data or output space, this function will
+ * keep returning XZ_OK. Thus, the calling code must be written so that it
+ * will eventually provide input and output space matching (or exceeding)
+ * comp_size and uncomp_size arguments given to xz_dec_microlzma_reset().
+ * If the caller cannot do this (for example, if the input file is truncated
+ * or otherwise corrupt), the caller must detect this error by itself to
+ * avoid an infinite loop.
+ *
+ * If the compressed data seems to be corrupt, XZ_DATA_ERROR is returned.
+ * This can happen also when incorrect dictionary, uncompressed, or
+ * compressed sizes have been specified.
+ *
+ * With XZ_PREALLOC only: As an extra feature, b->out may be NULL to skip over
+ * uncompressed data. This way the caller doesn't need to provide a temporary
+ * output buffer for the bytes that will be ignored.
+ *
+ * With XZ_SINGLE only: In contrast to xz_dec_run(), the return value XZ_OK
+ * is also possible and thus XZ_SINGLE is actually a limited multi-call mode.
+ * After XZ_OK the bytes decoded so far may be read from the output buffer.
+ * It is possible to continue decoding but the variables b->out and b->out_pos
+ * MUST NOT be changed by the caller. Increasing the value of b->out_size is
+ * allowed to make more output space available; one doesn't need to provide
+ * space for the whole uncompressed data on the first call. The input buffer
+ * may be changed normally like with XZ_PREALLOC. This way input data can be
+ * provided from non-contiguous memory.
+ */
+XZ_EXTERN enum xz_ret xz_dec_microlzma_run(struct xz_dec_microlzma *s,
+ struct xz_buf *b);
+
+/**
+ * xz_dec_microlzma_end() - Free the memory allocated for the decoder state
+ * @s: Decoder state allocated using xz_dec_microlzma_alloc().
+ * If s is NULL, this function does nothing.
+ */
+XZ_EXTERN void xz_dec_microlzma_end(struct xz_dec_microlzma *s);
+
+/*
+ * Standalone build (userspace build or in-kernel build for boot time use)
+ * needs a CRC32 implementation. For normal in-kernel use, kernel's own
+ * CRC32 module is used instead, and users of this module don't need to
+ * care about the functions below.
+ */
+#ifndef XZ_INTERNAL_CRC32
+# ifdef __KERNEL__
+# define XZ_INTERNAL_CRC32 0
+# else
+# define XZ_INTERNAL_CRC32 1
+# endif
+#endif
+
+/*
+ * If CRC64 support has been enabled with XZ_USE_CRC64, a CRC64
+ * implementation is needed too.
+ */
+#ifndef XZ_USE_CRC64
+# undef XZ_INTERNAL_CRC64
+# define XZ_INTERNAL_CRC64 0
+#endif
+#ifndef XZ_INTERNAL_CRC64
+# ifdef __KERNEL__
+# error Using CRC64 in the kernel has not been implemented.
+# else
+# define XZ_INTERNAL_CRC64 1
+# endif
+#endif
+
+#if XZ_INTERNAL_CRC32
+/*
+ * This must be called before any other xz_* function to initialize
+ * the CRC32 lookup table.
+ */
+XZ_EXTERN void xz_crc32_init(void);
+
+/*
+ * Update CRC32 value using the polynomial from IEEE-802.3. To start a new
+ * calculation, the third argument must be zero. To continue the calculation,
+ * the previously returned value is passed as the third argument.
+ */
+XZ_EXTERN uint32_t xz_crc32(const uint8_t *buf, size_t size, uint32_t crc);
+#endif
+
+#if XZ_INTERNAL_CRC64
+/*
+ * This must be called before any other xz_* function (except xz_crc32_init())
+ * to initialize the CRC64 lookup table.
+ */
+XZ_EXTERN void xz_crc64_init(void);
+
+/*
+ * Update CRC64 value using the polynomial from ECMA-182. To start a new
+ * calculation, the third argument must be zero. To continue the calculation,
+ * the previously returned value is passed as the third argument.
+ */
+XZ_EXTERN uint64_t xz_crc64(const uint8_t *buf, size_t size, uint64_t crc);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/source/luametatex/source/libraries/xzembedded/xz_config.h b/source/luametatex/source/libraries/xzembedded/xz_config.h
new file mode 100644
index 000000000..8baf99068
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/xz_config.h
@@ -0,0 +1,145 @@
+/* SPDX-License-Identifier: 0BSD */
+
+/*
+ * Private includes and definitions for userspace use of XZ Embedded
+ *
+ * Author: Lasse Collin <lasse.collin@tukaani.org>
+ */
+
+#ifndef XZ_CONFIG_H
+#define XZ_CONFIG_H
+
+/* Uncomment to enable building of xz_dec_catrun(). */
+#define XZ_DEC_CONCATENATED
+
+/* Uncomment to enable CRC64 support. */
+#define XZ_USE_CRC64
+
+/* Uncomment as needed to enable BCJ filter decoders. */
+/* #define XZ_DEC_X86 */
+/* #define XZ_DEC_ARM */
+/* #define XZ_DEC_ARMTHUMB */
+/* #define XZ_DEC_ARM64 */
+/* #define XZ_DEC_RISCV */
+/* #define XZ_DEC_POWERPC */
+/* #define XZ_DEC_IA64 */
+/* #define XZ_DEC_SPARC */
+
+/*
+ * Visual Studio 2013 update 2 supports only __inline, not inline.
+ * MSVC v19.0 / VS 2015 and newer support both.
+ */
+#if defined(_MSC_VER) && _MSC_VER < 1900 && !defined(inline)
+# define inline __inline
+#endif
+
+#include <stdbool.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "xz.h"
+
+// #define kmalloc(size, flags) malloc(size)
+// #define kfree(ptr) free(ptr)
+// #define vmalloc(size) malloc(size)
+// #define vfree(ptr) free(ptr)
+
+#include "utilities/auxmemory.h"
+
+# define kmalloc(size, flags) lmt_memory_malloc(size)
+# define kfree(ptr) lmt_memory_free (ptr)
+# define vmalloc(size) lmt_memory_malloc(size)
+# define vfree(ptr) lmt_memory_free (ptr)
+
+#define memeq(a, b, size) (memcmp(a, b, size) == 0)
+#define memzero(buf, size) memset(buf, 0, size)
+
+#ifndef min
+# define min(x, y) ((x) < (y) ? (x) : (y))
+#endif
+#define min_t(type, x, y) min(x, y)
+
+#ifndef fallthrough
+# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311
+# define fallthrough [[fallthrough]]
+# elif (defined(__GNUC__) && __GNUC__ >= 7) \
+ || (defined(__clang_major__) && __clang_major__ >= 10)
+# define fallthrough __attribute__((__fallthrough__))
+# else
+# define fallthrough do {} while (0)
+# endif
+#endif
+
+/*
+ * Some functions have been marked with __always_inline to keep the
+ * performance reasonable even when the compiler is optimizing for
+ * small code size. You may be able to save a few bytes by #defining
+ * __always_inline to plain inline, but don't complain if the code
+ * becomes slow.
+ *
+ * NOTE: System headers on GNU/Linux may #define this macro already,
+ * so if you want to change it, you need to #undef it first.
+ */
+#ifndef __always_inline
+# ifdef __GNUC__
+# define __always_inline \
+ inline __attribute__((__always_inline__))
+# else
+# define __always_inline inline
+# endif
+#endif
+
+/* Inline functions to access unaligned unsigned 32-bit integers */
+#ifndef get_unaligned_le32
+static inline uint32_t get_unaligned_le32(const uint8_t *buf)
+{
+ return (uint32_t)buf[0]
+ | ((uint32_t)buf[1] << 8)
+ | ((uint32_t)buf[2] << 16)
+ | ((uint32_t)buf[3] << 24);
+}
+#endif
+
+#ifndef get_unaligned_be32
+static inline uint32_t get_unaligned_be32(const uint8_t *buf)
+{
+ return (uint32_t)((uint32_t)buf[0] << 24)
+ | ((uint32_t)buf[1] << 16)
+ | ((uint32_t)buf[2] << 8)
+ | (uint32_t)buf[3];
+}
+#endif
+
+#ifndef put_unaligned_le32
+static inline void put_unaligned_le32(uint32_t val, uint8_t *buf)
+{
+ buf[0] = (uint8_t)val;
+ buf[1] = (uint8_t)(val >> 8);
+ buf[2] = (uint8_t)(val >> 16);
+ buf[3] = (uint8_t)(val >> 24);
+}
+#endif
+
+#ifndef put_unaligned_be32
+static inline void put_unaligned_be32(uint32_t val, uint8_t *buf)
+{
+ buf[0] = (uint8_t)(val >> 24);
+ buf[1] = (uint8_t)(val >> 16);
+ buf[2] = (uint8_t)(val >> 8);
+ buf[3] = (uint8_t)val;
+}
+#endif
+
+/*
+ * To keep things simpler, use the generic unaligned methods also for
+ * aligned access. The only place where performance could matter is
+ * SHA-256 but files using SHA-256 aren't common.
+ */
+#ifndef get_le32
+# define get_le32 get_unaligned_le32
+#endif
+#ifndef get_be32
+# define get_be32 get_unaligned_be32
+#endif
+
+#endif
diff --git a/source/luametatex/source/libraries/xzembedded/xz_crc32.c b/source/luametatex/source/libraries/xzembedded/xz_crc32.c
new file mode 100644
index 000000000..effdf34ec
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/xz_crc32.c
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: 0BSD
+
+/*
+ * CRC32 using the polynomial from IEEE-802.3
+ *
+ * Authors: Lasse Collin <lasse.collin@tukaani.org>
+ * Igor Pavlov <https://7-zip.org/>
+ */
+
+/*
+ * This is not the fastest implementation, but it is pretty compact.
+ * The fastest versions of xz_crc32() on modern CPUs without hardware
+ * accelerated CRC instruction are 3-5 times as fast as this version,
+ * but they are bigger and use more memory for the lookup table.
+ */
+
+#include "xz_private.h"
+
+/*
+ * STATIC_RW_DATA is used in the pre-boot environment on some architectures.
+ * See <linux/decompress/mm.h> for details.
+ */
+#ifndef STATIC_RW_DATA
+# define STATIC_RW_DATA static
+#endif
+
+STATIC_RW_DATA uint32_t xz_crc32_table[256];
+
+XZ_EXTERN void xz_crc32_init(void)
+{
+ const uint32_t poly = 0xEDB88320;
+
+ uint32_t i;
+ uint32_t j;
+ uint32_t r;
+
+ for (i = 0; i < 256; ++i) {
+ r = i;
+ for (j = 0; j < 8; ++j)
+ r = (r >> 1) ^ (poly & ~((r & 1) - 1));
+
+ xz_crc32_table[i] = r;
+ }
+
+ return;
+}
+
+XZ_EXTERN uint32_t xz_crc32(const uint8_t *buf, size_t size, uint32_t crc)
+{
+ crc = ~crc;
+
+ while (size != 0) {
+ crc = xz_crc32_table[*buf++ ^ (crc & 0xFF)] ^ (crc >> 8);
+ --size;
+ }
+
+ return ~crc;
+}
diff --git a/source/luametatex/source/libraries/xzembedded/xz_crc64.c b/source/luametatex/source/libraries/xzembedded/xz_crc64.c
new file mode 100644
index 000000000..20049ea55
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/xz_crc64.c
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: 0BSD
+
+/*
+ * CRC64 using the polynomial from ECMA-182
+ *
+ * This file is similar to xz_crc32.c. See the comments there.
+ *
+ * Authors: Lasse Collin <lasse.collin@tukaani.org>
+ * Igor Pavlov <https://7-zip.org/>
+ */
+
+#include "xz_private.h"
+
+#ifndef STATIC_RW_DATA
+# define STATIC_RW_DATA static
+#endif
+
+STATIC_RW_DATA uint64_t xz_crc64_table[256];
+
+XZ_EXTERN void xz_crc64_init(void)
+{
+ /*
+ * The ULL suffix is needed for -std=gnu89 compatibility
+ * on 32-bit platforms.
+ */
+ const uint64_t poly = 0xC96C5795D7870F42ULL;
+
+ uint32_t i;
+ uint32_t j;
+ uint64_t r;
+
+ for (i = 0; i < 256; ++i) {
+ r = i;
+ for (j = 0; j < 8; ++j)
+ r = (r >> 1) ^ (poly & ~((r & 1) - 1));
+
+ xz_crc64_table[i] = r;
+ }
+
+ return;
+}
+
+XZ_EXTERN uint64_t xz_crc64(const uint8_t *buf, size_t size, uint64_t crc)
+{
+ crc = ~crc;
+
+ while (size != 0) {
+ crc = xz_crc64_table[*buf++ ^ (crc & 0xFF)] ^ (crc >> 8);
+ --size;
+ }
+
+ return ~crc;
+}
diff --git a/source/luametatex/source/libraries/xzembedded/xz_dec_bcj.c b/source/luametatex/source/libraries/xzembedded/xz_dec_bcj.c
new file mode 100644
index 000000000..42d7f2687
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/xz_dec_bcj.c
@@ -0,0 +1,738 @@
+// SPDX-License-Identifier: 0BSD
+
+/*
+ * Branch/Call/Jump (BCJ) filter decoders
+ *
+ * Authors: Lasse Collin <lasse.collin@tukaani.org>
+ * Igor Pavlov <https://7-zip.org/>
+ */
+
+#include "xz_private.h"
+
+/*
+ * The rest of the file is inside this ifdef. It makes things a little more
+ * convenient when building without support for any BCJ filters.
+ */
+#ifdef XZ_DEC_BCJ
+
+struct xz_dec_bcj {
+ /* Type of the BCJ filter being used */
+ enum {
+ BCJ_X86 = 4, /* x86 or x86-64 */
+ BCJ_POWERPC = 5, /* Big endian only */
+ BCJ_IA64 = 6, /* Big or little endian */
+ BCJ_ARM = 7, /* Little endian only */
+ BCJ_ARMTHUMB = 8, /* Little endian only */
+ BCJ_SPARC = 9, /* Big or little endian */
+ BCJ_ARM64 = 10, /* AArch64 */
+ BCJ_RISCV = 11 /* RV32GQC_Zfh, RV64GQC_Zfh */
+ } type;
+
+ /*
+ * Return value of the next filter in the chain. We need to preserve
+ * this information across calls, because we must not call the next
+ * filter anymore once it has returned XZ_STREAM_END.
+ */
+ enum xz_ret ret;
+
+ /* True if we are operating in single-call mode. */
+ bool single_call;
+
+ /*
+ * Absolute position relative to the beginning of the uncompressed
+ * data (in a single .xz Block). We care only about the lowest 32
+ * bits so this doesn't need to be uint64_t even with big files.
+ */
+ uint32_t pos;
+
+ /* x86 filter state */
+ uint32_t x86_prev_mask;
+
+ /* Temporary space to hold the variables from struct xz_buf */
+ uint8_t *out;
+ size_t out_pos;
+ size_t out_size;
+
+ struct {
+ /* Amount of already filtered data in the beginning of buf */
+ size_t filtered;
+
+ /* Total amount of data currently stored in buf */
+ size_t size;
+
+ /*
+ * Buffer to hold a mix of filtered and unfiltered data. This
+ * needs to be big enough to hold Alignment + 2 * Look-ahead:
+ *
+ * Type Alignment Look-ahead
+ * x86 1 4
+ * PowerPC 4 0
+ * IA-64 16 0
+ * ARM 4 0
+ * ARM-Thumb 2 2
+ * SPARC 4 0
+ */
+ uint8_t buf[16];
+ } temp;
+};
+
+#ifdef XZ_DEC_X86
+/*
+ * This is used to test the most significant byte of a memory address
+ * in an x86 instruction.
+ */
+static inline int bcj_x86_test_msbyte(uint8_t b)
+{
+ return b == 0x00 || b == 0xFF;
+}
+
+static size_t bcj_x86(struct xz_dec_bcj *s, uint8_t *buf, size_t size)
+{
+ static const bool mask_to_allowed_status[8]
+ = { true, true, true, false, true, false, false, false };
+
+ static const uint8_t mask_to_bit_num[8] = { 0, 1, 2, 2, 3, 3, 3, 3 };
+
+ size_t i;
+ size_t prev_pos = (size_t)-1;
+ uint32_t prev_mask = s->x86_prev_mask;
+ uint32_t src;
+ uint32_t dest;
+ uint32_t j;
+ uint8_t b;
+
+ if (size <= 4)
+ return 0;
+
+ size -= 4;
+ for (i = 0; i < size; ++i) {
+ if ((buf[i] & 0xFE) != 0xE8)
+ continue;
+
+ prev_pos = i - prev_pos;
+ if (prev_pos > 3) {
+ prev_mask = 0;
+ } else {
+ prev_mask = (prev_mask << (prev_pos - 1)) & 7;
+ if (prev_mask != 0) {
+ b = buf[i + 4 - mask_to_bit_num[prev_mask]];
+ if (!mask_to_allowed_status[prev_mask]
+ || bcj_x86_test_msbyte(b)) {
+ prev_pos = i;
+ prev_mask = (prev_mask << 1) | 1;
+ continue;
+ }
+ }
+ }
+
+ prev_pos = i;
+
+ if (bcj_x86_test_msbyte(buf[i + 4])) {
+ src = get_unaligned_le32(buf + i + 1);
+ while (true) {
+ dest = src - (s->pos + (uint32_t)i + 5);
+ if (prev_mask == 0)
+ break;
+
+ j = mask_to_bit_num[prev_mask] * 8;
+ b = (uint8_t)(dest >> (24 - j));
+ if (!bcj_x86_test_msbyte(b))
+ break;
+
+ src = dest ^ (((uint32_t)1 << (32 - j)) - 1);
+ }
+
+ dest &= 0x01FFFFFF;
+ dest |= (uint32_t)0 - (dest & 0x01000000);
+ put_unaligned_le32(dest, buf + i + 1);
+ i += 4;
+ } else {
+ prev_mask = (prev_mask << 1) | 1;
+ }
+ }
+
+ prev_pos = i - prev_pos;
+ s->x86_prev_mask = prev_pos > 3 ? 0 : prev_mask << (prev_pos - 1);
+ return i;
+}
+#endif
+
+#ifdef XZ_DEC_POWERPC
+static size_t bcj_powerpc(struct xz_dec_bcj *s, uint8_t *buf, size_t size)
+{
+ size_t i;
+ uint32_t instr;
+
+ size &= ~(size_t)3;
+
+ for (i = 0; i < size; i += 4) {
+ instr = get_unaligned_be32(buf + i);
+ if ((instr & 0xFC000003) == 0x48000001) {
+ instr &= 0x03FFFFFC;
+ instr -= s->pos + (uint32_t)i;
+ instr &= 0x03FFFFFC;
+ instr |= 0x48000001;
+ put_unaligned_be32(instr, buf + i);
+ }
+ }
+
+ return i;
+}
+#endif
+
+#ifdef XZ_DEC_IA64
+static size_t bcj_ia64(struct xz_dec_bcj *s, uint8_t *buf, size_t size)
+{
+ static const uint8_t branch_table[32] = {
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 4, 4, 6, 6, 0, 0, 7, 7,
+ 4, 4, 0, 0, 4, 4, 0, 0
+ };
+
+ /*
+ * The local variables take a little bit stack space, but it's less
+ * than what LZMA2 decoder takes, so it doesn't make sense to reduce
+ * stack usage here without doing that for the LZMA2 decoder too.
+ */
+
+ /* Loop counters */
+ size_t i;
+ size_t j;
+
+ /* Instruction slot (0, 1, or 2) in the 128-bit instruction word */
+ uint32_t slot;
+
+ /* Bitwise offset of the instruction indicated by slot */
+ uint32_t bit_pos;
+
+ /* bit_pos split into byte and bit parts */
+ uint32_t byte_pos;
+ uint32_t bit_res;
+
+ /* Address part of an instruction */
+ uint32_t addr;
+
+ /* Mask used to detect which instructions to convert */
+ uint32_t mask;
+
+ /* 41-bit instruction stored somewhere in the lowest 48 bits */
+ uint64_t instr;
+
+ /* Instruction normalized with bit_res for easier manipulation */
+ uint64_t norm;
+
+ size &= ~(size_t)15;
+
+ for (i = 0; i < size; i += 16) {
+ mask = branch_table[buf[i] & 0x1F];
+ for (slot = 0, bit_pos = 5; slot < 3; ++slot, bit_pos += 41) {
+ if (((mask >> slot) & 1) == 0)
+ continue;
+
+ byte_pos = bit_pos >> 3;
+ bit_res = bit_pos & 7;
+ instr = 0;
+ for (j = 0; j < 6; ++j)
+ instr |= (uint64_t)(buf[i + j + byte_pos])
+ << (8 * j);
+
+ norm = instr >> bit_res;
+
+ if (((norm >> 37) & 0x0F) == 0x05
+ && ((norm >> 9) & 0x07) == 0) {
+ addr = (norm >> 13) & 0x0FFFFF;
+ addr |= ((uint32_t)(norm >> 36) & 1) << 20;
+ addr <<= 4;
+ addr -= s->pos + (uint32_t)i;
+ addr >>= 4;
+
+ norm &= ~((uint64_t)0x8FFFFF << 13);
+ norm |= (uint64_t)(addr & 0x0FFFFF) << 13;
+ norm |= (uint64_t)(addr & 0x100000)
+ << (36 - 20);
+
+ instr &= (1 << bit_res) - 1;
+ instr |= norm << bit_res;
+
+ for (j = 0; j < 6; j++)
+ buf[i + j + byte_pos]
+ = (uint8_t)(instr >> (8 * j));
+ }
+ }
+ }
+
+ return i;
+}
+#endif
+
+#ifdef XZ_DEC_ARM
+static size_t bcj_arm(struct xz_dec_bcj *s, uint8_t *buf, size_t size)
+{
+ size_t i;
+ uint32_t addr;
+
+ size &= ~(size_t)3;
+
+ for (i = 0; i < size; i += 4) {
+ if (buf[i + 3] == 0xEB) {
+ addr = (uint32_t)buf[i] | ((uint32_t)buf[i + 1] << 8)
+ | ((uint32_t)buf[i + 2] << 16);
+ addr <<= 2;
+ addr -= s->pos + (uint32_t)i + 8;
+ addr >>= 2;
+ buf[i] = (uint8_t)addr;
+ buf[i + 1] = (uint8_t)(addr >> 8);
+ buf[i + 2] = (uint8_t)(addr >> 16);
+ }
+ }
+
+ return i;
+}
+#endif
+
+#ifdef XZ_DEC_ARMTHUMB
+static size_t bcj_armthumb(struct xz_dec_bcj *s, uint8_t *buf, size_t size)
+{
+ size_t i;
+ uint32_t addr;
+
+ if (size < 4)
+ return 0;
+
+ size -= 4;
+
+ for (i = 0; i <= size; i += 2) {
+ if ((buf[i + 1] & 0xF8) == 0xF0
+ && (buf[i + 3] & 0xF8) == 0xF8) {
+ addr = (((uint32_t)buf[i + 1] & 0x07) << 19)
+ | ((uint32_t)buf[i] << 11)
+ | (((uint32_t)buf[i + 3] & 0x07) << 8)
+ | (uint32_t)buf[i + 2];
+ addr <<= 1;
+ addr -= s->pos + (uint32_t)i + 4;
+ addr >>= 1;
+ buf[i + 1] = (uint8_t)(0xF0 | ((addr >> 19) & 0x07));
+ buf[i] = (uint8_t)(addr >> 11);
+ buf[i + 3] = (uint8_t)(0xF8 | ((addr >> 8) & 0x07));
+ buf[i + 2] = (uint8_t)addr;
+ i += 2;
+ }
+ }
+
+ return i;
+}
+#endif
+
+#ifdef XZ_DEC_SPARC
+static size_t bcj_sparc(struct xz_dec_bcj *s, uint8_t *buf, size_t size)
+{
+ size_t i;
+ uint32_t instr;
+
+ size &= ~(size_t)3;
+
+ for (i = 0; i < size; i += 4) {
+ instr = get_unaligned_be32(buf + i);
+ if ((instr >> 22) == 0x100 || (instr >> 22) == 0x1FF) {
+ instr <<= 2;
+ instr -= s->pos + (uint32_t)i;
+ instr >>= 2;
+ instr = ((uint32_t)0x40000000 - (instr & 0x400000))
+ | 0x40000000 | (instr & 0x3FFFFF);
+ put_unaligned_be32(instr, buf + i);
+ }
+ }
+
+ return i;
+}
+#endif
+
+#ifdef XZ_DEC_ARM64
+static size_t bcj_arm64(struct xz_dec_bcj *s, uint8_t *buf, size_t size)
+{
+ size_t i;
+ uint32_t instr;
+ uint32_t addr;
+
+ size &= ~(size_t)3;
+
+ for (i = 0; i < size; i += 4) {
+ instr = get_unaligned_le32(buf + i);
+
+ if ((instr >> 26) == 0x25) {
+ /* BL instruction */
+ addr = instr - ((s->pos + (uint32_t)i) >> 2);
+ instr = 0x94000000 | (addr & 0x03FFFFFF);
+ put_unaligned_le32(instr, buf + i);
+
+ } else if ((instr & 0x9F000000) == 0x90000000) {
+ /* ADRP instruction */
+ addr = ((instr >> 29) & 3) | ((instr >> 3) & 0x1FFFFC);
+
+ /* Only convert values in the range +/-512 MiB. */
+ if ((addr + 0x020000) & 0x1C0000)
+ continue;
+
+ addr -= (s->pos + (uint32_t)i) >> 12;
+
+ instr &= 0x9000001F;
+ instr |= (addr & 3) << 29;
+ instr |= (addr & 0x03FFFC) << 3;
+ instr |= (0U - (addr & 0x020000)) & 0xE00000;
+
+ put_unaligned_le32(instr, buf + i);
+ }
+ }
+
+ return i;
+}
+#endif
+
+#ifdef XZ_DEC_RISCV
+static size_t bcj_riscv(struct xz_dec_bcj *s, uint8_t *buf, size_t size)
+{
+ size_t i;
+ uint32_t b1;
+ uint32_t b2;
+ uint32_t b3;
+ uint32_t instr;
+ uint32_t instr2;
+ uint32_t instr2_rs1;
+ uint32_t addr;
+
+ if (size < 8)
+ return 0;
+
+ size -= 8;
+
+ for (i = 0; i <= size; i += 2) {
+ instr = buf[i];
+
+ if (instr == 0xEF) {
+ /* JAL */
+ b1 = buf[i + 1];
+ if ((b1 & 0x0D) != 0)
+ continue;
+
+ b2 = buf[i + 2];
+ b3 = buf[i + 3];
+
+ addr = ((b1 & 0xF0) << 13) | (b2 << 9) | (b3 << 1);
+ addr -= s->pos + (uint32_t)i;
+
+ buf[i + 1] = (uint8_t)((b1 & 0x0F)
+ | ((addr >> 8) & 0xF0));
+
+ buf[i + 2] = (uint8_t)(((addr >> 16) & 0x0F)
+ | ((addr >> 7) & 0x10)
+ | ((addr << 4) & 0xE0));
+
+ buf[i + 3] = (uint8_t)(((addr >> 4) & 0x7F)
+ | ((addr >> 13) & 0x80));
+
+ i += 4 - 2;
+
+ } else if ((instr & 0x7F) == 0x17) {
+ /* AUIPC */
+ instr |= (uint32_t)buf[i + 1] << 8;
+ instr |= (uint32_t)buf[i + 2] << 16;
+ instr |= (uint32_t)buf[i + 3] << 24;
+
+ if (instr & 0xE80) {
+ /* AUIPC's rd doesn't equal x0 or x2. */
+ instr2 = get_unaligned_le32(buf + i + 4);
+
+ if (((instr << 8) ^ (instr2 - 3)) & 0xF8003) {
+ i += 6 - 2;
+ continue;
+ }
+
+ addr = (instr & 0xFFFFF000) + (instr2 >> 20);
+
+ instr = 0x17 | (2 << 7) | (instr2 << 12);
+ instr2 = addr;
+ } else {
+ /* AUIPC's rd equals x0 or x2. */
+ instr2_rs1 = instr >> 27;
+
+ if ((uint32_t)((instr - 0x3117) << 18)
+ >= (instr2_rs1 & 0x1D)) {
+ i += 4 - 2;
+ continue;
+ }
+
+ addr = get_unaligned_be32(buf + i + 4);
+ addr -= s->pos + (uint32_t)i;
+
+ instr2 = (instr >> 12) | (addr << 20);
+
+ instr = 0x17 | (instr2_rs1 << 7)
+ | ((addr + 0x800) & 0xFFFFF000);
+ }
+
+ put_unaligned_le32(instr, buf + i);
+ put_unaligned_le32(instr2, buf + i + 4);
+
+ i += 8 - 2;
+ }
+ }
+
+ return i;
+}
+#endif
+
+/*
+ * Apply the selected BCJ filter. Update *pos and s->pos to match the amount
+ * of data that got filtered.
+ *
+ * NOTE: This is implemented as a switch statement to avoid using function
+ * pointers, which could be problematic in the kernel boot code, which must
+ * avoid pointers to static data (at least on x86).
+ */
+static void bcj_apply(struct xz_dec_bcj *s,
+ uint8_t *buf, size_t *pos, size_t size)
+{
+ size_t filtered;
+
+ buf += *pos;
+ size -= *pos;
+
+ switch (s->type) {
+#ifdef XZ_DEC_X86
+ case BCJ_X86:
+ filtered = bcj_x86(s, buf, size);
+ break;
+#endif
+#ifdef XZ_DEC_POWERPC
+ case BCJ_POWERPC:
+ filtered = bcj_powerpc(s, buf, size);
+ break;
+#endif
+#ifdef XZ_DEC_IA64
+ case BCJ_IA64:
+ filtered = bcj_ia64(s, buf, size);
+ break;
+#endif
+#ifdef XZ_DEC_ARM
+ case BCJ_ARM:
+ filtered = bcj_arm(s, buf, size);
+ break;
+#endif
+#ifdef XZ_DEC_ARMTHUMB
+ case BCJ_ARMTHUMB:
+ filtered = bcj_armthumb(s, buf, size);
+ break;
+#endif
+#ifdef XZ_DEC_SPARC
+ case BCJ_SPARC:
+ filtered = bcj_sparc(s, buf, size);
+ break;
+#endif
+#ifdef XZ_DEC_ARM64
+ case BCJ_ARM64:
+ filtered = bcj_arm64(s, buf, size);
+ break;
+#endif
+#ifdef XZ_DEC_RISCV
+ case BCJ_RISCV:
+ filtered = bcj_riscv(s, buf, size);
+ break;
+#endif
+ default:
+ /* Never reached but silence compiler warnings. */
+ filtered = 0;
+ break;
+ }
+
+ *pos += filtered;
+ s->pos += filtered;
+}
+
+/*
+ * Flush pending filtered data from temp to the output buffer.
+ * Move the remaining mixture of possibly filtered and unfiltered
+ * data to the beginning of temp.
+ */
+static void bcj_flush(struct xz_dec_bcj *s, struct xz_buf *b)
+{
+ size_t copy_size;
+
+ copy_size = min_t(size_t, s->temp.filtered, b->out_size - b->out_pos);
+ memcpy(b->out + b->out_pos, s->temp.buf, copy_size);
+ b->out_pos += copy_size;
+
+ s->temp.filtered -= copy_size;
+ s->temp.size -= copy_size;
+ memmove(s->temp.buf, s->temp.buf + copy_size, s->temp.size);
+}
+
+/*
+ * The BCJ filter functions are primitive in sense that they process the
+ * data in chunks of 1-16 bytes. To hide this issue, this function does
+ * some buffering.
+ */
+XZ_EXTERN enum xz_ret xz_dec_bcj_run(struct xz_dec_bcj *s,
+ struct xz_dec_lzma2 *lzma2,
+ struct xz_buf *b)
+{
+ size_t out_start;
+
+ /*
+ * Flush pending already filtered data to the output buffer. Return
+ * immediately if we couldn't flush everything, or if the next
+ * filter in the chain had already returned XZ_STREAM_END.
+ */
+ if (s->temp.filtered > 0) {
+ bcj_flush(s, b);
+ if (s->temp.filtered > 0)
+ return XZ_OK;
+
+ if (s->ret == XZ_STREAM_END)
+ return XZ_STREAM_END;
+ }
+
+ /*
+ * If we have more output space than what is currently pending in
+ * temp, copy the unfiltered data from temp to the output buffer
+ * and try to fill the output buffer by decoding more data from the
+ * next filter in the chain. Apply the BCJ filter on the new data
+ * in the output buffer. If everything cannot be filtered, copy it
+ * to temp and rewind the output buffer position accordingly.
+ *
+ * This needs to be always run when temp.size == 0 to handle a special
+ * case where the output buffer is full and the next filter has no
+ * more output coming but hasn't returned XZ_STREAM_END yet.
+ */
+ if (s->temp.size < b->out_size - b->out_pos || s->temp.size == 0) {
+ out_start = b->out_pos;
+ memcpy(b->out + b->out_pos, s->temp.buf, s->temp.size);
+ b->out_pos += s->temp.size;
+
+ s->ret = xz_dec_lzma2_run(lzma2, b);
+ if (s->ret != XZ_STREAM_END
+ && (s->ret != XZ_OK || s->single_call))
+ return s->ret;
+
+ bcj_apply(s, b->out, &out_start, b->out_pos);
+
+ /*
+ * As an exception, if the next filter returned XZ_STREAM_END,
+ * we can do that too, since the last few bytes that remain
+ * unfiltered are meant to remain unfiltered.
+ */
+ if (s->ret == XZ_STREAM_END)
+ return XZ_STREAM_END;
+
+ s->temp.size = b->out_pos - out_start;
+ b->out_pos -= s->temp.size;
+ memcpy(s->temp.buf, b->out + b->out_pos, s->temp.size);
+
+ /*
+ * If there wasn't enough input to the next filter to fill
+ * the output buffer with unfiltered data, there's no point
+ * to try decoding more data to temp.
+ */
+ if (b->out_pos + s->temp.size < b->out_size)
+ return XZ_OK;
+ }
+
+ /*
+ * We have unfiltered data in temp. If the output buffer isn't full
+ * yet, try to fill the temp buffer by decoding more data from the
+ * next filter. Apply the BCJ filter on temp. Then we hopefully can
+ * fill the actual output buffer by copying filtered data from temp.
+ * A mix of filtered and unfiltered data may be left in temp; it will
+ * be taken care on the next call to this function.
+ */
+ if (b->out_pos < b->out_size) {
+ /* Make b->out{,_pos,_size} temporarily point to s->temp. */
+ s->out = b->out;
+ s->out_pos = b->out_pos;
+ s->out_size = b->out_size;
+ b->out = s->temp.buf;
+ b->out_pos = s->temp.size;
+ b->out_size = sizeof(s->temp.buf);
+
+ s->ret = xz_dec_lzma2_run(lzma2, b);
+
+ s->temp.size = b->out_pos;
+ b->out = s->out;
+ b->out_pos = s->out_pos;
+ b->out_size = s->out_size;
+
+ if (s->ret != XZ_OK && s->ret != XZ_STREAM_END)
+ return s->ret;
+
+ bcj_apply(s, s->temp.buf, &s->temp.filtered, s->temp.size);
+
+ /*
+ * If the next filter returned XZ_STREAM_END, we mark that
+ * everything is filtered, since the last unfiltered bytes
+ * of the stream are meant to be left as is.
+ */
+ if (s->ret == XZ_STREAM_END)
+ s->temp.filtered = s->temp.size;
+
+ bcj_flush(s, b);
+ if (s->temp.filtered > 0)
+ return XZ_OK;
+ }
+
+ return s->ret;
+}
+
+XZ_EXTERN struct xz_dec_bcj *xz_dec_bcj_create(bool single_call)
+{
+ struct xz_dec_bcj *s = kmalloc(sizeof(*s), GFP_KERNEL);
+ if (s != NULL)
+ s->single_call = single_call;
+
+ return s;
+}
+
+XZ_EXTERN enum xz_ret xz_dec_bcj_reset(struct xz_dec_bcj *s, uint8_t id)
+{
+ switch (id) {
+#ifdef XZ_DEC_X86
+ case BCJ_X86:
+#endif
+#ifdef XZ_DEC_POWERPC
+ case BCJ_POWERPC:
+#endif
+#ifdef XZ_DEC_IA64
+ case BCJ_IA64:
+#endif
+#ifdef XZ_DEC_ARM
+ case BCJ_ARM:
+#endif
+#ifdef XZ_DEC_ARMTHUMB
+ case BCJ_ARMTHUMB:
+#endif
+#ifdef XZ_DEC_SPARC
+ case BCJ_SPARC:
+#endif
+#ifdef XZ_DEC_ARM64
+ case BCJ_ARM64:
+#endif
+#ifdef XZ_DEC_RISCV
+ case BCJ_RISCV:
+#endif
+ break;
+
+ default:
+ /* Unsupported Filter ID */
+ return XZ_OPTIONS_ERROR;
+ }
+
+ s->type = id;
+ s->ret = XZ_OK;
+ s->pos = 0;
+ s->x86_prev_mask = 0;
+ s->temp.filtered = 0;
+ s->temp.size = 0;
+
+ return XZ_OK;
+}
+
+#endif
diff --git a/source/luametatex/source/libraries/xzembedded/xz_dec_lzma2.c b/source/luametatex/source/libraries/xzembedded/xz_dec_lzma2.c
new file mode 100644
index 000000000..475c378e2
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/xz_dec_lzma2.c
@@ -0,0 +1,1345 @@
+// SPDX-License-Identifier: 0BSD
+
+/*
+ * LZMA2 decoder
+ *
+ * Authors: Lasse Collin <lasse.collin@tukaani.org>
+ * Igor Pavlov <https://7-zip.org/>
+ */
+
+#include "xz_private.h"
+#include "xz_lzma2.h"
+
+/*
+ * Range decoder initialization eats the first five bytes of each LZMA chunk.
+ */
+#define RC_INIT_BYTES 5
+
+/*
+ * Minimum number of usable input buffer to safely decode one LZMA symbol.
+ * The worst case is that we decode 22 bits using probabilities and 26
+ * direct bits. This may decode at maximum of 20 bytes of input. However,
+ * lzma_main() does an extra normalization before returning, thus we
+ * need to put 21 here.
+ */
+#define LZMA_IN_REQUIRED 21
+
+/*
+ * Dictionary (history buffer)
+ *
+ * These are always true:
+ * start <= pos <= full <= end
+ * pos <= limit <= end
+ *
+ * In multi-call mode, also these are true:
+ * end == size
+ * size <= size_max
+ * allocated <= size
+ *
+ * Most of these variables are size_t to support single-call mode,
+ * in which the dictionary variables address the actual output
+ * buffer directly.
+ */
+struct dictionary {
+ /* Beginning of the history buffer */
+ uint8_t *buf;
+
+ /* Old position in buf (before decoding more data) */
+ size_t start;
+
+ /* Position in buf */
+ size_t pos;
+
+ /*
+ * How full dictionary is. This is used to detect corrupt input that
+ * would read beyond the beginning of the uncompressed stream.
+ */
+ size_t full;
+
+ /* Write limit; we don't write to buf[limit] or later bytes. */
+ size_t limit;
+
+ /*
+ * End of the dictionary buffer. In multi-call mode, this is
+ * the same as the dictionary size. In single-call mode, this
+ * indicates the size of the output buffer.
+ */
+ size_t end;
+
+ /*
+ * Size of the dictionary as specified in Block Header. This is used
+ * together with "full" to detect corrupt input that would make us
+ * read beyond the beginning of the uncompressed stream.
+ */
+ uint32_t size;
+
+ /*
+ * Maximum allowed dictionary size in multi-call mode.
+ * This is ignored in single-call mode.
+ */
+ uint32_t size_max;
+
+ /*
+ * Amount of memory currently allocated for the dictionary.
+ * This is used only with XZ_DYNALLOC. (With XZ_PREALLOC,
+ * size_max is always the same as the allocated size.)
+ */
+ uint32_t allocated;
+
+ /* Operation mode */
+ enum xz_mode mode;
+};
+
+/* Range decoder */
+struct rc_dec {
+ uint32_t range;
+ uint32_t code;
+
+ /*
+ * Number of initializing bytes remaining to be read
+ * by rc_read_init().
+ */
+ uint32_t init_bytes_left;
+
+ /*
+ * Buffer from which we read our input. It can be either
+ * temp.buf or the caller-provided input buffer.
+ */
+ const uint8_t *in;
+ size_t in_pos;
+ size_t in_limit;
+};
+
+/* Probabilities for a length decoder. */
+struct lzma_len_dec {
+ /* Probability of match length being at least 10 */
+ uint16_t choice;
+
+ /* Probability of match length being at least 18 */
+ uint16_t choice2;
+
+ /* Probabilities for match lengths 2-9 */
+ uint16_t low[POS_STATES_MAX][LEN_LOW_SYMBOLS];
+
+ /* Probabilities for match lengths 10-17 */
+ uint16_t mid[POS_STATES_MAX][LEN_MID_SYMBOLS];
+
+ /* Probabilities for match lengths 18-273 */
+ uint16_t high[LEN_HIGH_SYMBOLS];
+};
+
+struct lzma_dec {
+ /* Distances of latest four matches */
+ uint32_t rep0;
+ uint32_t rep1;
+ uint32_t rep2;
+ uint32_t rep3;
+
+ /* Types of the most recently seen LZMA symbols */
+ enum lzma_state state;
+
+ /*
+ * Length of a match. This is updated so that dict_repeat can
+ * be called again to finish repeating the whole match.
+ */
+ uint32_t len;
+
+ /*
+ * LZMA properties or related bit masks (number of literal
+ * context bits, a mask derived from the number of literal
+ * position bits, and a mask derived from the number
+ * position bits)
+ */
+ uint32_t lc;
+ uint32_t literal_pos_mask; /* (1 << lp) - 1 */
+ uint32_t pos_mask; /* (1 << pb) - 1 */
+
+ /* If 1, it's a match. Otherwise it's a single 8-bit literal. */
+ uint16_t is_match[STATES][POS_STATES_MAX];
+
+ /* If 1, it's a repeated match. The distance is one of rep0 .. rep3. */
+ uint16_t is_rep[STATES];
+
+ /*
+ * If 0, distance of a repeated match is rep0.
+ * Otherwise check is_rep1.
+ */
+ uint16_t is_rep0[STATES];
+
+ /*
+ * If 0, distance of a repeated match is rep1.
+ * Otherwise check is_rep2.
+ */
+ uint16_t is_rep1[STATES];
+
+ /* If 0, distance of a repeated match is rep2. Otherwise it is rep3. */
+ uint16_t is_rep2[STATES];
+
+ /*
+ * If 1, the repeated match has length of one byte. Otherwise
+ * the length is decoded from rep_len_decoder.
+ */
+ uint16_t is_rep0_long[STATES][POS_STATES_MAX];
+
+ /*
+ * Probability tree for the highest two bits of the match
+ * distance. There is a separate probability tree for match
+ * lengths of 2 (i.e. MATCH_LEN_MIN), 3, 4, and [5, 273].
+ */
+ uint16_t dist_slot[DIST_STATES][DIST_SLOTS];
+
+ /*
+ * Probability trees for additional bits for match distance
+ * when the distance is in the range [4, 127].
+ */
+ uint16_t dist_special[FULL_DISTANCES - DIST_MODEL_END];
+
+ /*
+ * Probability tree for the lowest four bits of a match
+ * distance that is equal to or greater than 128.
+ */
+ uint16_t dist_align[ALIGN_SIZE];
+
+ /* Length of a normal match */
+ struct lzma_len_dec match_len_dec;
+
+ /* Length of a repeated match */
+ struct lzma_len_dec rep_len_dec;
+
+ /* Probabilities of literals */
+ uint16_t literal[LITERAL_CODERS_MAX][LITERAL_CODER_SIZE];
+};
+
+struct lzma2_dec {
+ /* Position in xz_dec_lzma2_run(). */
+ enum lzma2_seq {
+ SEQ_CONTROL,
+ SEQ_UNCOMPRESSED_1,
+ SEQ_UNCOMPRESSED_2,
+ SEQ_COMPRESSED_0,
+ SEQ_COMPRESSED_1,
+ SEQ_PROPERTIES,
+ SEQ_LZMA_PREPARE,
+ SEQ_LZMA_RUN,
+ SEQ_COPY
+ } sequence;
+
+ /* Next position after decoding the compressed size of the chunk. */
+ enum lzma2_seq next_sequence;
+
+ /* Uncompressed size of LZMA chunk (2 MiB at maximum) */
+ uint32_t uncompressed;
+
+ /*
+ * Compressed size of LZMA chunk or compressed/uncompressed
+ * size of uncompressed chunk (64 KiB at maximum)
+ */
+ uint32_t compressed;
+
+ /*
+ * True if dictionary reset is needed. This is false before
+ * the first chunk (LZMA or uncompressed).
+ */
+ bool need_dict_reset;
+
+ /*
+ * True if new LZMA properties are needed. This is false
+ * before the first LZMA chunk.
+ */
+ bool need_props;
+
+#ifdef XZ_DEC_MICROLZMA
+ bool pedantic_microlzma;
+#endif
+};
+
+struct xz_dec_lzma2 {
+ /*
+ * The order below is important on x86 to reduce code size and
+ * it shouldn't hurt on other platforms. Everything up to and
+ * including lzma.pos_mask are in the first 128 bytes on x86-32,
+ * which allows using smaller instructions to access those
+ * variables. On x86-64, fewer variables fit into the first 128
+ * bytes, but this is still the best order without sacrificing
+ * the readability by splitting the structures.
+ */
+ struct rc_dec rc;
+ struct dictionary dict;
+ struct lzma2_dec lzma2;
+ struct lzma_dec lzma;
+
+ /*
+ * Temporary buffer which holds small number of input bytes between
+ * decoder calls. See lzma2_lzma() for details.
+ */
+ struct {
+ uint32_t size;
+ uint8_t buf[3 * LZMA_IN_REQUIRED];
+ } temp;
+};
+
+/**************
+ * Dictionary *
+ **************/
+
+/*
+ * Reset the dictionary state. When in single-call mode, set up the beginning
+ * of the dictionary to point to the actual output buffer.
+ */
+static void dict_reset(struct dictionary *dict, struct xz_buf *b)
+{
+ if (DEC_IS_SINGLE(dict->mode)) {
+ dict->buf = b->out + b->out_pos;
+ dict->end = b->out_size - b->out_pos;
+ }
+
+ dict->start = 0;
+ dict->pos = 0;
+ dict->limit = 0;
+ dict->full = 0;
+}
+
+/* Set dictionary write limit */
+static void dict_limit(struct dictionary *dict, size_t out_max)
+{
+ if (dict->end - dict->pos <= out_max)
+ dict->limit = dict->end;
+ else
+ dict->limit = dict->pos + out_max;
+}
+
+/* Return true if at least one byte can be written into the dictionary. */
+static inline bool dict_has_space(const struct dictionary *dict)
+{
+ return dict->pos < dict->limit;
+}
+
+/*
+ * Get a byte from the dictionary at the given distance. The distance is
+ * assumed to valid, or as a special case, zero when the dictionary is
+ * still empty. This special case is needed for single-call decoding to
+ * avoid writing a '\0' to the end of the destination buffer.
+ */
+static inline uint32_t dict_get(const struct dictionary *dict, uint32_t dist)
+{
+ size_t offset = dict->pos - dist - 1;
+
+ if (dist >= dict->pos)
+ offset += dict->end;
+
+ return dict->full > 0 ? dict->buf[offset] : 0;
+}
+
+/*
+ * Put one byte into the dictionary. It is assumed that there is space for it.
+ */
+static inline void dict_put(struct dictionary *dict, uint8_t byte)
+{
+ dict->buf[dict->pos++] = byte;
+
+ if (dict->full < dict->pos)
+ dict->full = dict->pos;
+}
+
+/*
+ * Repeat given number of bytes from the given distance. If the distance is
+ * invalid, false is returned. On success, true is returned and *len is
+ * updated to indicate how many bytes were left to be repeated.
+ */
+static bool dict_repeat(struct dictionary *dict, uint32_t *len, uint32_t dist)
+{
+ size_t back;
+ uint32_t left;
+
+ if (dist >= dict->full || dist >= dict->size)
+ return false;
+
+ left = min_t(size_t, dict->limit - dict->pos, *len);
+ *len -= left;
+
+ back = dict->pos - dist - 1;
+ if (dist >= dict->pos)
+ back += dict->end;
+
+ do {
+ dict->buf[dict->pos++] = dict->buf[back++];
+ if (back == dict->end)
+ back = 0;
+ } while (--left > 0);
+
+ if (dict->full < dict->pos)
+ dict->full = dict->pos;
+
+ return true;
+}
+
+/* Copy uncompressed data as is from input to dictionary and output buffers. */
+static void dict_uncompressed(struct dictionary *dict, struct xz_buf *b,
+ uint32_t *left)
+{
+ size_t copy_size;
+
+ while (*left > 0 && b->in_pos < b->in_size
+ && b->out_pos < b->out_size) {
+ copy_size = min(b->in_size - b->in_pos,
+ b->out_size - b->out_pos);
+ if (copy_size > dict->end - dict->pos)
+ copy_size = dict->end - dict->pos;
+ if (copy_size > *left)
+ copy_size = *left;
+
+ *left -= copy_size;
+
+ /*
+ * If doing in-place decompression in single-call mode and the
+ * uncompressed size of the file is larger than the caller
+ * thought (i.e. it is invalid input!), the buffers below may
+ * overlap and cause undefined behavior with memcpy().
+ * With valid inputs memcpy() would be fine here.
+ */
+ memmove(dict->buf + dict->pos, b->in + b->in_pos, copy_size);
+ dict->pos += copy_size;
+
+ if (dict->full < dict->pos)
+ dict->full = dict->pos;
+
+ if (DEC_IS_MULTI(dict->mode)) {
+ if (dict->pos == dict->end)
+ dict->pos = 0;
+
+ /*
+ * Like above but for multi-call mode: use memmove()
+ * to avoid undefined behavior with invalid input.
+ */
+ memmove(b->out + b->out_pos, b->in + b->in_pos,
+ copy_size);
+ }
+
+ dict->start = dict->pos;
+
+ b->out_pos += copy_size;
+ b->in_pos += copy_size;
+ }
+}
+
+#ifdef XZ_DEC_MICROLZMA
+# define DICT_FLUSH_SUPPORTS_SKIPPING true
+#else
+# define DICT_FLUSH_SUPPORTS_SKIPPING false
+#endif
+
+/*
+ * Flush pending data from dictionary to b->out. It is assumed that there is
+ * enough space in b->out. This is guaranteed because caller uses dict_limit()
+ * before decoding data into the dictionary.
+ */
+static uint32_t dict_flush(struct dictionary *dict, struct xz_buf *b)
+{
+ size_t copy_size = dict->pos - dict->start;
+
+ if (DEC_IS_MULTI(dict->mode)) {
+ if (dict->pos == dict->end)
+ dict->pos = 0;
+
+ /*
+ * These buffers cannot overlap even if doing in-place
+ * decompression because in multi-call mode dict->buf
+ * has been allocated by us in this file; it's not
+ * provided by the caller like in single-call mode.
+ *
+ * With MicroLZMA, b->out can be NULL to skip bytes that
+ * the caller doesn't need. This cannot be done with XZ
+ * because it would break BCJ filters.
+ */
+ if (!DICT_FLUSH_SUPPORTS_SKIPPING || b->out != NULL)
+ memcpy(b->out + b->out_pos, dict->buf + dict->start,
+ copy_size);
+ }
+
+ dict->start = dict->pos;
+ b->out_pos += copy_size;
+ return copy_size;
+}
+
+/*****************
+ * Range decoder *
+ *****************/
+
+/* Reset the range decoder. */
+static void rc_reset(struct rc_dec *rc)
+{
+ rc->range = (uint32_t)-1;
+ rc->code = 0;
+ rc->init_bytes_left = RC_INIT_BYTES;
+}
+
+/*
+ * Read the first five initial bytes into rc->code if they haven't been
+ * read already. (Yes, the first byte gets completely ignored.)
+ */
+static bool rc_read_init(struct rc_dec *rc, struct xz_buf *b)
+{
+ while (rc->init_bytes_left > 0) {
+ if (b->in_pos == b->in_size)
+ return false;
+
+ rc->code = (rc->code << 8) + b->in[b->in_pos++];
+ --rc->init_bytes_left;
+ }
+
+ return true;
+}
+
+/* Return true if there may not be enough input for the next decoding loop. */
+static inline bool rc_limit_exceeded(const struct rc_dec *rc)
+{
+ return rc->in_pos > rc->in_limit;
+}
+
+/*
+ * Return true if it is possible (from point of view of range decoder) that
+ * we have reached the end of the LZMA chunk.
+ */
+static inline bool rc_is_finished(const struct rc_dec *rc)
+{
+ return rc->code == 0;
+}
+
+/* Read the next input byte if needed. */
+static __always_inline void rc_normalize(struct rc_dec *rc)
+{
+ if (rc->range < RC_TOP_VALUE) {
+ rc->range <<= RC_SHIFT_BITS;
+ rc->code = (rc->code << RC_SHIFT_BITS) + rc->in[rc->in_pos++];
+ }
+}
+
+/*
+ * Decode one bit. In some versions, this function has been split in three
+ * functions so that the compiler is supposed to be able to more easily avoid
+ * an extra branch. In this particular version of the LZMA decoder, this
+ * doesn't seem to be a good idea (tested with GCC 3.3.6, 3.4.6, and 4.3.3
+ * on x86). Using a non-split version results in nicer looking code too.
+ *
+ * NOTE: This must return an int. Do not make it return a bool or the speed
+ * of the code generated by GCC 3.x decreases 10-15 %. (GCC 4.3 doesn't care,
+ * and it generates 10-20 % faster code than GCC 3.x from this file anyway.)
+ */
+static __always_inline int rc_bit(struct rc_dec *rc, uint16_t *prob)
+{
+ uint32_t bound;
+ int bit;
+
+ rc_normalize(rc);
+ bound = (rc->range >> RC_BIT_MODEL_TOTAL_BITS) * *prob;
+ if (rc->code < bound) {
+ rc->range = bound;
+ *prob += (RC_BIT_MODEL_TOTAL - *prob) >> RC_MOVE_BITS;
+ bit = 0;
+ } else {
+ rc->range -= bound;
+ rc->code -= bound;
+ *prob -= *prob >> RC_MOVE_BITS;
+ bit = 1;
+ }
+
+ return bit;
+}
+
+/* Decode a bittree starting from the most significant bit. */
+static __always_inline uint32_t rc_bittree(struct rc_dec *rc,
+ uint16_t *probs, uint32_t limit)
+{
+ uint32_t symbol = 1;
+
+ do {
+ if (rc_bit(rc, &probs[symbol]))
+ symbol = (symbol << 1) + 1;
+ else
+ symbol <<= 1;
+ } while (symbol < limit);
+
+ return symbol;
+}
+
+/* Decode a bittree starting from the least significant bit. */
+static __always_inline void rc_bittree_reverse(struct rc_dec *rc,
+ uint16_t *probs,
+ uint32_t *dest, uint32_t limit)
+{
+ uint32_t symbol = 1;
+ uint32_t i = 0;
+
+ do {
+ if (rc_bit(rc, &probs[symbol])) {
+ symbol = (symbol << 1) + 1;
+ *dest += 1 << i;
+ } else {
+ symbol <<= 1;
+ }
+ } while (++i < limit);
+}
+
+/* Decode direct bits (fixed fifty-fifty probability) */
+static inline void rc_direct(struct rc_dec *rc, uint32_t *dest, uint32_t limit)
+{
+ uint32_t mask;
+
+ do {
+ rc_normalize(rc);
+ rc->range >>= 1;
+ rc->code -= rc->range;
+ mask = (uint32_t)0 - (rc->code >> 31);
+ rc->code += rc->range & mask;
+ *dest = (*dest << 1) + (mask + 1);
+ } while (--limit > 0);
+}
+
+/********
+ * LZMA *
+ ********/
+
+/* Get pointer to literal coder probability array. */
+static uint16_t *lzma_literal_probs(struct xz_dec_lzma2 *s)
+{
+ uint32_t prev_byte = dict_get(&s->dict, 0);
+ uint32_t low = prev_byte >> (8 - s->lzma.lc);
+ uint32_t high = (s->dict.pos & s->lzma.literal_pos_mask) << s->lzma.lc;
+ return s->lzma.literal[low + high];
+}
+
+/* Decode a literal (one 8-bit byte) */
+static void lzma_literal(struct xz_dec_lzma2 *s)
+{
+ uint16_t *probs;
+ uint32_t symbol;
+ uint32_t match_byte;
+ uint32_t match_bit;
+ uint32_t offset;
+ uint32_t i;
+
+ probs = lzma_literal_probs(s);
+
+ if (lzma_state_is_literal(s->lzma.state)) {
+ symbol = rc_bittree(&s->rc, probs, 0x100);
+ } else {
+ symbol = 1;
+ match_byte = dict_get(&s->dict, s->lzma.rep0) << 1;
+ offset = 0x100;
+
+ do {
+ match_bit = match_byte & offset;
+ match_byte <<= 1;
+ i = offset + match_bit + symbol;
+
+ if (rc_bit(&s->rc, &probs[i])) {
+ symbol = (symbol << 1) + 1;
+ offset &= match_bit;
+ } else {
+ symbol <<= 1;
+ offset &= ~match_bit;
+ }
+ } while (symbol < 0x100);
+ }
+
+ dict_put(&s->dict, (uint8_t)symbol);
+ lzma_state_literal(&s->lzma.state);
+}
+
+/* Decode the length of the match into s->lzma.len. */
+static void lzma_len(struct xz_dec_lzma2 *s, struct lzma_len_dec *l,
+ uint32_t pos_state)
+{
+ uint16_t *probs;
+ uint32_t limit;
+
+ if (!rc_bit(&s->rc, &l->choice)) {
+ probs = l->low[pos_state];
+ limit = LEN_LOW_SYMBOLS;
+ s->lzma.len = MATCH_LEN_MIN;
+ } else {
+ if (!rc_bit(&s->rc, &l->choice2)) {
+ probs = l->mid[pos_state];
+ limit = LEN_MID_SYMBOLS;
+ s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS;
+ } else {
+ probs = l->high;
+ limit = LEN_HIGH_SYMBOLS;
+ s->lzma.len = MATCH_LEN_MIN + LEN_LOW_SYMBOLS
+ + LEN_MID_SYMBOLS;
+ }
+ }
+
+ s->lzma.len += rc_bittree(&s->rc, probs, limit) - limit;
+}
+
+/* Decode a match. The distance will be stored in s->lzma.rep0. */
+static void lzma_match(struct xz_dec_lzma2 *s, uint32_t pos_state)
+{
+ uint16_t *probs;
+ uint32_t dist_slot;
+ uint32_t limit;
+
+ lzma_state_match(&s->lzma.state);
+
+ s->lzma.rep3 = s->lzma.rep2;
+ s->lzma.rep2 = s->lzma.rep1;
+ s->lzma.rep1 = s->lzma.rep0;
+
+ lzma_len(s, &s->lzma.match_len_dec, pos_state);
+
+ probs = s->lzma.dist_slot[lzma_get_dist_state(s->lzma.len)];
+ dist_slot = rc_bittree(&s->rc, probs, DIST_SLOTS) - DIST_SLOTS;
+
+ if (dist_slot < DIST_MODEL_START) {
+ s->lzma.rep0 = dist_slot;
+ } else {
+ limit = (dist_slot >> 1) - 1;
+ s->lzma.rep0 = 2 + (dist_slot & 1);
+
+ if (dist_slot < DIST_MODEL_END) {
+ s->lzma.rep0 <<= limit;
+ probs = s->lzma.dist_special + s->lzma.rep0
+ - dist_slot - 1;
+ rc_bittree_reverse(&s->rc, probs,
+ &s->lzma.rep0, limit);
+ } else {
+ rc_direct(&s->rc, &s->lzma.rep0, limit - ALIGN_BITS);
+ s->lzma.rep0 <<= ALIGN_BITS;
+ rc_bittree_reverse(&s->rc, s->lzma.dist_align,
+ &s->lzma.rep0, ALIGN_BITS);
+ }
+ }
+}
+
+/*
+ * Decode a repeated match. The distance is one of the four most recently
+ * seen matches. The distance will be stored in s->lzma.rep0.
+ */
+static void lzma_rep_match(struct xz_dec_lzma2 *s, uint32_t pos_state)
+{
+ uint32_t tmp;
+
+ if (!rc_bit(&s->rc, &s->lzma.is_rep0[s->lzma.state])) {
+ if (!rc_bit(&s->rc, &s->lzma.is_rep0_long[
+ s->lzma.state][pos_state])) {
+ lzma_state_short_rep(&s->lzma.state);
+ s->lzma.len = 1;
+ return;
+ }
+ } else {
+ if (!rc_bit(&s->rc, &s->lzma.is_rep1[s->lzma.state])) {
+ tmp = s->lzma.rep1;
+ } else {
+ if (!rc_bit(&s->rc, &s->lzma.is_rep2[s->lzma.state])) {
+ tmp = s->lzma.rep2;
+ } else {
+ tmp = s->lzma.rep3;
+ s->lzma.rep3 = s->lzma.rep2;
+ }
+
+ s->lzma.rep2 = s->lzma.rep1;
+ }
+
+ s->lzma.rep1 = s->lzma.rep0;
+ s->lzma.rep0 = tmp;
+ }
+
+ lzma_state_long_rep(&s->lzma.state);
+ lzma_len(s, &s->lzma.rep_len_dec, pos_state);
+}
+
+/* LZMA decoder core */
+static bool lzma_main(struct xz_dec_lzma2 *s)
+{
+ uint32_t pos_state;
+
+ /*
+ * If the dictionary was reached during the previous call, try to
+ * finish the possibly pending repeat in the dictionary.
+ */
+ if (dict_has_space(&s->dict) && s->lzma.len > 0)
+ dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0);
+
+ /*
+ * Decode more LZMA symbols. One iteration may consume up to
+ * LZMA_IN_REQUIRED - 1 bytes.
+ */
+ while (dict_has_space(&s->dict) && !rc_limit_exceeded(&s->rc)) {
+ pos_state = s->dict.pos & s->lzma.pos_mask;
+
+ if (!rc_bit(&s->rc, &s->lzma.is_match[
+ s->lzma.state][pos_state])) {
+ lzma_literal(s);
+ } else {
+ if (rc_bit(&s->rc, &s->lzma.is_rep[s->lzma.state]))
+ lzma_rep_match(s, pos_state);
+ else
+ lzma_match(s, pos_state);
+
+ if (!dict_repeat(&s->dict, &s->lzma.len, s->lzma.rep0))
+ return false;
+ }
+ }
+
+ /*
+ * Having the range decoder always normalized when we are outside
+ * this function makes it easier to correctly handle end of the chunk.
+ */
+ rc_normalize(&s->rc);
+
+ return true;
+}
+
+/*
+ * Reset the LZMA decoder and range decoder state. Dictionary is not reset
+ * here, because LZMA state may be reset without resetting the dictionary.
+ */
+static void lzma_reset(struct xz_dec_lzma2 *s)
+{
+ uint16_t *probs;
+ size_t i;
+
+ s->lzma.state = STATE_LIT_LIT;
+ s->lzma.rep0 = 0;
+ s->lzma.rep1 = 0;
+ s->lzma.rep2 = 0;
+ s->lzma.rep3 = 0;
+ s->lzma.len = 0;
+
+ /*
+ * All probabilities are initialized to the same value. This hack
+ * makes the code smaller by avoiding a separate loop for each
+ * probability array.
+ *
+ * This could be optimized so that only that part of literal
+ * probabilities that are actually required. In the common case
+ * we would write 12 KiB less.
+ */
+ probs = s->lzma.is_match[0];
+ for (i = 0; i < PROBS_TOTAL; ++i)
+ probs[i] = RC_BIT_MODEL_TOTAL / 2;
+
+ rc_reset(&s->rc);
+}
+
+/*
+ * Decode and validate LZMA properties (lc/lp/pb) and calculate the bit masks
+ * from the decoded lp and pb values. On success, the LZMA decoder state is
+ * reset and true is returned.
+ */
+static bool lzma_props(struct xz_dec_lzma2 *s, uint8_t props)
+{
+ if (props > (4 * 5 + 4) * 9 + 8)
+ return false;
+
+ s->lzma.pos_mask = 0;
+ while (props >= 9 * 5) {
+ props -= 9 * 5;
+ ++s->lzma.pos_mask;
+ }
+
+ s->lzma.pos_mask = (1 << s->lzma.pos_mask) - 1;
+
+ s->lzma.literal_pos_mask = 0;
+ while (props >= 9) {
+ props -= 9;
+ ++s->lzma.literal_pos_mask;
+ }
+
+ s->lzma.lc = props;
+
+ if (s->lzma.lc + s->lzma.literal_pos_mask > 4)
+ return false;
+
+ s->lzma.literal_pos_mask = (1 << s->lzma.literal_pos_mask) - 1;
+
+ lzma_reset(s);
+
+ return true;
+}
+
+/*********
+ * LZMA2 *
+ *********/
+
+/*
+ * The LZMA decoder assumes that if the input limit (s->rc.in_limit) hasn't
+ * been exceeded, it is safe to read up to LZMA_IN_REQUIRED bytes. This
+ * wrapper function takes care of making the LZMA decoder's assumption safe.
+ *
+ * As long as there is plenty of input left to be decoded in the current LZMA
+ * chunk, we decode directly from the caller-supplied input buffer until
+ * there's LZMA_IN_REQUIRED bytes left. Those remaining bytes are copied into
+ * s->temp.buf, which (hopefully) gets filled on the next call to this
+ * function. We decode a few bytes from the temporary buffer so that we can
+ * continue decoding from the caller-supplied input buffer again.
+ */
+static bool lzma2_lzma(struct xz_dec_lzma2 *s, struct xz_buf *b)
+{
+ size_t in_avail;
+ uint32_t tmp;
+
+ in_avail = b->in_size - b->in_pos;
+ if (s->temp.size > 0 || s->lzma2.compressed == 0) {
+ tmp = 2 * LZMA_IN_REQUIRED - s->temp.size;
+ if (tmp > s->lzma2.compressed - s->temp.size)
+ tmp = s->lzma2.compressed - s->temp.size;
+ if (tmp > in_avail)
+ tmp = in_avail;
+
+ memcpy(s->temp.buf + s->temp.size, b->in + b->in_pos, tmp);
+
+ if (s->temp.size + tmp == s->lzma2.compressed) {
+ memzero(s->temp.buf + s->temp.size + tmp,
+ sizeof(s->temp.buf)
+ - s->temp.size - tmp);
+ s->rc.in_limit = s->temp.size + tmp;
+ } else if (s->temp.size + tmp < LZMA_IN_REQUIRED) {
+ s->temp.size += tmp;
+ b->in_pos += tmp;
+ return true;
+ } else {
+ s->rc.in_limit = s->temp.size + tmp - LZMA_IN_REQUIRED;
+ }
+
+ s->rc.in = s->temp.buf;
+ s->rc.in_pos = 0;
+
+ if (!lzma_main(s) || s->rc.in_pos > s->temp.size + tmp)
+ return false;
+
+ s->lzma2.compressed -= s->rc.in_pos;
+
+ if (s->rc.in_pos < s->temp.size) {
+ s->temp.size -= s->rc.in_pos;
+ memmove(s->temp.buf, s->temp.buf + s->rc.in_pos,
+ s->temp.size);
+ return true;
+ }
+
+ b->in_pos += s->rc.in_pos - s->temp.size;
+ s->temp.size = 0;
+ }
+
+ in_avail = b->in_size - b->in_pos;
+ if (in_avail >= LZMA_IN_REQUIRED) {
+ s->rc.in = b->in;
+ s->rc.in_pos = b->in_pos;
+
+ if (in_avail >= s->lzma2.compressed + LZMA_IN_REQUIRED)
+ s->rc.in_limit = b->in_pos + s->lzma2.compressed;
+ else
+ s->rc.in_limit = b->in_size - LZMA_IN_REQUIRED;
+
+ if (!lzma_main(s))
+ return false;
+
+ in_avail = s->rc.in_pos - b->in_pos;
+ if (in_avail > s->lzma2.compressed)
+ return false;
+
+ s->lzma2.compressed -= in_avail;
+ b->in_pos = s->rc.in_pos;
+ }
+
+ in_avail = b->in_size - b->in_pos;
+ if (in_avail < LZMA_IN_REQUIRED) {
+ if (in_avail > s->lzma2.compressed)
+ in_avail = s->lzma2.compressed;
+
+ memcpy(s->temp.buf, b->in + b->in_pos, in_avail);
+ s->temp.size = in_avail;
+ b->in_pos += in_avail;
+ }
+
+ return true;
+}
+
+/*
+ * Take care of the LZMA2 control layer, and forward the job of actual LZMA
+ * decoding or copying of uncompressed chunks to other functions.
+ */
+XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s,
+ struct xz_buf *b)
+{
+ uint32_t tmp;
+
+ while (b->in_pos < b->in_size || s->lzma2.sequence == SEQ_LZMA_RUN) {
+ switch (s->lzma2.sequence) {
+ case SEQ_CONTROL:
+ /*
+ * LZMA2 control byte
+ *
+ * Exact values:
+ * 0x00 End marker
+ * 0x01 Dictionary reset followed by
+ * an uncompressed chunk
+ * 0x02 Uncompressed chunk (no dictionary reset)
+ *
+ * Highest three bits (s->control & 0xE0):
+ * 0xE0 Dictionary reset, new properties and state
+ * reset, followed by LZMA compressed chunk
+ * 0xC0 New properties and state reset, followed
+ * by LZMA compressed chunk (no dictionary
+ * reset)
+ * 0xA0 State reset using old properties,
+ * followed by LZMA compressed chunk (no
+ * dictionary reset)
+ * 0x80 LZMA chunk (no dictionary or state reset)
+ *
+ * For LZMA compressed chunks, the lowest five bits
+ * (s->control & 1F) are the highest bits of the
+ * uncompressed size (bits 16-20).
+ *
+ * A new LZMA2 stream must begin with a dictionary
+ * reset. The first LZMA chunk must set new
+ * properties and reset the LZMA state.
+ *
+ * Values that don't match anything described above
+ * are invalid and we return XZ_DATA_ERROR.
+ */
+ tmp = b->in[b->in_pos++];
+
+ if (tmp == 0x00)
+ return XZ_STREAM_END;
+
+ if (tmp >= 0xE0 || tmp == 0x01) {
+ s->lzma2.need_props = true;
+ s->lzma2.need_dict_reset = false;
+ dict_reset(&s->dict, b);
+ } else if (s->lzma2.need_dict_reset) {
+ return XZ_DATA_ERROR;
+ }
+
+ if (tmp >= 0x80) {
+ s->lzma2.uncompressed = (tmp & 0x1F) << 16;
+ s->lzma2.sequence = SEQ_UNCOMPRESSED_1;
+
+ if (tmp >= 0xC0) {
+ /*
+ * When there are new properties,
+ * state reset is done at
+ * SEQ_PROPERTIES.
+ */
+ s->lzma2.need_props = false;
+ s->lzma2.next_sequence
+ = SEQ_PROPERTIES;
+
+ } else if (s->lzma2.need_props) {
+ return XZ_DATA_ERROR;
+
+ } else {
+ s->lzma2.next_sequence
+ = SEQ_LZMA_PREPARE;
+ if (tmp >= 0xA0)
+ lzma_reset(s);
+ }
+ } else {
+ if (tmp > 0x02)
+ return XZ_DATA_ERROR;
+
+ s->lzma2.sequence = SEQ_COMPRESSED_0;
+ s->lzma2.next_sequence = SEQ_COPY;
+ }
+
+ break;
+
+ case SEQ_UNCOMPRESSED_1:
+ s->lzma2.uncompressed
+ += (uint32_t)b->in[b->in_pos++] << 8;
+ s->lzma2.sequence = SEQ_UNCOMPRESSED_2;
+ break;
+
+ case SEQ_UNCOMPRESSED_2:
+ s->lzma2.uncompressed
+ += (uint32_t)b->in[b->in_pos++] + 1;
+ s->lzma2.sequence = SEQ_COMPRESSED_0;
+ break;
+
+ case SEQ_COMPRESSED_0:
+ s->lzma2.compressed
+ = (uint32_t)b->in[b->in_pos++] << 8;
+ s->lzma2.sequence = SEQ_COMPRESSED_1;
+ break;
+
+ case SEQ_COMPRESSED_1:
+ s->lzma2.compressed
+ += (uint32_t)b->in[b->in_pos++] + 1;
+ s->lzma2.sequence = s->lzma2.next_sequence;
+ break;
+
+ case SEQ_PROPERTIES:
+ if (!lzma_props(s, b->in[b->in_pos++]))
+ return XZ_DATA_ERROR;
+
+ s->lzma2.sequence = SEQ_LZMA_PREPARE;
+
+ fallthrough;
+
+ case SEQ_LZMA_PREPARE:
+ if (s->lzma2.compressed < RC_INIT_BYTES)
+ return XZ_DATA_ERROR;
+
+ if (!rc_read_init(&s->rc, b))
+ return XZ_OK;
+
+ s->lzma2.compressed -= RC_INIT_BYTES;
+ s->lzma2.sequence = SEQ_LZMA_RUN;
+
+ fallthrough;
+
+ case SEQ_LZMA_RUN:
+ /*
+ * Set dictionary limit to indicate how much we want
+ * to be encoded at maximum. Decode new data into the
+ * dictionary. Flush the new data from dictionary to
+ * b->out. Check if we finished decoding this chunk.
+ * In case the dictionary got full but we didn't fill
+ * the output buffer yet, we may run this loop
+ * multiple times without changing s->lzma2.sequence.
+ */
+ dict_limit(&s->dict, min_t(size_t,
+ b->out_size - b->out_pos,
+ s->lzma2.uncompressed));
+ if (!lzma2_lzma(s, b))
+ return XZ_DATA_ERROR;
+
+ s->lzma2.uncompressed -= dict_flush(&s->dict, b);
+
+ if (s->lzma2.uncompressed == 0) {
+ if (s->lzma2.compressed > 0 || s->lzma.len > 0
+ || !rc_is_finished(&s->rc))
+ return XZ_DATA_ERROR;
+
+ rc_reset(&s->rc);
+ s->lzma2.sequence = SEQ_CONTROL;
+
+ } else if (b->out_pos == b->out_size
+ || (b->in_pos == b->in_size
+ && s->temp.size
+ < s->lzma2.compressed)) {
+ return XZ_OK;
+ }
+
+ break;
+
+ case SEQ_COPY:
+ dict_uncompressed(&s->dict, b, &s->lzma2.compressed);
+ if (s->lzma2.compressed > 0)
+ return XZ_OK;
+
+ s->lzma2.sequence = SEQ_CONTROL;
+ break;
+ }
+ }
+
+ return XZ_OK;
+}
+
+XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode,
+ uint32_t dict_max)
+{
+ struct xz_dec_lzma2 *s = kmalloc(sizeof(*s), GFP_KERNEL);
+ if (s == NULL)
+ return NULL;
+
+ s->dict.mode = mode;
+ s->dict.size_max = dict_max;
+
+ if (DEC_IS_PREALLOC(mode)) {
+ s->dict.buf = vmalloc(dict_max);
+ if (s->dict.buf == NULL) {
+ kfree(s);
+ return NULL;
+ }
+ } else if (DEC_IS_DYNALLOC(mode)) {
+ s->dict.buf = NULL;
+ s->dict.allocated = 0;
+ }
+
+ return s;
+}
+
+XZ_EXTERN enum xz_ret xz_dec_lzma2_reset(struct xz_dec_lzma2 *s, uint8_t props)
+{
+ /* This limits dictionary size to 3 GiB to keep parsing simpler. */
+ if (props > 39)
+ return XZ_OPTIONS_ERROR;
+
+ s->dict.size = 2 + (props & 1);
+ s->dict.size <<= (props >> 1) + 11;
+
+ if (DEC_IS_MULTI(s->dict.mode)) {
+ if (s->dict.size > s->dict.size_max)
+ return XZ_MEMLIMIT_ERROR;
+
+ s->dict.end = s->dict.size;
+
+ if (DEC_IS_DYNALLOC(s->dict.mode)) {
+ if (s->dict.allocated < s->dict.size) {
+ s->dict.allocated = s->dict.size;
+ vfree(s->dict.buf);
+ s->dict.buf = vmalloc(s->dict.size);
+ if (s->dict.buf == NULL) {
+ s->dict.allocated = 0;
+ return XZ_MEM_ERROR;
+ }
+ }
+ }
+ }
+
+ s->lzma2.sequence = SEQ_CONTROL;
+ s->lzma2.need_dict_reset = true;
+
+ s->temp.size = 0;
+
+ return XZ_OK;
+}
+
+XZ_EXTERN void xz_dec_lzma2_end(struct xz_dec_lzma2 *s)
+{
+ if (DEC_IS_MULTI(s->dict.mode))
+ vfree(s->dict.buf);
+
+ kfree(s);
+}
+
+#ifdef XZ_DEC_MICROLZMA
+/* This is a wrapper struct to have a nice struct name in the public API. */
+struct xz_dec_microlzma {
+ struct xz_dec_lzma2 s;
+};
+
+XZ_EXTERN enum xz_ret xz_dec_microlzma_run(struct xz_dec_microlzma *s_ptr,
+ struct xz_buf *b)
+{
+ struct xz_dec_lzma2 *s = &s_ptr->s;
+
+ /*
+ * sequence is SEQ_PROPERTIES before the first input byte,
+ * SEQ_LZMA_PREPARE until a total of five bytes have been read,
+ * and SEQ_LZMA_RUN for the rest of the input stream.
+ */
+ if (s->lzma2.sequence != SEQ_LZMA_RUN) {
+ if (s->lzma2.sequence == SEQ_PROPERTIES) {
+ /* One byte is needed for the props. */
+ if (b->in_pos >= b->in_size)
+ return XZ_OK;
+
+ /*
+ * Don't increment b->in_pos here. The same byte is
+ * also passed to rc_read_init() which will ignore it.
+ */
+ if (!lzma_props(s, ~b->in[b->in_pos]))
+ return XZ_DATA_ERROR;
+
+ s->lzma2.sequence = SEQ_LZMA_PREPARE;
+ }
+
+ /*
+ * xz_dec_microlzma_reset() doesn't validate the compressed
+ * size so we do it here. We have to limit the maximum size
+ * to avoid integer overflows in lzma2_lzma(). 3 GiB is a nice
+ * round number and much more than users of this code should
+ * ever need.
+ */
+ if (s->lzma2.compressed < RC_INIT_BYTES
+ || s->lzma2.compressed > (3U << 30))
+ return XZ_DATA_ERROR;
+
+ if (!rc_read_init(&s->rc, b))
+ return XZ_OK;
+
+ s->lzma2.compressed -= RC_INIT_BYTES;
+ s->lzma2.sequence = SEQ_LZMA_RUN;
+
+ dict_reset(&s->dict, b);
+ }
+
+ /* This is to allow increasing b->out_size between calls. */
+ if (DEC_IS_SINGLE(s->dict.mode))
+ s->dict.end = b->out_size - b->out_pos;
+
+ while (true) {
+ dict_limit(&s->dict, min_t(size_t, b->out_size - b->out_pos,
+ s->lzma2.uncompressed));
+
+ if (!lzma2_lzma(s, b))
+ return XZ_DATA_ERROR;
+
+ s->lzma2.uncompressed -= dict_flush(&s->dict, b);
+
+ if (s->lzma2.uncompressed == 0) {
+ if (s->lzma2.pedantic_microlzma) {
+ if (s->lzma2.compressed > 0 || s->lzma.len > 0
+ || !rc_is_finished(&s->rc))
+ return XZ_DATA_ERROR;
+ }
+
+ return XZ_STREAM_END;
+ }
+
+ if (b->out_pos == b->out_size)
+ return XZ_OK;
+
+ if (b->in_pos == b->in_size
+ && s->temp.size < s->lzma2.compressed)
+ return XZ_OK;
+ }
+}
+
+XZ_EXTERN struct xz_dec_microlzma *xz_dec_microlzma_alloc(enum xz_mode mode,
+ uint32_t dict_size)
+{
+ struct xz_dec_microlzma *s;
+
+ /* Restrict dict_size to the same range as in the LZMA2 code. */
+ if (dict_size < 4096 || dict_size > (3U << 30))
+ return NULL;
+
+ s = kmalloc(sizeof(*s), GFP_KERNEL);
+ if (s == NULL)
+ return NULL;
+
+ s->s.dict.mode = mode;
+ s->s.dict.size = dict_size;
+
+ if (DEC_IS_MULTI(mode)) {
+ s->s.dict.end = dict_size;
+
+ s->s.dict.buf = vmalloc(dict_size);
+ if (s->s.dict.buf == NULL) {
+ kfree(s);
+ return NULL;
+ }
+ }
+
+ return s;
+}
+
+XZ_EXTERN void xz_dec_microlzma_reset(struct xz_dec_microlzma *s,
+ uint32_t comp_size,
+ uint32_t uncomp_size,
+ int uncomp_size_is_exact)
+{
+ /*
+ * comp_size is validated in xz_dec_microlzma_run().
+ * uncomp_size can safely be anything.
+ */
+ s->s.lzma2.compressed = comp_size;
+ s->s.lzma2.uncompressed = uncomp_size;
+ s->s.lzma2.pedantic_microlzma = uncomp_size_is_exact;
+
+ s->s.lzma2.sequence = SEQ_PROPERTIES;
+ s->s.temp.size = 0;
+}
+
+XZ_EXTERN void xz_dec_microlzma_end(struct xz_dec_microlzma *s)
+{
+ if (DEC_IS_MULTI(s->s.dict.mode))
+ vfree(s->s.dict.buf);
+
+ kfree(s);
+}
+#endif
diff --git a/source/luametatex/source/libraries/xzembedded/xz_dec_stream.c b/source/luametatex/source/libraries/xzembedded/xz_dec_stream.c
new file mode 100644
index 000000000..33927e8e8
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/xz_dec_stream.c
@@ -0,0 +1,984 @@
+// SPDX-License-Identifier: 0BSD
+
+/*
+ * .xz Stream decoder
+ *
+ * Author: Lasse Collin <lasse.collin@tukaani.org>
+ */
+
+#include "xz_private.h"
+#include "xz_stream.h"
+
+#ifdef XZ_USE_CRC64
+# define IS_CRC64(check_type) ((check_type) == XZ_CHECK_CRC64)
+#else
+# define IS_CRC64(check_type) false
+#endif
+
+#ifdef XZ_USE_SHA256
+# define IS_SHA256(check_type) ((check_type) == XZ_CHECK_SHA256)
+#else
+# define IS_SHA256(check_type) false
+#endif
+
+/* Hash used to validate the Index field */
+struct xz_dec_hash {
+ vli_type unpadded;
+ vli_type uncompressed;
+ uint32_t crc32;
+};
+
+struct xz_dec {
+ /* Position in dec_main() */
+ enum {
+ SEQ_STREAM_HEADER,
+ SEQ_BLOCK_START,
+ SEQ_BLOCK_HEADER,
+ SEQ_BLOCK_UNCOMPRESS,
+ SEQ_BLOCK_PADDING,
+ SEQ_BLOCK_CHECK,
+ SEQ_INDEX,
+ SEQ_INDEX_PADDING,
+ SEQ_INDEX_CRC32,
+ SEQ_STREAM_FOOTER,
+ SEQ_STREAM_PADDING
+ } sequence;
+
+ /* Position in variable-length integers and Check fields */
+ uint32_t pos;
+
+ /* Variable-length integer decoded by dec_vli() */
+ vli_type vli;
+
+ /* Saved in_pos and out_pos */
+ size_t in_start;
+ size_t out_start;
+
+#ifdef XZ_USE_CRC64
+ /* CRC32 or CRC64 value in Block or CRC32 value in Index */
+ uint64_t crc;
+#else
+ /* CRC32 value in Block or Index */
+ uint32_t crc;
+#endif
+
+ /* Type of the integrity check calculated from uncompressed data */
+ enum xz_check check_type;
+
+ /* Operation mode */
+ enum xz_mode mode;
+
+ /*
+ * True if the next call to xz_dec_run() is allowed to return
+ * XZ_BUF_ERROR.
+ */
+ bool allow_buf_error;
+
+ /* Information stored in Block Header */
+ struct {
+ /*
+ * Value stored in the Compressed Size field, or
+ * VLI_UNKNOWN if Compressed Size is not present.
+ */
+ vli_type compressed;
+
+ /*
+ * Value stored in the Uncompressed Size field, or
+ * VLI_UNKNOWN if Uncompressed Size is not present.
+ */
+ vli_type uncompressed;
+
+ /* Size of the Block Header field */
+ uint32_t size;
+ } block_header;
+
+ /* Information collected when decoding Blocks */
+ struct {
+ /* Observed compressed size of the current Block */
+ vli_type compressed;
+
+ /* Observed uncompressed size of the current Block */
+ vli_type uncompressed;
+
+ /* Number of Blocks decoded so far */
+ vli_type count;
+
+ /*
+ * Hash calculated from the Block sizes. This is used to
+ * validate the Index field.
+ */
+ struct xz_dec_hash hash;
+ } block;
+
+ /* Variables needed when verifying the Index field */
+ struct {
+ /* Position in dec_index() */
+ enum {
+ SEQ_INDEX_COUNT,
+ SEQ_INDEX_UNPADDED,
+ SEQ_INDEX_UNCOMPRESSED
+ } sequence;
+
+ /* Size of the Index in bytes */
+ vli_type size;
+
+ /* Number of Records (matches block.count in valid files) */
+ vli_type count;
+
+ /*
+ * Hash calculated from the Records (matches block.hash in
+ * valid files).
+ */
+ struct xz_dec_hash hash;
+ } index;
+
+ /*
+ * Temporary buffer needed to hold Stream Header, Block Header,
+ * and Stream Footer. The Block Header is the biggest (1 KiB)
+ * so we reserve space according to that. buf[] has to be aligned
+ * to a multiple of four bytes; the size_t variables before it
+ * should guarantee this.
+ */
+ struct {
+ size_t pos;
+ size_t size;
+ uint8_t buf[1024];
+ } temp;
+
+ struct xz_dec_lzma2 *lzma2;
+
+#ifdef XZ_DEC_BCJ
+ struct xz_dec_bcj *bcj;
+ bool bcj_active;
+#endif
+
+#ifdef XZ_USE_SHA256
+ /*
+ * SHA-256 value in Block
+ *
+ * struct xz_sha256 is over a hundred bytes and it's only accessed
+ * from a few places. By putting the SHA-256 state near the end
+ * of struct xz_dec (somewhere after the "index" member) reduces
+ * code size at least on x86 and RISC-V. It's because the first bytes
+ * of the struct can be accessed with smaller instructions; the
+ * members that are accessed from many places should be at the top.
+ */
+ struct xz_sha256 sha256;
+#endif
+};
+
+#if defined(XZ_DEC_ANY_CHECK) || defined(XZ_USE_SHA256)
+/* Sizes of the Check field with different Check IDs */
+static const uint8_t check_sizes[16] = {
+ 0,
+ 4, 4, 4,
+ 8, 8, 8,
+ 16, 16, 16,
+ 32, 32, 32,
+ 64, 64, 64
+};
+#endif
+
+/*
+ * Fill s->temp by copying data starting from b->in[b->in_pos]. Caller
+ * must have set s->temp.pos and s->temp.size to indicate how much data
+ * we are supposed to copy into s->temp.buf. Return true once s->temp.pos
+ * has reached s->temp.size.
+ */
+static bool fill_temp(struct xz_dec *s, struct xz_buf *b)
+{
+ size_t copy_size = min_t(size_t,
+ b->in_size - b->in_pos, s->temp.size - s->temp.pos);
+
+ memcpy(s->temp.buf + s->temp.pos, b->in + b->in_pos, copy_size);
+ b->in_pos += copy_size;
+ s->temp.pos += copy_size;
+
+ if (s->temp.pos == s->temp.size) {
+ s->temp.pos = 0;
+ return true;
+ }
+
+ return false;
+}
+
+/* Decode a variable-length integer (little-endian base-128 encoding) */
+static enum xz_ret dec_vli(struct xz_dec *s, const uint8_t *in,
+ size_t *in_pos, size_t in_size)
+{
+ uint8_t byte;
+
+ if (s->pos == 0)
+ s->vli = 0;
+
+ while (*in_pos < in_size) {
+ byte = in[*in_pos];
+ ++*in_pos;
+
+ s->vli |= (vli_type)(byte & 0x7F) << s->pos;
+
+ if ((byte & 0x80) == 0) {
+ /* Don't allow non-minimal encodings. */
+ if (byte == 0 && s->pos != 0)
+ return XZ_DATA_ERROR;
+
+ s->pos = 0;
+ return XZ_STREAM_END;
+ }
+
+ s->pos += 7;
+ if (s->pos == 7 * VLI_BYTES_MAX)
+ return XZ_DATA_ERROR;
+ }
+
+ return XZ_OK;
+}
+
+/*
+ * Decode the Compressed Data field from a Block. Update and validate
+ * the observed compressed and uncompressed sizes of the Block so that
+ * they don't exceed the values possibly stored in the Block Header
+ * (validation assumes that no integer overflow occurs, since vli_type
+ * is normally uint64_t). Update the CRC32 or CRC64 value if presence of
+ * the CRC32 or CRC64 field was indicated in Stream Header.
+ *
+ * Once the decoding is finished, validate that the observed sizes match
+ * the sizes possibly stored in the Block Header. Update the hash and
+ * Block count, which are later used to validate the Index field.
+ */
+static enum xz_ret dec_block(struct xz_dec *s, struct xz_buf *b)
+{
+ enum xz_ret ret;
+
+ s->in_start = b->in_pos;
+ s->out_start = b->out_pos;
+
+#ifdef XZ_DEC_BCJ
+ if (s->bcj_active)
+ ret = xz_dec_bcj_run(s->bcj, s->lzma2, b);
+ else
+#endif
+ ret = xz_dec_lzma2_run(s->lzma2, b);
+
+ s->block.compressed += b->in_pos - s->in_start;
+ s->block.uncompressed += b->out_pos - s->out_start;
+
+ /*
+ * There is no need to separately check for VLI_UNKNOWN, since
+ * the observed sizes are always smaller than VLI_UNKNOWN.
+ */
+ if (s->block.compressed > s->block_header.compressed
+ || s->block.uncompressed
+ > s->block_header.uncompressed)
+ return XZ_DATA_ERROR;
+
+ if (s->check_type == XZ_CHECK_CRC32)
+ s->crc = xz_crc32(b->out + s->out_start,
+ b->out_pos - s->out_start, s->crc);
+#ifdef XZ_USE_CRC64
+ else if (s->check_type == XZ_CHECK_CRC64)
+ s->crc = xz_crc64(b->out + s->out_start,
+ b->out_pos - s->out_start, s->crc);
+#endif
+#ifdef XZ_USE_SHA256
+ else if (s->check_type == XZ_CHECK_SHA256)
+ xz_sha256_update(b->out + s->out_start,
+ b->out_pos - s->out_start, &s->sha256);
+#endif
+
+ if (ret == XZ_STREAM_END) {
+ if (s->block_header.compressed != VLI_UNKNOWN
+ && s->block_header.compressed
+ != s->block.compressed)
+ return XZ_DATA_ERROR;
+
+ if (s->block_header.uncompressed != VLI_UNKNOWN
+ && s->block_header.uncompressed
+ != s->block.uncompressed)
+ return XZ_DATA_ERROR;
+
+ s->block.hash.unpadded += s->block_header.size
+ + s->block.compressed;
+
+#if defined(XZ_DEC_ANY_CHECK) || defined(XZ_USE_SHA256)
+ s->block.hash.unpadded += check_sizes[s->check_type];
+#else
+ if (s->check_type == XZ_CHECK_CRC32)
+ s->block.hash.unpadded += 4;
+ else if (IS_CRC64(s->check_type))
+ s->block.hash.unpadded += 8;
+#endif
+
+ s->block.hash.uncompressed += s->block.uncompressed;
+ s->block.hash.crc32 = xz_crc32(
+ (const uint8_t *)&s->block.hash,
+ sizeof(s->block.hash), s->block.hash.crc32);
+
+ ++s->block.count;
+ }
+
+ return ret;
+}
+
+/* Update the Index size and the CRC32 value. */
+static void index_update(struct xz_dec *s, const struct xz_buf *b)
+{
+ size_t in_used = b->in_pos - s->in_start;
+ s->index.size += in_used;
+ s->crc = xz_crc32(b->in + s->in_start, in_used, s->crc);
+}
+
+/*
+ * Decode the Number of Records, Unpadded Size, and Uncompressed Size
+ * fields from the Index field. That is, Index Padding and CRC32 are not
+ * decoded by this function.
+ *
+ * This can return XZ_OK (more input needed), XZ_STREAM_END (everything
+ * successfully decoded), or XZ_DATA_ERROR (input is corrupt).
+ */
+static enum xz_ret dec_index(struct xz_dec *s, struct xz_buf *b)
+{
+ enum xz_ret ret;
+
+ do {
+ ret = dec_vli(s, b->in, &b->in_pos, b->in_size);
+ if (ret != XZ_STREAM_END) {
+ index_update(s, b);
+ return ret;
+ }
+
+ switch (s->index.sequence) {
+ case SEQ_INDEX_COUNT:
+ s->index.count = s->vli;
+
+ /*
+ * Validate that the Number of Records field
+ * indicates the same number of Records as
+ * there were Blocks in the Stream.
+ */
+ if (s->index.count != s->block.count)
+ return XZ_DATA_ERROR;
+
+ s->index.sequence = SEQ_INDEX_UNPADDED;
+ break;
+
+ case SEQ_INDEX_UNPADDED:
+ s->index.hash.unpadded += s->vli;
+ s->index.sequence = SEQ_INDEX_UNCOMPRESSED;
+ break;
+
+ case SEQ_INDEX_UNCOMPRESSED:
+ s->index.hash.uncompressed += s->vli;
+ s->index.hash.crc32 = xz_crc32(
+ (const uint8_t *)&s->index.hash,
+ sizeof(s->index.hash),
+ s->index.hash.crc32);
+ --s->index.count;
+ s->index.sequence = SEQ_INDEX_UNPADDED;
+ break;
+ }
+ } while (s->index.count > 0);
+
+ return XZ_STREAM_END;
+}
+
+/*
+ * Validate that the next four or eight input bytes match the value
+ * of s->crc. s->pos must be zero when starting to validate the first byte.
+ * The "bits" argument allows using the same code for both CRC32 and CRC64.
+ */
+static enum xz_ret crc_validate(struct xz_dec *s, struct xz_buf *b,
+ uint32_t bits)
+{
+ do {
+ if (b->in_pos == b->in_size)
+ return XZ_OK;
+
+ if (((s->crc >> s->pos) & 0xFF) != b->in[b->in_pos++])
+ return XZ_DATA_ERROR;
+
+ s->pos += 8;
+
+ } while (s->pos < bits);
+
+ s->crc = 0;
+ s->pos = 0;
+
+ return XZ_STREAM_END;
+}
+
+#ifdef XZ_DEC_ANY_CHECK
+/*
+ * Skip over the Check field when the Check ID is not supported.
+ * Returns true once the whole Check field has been skipped over.
+ */
+static bool check_skip(struct xz_dec *s, struct xz_buf *b)
+{
+ while (s->pos < check_sizes[s->check_type]) {
+ if (b->in_pos == b->in_size)
+ return false;
+
+ ++b->in_pos;
+ ++s->pos;
+ }
+
+ s->pos = 0;
+
+ return true;
+}
+#endif
+
+/* Decode the Stream Header field (the first 12 bytes of the .xz Stream). */
+static enum xz_ret dec_stream_header(struct xz_dec *s)
+{
+ if (!memeq(s->temp.buf, HEADER_MAGIC, HEADER_MAGIC_SIZE))
+ return XZ_FORMAT_ERROR;
+
+ if (xz_crc32(s->temp.buf + HEADER_MAGIC_SIZE, 2, 0)
+ != get_le32(s->temp.buf + HEADER_MAGIC_SIZE + 2))
+ return XZ_DATA_ERROR;
+
+ if (s->temp.buf[HEADER_MAGIC_SIZE] != 0)
+ return XZ_OPTIONS_ERROR;
+
+ /*
+ * Of integrity checks, we support none (Check ID = 0),
+ * CRC32 (Check ID = 1), and optionally CRC64 (Check ID = 4).
+ * However, if XZ_DEC_ANY_CHECK is defined, we will accept other
+ * check types too, but then the check won't be verified and
+ * a warning (XZ_UNSUPPORTED_CHECK) will be given.
+ */
+ if (s->temp.buf[HEADER_MAGIC_SIZE + 1] > XZ_CHECK_MAX)
+ return XZ_OPTIONS_ERROR;
+
+ s->check_type = s->temp.buf[HEADER_MAGIC_SIZE + 1];
+
+ if (s->check_type > XZ_CHECK_CRC32 && !IS_CRC64(s->check_type)
+ && !IS_SHA256(s->check_type)) {
+#ifdef XZ_DEC_ANY_CHECK
+ return XZ_UNSUPPORTED_CHECK;
+#else
+ return XZ_OPTIONS_ERROR;
+#endif
+ }
+
+ return XZ_OK;
+}
+
+/* Decode the Stream Footer field (the last 12 bytes of the .xz Stream) */
+static enum xz_ret dec_stream_footer(struct xz_dec *s)
+{
+ if (!memeq(s->temp.buf + 10, FOOTER_MAGIC, FOOTER_MAGIC_SIZE))
+ return XZ_DATA_ERROR;
+
+ if (xz_crc32(s->temp.buf + 4, 6, 0) != get_le32(s->temp.buf))
+ return XZ_DATA_ERROR;
+
+ /*
+ * Validate Backward Size. Note that we never added the size of the
+ * Index CRC32 field to s->index.size, thus we use s->index.size / 4
+ * instead of s->index.size / 4 - 1.
+ */
+ if ((s->index.size >> 2) != get_le32(s->temp.buf + 4))
+ return XZ_DATA_ERROR;
+
+ if (s->temp.buf[8] != 0 || s->temp.buf[9] != s->check_type)
+ return XZ_DATA_ERROR;
+
+ /*
+ * Use XZ_STREAM_END instead of XZ_OK to be more convenient
+ * for the caller.
+ */
+ return XZ_STREAM_END;
+}
+
+/* Decode the Block Header and initialize the filter chain. */
+static enum xz_ret dec_block_header(struct xz_dec *s)
+{
+ enum xz_ret ret;
+
+ /*
+ * Validate the CRC32. We know that the temp buffer is at least
+ * eight bytes so this is safe.
+ */
+ s->temp.size -= 4;
+ if (xz_crc32(s->temp.buf, s->temp.size, 0)
+ != get_le32(s->temp.buf + s->temp.size))
+ return XZ_DATA_ERROR;
+
+ s->temp.pos = 2;
+
+ /*
+ * Catch unsupported Block Flags. We support only one or two filters
+ * in the chain, so we catch that with the same test.
+ */
+#ifdef XZ_DEC_BCJ
+ if (s->temp.buf[1] & 0x3E)
+#else
+ if (s->temp.buf[1] & 0x3F)
+#endif
+ return XZ_OPTIONS_ERROR;
+
+ /* Compressed Size */
+ if (s->temp.buf[1] & 0x40) {
+ if (dec_vli(s, s->temp.buf, &s->temp.pos, s->temp.size)
+ != XZ_STREAM_END)
+ return XZ_DATA_ERROR;
+
+ s->block_header.compressed = s->vli;
+ } else {
+ s->block_header.compressed = VLI_UNKNOWN;
+ }
+
+ /* Uncompressed Size */
+ if (s->temp.buf[1] & 0x80) {
+ if (dec_vli(s, s->temp.buf, &s->temp.pos, s->temp.size)
+ != XZ_STREAM_END)
+ return XZ_DATA_ERROR;
+
+ s->block_header.uncompressed = s->vli;
+ } else {
+ s->block_header.uncompressed = VLI_UNKNOWN;
+ }
+
+#ifdef XZ_DEC_BCJ
+ /* If there are two filters, the first one must be a BCJ filter. */
+ s->bcj_active = s->temp.buf[1] & 0x01;
+ if (s->bcj_active) {
+ if (s->temp.size - s->temp.pos < 2)
+ return XZ_OPTIONS_ERROR;
+
+ ret = xz_dec_bcj_reset(s->bcj, s->temp.buf[s->temp.pos++]);
+ if (ret != XZ_OK)
+ return ret;
+
+ /*
+ * We don't support custom start offset,
+ * so Size of Properties must be zero.
+ */
+ if (s->temp.buf[s->temp.pos++] != 0x00)
+ return XZ_OPTIONS_ERROR;
+ }
+#endif
+
+ /* Valid Filter Flags always take at least two bytes. */
+ if (s->temp.size - s->temp.pos < 2)
+ return XZ_DATA_ERROR;
+
+ /* Filter ID = LZMA2 */
+ if (s->temp.buf[s->temp.pos++] != 0x21)
+ return XZ_OPTIONS_ERROR;
+
+ /* Size of Properties = 1-byte Filter Properties */
+ if (s->temp.buf[s->temp.pos++] != 0x01)
+ return XZ_OPTIONS_ERROR;
+
+ /* Filter Properties contains LZMA2 dictionary size. */
+ if (s->temp.size - s->temp.pos < 1)
+ return XZ_DATA_ERROR;
+
+ ret = xz_dec_lzma2_reset(s->lzma2, s->temp.buf[s->temp.pos++]);
+ if (ret != XZ_OK)
+ return ret;
+
+ /* The rest must be Header Padding. */
+ while (s->temp.pos < s->temp.size)
+ if (s->temp.buf[s->temp.pos++] != 0x00)
+ return XZ_OPTIONS_ERROR;
+
+ s->temp.pos = 0;
+ s->block.compressed = 0;
+ s->block.uncompressed = 0;
+
+ return XZ_OK;
+}
+
+static enum xz_ret dec_main(struct xz_dec *s, struct xz_buf *b)
+{
+ enum xz_ret ret;
+
+ /*
+ * Store the start position for the case when we are in the middle
+ * of the Index field.
+ */
+ s->in_start = b->in_pos;
+
+ while (true) {
+ switch (s->sequence) {
+ case SEQ_STREAM_HEADER:
+ /*
+ * Stream Header is copied to s->temp, and then
+ * decoded from there. This way if the caller
+ * gives us only little input at a time, we can
+ * still keep the Stream Header decoding code
+ * simple. Similar approach is used in many places
+ * in this file.
+ */
+ if (!fill_temp(s, b))
+ return XZ_OK;
+
+ /*
+ * If dec_stream_header() returns
+ * XZ_UNSUPPORTED_CHECK, it is still possible
+ * to continue decoding if working in multi-call
+ * mode. Thus, update s->sequence before calling
+ * dec_stream_header().
+ */
+ s->sequence = SEQ_BLOCK_START;
+
+ ret = dec_stream_header(s);
+ if (ret != XZ_OK)
+ return ret;
+
+ fallthrough;
+
+ case SEQ_BLOCK_START:
+ /* We need one byte of input to continue. */
+ if (b->in_pos == b->in_size)
+ return XZ_OK;
+
+ /* See if this is the beginning of the Index field. */
+ if (b->in[b->in_pos] == 0) {
+ s->in_start = b->in_pos++;
+ s->sequence = SEQ_INDEX;
+ break;
+ }
+
+ /*
+ * Calculate the size of the Block Header and
+ * prepare to decode it.
+ */
+ s->block_header.size
+ = ((uint32_t)b->in[b->in_pos] + 1) * 4;
+
+ s->temp.size = s->block_header.size;
+ s->temp.pos = 0;
+ s->sequence = SEQ_BLOCK_HEADER;
+
+ fallthrough;
+
+ case SEQ_BLOCK_HEADER:
+ if (!fill_temp(s, b))
+ return XZ_OK;
+
+ ret = dec_block_header(s);
+ if (ret != XZ_OK)
+ return ret;
+
+#ifdef XZ_USE_SHA256
+ if (s->check_type == XZ_CHECK_SHA256)
+ xz_sha256_reset(&s->sha256);
+#endif
+
+ s->sequence = SEQ_BLOCK_UNCOMPRESS;
+
+ fallthrough;
+
+ case SEQ_BLOCK_UNCOMPRESS:
+ ret = dec_block(s, b);
+ if (ret != XZ_STREAM_END)
+ return ret;
+
+ s->sequence = SEQ_BLOCK_PADDING;
+
+ fallthrough;
+
+ case SEQ_BLOCK_PADDING:
+ /*
+ * Size of Compressed Data + Block Padding
+ * must be a multiple of four. We don't need
+ * s->block.compressed for anything else
+ * anymore, so we use it here to test the size
+ * of the Block Padding field.
+ */
+ while (s->block.compressed & 3) {
+ if (b->in_pos == b->in_size)
+ return XZ_OK;
+
+ if (b->in[b->in_pos++] != 0)
+ return XZ_DATA_ERROR;
+
+ ++s->block.compressed;
+ }
+
+ s->sequence = SEQ_BLOCK_CHECK;
+
+ fallthrough;
+
+ case SEQ_BLOCK_CHECK:
+ if (s->check_type == XZ_CHECK_CRC32) {
+ ret = crc_validate(s, b, 32);
+ if (ret != XZ_STREAM_END)
+ return ret;
+ }
+ else if (IS_CRC64(s->check_type)) {
+ ret = crc_validate(s, b, 64);
+ if (ret != XZ_STREAM_END)
+ return ret;
+ }
+#ifdef XZ_USE_SHA256
+ else if (s->check_type == XZ_CHECK_SHA256) {
+ s->temp.size = 32;
+ if (!fill_temp(s, b))
+ return XZ_OK;
+
+ if (!xz_sha256_validate(s->temp.buf,
+ &s->sha256))
+ return XZ_DATA_ERROR;
+
+ s->pos = 0;
+ }
+#endif
+#ifdef XZ_DEC_ANY_CHECK
+ else if (!check_skip(s, b)) {
+ return XZ_OK;
+ }
+#endif
+
+ s->sequence = SEQ_BLOCK_START;
+ break;
+
+ case SEQ_INDEX:
+ ret = dec_index(s, b);
+ if (ret != XZ_STREAM_END)
+ return ret;
+
+ s->sequence = SEQ_INDEX_PADDING;
+
+ fallthrough;
+
+ case SEQ_INDEX_PADDING:
+ while ((s->index.size + (b->in_pos - s->in_start))
+ & 3) {
+ if (b->in_pos == b->in_size) {
+ index_update(s, b);
+ return XZ_OK;
+ }
+
+ if (b->in[b->in_pos++] != 0)
+ return XZ_DATA_ERROR;
+ }
+
+ /* Finish the CRC32 value and Index size. */
+ index_update(s, b);
+
+ /* Compare the hashes to validate the Index field. */
+ if (!memeq(&s->block.hash, &s->index.hash,
+ sizeof(s->block.hash)))
+ return XZ_DATA_ERROR;
+
+ s->sequence = SEQ_INDEX_CRC32;
+
+ fallthrough;
+
+ case SEQ_INDEX_CRC32:
+ ret = crc_validate(s, b, 32);
+ if (ret != XZ_STREAM_END)
+ return ret;
+
+ s->temp.size = STREAM_HEADER_SIZE;
+ s->sequence = SEQ_STREAM_FOOTER;
+
+ fallthrough;
+
+ case SEQ_STREAM_FOOTER:
+ if (!fill_temp(s, b))
+ return XZ_OK;
+
+ return dec_stream_footer(s);
+
+ case SEQ_STREAM_PADDING:
+ /* Never reached, only silencing a warning */
+ break;
+ }
+ }
+
+ /* Never reached */
+}
+
+/*
+ * xz_dec_run() is a wrapper for dec_main() to handle some special cases in
+ * multi-call and single-call decoding.
+ *
+ * In multi-call mode, we must return XZ_BUF_ERROR when it seems clear that we
+ * are not going to make any progress anymore. This is to prevent the caller
+ * from calling us infinitely when the input file is truncated or otherwise
+ * corrupt. Since zlib-style API allows that the caller fills the input buffer
+ * only when the decoder doesn't produce any new output, we have to be careful
+ * to avoid returning XZ_BUF_ERROR too easily: XZ_BUF_ERROR is returned only
+ * after the second consecutive call to xz_dec_run() that makes no progress.
+ *
+ * In single-call mode, if we couldn't decode everything and no error
+ * occurred, either the input is truncated or the output buffer is too small.
+ * Since we know that the last input byte never produces any output, we know
+ * that if all the input was consumed and decoding wasn't finished, the file
+ * must be corrupt. Otherwise the output buffer has to be too small or the
+ * file is corrupt in a way that decoding it produces too big output.
+ *
+ * If single-call decoding fails, we reset b->in_pos and b->out_pos back to
+ * their original values. This is because with some filter chains there won't
+ * be any valid uncompressed data in the output buffer unless the decoding
+ * actually succeeds (that's the price to pay of using the output buffer as
+ * the workspace).
+ */
+XZ_EXTERN enum xz_ret xz_dec_run(struct xz_dec *s, struct xz_buf *b)
+{
+ size_t in_start;
+ size_t out_start;
+ enum xz_ret ret;
+
+ if (DEC_IS_SINGLE(s->mode))
+ xz_dec_reset(s);
+
+ in_start = b->in_pos;
+ out_start = b->out_pos;
+ ret = dec_main(s, b);
+
+ if (DEC_IS_SINGLE(s->mode)) {
+ if (ret == XZ_OK)
+ ret = b->in_pos == b->in_size
+ ? XZ_DATA_ERROR : XZ_BUF_ERROR;
+
+ if (ret != XZ_STREAM_END) {
+ b->in_pos = in_start;
+ b->out_pos = out_start;
+ }
+
+ } else if (ret == XZ_OK && in_start == b->in_pos
+ && out_start == b->out_pos) {
+ if (s->allow_buf_error)
+ ret = XZ_BUF_ERROR;
+
+ s->allow_buf_error = true;
+ } else {
+ s->allow_buf_error = false;
+ }
+
+ return ret;
+}
+
+#ifdef XZ_DEC_CONCATENATED
+XZ_EXTERN enum xz_ret xz_dec_catrun(struct xz_dec *s, struct xz_buf *b,
+ int finish)
+{
+ enum xz_ret ret;
+
+ if (DEC_IS_SINGLE(s->mode)) {
+ xz_dec_reset(s);
+ finish = true;
+ }
+
+ while (true) {
+ if (s->sequence == SEQ_STREAM_PADDING) {
+ /*
+ * Skip Stream Padding. Its size must be a multiple
+ * of four bytes which is tracked with s->pos.
+ */
+ while (true) {
+ if (b->in_pos == b->in_size) {
+ /*
+ * Note that if we are repeatedly
+ * given no input and finish is false,
+ * we will keep returning XZ_OK even
+ * though no progress is being made.
+ * The lack of XZ_BUF_ERROR support
+ * isn't a problem here because a
+ * reasonable caller will eventually
+ * provide more input or set finish
+ * to true.
+ */
+ if (!finish)
+ return XZ_OK;
+
+ if (s->pos != 0)
+ return XZ_DATA_ERROR;
+
+ return XZ_STREAM_END;
+ }
+
+ if (b->in[b->in_pos] != 0x00) {
+ if (s->pos != 0)
+ return XZ_DATA_ERROR;
+
+ break;
+ }
+
+ ++b->in_pos;
+ s->pos = (s->pos + 1) & 3;
+ }
+
+ /*
+ * More input remains. It should be a new Stream.
+ *
+ * In single-call mode xz_dec_run() will always call
+ * xz_dec_reset(). Thus, we need to do it here only
+ * in multi-call mode.
+ */
+ if (DEC_IS_MULTI(s->mode))
+ xz_dec_reset(s);
+ }
+
+ ret = xz_dec_run(s, b);
+
+ if (ret != XZ_STREAM_END)
+ break;
+
+ s->sequence = SEQ_STREAM_PADDING;
+ }
+
+ return ret;
+}
+#endif
+
+XZ_EXTERN struct xz_dec *xz_dec_init(enum xz_mode mode, uint32_t dict_max)
+{
+ struct xz_dec *s = kmalloc(sizeof(*s), GFP_KERNEL);
+ if (s == NULL)
+ return NULL;
+
+ s->mode = mode;
+
+#ifdef XZ_DEC_BCJ
+ s->bcj = xz_dec_bcj_create(DEC_IS_SINGLE(mode));
+ if (s->bcj == NULL)
+ goto error_bcj;
+#endif
+
+ s->lzma2 = xz_dec_lzma2_create(mode, dict_max);
+ if (s->lzma2 == NULL)
+ goto error_lzma2;
+
+ xz_dec_reset(s);
+ return s;
+
+error_lzma2:
+#ifdef XZ_DEC_BCJ
+ xz_dec_bcj_end(s->bcj);
+error_bcj:
+#endif
+ kfree(s);
+ return NULL;
+}
+
+XZ_EXTERN void xz_dec_reset(struct xz_dec *s)
+{
+ s->sequence = SEQ_STREAM_HEADER;
+ s->allow_buf_error = false;
+ s->pos = 0;
+ s->crc = 0;
+ memzero(&s->block, sizeof(s->block));
+ memzero(&s->index, sizeof(s->index));
+ s->temp.pos = 0;
+ s->temp.size = STREAM_HEADER_SIZE;
+}
+
+XZ_EXTERN void xz_dec_end(struct xz_dec *s)
+{
+ if (s != NULL) {
+ xz_dec_lzma2_end(s->lzma2);
+#ifdef XZ_DEC_BCJ
+ xz_dec_bcj_end(s->bcj);
+#endif
+ kfree(s);
+ }
+}
diff --git a/source/luametatex/source/libraries/xzembedded/xz_dec_syms.c b/source/luametatex/source/libraries/xzembedded/xz_dec_syms.c
new file mode 100644
index 000000000..f40817d65
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/xz_dec_syms.c
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: 0BSD
+
+/*
+ * XZ decoder module information
+ *
+ * Author: Lasse Collin <lasse.collin@tukaani.org>
+ */
+
+#include <linux/module.h>
+#include <linux/xz.h>
+
+EXPORT_SYMBOL(xz_dec_init);
+EXPORT_SYMBOL(xz_dec_reset);
+EXPORT_SYMBOL(xz_dec_run);
+EXPORT_SYMBOL(xz_dec_end);
+
+#ifdef CONFIG_XZ_DEC_MICROLZMA
+EXPORT_SYMBOL(xz_dec_microlzma_alloc);
+EXPORT_SYMBOL(xz_dec_microlzma_reset);
+EXPORT_SYMBOL(xz_dec_microlzma_run);
+EXPORT_SYMBOL(xz_dec_microlzma_end);
+#endif
+
+MODULE_DESCRIPTION("XZ decompressor");
+MODULE_VERSION("1.2");
+MODULE_AUTHOR("Lasse Collin <lasse.collin@tukaani.org> and Igor Pavlov");
+MODULE_LICENSE("Dual BSD/GPL");
diff --git a/source/luametatex/source/libraries/xzembedded/xz_lzma2.h b/source/luametatex/source/libraries/xzembedded/xz_lzma2.h
new file mode 100644
index 000000000..d2632b7df
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/xz_lzma2.h
@@ -0,0 +1,203 @@
+/* SPDX-License-Identifier: 0BSD */
+
+/*
+ * LZMA2 definitions
+ *
+ * Authors: Lasse Collin <lasse.collin@tukaani.org>
+ * Igor Pavlov <https://7-zip.org/>
+ */
+
+#ifndef XZ_LZMA2_H
+#define XZ_LZMA2_H
+
+/* Range coder constants */
+#define RC_SHIFT_BITS 8
+#define RC_TOP_BITS 24
+#define RC_TOP_VALUE (1 << RC_TOP_BITS)
+#define RC_BIT_MODEL_TOTAL_BITS 11
+#define RC_BIT_MODEL_TOTAL (1 << RC_BIT_MODEL_TOTAL_BITS)
+#define RC_MOVE_BITS 5
+
+/*
+ * Maximum number of position states. A position state is the lowest pb
+ * number of bits of the current uncompressed offset. In some places there
+ * are different sets of probabilities for different position states.
+ */
+#define POS_STATES_MAX (1 << 4)
+
+/*
+ * This enum is used to track which LZMA symbols have occurred most recently
+ * and in which order. This information is used to predict the next symbol.
+ *
+ * Symbols:
+ * - Literal: One 8-bit byte
+ * - Match: Repeat a chunk of data at some distance
+ * - Long repeat: Multi-byte match at a recently seen distance
+ * - Short repeat: One-byte repeat at a recently seen distance
+ *
+ * The symbol names are in from STATE_oldest_older_previous. REP means
+ * either short or long repeated match, and NONLIT means any non-literal.
+ */
+enum lzma_state {
+ STATE_LIT_LIT,
+ STATE_MATCH_LIT_LIT,
+ STATE_REP_LIT_LIT,
+ STATE_SHORTREP_LIT_LIT,
+ STATE_MATCH_LIT,
+ STATE_REP_LIT,
+ STATE_SHORTREP_LIT,
+ STATE_LIT_MATCH,
+ STATE_LIT_LONGREP,
+ STATE_LIT_SHORTREP,
+ STATE_NONLIT_MATCH,
+ STATE_NONLIT_REP
+};
+
+/* Total number of states */
+#define STATES 12
+
+/* The lowest 7 states indicate that the previous state was a literal. */
+#define LIT_STATES 7
+
+/* Indicate that the latest symbol was a literal. */
+static inline void lzma_state_literal(enum lzma_state *state)
+{
+ if (*state <= STATE_SHORTREP_LIT_LIT)
+ *state = STATE_LIT_LIT;
+ else if (*state <= STATE_LIT_SHORTREP)
+ *state -= 3;
+ else
+ *state -= 6;
+}
+
+/* Indicate that the latest symbol was a match. */
+static inline void lzma_state_match(enum lzma_state *state)
+{
+ *state = *state < LIT_STATES ? STATE_LIT_MATCH : STATE_NONLIT_MATCH;
+}
+
+/* Indicate that the latest state was a long repeated match. */
+static inline void lzma_state_long_rep(enum lzma_state *state)
+{
+ *state = *state < LIT_STATES ? STATE_LIT_LONGREP : STATE_NONLIT_REP;
+}
+
+/* Indicate that the latest symbol was a short match. */
+static inline void lzma_state_short_rep(enum lzma_state *state)
+{
+ *state = *state < LIT_STATES ? STATE_LIT_SHORTREP : STATE_NONLIT_REP;
+}
+
+/* Test if the previous symbol was a literal. */
+static inline bool lzma_state_is_literal(enum lzma_state state)
+{
+ return state < LIT_STATES;
+}
+
+/* Each literal coder is divided in three sections:
+ * - 0x001-0x0FF: Without match byte
+ * - 0x101-0x1FF: With match byte; match bit is 0
+ * - 0x201-0x2FF: With match byte; match bit is 1
+ *
+ * Match byte is used when the previous LZMA symbol was something else than
+ * a literal (that is, it was some kind of match).
+ */
+#define LITERAL_CODER_SIZE 0x300
+
+/* Maximum number of literal coders */
+#define LITERAL_CODERS_MAX (1 << 4)
+
+/* Minimum length of a match is two bytes. */
+#define MATCH_LEN_MIN 2
+
+/* Match length is encoded with 4, 5, or 10 bits.
+ *
+ * Length Bits
+ * 2-9 4 = Choice=0 + 3 bits
+ * 10-17 5 = Choice=1 + Choice2=0 + 3 bits
+ * 18-273 10 = Choice=1 + Choice2=1 + 8 bits
+ */
+#define LEN_LOW_BITS 3
+#define LEN_LOW_SYMBOLS (1 << LEN_LOW_BITS)
+#define LEN_MID_BITS 3
+#define LEN_MID_SYMBOLS (1 << LEN_MID_BITS)
+#define LEN_HIGH_BITS 8
+#define LEN_HIGH_SYMBOLS (1 << LEN_HIGH_BITS)
+#define LEN_SYMBOLS (LEN_LOW_SYMBOLS + LEN_MID_SYMBOLS + LEN_HIGH_SYMBOLS)
+
+/*
+ * Maximum length of a match is 273 which is a result of the encoding
+ * described above.
+ */
+#define MATCH_LEN_MAX (MATCH_LEN_MIN + LEN_SYMBOLS - 1)
+
+/*
+ * Different sets of probabilities are used for match distances that have
+ * very short match length: Lengths of 2, 3, and 4 bytes have a separate
+ * set of probabilities for each length. The matches with longer length
+ * use a shared set of probabilities.
+ */
+#define DIST_STATES 4
+
+/*
+ * Get the index of the appropriate probability array for decoding
+ * the distance slot.
+ */
+static inline uint32_t lzma_get_dist_state(uint32_t len)
+{
+ return len < DIST_STATES + MATCH_LEN_MIN
+ ? len - MATCH_LEN_MIN : DIST_STATES - 1;
+}
+
+/*
+ * The highest two bits of a 32-bit match distance are encoded using six bits.
+ * This six-bit value is called a distance slot. This way encoding a 32-bit
+ * value takes 6-36 bits, larger values taking more bits.
+ */
+#define DIST_SLOT_BITS 6
+#define DIST_SLOTS (1 << DIST_SLOT_BITS)
+
+/* Match distances up to 127 are fully encoded using probabilities. Since
+ * the highest two bits (distance slot) are always encoded using six bits,
+ * the distances 0-3 don't need any additional bits to encode, since the
+ * distance slot itself is the same as the actual distance. DIST_MODEL_START
+ * indicates the first distance slot where at least one additional bit is
+ * needed.
+ */
+#define DIST_MODEL_START 4
+
+/*
+ * Match distances greater than 127 are encoded in three pieces:
+ * - distance slot: the highest two bits
+ * - direct bits: 2-26 bits below the highest two bits
+ * - alignment bits: four lowest bits
+ *
+ * Direct bits don't use any probabilities.
+ *
+ * The distance slot value of 14 is for distances 128-191.
+ */
+#define DIST_MODEL_END 14
+
+/* Distance slots that indicate a distance <= 127. */
+#define FULL_DISTANCES_BITS (DIST_MODEL_END / 2)
+#define FULL_DISTANCES (1 << FULL_DISTANCES_BITS)
+
+/*
+ * For match distances greater than 127, only the highest two bits and the
+ * lowest four bits (alignment) is encoded using probabilities.
+ */
+#define ALIGN_BITS 4
+#define ALIGN_SIZE (1 << ALIGN_BITS)
+#define ALIGN_MASK (ALIGN_SIZE - 1)
+
+/* Total number of all probability variables */
+#define PROBS_TOTAL (1846 + LITERAL_CODERS_MAX * LITERAL_CODER_SIZE)
+
+/*
+ * LZMA remembers the four most recent match distances. Reusing these
+ * distances tends to take less space than re-encoding the actual
+ * distance value.
+ */
+#define REPS 4
+
+#endif
diff --git a/source/luametatex/source/libraries/xzembedded/xz_private.h b/source/luametatex/source/libraries/xzembedded/xz_private.h
new file mode 100644
index 000000000..7387401da
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/xz_private.h
@@ -0,0 +1,189 @@
+/* SPDX-License-Identifier: 0BSD */
+
+/*
+ * Private includes and definitions
+ *
+ * Author: Lasse Collin <lasse.collin@tukaani.org>
+ */
+
+#ifndef XZ_PRIVATE_H
+#define XZ_PRIVATE_H
+
+#ifdef __KERNEL__
+# include <linux/xz.h>
+# include <linux/kernel.h>
+# include <linux/unaligned.h>
+ /* XZ_PREBOOT may be defined only via decompress_unxz.c. */
+# ifndef XZ_PREBOOT
+# include <linux/slab.h>
+# include <linux/vmalloc.h>
+# include <linux/string.h>
+# ifdef CONFIG_XZ_DEC_X86
+# define XZ_DEC_X86
+# endif
+# ifdef CONFIG_XZ_DEC_POWERPC
+# define XZ_DEC_POWERPC
+# endif
+# ifdef CONFIG_XZ_DEC_IA64
+# define XZ_DEC_IA64
+# endif
+# ifdef CONFIG_XZ_DEC_ARM
+# define XZ_DEC_ARM
+# endif
+# ifdef CONFIG_XZ_DEC_ARMTHUMB
+# define XZ_DEC_ARMTHUMB
+# endif
+# ifdef CONFIG_XZ_DEC_SPARC
+# define XZ_DEC_SPARC
+# endif
+# ifdef CONFIG_XZ_DEC_ARM64
+# define XZ_DEC_ARM64
+# endif
+# ifdef CONFIG_XZ_DEC_RISCV
+# define XZ_DEC_RISCV
+# endif
+# ifdef CONFIG_XZ_DEC_MICROLZMA
+# define XZ_DEC_MICROLZMA
+# endif
+# define memeq(a, b, size) (memcmp(a, b, size) == 0)
+# define memzero(buf, size) memset(buf, 0, size)
+# endif
+# define get_le32(p) le32_to_cpup((const uint32_t *)(p))
+#else
+ /*
+ * For userspace builds, use a separate header to define the required
+ * macros and functions. This makes it easier to adapt the code into
+ * different environments and avoids clutter in the Linux kernel tree.
+ */
+# include "xz_config.h"
+#endif
+
+/* If no specific decoding mode is requested, enable support for all modes. */
+#if !defined(XZ_DEC_SINGLE) && !defined(XZ_DEC_PREALLOC) \
+ && !defined(XZ_DEC_DYNALLOC)
+# define XZ_DEC_SINGLE
+# define XZ_DEC_PREALLOC
+# define XZ_DEC_DYNALLOC
+#endif
+
+/*
+ * The DEC_IS_foo(mode) macros are used in "if" statements. If only some
+ * of the supported modes are enabled, these macros will evaluate to true or
+ * false at compile time and thus allow the compiler to omit unneeded code.
+ */
+#ifdef XZ_DEC_SINGLE
+# define DEC_IS_SINGLE(mode) ((mode) == XZ_SINGLE)
+#else
+# define DEC_IS_SINGLE(mode) (false)
+#endif
+
+#ifdef XZ_DEC_PREALLOC
+# define DEC_IS_PREALLOC(mode) ((mode) == XZ_PREALLOC)
+#else
+# define DEC_IS_PREALLOC(mode) (false)
+#endif
+
+#ifdef XZ_DEC_DYNALLOC
+# define DEC_IS_DYNALLOC(mode) ((mode) == XZ_DYNALLOC)
+#else
+# define DEC_IS_DYNALLOC(mode) (false)
+#endif
+
+#if !defined(XZ_DEC_SINGLE)
+# define DEC_IS_MULTI(mode) (true)
+#elif defined(XZ_DEC_PREALLOC) || defined(XZ_DEC_DYNALLOC)
+# define DEC_IS_MULTI(mode) ((mode) != XZ_SINGLE)
+#else
+# define DEC_IS_MULTI(mode) (false)
+#endif
+
+/*
+ * If any of the BCJ filter decoders are wanted, define XZ_DEC_BCJ.
+ * XZ_DEC_BCJ is used to enable generic support for BCJ decoders.
+ */
+#ifndef XZ_DEC_BCJ
+# if defined(XZ_DEC_X86) || defined(XZ_DEC_POWERPC) \
+ || defined(XZ_DEC_IA64) \
+ || defined(XZ_DEC_ARM) || defined(XZ_DEC_ARMTHUMB) \
+ || defined(XZ_DEC_SPARC) || defined(XZ_DEC_ARM64) \
+ || defined(XZ_DEC_RISCV)
+# define XZ_DEC_BCJ
+# endif
+#endif
+
+struct xz_sha256 {
+ /* Buffered input data */
+ uint8_t data[64];
+
+ /* Internal state and the final hash value */
+ uint32_t state[8];
+
+ /* Size of the input data */
+ uint64_t size;
+};
+
+/* Reset the SHA-256 state to prepare for a new calculation. */
+XZ_EXTERN void xz_sha256_reset(struct xz_sha256 *s);
+
+/* Update the SHA-256 state with new data. */
+XZ_EXTERN void xz_sha256_update(const uint8_t *buf, size_t size,
+ struct xz_sha256 *s);
+
+/*
+ * Finish the SHA-256 calculation. Compare the result with the first 32 bytes
+ * from buf. Return true if the values are equal and false if they aren't.
+ */
+XZ_EXTERN bool xz_sha256_validate(const uint8_t *buf, struct xz_sha256 *s);
+
+/*
+ * Allocate memory for LZMA2 decoder. xz_dec_lzma2_reset() must be used
+ * before calling xz_dec_lzma2_run().
+ */
+XZ_EXTERN struct xz_dec_lzma2 *xz_dec_lzma2_create(enum xz_mode mode,
+ uint32_t dict_max);
+
+/*
+ * Decode the LZMA2 properties (one byte) and reset the decoder. Return
+ * XZ_OK on success, XZ_MEMLIMIT_ERROR if the preallocated dictionary is not
+ * big enough, and XZ_OPTIONS_ERROR if props indicates something that this
+ * decoder doesn't support.
+ */
+XZ_EXTERN enum xz_ret xz_dec_lzma2_reset(struct xz_dec_lzma2 *s,
+ uint8_t props);
+
+/* Decode raw LZMA2 stream from b->in to b->out. */
+XZ_EXTERN enum xz_ret xz_dec_lzma2_run(struct xz_dec_lzma2 *s,
+ struct xz_buf *b);
+
+/* Free the memory allocated for the LZMA2 decoder. */
+XZ_EXTERN void xz_dec_lzma2_end(struct xz_dec_lzma2 *s);
+
+#ifdef XZ_DEC_BCJ
+/*
+ * Allocate memory for BCJ decoders. xz_dec_bcj_reset() must be used before
+ * calling xz_dec_bcj_run().
+ */
+XZ_EXTERN struct xz_dec_bcj *xz_dec_bcj_create(bool single_call);
+
+/*
+ * Decode the Filter ID of a BCJ filter. This implementation doesn't
+ * support custom start offsets, so no decoding of Filter Properties
+ * is needed. Returns XZ_OK if the given Filter ID is supported.
+ * Otherwise XZ_OPTIONS_ERROR is returned.
+ */
+XZ_EXTERN enum xz_ret xz_dec_bcj_reset(struct xz_dec_bcj *s, uint8_t id);
+
+/*
+ * Decode raw BCJ + LZMA2 stream. This must be used only if there actually is
+ * a BCJ filter in the chain. If the chain has only LZMA2, xz_dec_lzma2_run()
+ * must be called directly.
+ */
+XZ_EXTERN enum xz_ret xz_dec_bcj_run(struct xz_dec_bcj *s,
+ struct xz_dec_lzma2 *lzma2,
+ struct xz_buf *b);
+
+/* Free the memory allocated for the BCJ filters. */
+#define xz_dec_bcj_end(s) kfree(s)
+#endif
+
+#endif
diff --git a/source/luametatex/source/libraries/xzembedded/xz_sha256.c b/source/luametatex/source/libraries/xzembedded/xz_sha256.c
new file mode 100644
index 000000000..078cad2c8
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/xz_sha256.c
@@ -0,0 +1,182 @@
+// SPDX-License-Identifier: 0BSD
+
+/*
+ * SHA-256
+ *
+ * This is based on the XZ Utils version which is based public domain code
+ * from Crypto++ Library 5.5.1 released in 2007: https://www.cryptopp.com/
+ *
+ * Authors: Wei Dai
+ * Lasse Collin <lasse.collin@tukaani.org>
+ */
+
+#include "xz_private.h"
+
+static inline uint32_t
+rotr_32(uint32_t num, unsigned amount)
+{
+ return (num >> amount) | (num << (32 - amount));
+}
+
+#define blk0(i) (W[i] = get_be32(&data[4 * i]))
+#define blk2(i) (W[i & 15] += s1(W[(i - 2) & 15]) + W[(i - 7) & 15] \
+ + s0(W[(i - 15) & 15]))
+
+#define Ch(x, y, z) (z ^ (x & (y ^ z)))
+#define Maj(x, y, z) ((x & (y ^ z)) + (y & z))
+
+#define a(i) T[(0 - i) & 7]
+#define b(i) T[(1 - i) & 7]
+#define c(i) T[(2 - i) & 7]
+#define d(i) T[(3 - i) & 7]
+#define e(i) T[(4 - i) & 7]
+#define f(i) T[(5 - i) & 7]
+#define g(i) T[(6 - i) & 7]
+#define h(i) T[(7 - i) & 7]
+
+#define R(i, j, blk) \
+ h(i) += S1(e(i)) + Ch(e(i), f(i), g(i)) + SHA256_K[i + j] + blk; \
+ d(i) += h(i); \
+ h(i) += S0(a(i)) + Maj(a(i), b(i), c(i))
+#define R0(i) R(i, 0, blk0(i))
+#define R2(i) R(i, j, blk2(i))
+
+#define S0(x) rotr_32(x ^ rotr_32(x ^ rotr_32(x, 9), 11), 2)
+#define S1(x) rotr_32(x ^ rotr_32(x ^ rotr_32(x, 14), 5), 6)
+#define s0(x) (rotr_32(x ^ rotr_32(x, 11), 7) ^ (x >> 3))
+#define s1(x) (rotr_32(x ^ rotr_32(x, 2), 17) ^ (x >> 10))
+
+static const uint32_t SHA256_K[64] = {
+ 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
+ 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
+ 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
+ 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
+ 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
+ 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
+ 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
+ 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
+ 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
+ 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
+ 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
+ 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
+ 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
+ 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
+ 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
+ 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
+};
+
+static void
+transform(uint32_t state[8], const uint8_t data[64])
+{
+ uint32_t W[16];
+ uint32_t T[8];
+ unsigned int j;
+
+ /* Copy state[] to working vars. */
+ memcpy(T, state, sizeof(T));
+
+ /* The first 16 operations unrolled */
+ R0( 0); R0( 1); R0( 2); R0( 3);
+ R0( 4); R0( 5); R0( 6); R0( 7);
+ R0( 8); R0( 9); R0(10); R0(11);
+ R0(12); R0(13); R0(14); R0(15);
+
+ /* The remaining 48 operations partially unrolled */
+ for (j = 16; j < 64; j += 16) {
+ R2( 0); R2( 1); R2( 2); R2( 3);
+ R2( 4); R2( 5); R2( 6); R2( 7);
+ R2( 8); R2( 9); R2(10); R2(11);
+ R2(12); R2(13); R2(14); R2(15);
+ }
+
+ /* Add the working vars back into state[]. */
+ state[0] += a(0);
+ state[1] += b(0);
+ state[2] += c(0);
+ state[3] += d(0);
+ state[4] += e(0);
+ state[5] += f(0);
+ state[6] += g(0);
+ state[7] += h(0);
+}
+
+XZ_EXTERN void xz_sha256_reset(struct xz_sha256 *s)
+{
+ static const uint32_t initial_state[8] = {
+ 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,
+ 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19
+ };
+
+ memcpy(s->state, initial_state, sizeof(initial_state));
+ s->size = 0;
+}
+
+XZ_EXTERN void xz_sha256_update(const uint8_t *buf, size_t size,
+ struct xz_sha256 *s)
+{
+ size_t copy_start;
+ size_t copy_size;
+
+ /*
+ * Copy the input data into a properly aligned temporary buffer.
+ * This way we can be called with arbitrarily sized buffers
+ * (no need to be a multiple of 64 bytes).
+ *
+ * Full 64-byte chunks could be processed directly from buf with
+ * unaligned access. It seemed to make very little difference in
+ * speed on x86-64 though. Thus it was omitted.
+ */
+ while (size > 0) {
+ copy_start = s->size & 0x3F;
+ copy_size = 64 - copy_start;
+ if (copy_size > size)
+ copy_size = size;
+
+ memcpy(s->data + copy_start, buf, copy_size);
+
+ buf += copy_size;
+ size -= copy_size;
+ s->size += copy_size;
+
+ if ((s->size & 0x3F) == 0)
+ transform(s->state, s->data);
+ }
+}
+
+XZ_EXTERN bool xz_sha256_validate(const uint8_t *buf, struct xz_sha256 *s)
+{
+ /*
+ * Add padding as described in RFC 3174 (it describes SHA-1 but
+ * the same padding style is used for SHA-256 too).
+ */
+ size_t i = s->size & 0x3F;
+ s->data[i++] = 0x80;
+
+ while (i != 64 - 8) {
+ if (i == 64) {
+ transform(s->state, s->data);
+ i = 0;
+ }
+
+ s->data[i++] = 0x00;
+ }
+
+ /* Convert the message size from bytes to bits. */
+ s->size *= 8;
+
+ /*
+ * Store the message size in big endian byte order and
+ * calculate the final hash value.
+ */
+ for (i = 0; i < 8; ++i)
+ s->data[64 - 8 + i] = (uint8_t)(s->size >> ((7 - i) * 8));
+
+ transform(s->state, s->data);
+
+ /* Compare if the hash value matches the first 32 bytes in buf. */
+ for (i = 0; i < 8; ++i)
+ if (get_unaligned_be32(buf + 4 * i) != s->state[i])
+ return false;
+
+ return true;
+}
diff --git a/source/luametatex/source/libraries/xzembedded/xz_stream.h b/source/luametatex/source/libraries/xzembedded/xz_stream.h
new file mode 100644
index 000000000..55f9f6f94
--- /dev/null
+++ b/source/luametatex/source/libraries/xzembedded/xz_stream.h
@@ -0,0 +1,61 @@
+/* SPDX-License-Identifier: 0BSD */
+
+/*
+ * Definitions for handling the .xz file format
+ *
+ * Author: Lasse Collin <lasse.collin@tukaani.org>
+ */
+
+#ifndef XZ_STREAM_H
+#define XZ_STREAM_H
+
+#if defined(__KERNEL__) && !XZ_INTERNAL_CRC32
+# include <linux/crc32.h>
+# undef crc32
+# define xz_crc32(buf, size, crc) \
+ (~crc32_le(~(uint32_t)(crc), buf, size))
+#endif
+
+/*
+ * See the .xz file format specification at
+ * https://tukaani.org/xz/xz-file-format.txt
+ * to understand the container format.
+ */
+
+#define STREAM_HEADER_SIZE 12
+
+#define HEADER_MAGIC "\3757zXZ"
+#define HEADER_MAGIC_SIZE 6
+
+#define FOOTER_MAGIC "YZ"
+#define FOOTER_MAGIC_SIZE 2
+
+/*
+ * Variable-length integer can hold a 63-bit unsigned integer or a special
+ * value indicating that the value is unknown.
+ *
+ * Experimental: vli_type can be defined to uint32_t to save a few bytes
+ * in code size (no effect on speed). Doing so limits the uncompressed and
+ * compressed size of the file to less than 256 MiB and may also weaken
+ * error detection slightly.
+ */
+typedef uint64_t vli_type;
+
+#define VLI_MAX ((vli_type)-1 / 2)
+#define VLI_UNKNOWN ((vli_type)-1)
+
+/* Maximum encoded size of a VLI */
+#define VLI_BYTES_MAX (sizeof(vli_type) * 8 / 7)
+
+/* Integrity Check types */
+enum xz_check {
+ XZ_CHECK_NONE = 0,
+ XZ_CHECK_CRC32 = 1,
+ XZ_CHECK_CRC64 = 4,
+ XZ_CHECK_SHA256 = 10
+};
+
+/* Maximum possible Check ID */
+#define XZ_CHECK_MAX 15
+
+#endif
diff --git a/source/luametatex/source/lua/lmtenginelib.c b/source/luametatex/source/lua/lmtenginelib.c
index 5e6590fa3..7a5da594d 100644
--- a/source/luametatex/source/lua/lmtenginelib.c
+++ b/source/luametatex/source/lua/lmtenginelib.c
@@ -5,16 +5,16 @@
# include "luametatex.h"
engine_state_info lmt_engine_state = {
- .lua_init = 0,
- .lua_only = 0,
- .luatex_banner = NULL,
- .engine_name = NULL,
- .startup_filename = NULL,
- .startup_jobname = NULL,
- .dump_name = NULL,
- .utc_time = 0,
- .permit_loadlib = 0,
- .permit_shebang = load_shebang_enabled,
+ .lua_init = 0,
+ .lua_only = 0,
+ .luametatex_banner = NULL,
+ .engine_name = NULL,
+ .startup_filename = NULL,
+ .startup_jobname = NULL,
+ .dump_name = NULL,
+ .utc_time = 0,
+ .permit_loadlib = 0,
+ .permit_shebang = load_shebang_enabled,
};
/*tex
@@ -48,25 +48,25 @@ typedef struct environment_state_info {
char *owncore;
char *ownlink;
char *input_name;
- int luatex_lua_offset;
+ int lua_offset;
int padding;
} environment_state_info;
static environment_state_info lmt_environment_state = {
- .argv = NULL,
- .argc = 0,
- .npos = 0,
- .flag = NULL,
- .value = NULL,
- .name = NULL,
- .ownpath = NULL,
- .ownbase = NULL,
- .ownname = NULL,
- .owncore = NULL,
- .ownlink = NULL,
- .input_name = NULL,
- .luatex_lua_offset = 0,
- .padding = 0,
+ .argv = NULL,
+ .argc = 0,
+ .npos = 0,
+ .flag = NULL,
+ .value = NULL,
+ .name = NULL,
+ .ownpath = NULL,
+ .ownbase = NULL,
+ .ownname = NULL,
+ .owncore = NULL,
+ .ownlink = NULL,
+ .input_name = NULL,
+ .lua_offset = 0,
+ .padding = 0,
};
/*tex todo: make helpers in |lmtoslibext| which has similar code */
@@ -236,9 +236,13 @@ static void enginelib_show_version_info(void)
"version. For more information about these matters, see the file named COPYING\n"
"and the LuaMetaTeX source.\n"
"\n"
- "Functionality : level " LMT_TOSTRING(luametatex_development_id) "\n"
+ "Functionality : level " LMT_TOSTRING(luametatex_functionality) "\n"
"Support : " luametatex_support_address "\n"
- "Copyright : The Lua(Meta)TeX Team(s) (2005-2024+)\n"
+ "Copyright : The Lua(Meta)TeX Team(s) (2005-2026+)\n"
+# if defined(LMT_DISTRIBUTION_USED)
+ "\n"
+ "Distribution : " LMT_DISTRIBUTION_USED "\n"
+# endif
"\n"
"The LuaMetaTeX project is related to ConTeXt development. This macro package\n"
"tightly integrates TeX and MetaPost in close cooperation with Lua. Updates will\n"
@@ -324,7 +328,9 @@ static void enginelib_show_credits(void)
" pplib : Paweł Jackowski (with partial code from libraries)\n"
" md5 : Peter Deutsch (with partial code from pplib libraries)\n"
" sha2 : Aaron D. Gifford (with partial code from pplib libraries)\n"
+# ifdef LMT_SOCKET_TOO
" socket : Diego Nehab (partial and adapted)\n"
+# endif
" libcerf : Joachim Wuttke (adapted for MSVC)\n"
" decnumber : Mike Cowlishaw from IBM (one of the number models in MP)\n"
" avl : Richard (adapted a bit to fit in)\n"
@@ -336,6 +342,7 @@ static void enginelib_show_credits(void)
" triangles : Moller, Guigue and Devillers (adapted)\n"
" effects : Ken Perlin and Stefan Gustavson (adapted)\n"
" filib : Werner Hofschuster, Walter Kraemer (adapted)\n"
+ " xzembedded : Igor Pavlov, Lasse Collin (partial)\n"
"\n"
"The code base contains more names and references. Some libraries are partially adapted or\n"
"have been replaced. The MetaPost library has additional functionality, some of which is\n"
@@ -348,7 +355,7 @@ static void enginelib_show_credits(void)
"simple foreign interface subsystem. Although this is provided and considered part of the\n"
"LuaMetaTeX engine it is not something ConTeXt depends (and will) depend on.\n"
"\n"
- "version : " luametatex_version_string " | " LMT_TOSTRING(luametatex_development_id) "\n"
+ "version : " luametatex_version_string " | " LMT_TOSTRING(luametatex_functionality) "\n"
"format id : " LMT_TOSTRING(luametatex_format_fingerprint) "\n"
# ifdef __DATE__
"date : " __TIME__ " | " __DATE__ "\n"
@@ -445,7 +452,7 @@ static void enginelib_check_option(char **options, int i)
return;
} else {
char *v = strchr(n, '=');
- size_t l = (int) (v ? (v - n) : strlen(n));
+ size_t l = v ? (size_t)(v - n) : strlen(n);
lmt_environment_state.flag = lmt_memory_malloc(l + 1);
if (lmt_environment_state.flag) {
memcpy(lmt_environment_state.flag, n, l);
@@ -490,7 +497,7 @@ static void enginelib_parse_options(void)
if (aux_is_readable(firstfile)) {
lmt_memory_free(lmt_engine_state.startup_filename);
lmt_engine_state.startup_filename = firstfile;
- lmt_environment_state.luatex_lua_offset = 0;
+ lmt_environment_state.lua_offset = 0;
lmt_engine_state.lua_only = 1;
lmt_engine_state.lua_init = 1;
return;
@@ -509,13 +516,13 @@ static void enginelib_parse_options(void)
continue;
} else if (strcmp(lmt_environment_state.flag, "luaonly") == 0) {
lmt_engine_state.lua_only = 1;
- lmt_environment_state.luatex_lua_offset = i;
+ lmt_environment_state.lua_offset = i;
lmt_engine_state.lua_init = 1;
} else if (strcmp(lmt_environment_state.flag, "lua") == 0) {
if (lmt_environment_state.value) {
lmt_memory_free(lmt_engine_state.startup_filename);
lmt_engine_state.startup_filename = lmt_memory_strdup(lmt_environment_state.value);
- lmt_environment_state.luatex_lua_offset = i - 1;
+ lmt_environment_state.lua_offset = i - 1;
lmt_engine_state.lua_init = 1;
}
} else if (strcmp(lmt_environment_state.flag, "jobname") == 0) {
@@ -553,7 +560,7 @@ static void enginelib_parse_options(void)
if (lmt_engine_state.lua_only) {
if (! lmt_engine_state.startup_filename) {
lmt_engine_state.startup_filename = lmt_memory_strdup(lmt_environment_state.argv[lmt_environment_state.npos]);
- lmt_environment_state.luatex_lua_offset = lmt_environment_state.npos;
+ lmt_environment_state.lua_offset = lmt_environment_state.npos;
}
} else if (lmt_environment_state.argv[lmt_environment_state.npos][0] == '&') {
/*tex This is historic but and might go away. */
@@ -576,7 +583,7 @@ static void enginelib_parse_options(void)
lmt_memory_free(firstfile);
} else {
lmt_engine_state.startup_filename = firstfile;
- lmt_environment_state.luatex_lua_offset = lmt_environment_state.npos;
+ lmt_environment_state.lua_offset = lmt_environment_state.npos;
lmt_engine_state.lua_only = 1;
lmt_engine_state.lua_init = 1;
}
@@ -662,7 +669,7 @@ void tex_engine_initialize(int ac, char **av)
lmt_engine_state.startup_jobname = NULL;
lmt_engine_state.engine_name = luametatex_name_lowercase;
lmt_engine_state.dump_name = NULL;
- lmt_engine_state.luatex_banner = lmt_memory_strdup(lmt_version_state.banner);
+ lmt_engine_state.luametatex_banner = lmt_memory_strdup(lmt_version_state.banner);
/* preparations */
lmt_environment_state.ownpath = aux_utf8_getownpath(lmt_environment_state.argv[0]);
lmt_environment_state.ownlink = aux_utf8_readlink(lmt_environment_state.ownpath);
@@ -689,7 +696,7 @@ void tex_engine_initialize(int ac, char **av)
lmt_tokenlib_initialize();
lmt_fontlib_initialize();
/*tex Collect arguments. */
- enginelib_prepare_cmdline(lmt_environment_state.luatex_lua_offset);
+ enginelib_prepare_cmdline(lmt_environment_state.lua_offset);
if (lmt_engine_state.startup_filename && ! aux_is_readable(lmt_engine_state.startup_filename)) {
lmt_memory_free(lmt_engine_state.startup_filename);
lmt_engine_state.startup_filename = NULL;
@@ -1117,7 +1124,9 @@ static const luaL_Reg lmt_libs_extra_function_list[] = {
{ "sio", luaopen_sio },
{ "sparse", luaopen_sparse },
{ "bitset", luaopen_bitset },
+ { "sequencer", luaopen_sequencer },
{ "xzip", luaopen_xzip },
+ { "xz", luaopen_xz },
{ "xmath", luaopen_xmath },
{ "xcomplex", luaopen_xcomplex },
{ "xdecimal", luaopen_xdecimal },
@@ -1133,17 +1142,24 @@ static const luaL_Reg lmt_libs_extra_function_list[] = {
{ "kdtree", luaopen_kdtree },
{ "serial", luaopen_serial },
{ "process", luaopen_process },
+ { "watcher", luaopen_watcher },
{ "timer", luaopen_timer },
{ "security", luaopen_security },
// { "specific", luaopen_specific },
+ { "client", luaopen_client },
+ { "server", luaopen_server },
{ NULL, NULL },
};
-static const luaL_Reg lmt_libs_socket_function_list[] = {
- { "socket", luaopen_socket_core },
- { "mime", luaopen_mime_core },
- { NULL, NULL },
-};
+# ifdef LMT_SOCKET_TOO
+
+ static const luaL_Reg lmt_libs_socket_function_list[] = {
+ { "socket", luaopen_socket_core },
+ { "mime", luaopen_mime_core },
+ { NULL, NULL },
+ };
+
+# endif
static const luaL_Reg lmt_libs_more_function_list[] = {
{ "lua", luaopen_lua },
@@ -1267,8 +1283,10 @@ void lmt_initialize(void)
luaextend_os(L);
luaextend_io(L);
luaextend_string(L);
+# ifdef LMT_SOCKET_TOO
/*tex Loading the socket library is a bit odd (old stuff). */
enginelib_luaopen_liblist(L, lmt_libs_socket_function_list);
+# endif
/*tex This initializes the 'tex' related libraries that have some luaonly functionality */
enginelib_luaopen_liblist(L, lmt_libs_more_function_list);
/*tex This initializes the 'tex' related libraries. */
diff --git a/source/luametatex/source/lua/lmtenginelib.h b/source/luametatex/source/lua/lmtenginelib.h
index 043a5d807..430eccafc 100644
--- a/source/luametatex/source/lua/lmtenginelib.h
+++ b/source/luametatex/source/lua/lmtenginelib.h
@@ -14,7 +14,7 @@ typedef enum permits_shebang_modes {
typedef struct engine_state_info {
int lua_init;
int lua_only;
- const char *luatex_banner;
+ const char *luametatex_banner;
const char *engine_name;
char *startup_filename;
char *startup_jobname;
diff --git a/source/luametatex/source/lua/lmtfontlib.c b/source/luametatex/source/lua/lmtfontlib.c
index 2ff51c871..fad4401cc 100644
--- a/source/luametatex/source/lua/lmtfontlib.c
+++ b/source/luametatex/source/lua/lmtfontlib.c
@@ -117,14 +117,14 @@ static void fontlib_aux_read_lua_parameters(lua_State *L, int f)
*/
for (int i = 1; i <= maxindex; i++) {
if (lua_rawgeti(L, -1, i) == LUA_TNUMBER) {
- halfword value = lmt_roundnumber(L, -1);
+ scaled value = lmt_roundnumber(L, -1);
tex_set_font_parameter(f, i, value);
}
lua_pop(L, 1);
}
lua_pushnil(L);
while (lua_next(L, -2)) {
- halfword value = lua_type(L, -1) == LUA_TNUMBER ? lmt_roundnumber(L, -1) : 0;
+ scaled value = lua_type(L, -1) == LUA_TNUMBER ? lmt_roundnumber(L, -1) : 0;
switch (lua_type(L, -2)) {
case LUA_TSTRING:
{
diff --git a/source/luametatex/source/lua/lmthelperlib.c b/source/luametatex/source/lua/lmthelperlib.c
index 0c0140441..62beea862 100644
--- a/source/luametatex/source/lua/lmthelperlib.c
+++ b/source/luametatex/source/lua/lmthelperlib.c
@@ -32,6 +32,26 @@ typedef struct profiling_specification {
halfword parent;
} profiling_specification;
+static inline scaled tex_aux_discretize_position(scaled num, scaled step)
+{
+ if (step <= 0) return 0;
+ /* Round to nearest step: (num + step/2) / step */
+ long long n = (long long) num;
+ long long s = (long long) step;
+ long long q = (n >= 0) ? (n + s / 2LL) / s : (n - s / 2LL) / s;
+ return (scaled) (q < 0 ? 0 : q);
+}
+
+static inline scaled tex_aux_discretize_width(scaled num, scaled step)
+{
+ if (step <= 0) return 0;
+ /* Round down / inward: (num - step/2) / step */
+ long long n = (long long) num;
+ long long s = (long long) step;
+ long long q = (n >= 0) ? (n - s / 2LL) / s : (n + s / 2LL) / s;
+ return (scaled) (q < 0 ? 0 : q);
+}
+
static void helperlib_aux_resetprofile(profiling_specification *profile)
{
memset(profile, 0, sizeof(profiling_specification));
@@ -142,16 +162,8 @@ static void helperlib_aux_getprofile(lua_State *L, profiling_specification *prof
profile->position = profile->width;
profile->width = profile->position + profile->whd.wd;
{
- // scaled p = lround((double) (profile->position - profile->margin) / profile->step);
- // scaled w = lround((double) (profile->width + profile->margin) / profile->step);
- scaled p = (scaled) lfloor((double) (profile->position - profile->margin)/profile->step + 0.5);
- scaled w = (scaled) lfloor((double) (profile->width + profile->margin)/profile->step - 0.5);
- if (p < 0) {
- p = 0;
- }
- if (w < 0) {
- w = 0;
- }
+ scaled p = tex_aux_discretize_position(profile->position - profile->margin, profile->step);
+ scaled w = tex_aux_discretize_width(profile->width + profile->margin, profile->step);
if (p > w) {
scaled t = w;
w = p;
@@ -1026,7 +1038,8 @@ static struct luaL_Reg helperlib_function_list[] = {
{ NULL, NULL },
};
-int luaopen_helper(lua_State *L) {
+int luaopen_helper(lua_State *L)
+{
lua_newtable(L);
luaL_setfuncs(L, helperlib_function_list, 0);
return 1;
diff --git a/source/luametatex/source/lua/lmtinterface.c b/source/luametatex/source/lua/lmtinterface.c
index ecfcd13f6..6560971fe 100644
--- a/source/luametatex/source/lua/lmtinterface.c
+++ b/source/luametatex/source/lua/lmtinterface.c
@@ -35,6 +35,7 @@ lua_state_info lmt_lua_state = {
.last_node_error = lua_no_node_error,
.ignore_node_error = 0,
.security_checkers = { LUA_NOREF },
+ .security_states = { 0 },
};
/*tex
diff --git a/source/luametatex/source/lua/lmtinterface.h b/source/luametatex/source/lua/lmtinterface.h
index 233de8b34..d65790fb8 100644
--- a/source/luametatex/source/lua/lmtinterface.h
+++ b/source/luametatex/source/lua/lmtinterface.h
@@ -72,24 +72,37 @@ typedef enum security_actions {
security_load_library = 0x0E,
/* */
security_open_database = 0x0F,
+ /* */
+ security_launch_command = 0x10,
+ /* */
+ security_http_request = 0x11,
} security_actions;
typedef enum security_targets {
security_generic = 0x00,
security_readable = 0x01,
- security_writeable = 0x02,
+ security_writable = 0x02,
security_executable = 0x03,
security_library = 0x04,
security_loadable = 0x05,
+ security_launchable = 0x06,
+ security_client = 0x07,
} security_targets;
-# define n_of_security_targets 6
+typedef enum security_states {
+ security_state_unset,
+ security_state_set,
+ security_state_frozen,
+} security_states;
+
+# define n_of_security_targets 8
typedef struct lua_state_info {
lua_State *lua_instance;
lua_State *mps_instance;
luaL_Buffer *used_buffer;
int security_checkers[n_of_security_targets];
+ int security_states[n_of_security_targets];
int used_bytes;
int used_bytes_max;
int function_table_id;
@@ -146,6 +159,7 @@ extern int luaopen_sha2 (lua_State *L);
extern int luaopen_sio (lua_State *L);
extern int luaopen_socket_core (lua_State *L);
extern int luaopen_bitset (lua_State *L);
+extern int luaopen_sequencer (lua_State *L);
extern int luaopen_sparse (lua_State *L);
extern int luaopen_status (lua_State *L);
extern int luaopen_tex (lua_State *L);
@@ -156,13 +170,17 @@ extern int luaopen_xdecimal (lua_State *L);
extern int luaopen_xinterval (lua_State *L);
extern int luaopen_xmath (lua_State *L);
extern int luaopen_xzip (lua_State *L);
+extern int luaopen_xz (lua_State *L);
extern int luaopen_serial (lua_State *L);
extern int luaopen_process (lua_State *L);
+extern int luaopen_watcher (lua_State *L);
extern int luaopen_timer (lua_State *L);
extern int luaopen_security (lua_State *L);
extern int luaopen_vector (lua_State *L);
extern int luaopen_zbuffer (lua_State *L);
// int luaopen_specific (lua_State *L);
+extern int luaopen_client (lua_State *L);
+extern int luaopen_server (lua_State *L);
extern int luaextend_io (lua_State *L);
extern int luaextend_os (lua_State *L);
@@ -365,6 +383,7 @@ extern int luaextend_xcomplex (lua_State *L);
# define BYTEMAP_METATABLE_INSTANCE "bytemap"
# define SERIAL_METATABLE_INSTANCE "serial"
# define PROCESS_METATABLE_INSTANCE "process"
+# define WATCHER_METATABLE_INSTANCE "watcher"
# define TIMER_METATABLE_INSTANCE "timer"
# define INTERVAL_METATABLE_INSTANCE "interval"
# define KDTREE_METATABLE_INSTANCE "kdtree"
@@ -424,6 +443,7 @@ typedef struct node_info {
int definable;
int first;
int last;
+ int max;
} node_info;
typedef struct par_info {
@@ -897,6 +917,7 @@ make_lua_key(L, glueset);\
make_lua_key(L, gluesign);\
make_lua_key(L, gluespec);\
make_lua_key(L, glyph);\
+make_lua_key(L, glyphscale);\
make_lua_key(L, group);\
make_lua_key(L, h);\
make_lua_key(L, halign);\
@@ -1892,6 +1913,22 @@ static inline long lmt_clamped_long(lua_Integer v)
return (v > LONG_MAX) ? LONG_MAX : ((v < LONG_MIN) ? LONG_MIN : (long) v);
}
+static inline unsigned long lmt_clamped_ulong(lua_Integer v)
+{
+ if (v < 0) {
+ return 0UL;
+ }
+ if ((lua_Unsigned) v > ULONG_MAX) {
+ return ULONG_MAX;
+ }
+ return (unsigned long) v;
+}
+
+// static inline unsigned long lmt_clamped_ulong(lua_Unsigned v)
+// {
+// return (v > ULONG_MAX) ? ULONG_MAX : (unsigned long) v;
+// }
+
static inline size_t lmt_clamped_sizet(lua_Integer v)
{
if (v < 0) {
@@ -1959,6 +1996,10 @@ static inline lua_Integer lmt_clamped_round(double d)
# define lmt_checklong(L,i) lmt_clamped_long(luaL_checkinteger(L,i))
# define lmt_optlong(L,i,j) lmt_clamped_long(luaL_optinteger(L,i,j))
+# define lmt_toulong(L,i) lmt_clamped_ulong(lua_tointeger(L,i))
+# define lmt_checkulong(L,i) lmt_clamped_ulong(luaL_checkinteger(L,i))
+# define lmt_optulong(L,i,j) lmt_clamped_ulong(luaL_optinteger(L,i,j))
+
# define lmt_tointeger(L,i) lmt_clamped_int(lua_tointeger(L,i))
# define lmt_checkinteger(L,i) lmt_clamped_int(luaL_checkinteger(L,i))
# define lmt_optinteger(L,i,j) lmt_clamped_int(luaL_optinteger(L,i,j))
diff --git a/source/luametatex/source/lua/lmtmplib.c b/source/luametatex/source/lua/lmtmplib.c
index c811f3545..7178a1366 100644
--- a/source/luametatex/source/lua/lmtmplib.c
+++ b/source/luametatex/source/lua/lmtmplib.c
@@ -2526,7 +2526,8 @@ static int mplib_getscaledbits(lua_State *L)
return 1;
}
-static int mplib_aux_set_direction(lua_State *L, MP mp, mp_knot p) {
+static int mplib_aux_set_direction(lua_State *L, MP mp, mp_knot p)
+{
double direction_x = (double) lua_tonumber(L, -1);
double direction_y = 0;
lua_pop(L, 1);
@@ -2540,19 +2541,22 @@ static int mplib_aux_set_direction(lua_State *L, MP mp, mp_knot p) {
}
}
-static int mplib_aux_set_left_curl(lua_State *L, MP mp, mp_knot p) {
+static int mplib_aux_set_left_curl(lua_State *L, MP mp, mp_knot p)
+{
double curl = (double) lua_tonumber(L, -1);
lua_pop(L, 1);
return mp_set_knot_left_curl(mp, p, curl) ? 1 : 0;
}
-static int mplib_aux_set_left_tension(lua_State *L, MP mp, mp_knot p) {
+static int mplib_aux_set_left_tension(lua_State *L, MP mp, mp_knot p)
+{
double tension = (double) lua_tonumber(L, -1);
lua_pop(L, 1);
return mp_set_knot_left_tension(mp, p, tension) ? 1 : 0;
}
-static int mplib_aux_set_left_control(lua_State *L, MP mp, mp_knot p) {
+static int mplib_aux_set_left_control(lua_State *L, MP mp, mp_knot p)
+{
double x = (double) lua_tonumber(L, -1);
lua_pop(L, 1);
lua_push_key(left_y);
@@ -2565,19 +2569,22 @@ static int mplib_aux_set_left_control(lua_State *L, MP mp, mp_knot p) {
}
}
-static int mplib_aux_set_right_curl(lua_State *L, MP mp, mp_knot p) {
+static int mplib_aux_set_right_curl(lua_State *L, MP mp, mp_knot p)
+{
double curl = (double) lua_tonumber(L, -1);
lua_pop(L, 1);
return mp_set_knot_right_curl(mp, p, curl) ? 1 : 0;
}
-static int mplib_aux_set_right_tension(lua_State *L, MP mp, mp_knot p) {
+static int mplib_aux_set_right_tension(lua_State *L, MP mp, mp_knot p)
+{
double tension = (double) lua_tonumber(L, -1);
lua_pop(L, 1);
return mp_set_knot_right_tension(mp, p, tension) ? 1 : 0;
}
-static int mplib_aux_set_right_control(lua_State *L, MP mp, mp_knot p) {
+static int mplib_aux_set_right_control(lua_State *L, MP mp, mp_knot p)
+{
double x = (double) lua_tonumber(L, -1);
lua_pop(L, 1);
lua_push_key(right_y);
diff --git a/source/luametatex/source/lua/lmtnodelib.c b/source/luametatex/source/lua/lmtnodelib.c
index e38161d81..974ebf11b 100644
--- a/source/luametatex/source/lua/lmtnodelib.c
+++ b/source/luametatex/source/lua/lmtnodelib.c
@@ -634,7 +634,7 @@ static int nodelib_direct_setsubtype(lua_State *L)
{
halfword n = nodelib_valid_direct_from_index(L, 1);
if (n && lua_type(L, 2) == LUA_TNUMBER) {
- node_subtype(n) = lmt_toquarterword(L, 2);
+ tex_set_subtype(n, lmt_toquarterword(L, 2));
}
return 0;
}
@@ -1117,17 +1117,17 @@ static int nodelib_direct_setclass(lua_State *L)
}
break;
case glyph_node:
- node_subtype(n) = glyph_math_ordinary_subtype + lmt_tosingleword(L, 2);
+ tex_set_subtype(n, glyph_math_ordinary_subtype + lmt_tosingleword(L, 2));
break;
case disc_node:
disc_class(n) = lmt_tosingleword(L, 2);
break;
case hlist_node:
case vlist_node:
- node_subtype(n) = noad_class_list_base + lmt_tosingleword(L, 2);
+ tex_set_subtype(n, noad_class_list_base + lmt_tosingleword(L, 2));
break;
case delimiter_node:
- node_subtype(n) = lmt_tosingleword(L, 2);
+ tex_set_subtype(n, lmt_tosingleword(L, 2));
return 1;
case choice_node:
choice_class(n) = lmt_tosingleword(L, 2);
@@ -1343,9 +1343,8 @@ static int nodelib_direct_getpenalty(lua_State *L)
if (tex_has_glue_option(n, glue_option_has_penalty)) {
lua_pushinteger(L, glue_penalty(n));
break;
- } else {
- /* fall through */
}
+ FALLTHROUGH
default:
lua_pushnil(L);
break;
@@ -1708,7 +1707,7 @@ static int nodelib_direct_setkern(lua_State *L)
case kern_node:
kern_amount(n) = lua_type(L, 2) == LUA_TNUMBER ? (halfword) lmt_roundnumber(L, 2) : 0;
if (lua_type(L, 3) == LUA_TNUMBER) {
- node_subtype(n) = lmt_toquarterword(L, 3);
+ tex_set_subtype(n, lmt_toquarterword(L, 3));
}
break;
case math_node:
@@ -1759,9 +1758,8 @@ static int nodelib_direct_setdirection(lua_State *L)
case dir_node:
dir_direction(n) = nodelib_getdirection(L, 2);
if (lua_type(L, 3) == LUA_TBOOLEAN) {
- // if (lua_toboolean(L, 3)) {
- node_subtype(n) = (quarterword) (lua_toboolean(L, 3) ? cancel_dir_subtype : normal_dir_subtype);
- // }
+ /* node_set_subtype(n, ...) */
+ node_subtype(n) = (quarterword) (lua_toboolean(L, 3) ? cancel_dir_subtype : normal_dir_subtype);
}
break;
case hlist_node:
@@ -1847,6 +1845,7 @@ static int nodelib_direct_setanchors(lua_State *L)
if (lua_toboolean(L, 2)) {
break;
}
+ FALLTHROUGH
default:
box_anchor(n) = 0;
break;
@@ -2079,49 +2078,117 @@ static int nodelib_direct_addmargins(lua_State *L)
return 0;
}
-static int nodelib_direct_addxymargins(lua_State *L)
-{
- halfword n = nodelib_valid_direct_from_index(L, 1);
- if (n && node_type(n) == glyph_node) {
- scaled s = glyph_scale(n);
- scaled x = glyph_x_scale(n);
- scaled y = glyph_y_scale(n);
- double sx, sy;
- if (s == 0 || s == 1000) {
- if (x == 0 || x == 1000) {
- sx = 1;
- } else {
- sx = 0.001 * x;
- }
- if (y == 0 || y == 1000) {
- sy = 1;
- } else {
- sy = 0.001 * y;
+// static int nodelib_direct_addxymargins(lua_State *L)
+// {
+// halfword n = nodelib_valid_direct_from_index(L, 1);
+// if (n && node_type(n) == glyph_node) {
+// scaled s = glyph_scale(n);
+// scaled x = glyph_x_scale(n);
+// scaled y = glyph_y_scale(n);
+// double sx, sy;
+// if (s == 0 || s == 1000) {
+// if (x == 0 || x == 1000) {
+// sx = 1;
+// } else {
+// sx = 0.001 * x;
+// }
+// if (y == 0 || y == 1000) {
+// sy = 1;
+// } else {
+// sy = 0.001 * y;
+// }
+// } else {
+// if (x == 0 || x == 1000) {
+// sx = 0.001 * s;
+// } else {
+// sx = 0.000001 * s * x;
+// }
+// if (y == 0 || y == 1000) {
+// sy = 0.001 * s;
+// } else {
+// sy = 0.000001 * s * y;
+// }
+// }
+// if (lua_type(L, 2) == LUA_TNUMBER) {
+// glyph_left(n) += scaledround(sx * lua_tonumber(L, 2));
+// }
+// if (lua_type(L, 3) == LUA_TNUMBER) {
+// glyph_right(n) += scaledround(sx * lua_tonumber(L, 3));
+// }
+// if (lua_type(L, 4) == LUA_TNUMBER) {
+// glyph_raise(n) += scaledround(sy * lua_tonumber(L, 4));
+// }
+// }
+// return 0;
+// }
+
+# if lmt_float_math
+
+ static int nodelib_direct_addxymargins(lua_State *L)
+ {
+ halfword n = nodelib_valid_direct_from_index(L, 1);
+ if (n && node_type(n) == glyph_node) {
+ double s = glyph_scale(n);
+ double x = glyph_x_scale(n);
+ double y = glyph_y_scale(n);
+ // 0.000001 = 1 / (1000 * 1000)
+ double sx = 0.000001 * (s ? s : 1000.0) * (x ? x : 1000.0);
+ double sy = 0.000001 * (s ? s : 1000.0) * (y ? y : 1000.0);
+ if (lua_type(L, 2) == LUA_TNUMBER) {
+ double left = lua_tonumber(L, 2);
+ if (left) {
+ glyph_left(n) += scaledround(sx * left);
+ }
}
- } else {
- if (x == 0 || x == 1000) {
- sx = 0.001 * s;
- } else {
- sx = 0.000001 * s * x;
+ if (lua_type(L, 3) == LUA_TNUMBER) {
+ double right = lua_tonumber(L, 3);
+ if (right) {
+ glyph_right(n) += scaledround(sx * right);
+ }
}
- if (y == 0 || y == 1000) {
- sy = 0.001 * s;
- } else {
- sy = 0.000001 * s * y;
+ if (lua_type(L, 4) == LUA_TNUMBER) {
+ double raise = lua_tonumber(L, 4);
+ if (raise) {
+ glyph_raise(n) += scaledround(sy * raise);
+ }
}
}
- if (lua_type(L, 2) == LUA_TNUMBER) {
- glyph_left(n) += scaledround(sx * lua_tonumber(L, 2));
- }
- if (lua_type(L, 3) == LUA_TNUMBER) {
- glyph_right(n) += scaledround(sx * lua_tonumber(L, 3));
- }
- if (lua_type(L, 4) == LUA_TNUMBER) {
- glyph_raise(n) += scaledround(sy * lua_tonumber(L, 4));
+ return 0;
+ }
+
+# else
+
+ static int nodelib_direct_addxymargins(lua_State *L)
+ {
+ halfword n = nodelib_valid_direct_from_index(L, 1);
+ if (n && node_type(n) == glyph_node) {
+ long long s = glyph_scale(n);
+ long long x = glyph_x_scale(n);
+ long long y = glyph_y_scale(n);
+
+ if (lua_type(L, 2) == LUA_TNUMBER) {
+ lua_Number left = lua_tonumber(L, 2);
+ if (left) {
+ glyph_left(n) += tex_aux_scale_1e6((scaled) left, s, x);
+ }
+ }
+ if (lua_type(L, 3) == LUA_TNUMBER) {
+ lua_Number right = lua_tonumber(L, 3);
+ if (right) {
+ glyph_right(n) += tex_aux_scale_1e6((scaled) right, s, x);
+ }
+ }
+ if (lua_type(L, 4) == LUA_TNUMBER) {
+ lua_Number raise = lua_tonumber(L, 4);
+ if (raise) {
+ glyph_raise(n) += tex_aux_scale_1e6((scaled) raise, s, y);
+ }
+ }
}
+ return 0;
}
- return 0;
-}
+
+# endif
/* node.direct.getscale */
@@ -2139,6 +2206,9 @@ static int nodelib_direct_getscale(lua_State *L)
case style_node:
lua_pushinteger(L, style_scale(n));
return 1;
+ /*tex When we need it: */
+ // lua_pushinteger(L, style_glyph_scale(n));
+ // return 2;
}
}
return 0;
@@ -2165,6 +2235,10 @@ static int nodelib_direct_setscale(lua_State *L)
// style_scale(n) = scaling_factor;
// }
}
+ /*tex When we need it: */
+ // if (lua_type(L, 3) == LUA_TNUMBER) {
+ // style_glyph_scale(n) = (halfword) lmt_roundnumber(L, 3);
+ // }
break;
}
}
@@ -2317,24 +2391,98 @@ static int nodelib_direct_getyscale(lua_State *L)
# define xscaled_usage glyph_usage
# define yscaled_usage xscaled_usage
+// static int nodelib_direct_xscaled(lua_State *L)
+// {
+// halfword n = nodelib_valid_direct_from_index(L, 1);
+// lua_Number v = lua_tonumber(L, 2);
+// if (n && node_type(n) == glyph_node) {
+// scaled s = glyph_scale(n);
+// scaled x = glyph_x_scale(n);
+// if (s == 0 || s == 1000) {
+// if (x == 0 || x == 1000) {
+// /* okay */
+// } else {
+// v = 0.001 * x * v;
+// }
+// } else if (x == 0 || x == 1000) {
+// v = 0.001 * s * v;
+// } else {
+// v = 0.000001 * s * x * v;
+// }
+// }
+// lua_pushnumber(L, v);
+// return 1;
+// }
+//
+// static int nodelib_direct_yscaled(lua_State *L)
+// {
+// halfword n = nodelib_valid_direct_from_index(L, 1);
+// lua_Number v = lua_tonumber(L, 2);
+// if (n && node_type(n) == glyph_node) {
+// scaled s = glyph_scale(n);
+// scaled y = glyph_y_scale(n);
+// if (s == 0 || s == 1000) {
+// if (y == 0 || y == 1000) {
+// /* okay */
+// } else {
+// v = 0.001 * y * v;
+// }
+// } else if (y == 0 || y == 1000) {
+// v = 0.001 * s * v;
+// } else {
+// v = 0.000001 * s * y * v;
+// }
+// }
+// lua_pushnumber(L, v);
+// return 1;
+// }
+//
+// static void nodelib_aux_pushxyscales(lua_State *L, halfword n)
+// {
+// scaled s = glyph_scale(n);
+// scaled x = glyph_x_scale(n);
+// scaled y = glyph_y_scale(n);
+// double dx;
+// double dy;
+// if (s && s != 1000) {
+// dx = (x && x != 1000) ? 0.000001 * s * x : 0.001 * s;
+// } else if (x && x != 1000) {
+// dx = 0.001 * x;
+// } else {
+// lua_pushinteger(L, 1);
+// goto DONEX;
+// }
+// lua_pushnumber(L, dx);
+// DONEX:
+// if (s && s != 1000) {
+// dy = (y && y != 1000) ? 0.000001 * s * y : 0.001 * s;
+// } else if (y && y != 1000) {
+// dy = 0.001 * y;
+// } else {
+// lua_pushinteger(L, 1);
+// goto DONEY;
+// }
+// lua_pushnumber(L, dy);
+// DONEY: ;
+// }
+
+static inline double nodelib_aux_calculate_scale_factor(scaled s, scaled axis_scale)
+{
+ s = (s == 0) ? 1000 : s;
+ axis_scale = (axis_scale == 0) ? 1000 : axis_scale;
+ if (s == 1000 && axis_scale == 1000) {
+ return 1.0;
+ }
+ return 0.000001 * (double)s * (double)axis_scale;
+}
+
static int nodelib_direct_xscaled(lua_State *L)
{
halfword n = nodelib_valid_direct_from_index(L, 1);
lua_Number v = lua_tonumber(L, 2);
if (n && node_type(n) == glyph_node) {
- scaled s = glyph_scale(n);
- scaled x = glyph_x_scale(n);
- if (s == 0 || s == 1000) {
- if (x == 0 || x == 1000) {
- /* okay */
- } else {
- v = 0.001 * x * v;
- }
- } else if (x == 0 || x == 1000) {
- v = 0.001 * s * v;
- } else {
- v = 0.000001 * s * x * v;
- }
+ double factor = nodelib_aux_calculate_scale_factor(glyph_scale(n), glyph_x_scale(n));
+ v *= factor;
}
lua_pushnumber(L, v);
return 1;
@@ -2345,19 +2493,8 @@ static int nodelib_direct_yscaled(lua_State *L)
halfword n = nodelib_valid_direct_from_index(L, 1);
lua_Number v = lua_tonumber(L, 2);
if (n && node_type(n) == glyph_node) {
- scaled s = glyph_scale(n);
- scaled y = glyph_y_scale(n);
- if (s == 0 || s == 1000) {
- if (y == 0 || y == 1000) {
- /* okay */
- } else {
- v = 0.001 * y * v;
- }
- } else if (y == 0 || y == 1000) {
- v = 0.001 * s * v;
- } else {
- v = 0.000001 * s * y * v;
- }
+ double factor = nodelib_aux_calculate_scale_factor(glyph_scale(n), glyph_y_scale(n));
+ v *= factor;
}
lua_pushnumber(L, v);
return 1;
@@ -2368,28 +2505,18 @@ static void nodelib_aux_pushxyscales(lua_State *L, halfword n)
scaled s = glyph_scale(n);
scaled x = glyph_x_scale(n);
scaled y = glyph_y_scale(n);
- double dx;
- double dy;
- if (s && s != 1000) {
- dx = (x && x != 1000) ? 0.000001 * s * x : 0.001 * s;
- } else if (x && x != 1000) {
- dx = 0.001 * x;
- } else {
+ double fx = nodelib_aux_calculate_scale_factor(s, x);
+ double fy = nodelib_aux_calculate_scale_factor(s, y);
+ if (fx == 1.0) {
lua_pushinteger(L, 1);
- goto DONEX;
- }
- lua_pushnumber(L, dx);
- DONEX:
- if (s && s != 1000) {
- dy = (y && y != 1000) ? 0.000001 * s * y : 0.001 * s;
- } else if (y && y != 1000) {
- dy = 0.001 * y;
} else {
+ lua_pushnumber(L, fx);
+ }
+ if (fy == 1.0) {
lua_pushinteger(L, 1);
- goto DONEY;
+ } else {
+ lua_pushnumber(L, fy);
}
- lua_pushnumber(L, dy);
- DONEY: ;
}
/* node.direct.getxyscales */
@@ -2524,7 +2651,7 @@ static int nodelib_direct_setdisc(lua_State *L)
if (t > 3) {
tex_set_disc_field(n, no_break_code, nodelib_valid_direct_from_index(L, 4));
if (t > 4) {
- node_subtype(n) = lmt_toquarterword(L, 5);
+ tex_set_subtype(n, lmt_toquarterword(L, 5));
if (t > 5) {
disc_penalty(n) = lmt_tohalfword(L, 6);
}
@@ -2881,7 +3008,7 @@ static int nodelib_direct_setheight(lua_State *L)
{
halfword n = nodelib_valid_direct_from_index(L, 1);
if (n) {
- halfword h = 0;
+ scaled h = 0;
if (lua_type(L, 2) == LUA_TNUMBER) {
h = lmt_roundnumber(L, 2);
}
@@ -2948,7 +3075,7 @@ static int nodelib_direct_setdepth(lua_State *L)
{
halfword n = nodelib_valid_direct_from_index(L, 1);
if (n) {
- halfword d = 0;
+ scaled d = 0;
if (lua_type(L, 2) == LUA_TNUMBER) {
d = lmt_roundnumber(L, 2);
}
@@ -3256,6 +3383,7 @@ static int nodelib_direct_setorientation(lua_State *L)
if (lua_toboolean(L, 2)) {
break;
}
+ FALLTHROUGH
default:
box_orientation(n) = 0;
break;
@@ -3268,6 +3396,7 @@ static int nodelib_direct_setorientation(lua_State *L)
if (lua_toboolean(L, 3)) {
break;
}
+ FALLTHROUGH
default:
box_x_offset(n) = 0;
break;
@@ -3280,6 +3409,7 @@ static int nodelib_direct_setorientation(lua_State *L)
if (lua_toboolean(L, 4)) {
break;
}
+ FALLTHROUGH
default:
box_y_offset(n) = 0;
break;
@@ -3292,6 +3422,7 @@ static int nodelib_direct_setorientation(lua_State *L)
if (lua_toboolean(L, 5)) {
break;
}
+ FALLTHROUGH
default:
box_w_offset(n) = 0;
break;
@@ -3304,6 +3435,7 @@ static int nodelib_direct_setorientation(lua_State *L)
if (lua_toboolean(L, 6)) {
break;
}
+ FALLTHROUGH
default:
box_h_offset(n) = 0;
break;
@@ -3316,6 +3448,7 @@ static int nodelib_direct_setorientation(lua_State *L)
if (lua_toboolean(L, 7)) {
break;
}
+ FALLTHROUGH
default:
box_d_offset(n) = 0;
break;
@@ -3725,7 +3858,9 @@ static int nodelib_direct_hasdimensions(lua_State *L)
# define getglyphdimensions_usage glyph_usage
-const double INV_1000 = 1.0 / 1000.0;
+// const double INV_1000 = 1.0 / 1000.0;
+
+# define INV_1000 (1.0 / 1000.0)
static int nodelib_direct_getglyphdimensions(lua_State *L)
{
@@ -4718,9 +4853,8 @@ static int nodelib_direct_setlink(lua_State *L)
if (lua_toboolean(L, i)) {
/*tex Just skip this one. */
break;
- } else {
- /* fall through */
}
+ FALLTHROUGH
default:
if (t) {
/* safeguard: a nil in the list can be meant as end so we nil the next of tail */
@@ -4958,7 +5092,8 @@ static halfword nodelib_new_node(lua_State *L)
break;
}
lmt_lua_state.last_node_error = lua_no_node_error;
- return tex_new_node(i, (j == unknown_subtype) ? 0 : j);
+ // return tex_new_node(i, (j == unknown_subtype) ? 0 : j);
+ return tex_new_node(i, tex_valid_subtype(i, (j == unknown_subtype) ? 0 : j));
} else {
lmt_lua_state.last_node_error = lua_new_node_error;
if (! lmt_lua_state.ignore_node_error) {
@@ -8821,6 +8956,8 @@ static int nodelib_common_getfield(lua_State *L, int direct, halfword n)
lmt_push_math_style_name(L, style_style(n));
} else if (lua_key_eq(s, scale)) {
lua_pushinteger(L, style_scale(n));
+ } else if (lua_key_eq(s, glyphscale)) {
+ lua_pushinteger(L, style_glyph_scale(n));
} else {
goto CANTGET;
}
@@ -9230,9 +9367,7 @@ static int nodelib_common_setfield(lua_State *L, int direct, halfword n)
goto CANTSET;
}
} else if (lua_key_eq(s, subtype)) {
- if (tex_nodetype_has_subtype(t)) {
- node_subtype(n) = lmt_toquarterword(L, 3);
- } else {
+ if (! tex_set_subtype(n, lmt_toquarterword(L, 3))) {
goto CANTSET;
}
} else {
@@ -9619,6 +9754,8 @@ static int nodelib_common_setfield(lua_State *L, int direct, halfword n)
style_style(n) = (quarterword) lmt_get_math_style(L, 2, text_style);
} else if (lua_key_eq(s, scale)) {
style_scale(n) = (halfword) lmt_roundnumber(L, 3);
+ } else if (lua_key_eq(s, glyphscale)) {
+ style_glyph_scale(n) = (halfword) lmt_roundnumber(L, 3);
} else {
/* return nodelib_cantset(L, n, s); */
}
@@ -11639,7 +11776,7 @@ static int nodelib_userdata_getpropertiestable(lua_State *L)
/* todo: use effective helper that returns double */
-static void nodelib_direct_effect_done(lua_State *L, halfword amount, halfword stretch, halfword shrink, halfword stretch_order, halfword shrink_order)
+static void nodelib_direct_effect_done(lua_State *L, scaled amount, scaled stretch, scaled shrink, halfword stretch_order, halfword shrink_order)
{
halfword parent = nodelib_valid_direct_from_index(L, 2);
if (parent) {
@@ -11833,9 +11970,9 @@ static int nodelib_direct_makeextensible(lua_State *L)
if (top >= 3) {
halfword fnt = lmt_tohalfword(L, 1);
halfword chr = lmt_tohalfword(L, 2);
- halfword target = lmt_tohalfword(L, 3);
+ scaled target = lmt_tohalfword(L, 3);
halfword size = 0;
- halfword overlap = 65536;
+ scaled overlap = 65536;
halfword attlist = null;
halfword b = null;
int horizontal = 0;
@@ -14243,7 +14380,7 @@ void lmt_local_box_callback(
int lmt_append_to_vlist_callback(
halfword box,
int location,
- halfword prevdepth,
+ scaled prevdepth,
halfword *result,
int *nextdepth,
int *prevset,
diff --git a/source/luametatex/source/lua/lmtnodelib.h b/source/luametatex/source/lua/lmtnodelib.h
index 50e94d2e1..5190a5c6b 100644
--- a/source/luametatex/source/lua/lmtnodelib.h
+++ b/source/luametatex/source/lua/lmtnodelib.h
@@ -114,7 +114,7 @@ extern void lmt_local_box_callback(
extern int lmt_append_to_vlist_callback(
halfword box,
int location,
- halfword prevdepth,
+ scaled prevdepth,
halfword *result,
int *nextdepth,
int *prevset,
diff --git a/source/luametatex/source/lua/lmtsecuritylib.c b/source/luametatex/source/lua/lmtsecuritylib.c
index 479482183..5bc8aeb90 100644
--- a/source/luametatex/source/lua/lmtsecuritylib.c
+++ b/source/luametatex/source/lua/lmtsecuritylib.c
@@ -6,27 +6,35 @@
static inline int security_target_okay(int target)
{
- return target >= security_generic && target <= security_loadable;
+ return target >= security_generic && target <= security_client;
}
static void securitylib_initialize(lua_State *L)
{
+ (void) L;
for (int i = 0; i < n_of_security_targets; i++) {
lmt_lua_state.security_checkers[i] = LUA_NOREF;
+ lmt_lua_state.security_states [i] = security_state_unset;
}
}
static int securitylib_setchecker(lua_State *L)
{
int target = lmt_tointeger(L, 1);
- luaL_checktype(L, 2, LUA_TFUNCTION);
- if (! security_target_okay(target)) {
- return luaL_error(L, "second argument must be a valid target");
- } else if (lmt_lua_state.security_checkers[target] != LUA_NOREF) {
- return luaL_error(L, "security checker for target %d is frozen and cannot be (re)set", target);
+ if (lua_type(L, 2) == LUA_TFUNCTION) {
+ int freeze = ! lua_toboolean(L, 3);
+ lua_settop(L, 2);
+ if (! security_target_okay(target)) {
+ return luaL_error(L, "first argument must be a valid target");
+ } else if (lmt_lua_state.security_states[target] == security_state_frozen) {
+ return luaL_error(L, "security checker for target %d is frozen and cannot be (re)set", target);
+ } else {
+ lmt_lua_state.security_checkers[target] = luaL_ref(L, LUA_REGISTRYINDEX);
+ lmt_lua_state.security_states [target] = freeze ? security_state_frozen : security_state_set;
+ return 0;
+ }
} else {
- lmt_lua_state.security_checkers[target] = luaL_ref(L, LUA_REGISTRYINDEX);
- return 0;
+ return luaL_error(L, "second argument must be a function");
}
}
@@ -112,19 +120,21 @@ static int securitylib_resetdebug(lua_State *L)
static int securitylib_gettargets(lua_State *L)
{
- lua_createtable(L, 5, 1);
+ lua_createtable(L, 7, 1);
lua_set_string_by_index(L, security_generic, "generic");
lua_set_string_by_index(L, security_readable, "readable");
- lua_set_string_by_index(L, security_writeable, "writeable");
+ lua_set_string_by_index(L, security_writable, "writable");
lua_set_string_by_index(L, security_executable, "executable");
lua_set_string_by_index(L, security_library, "library");
lua_set_string_by_index(L, security_loadable, "loadable");
+ lua_set_string_by_index(L, security_launchable, "launchable");
+ lua_set_string_by_index(L, security_client, "client");
return 1;
}
static int securitylib_getactions(lua_State *L)
{
- lua_createtable(L, 15, 1);
+ lua_createtable(L, 17, 1);
lua_set_string_by_index(L, security_generic_action, "generic");
lua_set_string_by_index(L, security_remove_directory, "remove directory");
lua_set_string_by_index(L, security_change_directory, "change directory");
@@ -141,6 +151,8 @@ static int securitylib_getactions(lua_State *L)
lua_set_string_by_index(L, security_run_executable, "run executable");
lua_set_string_by_index(L, security_load_library, "load library");
lua_set_string_by_index(L, security_open_database, "open database");
+ lua_set_string_by_index(L, security_launch_command, "launch command");
+ lua_set_string_by_index(L, security_http_request, "http request");
return 1;
}
diff --git a/source/luametatex/source/lua/lmtstatuslib.c b/source/luametatex/source/lua/lmtstatuslib.c
index f4f0ec940..4f1f846f7 100644
--- a/source/luametatex/source/lua/lmtstatuslib.c
+++ b/source/luametatex/source/lua/lmtstatuslib.c
@@ -228,29 +228,31 @@ static int statslib_readstate(lua_State *L)
static int statslib_enginestate(lua_State *L)
{
lua_createtable(L, 0, 16);
- lua_set_string_by_key (L, "logfilename", lmt_fileio_state.log_name);
- lua_set_string_by_key (L, "banner", lmt_engine_state.luatex_banner);
- lua_set_number_by_key (L, "version", lmt_version_state.luatexversion);
- lua_set_string_by_key (L, "luatex_engine", lmt_engine_state.engine_name);
- lua_set_integer_by_key(L, "luatex_version", lmt_version_state.version);
- lua_set_integer_by_key(L, "luatex_revision", lmt_version_state.revision);
- lua_set_integer_by_key(L, "luatex_release", lmt_version_state.release);
- lua_set_string_by_key(L, "luatex_verbose", lmt_version_state.verbose);
- lua_set_integer_by_key(L, "development_id", lmt_version_state.developmentid);
- lua_set_string_by_key (L, "copyright", lmt_version_state.copyright);
- lua_set_integer_by_key(L, "format_id", lmt_version_state.formatid);
- lua_set_integer_by_key(L, "tex_hash_size", hash_size);
- // lua_set_integer_by_key(L, "tex_hash_prime", hash_prime);
- // lua_set_integer_by_key(L, "tex_eqtb_size", eqtb_size);
- lua_set_integer_by_key(L, "tex_memory_mode", memory_mode);
- lua_set_string_by_key (L, "used_compiler", lmt_version_state.compiler);
- lua_set_integer_by_key(L, "used_cversion", lmt_version_state.cversion);
- lua_set_boolean_by_key(L, "used_likely", lmt_version_state.likely);
- // lua_set_string_by_key (L, "used_libc", lmt_version_state.libc);
- lua_set_integer_by_key(L, "run_state", lmt_main_state.run_state);
- lua_set_integer_by_key(L, "overload_state", lmt_main_state.overload_state);
- lua_set_boolean_by_key(L, "permit_loadlib", lmt_engine_state.permit_loadlib);
- lua_set_boolean_by_key(L, "permit_shebang", lmt_engine_state.permit_shebang);
+ lua_set_string_by_key (L, "logfilename", lmt_fileio_state.log_name);
+ lua_set_string_by_key (L, "banner", lmt_engine_state.luametatex_banner);
+ lua_set_number_by_key (L, "version", lmt_version_state.luametatexversion);
+ lua_set_string_by_key (L, "luametatex_engine", lmt_engine_state.engine_name);
+ lua_set_integer_by_key(L, "luametatex_version", lmt_version_state.version);
+ lua_set_integer_by_key(L, "luametatex_release", lmt_version_state.release);
+ lua_set_string_by_key (L, "luametatex_verbose", lmt_version_state.verbose);
+ lua_set_integer_by_key(L, "majorversion", lmt_version_state.majorversion);
+ lua_set_integer_by_key(L, "minorversion", lmt_version_state.minorversion);
+ lua_set_integer_by_key(L, "functionality", lmt_version_state.functionality);
+ lua_set_string_by_key (L, "distribution", lmt_version_state.distribution);
+ lua_set_string_by_key (L, "copyright", lmt_version_state.copyright);
+ lua_set_integer_by_key(L, "format_id", lmt_version_state.formatid);
+ lua_set_integer_by_key(L, "tex_hash_size", hash_size);
+ // lua_set_integer_by_key(L, "tex_hash_prime", hash_prime);
+ // lua_set_integer_by_key(L, "tex_eqtb_size", eqtb_size);
+ lua_set_integer_by_key(L, "tex_memory_mode", memory_mode);
+ lua_set_string_by_key (L, "used_compiler", lmt_version_state.compiler);
+ lua_set_integer_by_key(L, "used_cversion", lmt_version_state.cversion);
+ lua_set_boolean_by_key(L, "used_likely", lmt_version_state.likely);
+ // lua_set_string_by_key (L, "used_libc", lmt_version_state.libc);
+ lua_set_integer_by_key(L, "run_state", lmt_main_state.run_state);
+ lua_set_integer_by_key(L, "overload_state", lmt_main_state.overload_state);
+ lua_set_boolean_by_key(L, "permit_loadlib", lmt_engine_state.permit_loadlib);
+ lua_set_boolean_by_key(L, "permit_shebang", lmt_engine_state.permit_shebang);
return 1;
}
@@ -483,37 +485,37 @@ static struct statistic_entry statslib_entries[] = {
/*tex But these are now collected in tables: */
- { .name = "enginestate", .value = &statslib_enginestate, .type = 'f' },
- { .name = "errorlinestate", .value = &statslib_errorlinestate, .type = 'f' },
- { .name = "halferrorlinestate", .value = &statslib_halferrorlinestate, .type = 'f' },
- { .name = "expandstate", .value = &statslib_expandstate, .type = 'f' },
- { .name = "stringstate", .value = &statslib_stringstate, .type = 'f' },
- { .name = "poolstate", .value = &statslib_poolstate, .type = 'f' },
- { .name = "hashstate", .value = &statslib_hashstate, .type = 'f' },
- { .name = "lookupstate", .value = &statslib_lookupstate, .type = 'f' },
- { .name = "nodestate", .value = &statslib_nodestate, .type = 'f' },
- { .name = "tokenstate", .value = &statslib_tokenstate, .type = 'f' },
- { .name = "inputstate", .value = &statslib_inputstate, .type = 'f' },
- { .name = "filestate", .value = &statslib_filestate, .type = 'f' },
- { .name = "parameterstate", .value = &statslib_parameterstate, .type = 'f' },
- { .name = "neststate", .value = &statslib_neststate, .type = 'f' },
- { .name = "savestate", .value = &statslib_savestate, .type = 'f' },
- { .name = "bufferstate", .value = &statslib_bufferstate, .type = 'f' },
- { .name = "texstate", .value = &statslib_texstate, .type = 'f' },
- { .name = "luastate", .value = &statslib_luastate, .type = 'f' },
- { .name = "callbackstate", .value = &statslib_callbackstate, .type = 'f' },
- { .name = "linebreakstate", .value = &statslib_linebreakstate, .type = 'f' },
- { .name = "balancestate", .value = &statslib_balancestate, .type = 'f' },
- { .name = "hyphenationstate", .value = &statslib_hyphenationstate, .type = 'f' },
- { .name = "errorstate", .value = &statslib_errorstate, .type = 'f' },
- { .name = "warningstate", .value = &statslib_warningstate, .type = 'f' },
- { .name = "readstate", .value = &statslib_readstate, .type = 'f' },
- { .name = "fontstate", .value = &statslib_fontstate, .type = 'f' },
- { .name = "languagestate", .value = &statslib_languagestate, .type = 'f' },
- { .name = "markstate", .value = &statslib_markstate, .type = 'f' },
- { .name = "insertstate", .value = &statslib_insertstate, .type = 'f' },
- { .name = "sparsestate", .value = &statslib_sparsestate, .type = 'f' },
- { .name = "mvlstate", .value = &statslib_mvlstate, .type = 'f' },
+ { .name = "enginestate", .value = &statslib_enginestate, .type = 'f' },
+ { .name = "errorlinestate", .value = &statslib_errorlinestate, .type = 'f' },
+ { .name = "halferrorlinestate", .value = &statslib_halferrorlinestate, .type = 'f' },
+ { .name = "expandstate", .value = &statslib_expandstate, .type = 'f' },
+ { .name = "stringstate", .value = &statslib_stringstate, .type = 'f' },
+ { .name = "poolstate", .value = &statslib_poolstate, .type = 'f' },
+ { .name = "hashstate", .value = &statslib_hashstate, .type = 'f' },
+ { .name = "lookupstate", .value = &statslib_lookupstate, .type = 'f' },
+ { .name = "nodestate", .value = &statslib_nodestate, .type = 'f' },
+ { .name = "tokenstate", .value = &statslib_tokenstate, .type = 'f' },
+ { .name = "inputstate", .value = &statslib_inputstate, .type = 'f' },
+ { .name = "filestate", .value = &statslib_filestate, .type = 'f' },
+ { .name = "parameterstate", .value = &statslib_parameterstate, .type = 'f' },
+ { .name = "neststate", .value = &statslib_neststate, .type = 'f' },
+ { .name = "savestate", .value = &statslib_savestate, .type = 'f' },
+ { .name = "bufferstate", .value = &statslib_bufferstate, .type = 'f' },
+ { .name = "texstate", .value = &statslib_texstate, .type = 'f' },
+ { .name = "luastate", .value = &statslib_luastate, .type = 'f' },
+ { .name = "callbackstate", .value = &statslib_callbackstate, .type = 'f' },
+ { .name = "linebreakstate", .value = &statslib_linebreakstate, .type = 'f' },
+ { .name = "balancestate", .value = &statslib_balancestate, .type = 'f' },
+ { .name = "hyphenationstate", .value = &statslib_hyphenationstate, .type = 'f' },
+ { .name = "errorstate", .value = &statslib_errorstate, .type = 'f' },
+ { .name = "warningstate", .value = &statslib_warningstate, .type = 'f' },
+ { .name = "readstate", .value = &statslib_readstate, .type = 'f' },
+ { .name = "fontstate", .value = &statslib_fontstate, .type = 'f' },
+ { .name = "languagestate", .value = &statslib_languagestate, .type = 'f' },
+ { .name = "markstate", .value = &statslib_markstate, .type = 'f' },
+ { .name = "insertstate", .value = &statslib_insertstate, .type = 'f' },
+ { .name = "sparsestate", .value = &statslib_sparsestate, .type = 'f' },
+ { .name = "mvlstate", .value = &statslib_mvlstate, .type = 'f' },
/*tex Lua keys: */
@@ -525,56 +527,57 @@ static struct statistic_entry statslib_entries[] = {
/*tex We keep these as direct accessible keys: */
- { .name = "filename", .value = (void *) &tex_current_input_file_name, .type = 'S' },
- { .name = "logfilename", .value = (void *) &lmt_fileio_state.log_name, .type = 'c' },
- { .name = "banner", .value = (void *) &lmt_engine_state.luatex_banner, .type = 'c' },
- { .name = "copyright", .value = (void *) &lmt_version_state.copyright, .type = 'c' },
+ { .name = "filename", .value = (void *) &tex_current_input_file_name, .type = 'S' },
+ { .name = "logfilename", .value = (void *) &lmt_fileio_state.log_name, .type = 'c' },
+ { .name = "banner", .value = (void *) &lmt_engine_state.luametatex_banner, .type = 'c' },
+ { .name = "copyright", .value = (void *) &lmt_version_state.copyright, .type = 'c' },
/* */
- { .name = "majorversion", .value = (void *) &lmt_version_state.majorversion, .type = 'g' },
- { .name = "minorversion", .value = (void *) &lmt_version_state.minorversion, .type = 'g' },
- { .name = "release", .value = (void *) &lmt_version_state.release, .type = 'g' },
- { .name = "development_id", .value = (void *) &lmt_version_state.developmentid, .type = 'g' },
- { .name = "format_id", .value = (void *) &lmt_version_state.formatid, .type = 'g' },
+ { .name = "majorversion", .value = (void *) &lmt_version_state.majorversion, .type = 'g' },
+ { .name = "minorversion", .value = (void *) &lmt_version_state.minorversion, .type = 'g' },
+ { .name = "release", .value = (void *) &lmt_version_state.release, .type = 'g' },
+ { .name = "functionality", .value = (void *) &lmt_version_state.functionality, .type = 'g' },
+ { .name = "distribution", .value = (void *) &lmt_version_state.distribution, .type = 'c' },
+ { .name = "format_id", .value = (void *) &lmt_version_state.formatid, .type = 'g' },
/* */
- { .name = "version", .value = (void *) &lmt_version_state.luatexversion, .type = 'd' },
+ { .name = "version", .value = (void *) &lmt_version_state.luametatexversion, .type = 'd' },
/* */
- { .name = "luatex_engine", .value = (void *) &lmt_engine_state.engine_name, .type = 'c' },
- { .name = "luatex_version", .value = (void *) &lmt_version_state.version, .type = 'g' },
- { .name = "luatex_revision", .value = (void *) &lmt_version_state.revision, .type = 'g' },
- { .name = "luatex_release", .value = (void *) &lmt_version_state.release, .type = 'g' },
- { .name = "luatex_verbose", .value = (void *) &lmt_version_state.verbose, .type = 'c' },
+ { .name = "luametatex_engine", .value = (void *) &lmt_engine_state.engine_name, .type = 'c' },
+ { .name = "luametatex_version", .value = (void *) &lmt_version_state.version, .type = 'g' },
+ { .name = "luametatex_release", .value = (void *) &lmt_version_state.release, .type = 'g' },
+ { .name = "luametatex_verbose", .value = (void *) &lmt_version_state.verbose, .type = 'c' },
/* */
- { .name = "used_compiler", .value = (void *) &lmt_version_state.compiler, .type = 'c' }, /* can be moved up */
- { .name = "used_cversion", .value = (void *) &lmt_version_state.cversion, .type = 'g' }, /* can be moved up */
- { .name = "used_likely", .value = (void *) &lmt_version_state.likely, .type = 'b' }, /* can be moved up */
- { .name = "run_state", .value = (void *) &lmt_main_state.run_state, .type = 'g' },
- { .name = "overload_state", .value = (void *) &lmt_main_state.overload_state, .type = 'g' },
- { .name = "permit_loadlib", .value = (void *) &lmt_engine_state.permit_loadlib, .type = 'b' },
- { .name = "permit_shebang", .value = (void *) &lmt_engine_state.permit_shebang, .type = 'b' },
+ { .name = "used_compiler", .value = (void *) &lmt_version_state.compiler, .type = 'c' }, /* can be moved up */
+ { .name = "used_cversion", .value = (void *) &lmt_version_state.cversion, .type = 'g' }, /* can be moved up */
+ { .name = "used_likely", .value = (void *) &lmt_version_state.likely, .type = 'b' }, /* can be moved up */
+ { .name = "run_state", .value = (void *) &lmt_main_state.run_state, .type = 'g' },
+ { .name = "overload_state", .value = (void *) &lmt_main_state.overload_state, .type = 'g' },
+ { .name = "permit_loadlib", .value = (void *) &lmt_engine_state.permit_loadlib, .type = 'b' },
+ { .name = "permit_shebang", .value = (void *) &lmt_engine_state.permit_shebang, .type = 'b' },
/* */
- { .name = "tex_memory_mode", .value = &statslib_memory_mode, .type = 'f' }, /* can be moved up */
+ { .name = "tex_memory_mode", .value = &statslib_memory_mode, .type = 'f' }, /* can be moved up */
/* */
- { .name = NULL, .value = NULL, .type = 0 },
+ { .name = NULL, .value = NULL, .type = 0 },
};
static struct statistic_entry statslib_entries_only[] = {
{ .name = "filename", .value = (void *) &tex_current_input_file_name, .type = 'S' },
- { .name = "banner", .value = (void *) &lmt_engine_state.luatex_banner, .type = 'c' },
+ { .name = "banner", .value = (void *) &lmt_engine_state.luametatex_banner, .type = 'c' },
{ .name = "copyright", .value = (void *) &lmt_version_state.copyright, .type = 'c' },
/* */
{ .name = "majorversion", .value = (void *) &lmt_version_state.majorversion, .type = 'g' },
{ .name = "minorversion", .value = (void *) &lmt_version_state.minorversion, .type = 'g' },
{ .name = "release", .value = (void *) &lmt_version_state.release, .type = 'g' },
- { .name = "development_id", .value = (void *) &lmt_version_state.developmentid, .type = 'g' },
+ { .name = "functionality", .value = (void *) &lmt_version_state.functionality, .type = 'g' },
+ { .name = "distribution", .value = (void *) &lmt_version_state.distribution, .type = 'c' },
{ .name = "format_id", .value = (void *) &lmt_version_state.formatid, .type = 'g' },
/* */
- { .name = "version", .value = (void *) &lmt_version_state.luatexversion, .type = 'd' },
+ { .name = "version", .value = (void *) &lmt_version_state.luametatexversion, .type = 'd' },
/* */
- { .name = "luatex_engine", .value = (void *) &lmt_engine_state.engine_name, .type = 'c' },
- { .name = "luatex_version", .value = (void *) &lmt_version_state.version, .type = 'g' },
- { .name = "luatex_revision", .value = (void *) &lmt_version_state.revision, .type = 'g' },
- { .name = "luatex_release", .value = (void *) &lmt_version_state.release, .type = 'g' },
- { .name = "luatex_verbose", .value = (void *) &lmt_version_state.verbose, .type = 'c' },
+ { .name = "luametatex_engine", .value = (void *) &lmt_engine_state.engine_name, .type = 'c' },
+ { .name = "luametatex_version", .value = (void *) &lmt_version_state.version, .type = 'g' },
+ { .name = "luametatex_revision", .value = (void *) &lmt_version_state.revision, .type = 'g' },
+ { .name = "luametatex_release", .value = (void *) &lmt_version_state.release, .type = 'g' },
+ { .name = "luametatex_verbose", .value = (void *) &lmt_version_state.verbose, .type = 'c' },
/* */
{ .name = "used_compiler", .value = (void *) &lmt_version_state.compiler, .type = 'c' },
{ .name = "used_cversion", .value = (void *) &lmt_version_state.cversion, .type = 'g' },
@@ -634,6 +637,68 @@ static int statslib_resetmessages(lua_State *L)
return 0;
}
+/*
+
+ We formalize this here instead of delegating this to a lua helper:
+
+ function toversion(major,minor,release)
+ return (major or 1) * 100000000
+ + (minor or 0) * 10000
+ + (release or 0)
+ end
+
+ function fromversion(version)
+ return
+ version // 100000000 -- major
+ , (version % 100000000) // 10000 -- minor
+ , (version % 1000) -- release
+ end
+
+ currentversion = toversion(
+ status.majorversion,
+ status.minorversion,
+ status.release
+ )
+
+*/
+
+static int statslib_toversion(lua_State *L)
+{
+ int major = lmt_optunsigned(L, 1, 1);
+ int minor = lmt_optunsigned(L, 2, 0);
+ int release = lmt_optunsigned(L, 3, 0);
+ if (major > 1000) { major = 1000; }
+ if (minor > 1000) { minor = 1000; }
+ if (release > 1000) { release = 1000; }
+ lua_pushinteger(L, major * 100000000 + minor * 10000 + release);
+ return 1;
+}
+
+static int statslib_fromversion(lua_State *L)
+{
+ int version = lmt_optunsigned(L, 1, 0);
+ int major = version / 100000000;
+ int minor = (version % 100000000) / 10000;
+ int release = (version % 1000);
+ if (major > 1000) { major = 1000; }
+ if (minor > 1000) { minor = 1000; }
+ if (release > 1000) { release = 1000; }
+ lua_pushinteger(L, major);
+ lua_pushinteger(L, minor);
+ lua_pushinteger(L, release);
+ return 3;
+}
+
+static int statslib_currentversion(lua_State *L)
+{
+ lua_pushinteger(L,
+ lmt_version_state.luaversionmajor * 100000000
+ + lmt_version_state.luaversionminor * 10000
+ + lmt_version_state.luaversionrelease
+ );
+ return 1;
+}
+
static const struct luaL_Reg statslib_function_list[] = {
{ "list", statslib_statslist }, /* for old times sake */
{ "getconstants", statslib_getconstants },
@@ -674,12 +739,22 @@ static const struct luaL_Reg statslib_function_list[] = {
{ "getdumpstate", statslib_dumpstate },
+ { "toversion", statslib_toversion },
+ { "fromversion", statslib_fromversion },
+ { "currentversion", statslib_currentversion },
+
{ NULL, NULL },
};
static const struct luaL_Reg statslib_function_list_only[] = {
- { "list", statslib_statslist_only },
- { NULL, NULL },
+
+ { "list", statslib_statslist_only },
+
+ { "toversion", statslib_toversion },
+ { "fromversion", statslib_fromversion },
+ { "currentversion", statslib_currentversion },
+
+ { NULL, NULL },
};
int luaopen_status(lua_State *L)
diff --git a/source/luametatex/source/lua/lmttexiolib.c b/source/luametatex/source/lua/lmttexiolib.c
index df1932ff9..0eafcc5df 100644
--- a/source/luametatex/source/lua/lmttexiolib.c
+++ b/source/luametatex/source/lua/lmttexiolib.c
@@ -22,7 +22,7 @@
static const void *G_FILEHANDLE_METATABLE_PTR = NULL;
- FILE *lmt_valid_file(lua_State *L)
+ inline FILE *lmt_valid_file(lua_State *L)
{
luaL_Stream *p = (luaL_Stream *) lua_touserdata(L, 1);
if (p && lua_getmetatable(L, 1)) {
@@ -37,7 +37,7 @@
# else
- FILE *lmt_valid_file(lua_State *L)
+ inline FILE *lmt_valid_file(lua_State *L)
{
luaL_Stream *p = (luaL_Stream *) lua_touserdata(L, 1);
if (p && lua_getmetatable(L, 1)) {
@@ -332,7 +332,7 @@ static int texiolib_setlogfile(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- /* If not writeable then all goes into the void. */
+ /* If not writable then all goes into the void. */
if (! lmt_print_state.logfile) {
lmt_print_state.saved_logfile = lmt_print_state.logfile;
lmt_print_state.saved_logfile_offset = lmt_print_state.logfile_offset;
diff --git a/source/luametatex/source/lua/lmttexlib.c b/source/luametatex/source/lua/lmttexlib.c
index 5e8be2864..6d6d0c73b 100644
--- a/source/luametatex/source/lua/lmttexlib.c
+++ b/source/luametatex/source/lua/lmttexlib.c
@@ -603,7 +603,7 @@ static int texlib_sprint(lua_State *L)
static int texlib_mprint(lua_State *L)
{
int ini = 1;
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
tex_local_control_message("entering local control via (run) macro");
}
texlib_aux_store_token(token_val(end_local_cmd, 0), partial_line_mode, default_catcode_table_preset);
@@ -625,7 +625,7 @@ static int texlib_mprint(lua_State *L)
if (lua_gettop(L) >= ini) {
texlib_aux_cprint(L, partial_line_mode, default_catcode_table_preset, ini);
}
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
tex_local_control_message("entering local control via mprint");
}
tex_local_control(1);
@@ -638,7 +638,7 @@ static int texlib_mprint(lua_State *L)
static int texlib_pushlocal(lua_State *L)
{
(void) L;
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
tex_local_control_message("pushing local control");
}
texlib_aux_store_token(token_val(end_local_cmd, 0), partial_line_mode, default_catcode_table_preset);
@@ -651,7 +651,7 @@ static int texlib_pushlocal(lua_State *L)
static int texlib_poplocal(lua_State *L)
{
(void) L;
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
tex_local_control_message("entering local control via pop");
}
tex_local_control(1);
@@ -1545,7 +1545,7 @@ static int texlib_setdimen(lua_State *L)
int slot = lmt_check_for_flags(L, 1, &flags, 1, 0);
int state = texlib_aux_check_for_index(L, slot++, "dimen", &index, internal_dimension_cmd, register_dimension_cmd, internal_dimension_base, register_dimension_base, max_dimension_register_index, dimension_cmd);
if (state >= 0) {
- halfword value = 0;
+ scaled value = 0;
switch (lua_type(L, slot)) {
case LUA_TNUMBER:
value = lmt_toroundnumber(L, slot++);
@@ -2742,7 +2742,7 @@ static int texlib_getdelcodes(lua_State* L)
return 4;
}
-static halfword texlib_aux_getdimension(lua_State* L, int index)
+static scaled texlib_aux_getdimension(lua_State* L, int index)
{
switch (lua_type(L, index)) {
case LUA_TNUMBER:
@@ -2778,8 +2778,8 @@ static halfword texlib_toparshape(lua_State *L, int i)
}
lua_pop(L, 1);
for (int j = 1; j <= n; j++) {
- halfword indent = 0;
- halfword width = 0;
+ scaled indent = 0;
+ scaled width = 0;
if (lua_rawgeti(L, i, j) == LUA_TTABLE) {
if (lua_rawgeti(L, -1, 1) == LUA_TNUMBER) {
indent = lmt_toroundnumber(L, -1);
@@ -2990,7 +2990,7 @@ static int texlib_set_item(lua_State* L, int index, int prefixes)
case internal_dimension_cmd:
case register_dimension_cmd:
{
- halfword n = texlib_aux_getdimension(L, slot);
+ scaled n = texlib_aux_getdimension(L, slot);
if (cmd == register_dimension_cmd) {
tex_word_define(flags, eq_value(cs), n);
} else {
@@ -3087,6 +3087,7 @@ static int texlib_set_item(lua_State* L, int index, int prefixes)
default:
return 0;
}
+ break;
case auxiliary_cmd:
/*tex This could be |set_aux_value| instead. */
switch (eq_value(cs)) {
@@ -5073,7 +5074,7 @@ static int texlib_runlocal(lua_State *L)
if (lmt_token_state.luacstrings > 0) {
tex_lua_string_start();
}
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
tex_local_control_message("entering token scanner via function");
}
tex_local_control(obeymode);
@@ -5156,7 +5157,7 @@ static int texlib_runlocal(lua_State *L)
if (lmt_token_state.luacstrings > 0) {
tex_lua_string_start();
}
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
if (ismacro) {
tex_local_control_message("entering token scanner via macro");
} else {
@@ -5187,7 +5188,7 @@ static int texlib_runlocal(lua_State *L)
static int texlib_quitlocal(lua_State *L)
{
(void) L;
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
tex_local_control_message("quitting token scanner");
}
tex_end_local_control();
@@ -5206,7 +5207,7 @@ static int texlib_expandasvalue(lua_State *L) /* mostly like the mp one */
case lua_value_none_code:
case lua_value_dimension_code:
{
- halfword value = 0;
+ scaled value = 0;
halfword space = tex_get_available_token(space_token);
halfword relax = tex_get_available_token(deep_frozen_relax_token);
token_link(tail) = space;
@@ -5318,7 +5319,7 @@ static int texlib_runstring(lua_State *L)
if (lmt_token_state.luacstrings > 0) {
tex_lua_string_start();
}
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
tex_local_control_message("entering token scanner via register");
}
tex_local_control(obeymode);
@@ -6926,6 +6927,14 @@ static int texlib_getglyphdiscvalues(lua_State *L)
return 1;
}
+static int texlib_getvariablefamilyvalues(lua_State *L)
+{
+ lua_createtable(L, 0, 2);
+ lua_set_string_by_index(L, math_variable_mode_keep, "keep");
+ lua_set_string_by_index(L, math_variable_mode_unset, "unset");
+ return 1;
+}
+
static int texlib_getmathcontrolvalues(lua_State *L)
{
lua_createtable(L, 2, 24);
@@ -7406,7 +7415,7 @@ static const double texlib_sp_epsilon = 0.5;
static inline bool texlib_aux_equal(double a, double b, double eps)
{
- return fabs(a - b) <= texlib_sp_epsilon;
+ return fabs(a - b) <= eps;
}
static int texlib_equal(lua_State *L)
@@ -7439,314 +7448,315 @@ static int texlib_lessequal(lua_State *L)
/* till here */
static const struct luaL_Reg texlib_function_list[] = {
- { "write", texlib_write },
- { "print", texlib_print },
- { "sprint", texlib_sprint },
- { "mprint", texlib_mprint },
- { "tprint", texlib_tprint },
- { "cprint", texlib_cprint },
- { "isprintable", texlib_isprintable },
- { "pushlocal", texlib_pushlocal },
- { "poplocal", texlib_poplocal },
- { "runlocal", texlib_runlocal },
- { "runstring", texlib_runstring },
- { "quitlocal", texlib_quitlocal },
- { "expandasvalue", texlib_expandasvalue }, /* experiment */
- { "error", texlib_error },
- { "set", texlib_set },
- { "get", texlib_get },
- { "getregisterindex", texlib_getregisterindex },
- { "isdimen", texlib_isdimen },
- { "setdimen", texlib_setdimen },
- { "getdimen", texlib_getdimen },
- { "isfloat", texlib_isfloat },
- { "setfloat", texlib_setfloat },
- { "getfloat", texlib_getfloat },
- { "isskip", texlib_isskip },
- { "setskip", texlib_setskip },
- { "getskip", texlib_getskip },
- { "isglue", texlib_isglue },
- { "setglue", texlib_setglue },
- { "getglue", texlib_getglue },
- { "ismuskip", texlib_ismuskip },
- { "setmuskip", texlib_setmuskip },
- { "getmuskip", texlib_getmuskip },
- { "ismuglue", texlib_ismuglue },
- { "setmuglue", texlib_setmuglue },
- { "getmuglue", texlib_getmuglue },
- { "trackedattribute", texlib_trackedattribute },
- { "attributetracking", texlib_attributetracking },
- { "isattribute", texlib_isattribute },
- { "setattribute", texlib_setattribute },
- { "getattribute", texlib_getattribute },
- { "iscount", texlib_iscount },
- { "setcount", texlib_setcount },
- { "getcount", texlib_getcount },
- { "istoks", texlib_istoks },
- { "settoks", texlib_settoks },
- { "scantoks", texlib_scantoks },
- { "gettoks", texlib_gettoks },
- { "getmark", texlib_getmark },
- { "getmarknames", texlib_getmarknames },
- { "isbox", texlib_isbox },
- { "setbox", texlib_setbox },
- { "getbox", texlib_getbox },
- { "splitbox", texlib_splitbox },
- { "setlist", texlib_setlist },
- { "getlist", texlib_getlist },
- { "getlistfields", texlib_getlistfields },
- /* { "getspeciallistnames", texlib_getspeciallistnames }, */
- { "setnest", texlib_setnest }, /* only a message */
- { "getnest", texlib_getnest },
- { "getnestlevel", texlib_getnestlevel },
- { "getnestfields", texlib_getnestfields },
- { "setcatcode", texlib_setcatcode },
- { "getcatcode", texlib_getcatcode },
- { "setcccode", texlib_setcccode },
- { "getcccode", texlib_getcccode },
- { "setdelcode", texlib_setdelcode },
- { "getdelcode", texlib_getdelcode },
- { "getdelcodes", texlib_getdelcodes },
- { "sethccode", texlib_sethccode },
- { "gethccode", texlib_gethccode },
- { "sethmcode", texlib_sethmcode },
- { "gethmcode", texlib_gethmcode },
- { "setamcode", texlib_setamcode },
- { "getamcode", texlib_getamcode },
- { "setlccode", texlib_setlccode },
- { "getlccode", texlib_getlccode },
- { "setmathcode", texlib_setmathcode },
- { "getmathcode", texlib_getmathcode },
- { "getmathcodes", texlib_getmathcodes },
- { "setsfcode", texlib_setsfcode },
- { "getsfcode", texlib_getsfcode },
- { "setspcode", texlib_setspcode },
- { "getspcode", texlib_getspcode },
- { "setuccode", texlib_setuccode },
- { "getuccode", texlib_getuccode },
- { "fontname", texlib_getfontname },
- { "fontidentifier", texlib_getfontidentifier },
- { "getfontoffamily", texlib_getfontoffamily },
- { "getfontdimension", texlib_getfontdimension },
- { "number", texlib_getnumber },
- // { "dimension", texlib_getdimension },
- { "romannumeral", texlib_getromannumeral },
- { "definefont", texlib_definefont },
- { "hashtokens", texlib_hashtokens },
- { "primitives", texlib_primitives },
- { "extraprimitives", texlib_extraprimitives },
- { "enableprimitives", texlib_enableprimitives },
- { "shipout", texlib_shipout },
- { "badness", texlib_badness },
- { "setmath", texlib_setmath },
- { "getmath", texlib_getmath },
- { "linebreak", texlib_linebreak },
- { "getlinebreakparameterfields", texlib_getlinebreakparameterfields },
- { "getlinebreakresultfields", texlib_getlinebreakresultfields },
- { "preparelinebreak", texlib_preparelinebreak },
- { "getbalanceparameterfields", texlib_getbalanceparameterfields },
- { "getbalanceresultfields", texlib_getbalanceresultfields },
- { "balance", texlib_balance },
- { "resetparagraph", texlib_resetparagraph },
- { "showcontext", texlib_showcontext },
- { "triggerbuildpage", texlib_triggerbuildpage },
- // { "checkdelayedglue", texlib_checkdelayedglue },
- { "gethelptext", texlib_gethelptext },
- { "getpagestate", texlib_getpagestate },
- { "getpagestatevalues", texlib_getpagestatevalues },
- { "getlocallevel", texlib_getlocallevel },
- { "setinputstatemode", texlib_setinputstatemode },
- { "getinputstatemode", texlib_getinputstatemode },
- { "setinputstatefile", texlib_setinputstatefile },
- { "getinputstatefile", texlib_getinputstatefile },
- { "forceinputstatefile", texlib_forceinputstatefile },
- { "forceinputstateline", texlib_forceinputstateline },
- { "setinputstateline", texlib_setinputstateline },
- { "getinputstateline", texlib_getinputstateline },
- { "forcehmode", texlib_forcehmode },
- { "gettextdir", texlib_gettextdir },
- { "settextdir", texlib_settextdir },
- { "getlinedir", texlib_gettextdir }, /* we're nice */
- { "setlinedir", texlib_setlinedir },
- { "getmathdir", texlib_getmathdir },
- { "setmathdir", texlib_setmathdir },
- { "getpardir", texlib_getpardir },
- { "setpardir", texlib_setpardir },
- { "getboxdir", texlib_getboxdir },
- { "setboxdir", texlib_setboxdir },
- { "getinteraction", texlib_getinteraction },
- { "setinteraction", texlib_setinteraction },
- { "getglyphdata", texlib_getglyphdata },
- { "setglyphdata", texlib_setglyphdata },
- { "getglyphstate", texlib_getglyphstate },
- { "setglyphstate", texlib_setglyphstate },
- { "getglyphscript", texlib_getglyphscript },
- { "setglyphscript", texlib_setglyphscript },
- { "getglyphscales", texlib_getglyphscales },
- { "fatalerror", texlib_fatalerror },
- { "lastnodetype", texlib_lastnodetype },
- { "chardef", texlib_chardef },
- { "mathchardef", texlib_mathchardef },
- { "integerdef", texlib_setintegervalue },
- { "setintegervalue", texlib_setintegervalue },
- { "getintegervalue", texlib_getintegervalue },
- { "positdef", texlib_setfloatvalue },
- { "setpositvalue", texlib_setfloatvalue },
- { "getpositvalue", texlib_getfloatvalue },
- { "setcardinalvalue", texlib_setcardinalvalue },
- { "getcardinalvalue", texlib_getintegervalue },
- { "dimensiondef", texlib_setdimensionvalue },
- { "setdimensionvalue", texlib_setdimensionvalue },
- { "getdimensionvalue", texlib_getdimensionvalue },
- { "getspecification", texlib_getspecification },
- { "getmode", texlib_getmode },
- { "getmodevalues", texlib_getmodevalues },
- { "getrunstatevalues", texlib_getrunstatevalues },
- { "setrunstate", texlib_setrunstate },
- { "getrunstate", texlib_getrunstate },
- { "setoverloadstate", texlib_setoverloadstate },
- { "getoverloadstate", texlib_getoverloadstate },
- { "gethyphenationvalues", texlib_gethyphenationvalues },
- { "getglyphoptionvalues", texlib_getglyphoptionvalues },
- { "getinsertoptionvalues", texlib_getinsertoptionvalues },
- { "getinsertcategoryvalues", texlib_getinsertcategoryvalues },
- { "getinsertsplitvalues", texlib_getinsertsplitvalues },
- { "getglueoptionvalues", texlib_getglueoptionvalues },
- { "getkernoptionvalues", texlib_getkernoptionvalues },
- { "getmathoptionvalues", texlib_getmathoptionvalues },
- { "getsnappingvalues", texlib_getsnappingvalues },
- { "getpenaltyoptionvalues", texlib_getpenaltyoptionvalues },
- { "getuleaderlocationvalues", texlib_getuleaderlocationvalues },
- { "getnoadoptionvalues", texlib_getnoadoptionvalues },
- { "getbalancestepoptionvalues", texlib_getbalancestepoptionvalues },
- { "getparagraphoptionvalues", texlib_getparagraphoptionvalues },
- { "getparagraphfillmodevalues", texlib_getparagraphfillmodevalues },
- { "getdiscoptionvalues", texlib_getdiscoptionvalues },
- { "getruleoptionvalues", texlib_getruleoptionvalues },
- { "getboxoptionvalues", texlib_getboxoptionvalues },
- { "getboxcontinuationvalues", texlib_getboxcontinuationvalues },
- { "getmathsurroundvalues", texlib_getmathsurroundvalues },
- { "getlistanchorvalues", texlib_getlistanchorvalues },
- { "getlistsignvalues", texlib_getlistsignvalues },
- { "getlistgeometryvalues", texlib_getlistgeometryvalues },
- { "getmathgluevalues", texlib_getmathgluevalues },
- { "getglyphprotectionvalues", texlib_getglyphprotectionvalues },
- { "getdiscpartvalues", texlib_getdiscpartvalues },
- { "getglyphdiscvalues", texlib_getglyphdiscvalues },
- { "getspecificationoptionvalues", texlib_getspecificationoptionvalues },
- { "getmathparametervalues", texlib_getmathparametervalues },
- { "getmathstylenamevalues", texlib_getmathstylenamevalues },
- { "getmathstylevalues", texlib_getmathstylevalues },
- { "getmathvariantvalues", texlib_getmathvariantvalues },
- { "getmathvariantpresets", texlib_getmathvariantpresets },
- { "getmathcontrolvalues", texlib_getmathcontrolvalues },
- { "gettextcontrolvalues", texlib_gettextcontrolvalues },
- { "getpardataspecifications", texlib_getpardataspecifications },
- { "getprepoststatevalues", texlib_getprepoststatevalues },
- { "getadjustoptionvalues", texlib_getadjustoptionvalues },
- { "getnospacesmodevalues", texlib_getnospacesmodevalues },
- { "getspaceskipvalues", texlib_getspaceskipvalues },
- { "getspacefactorvalues", texlib_getspacefactorvalues },
- { "getemptyparagraphmodevalues", texlib_getemptyparagraphmodevalues },
- { "getpacktypevalues", texlib_getpacktypevalues },
- { "getgroupvalues", texlib_getgroupvalues },
- { "getparcontextvalues", texlib_getparcontextvalues },
- { "getpagecontextvalues", texlib_getpagecontextvalues },
- /* { "getappendlinecontextvalues", texlib_getappendlinecontextvalues }, */
- { "getappendadjustcontextvalues", texlib_getappendadjustcontextvalues },
- { "getappendmigratecontextvalues", texlib_getappendmigratecontextvalues },
- { "getalignmentcontextvalues", texlib_getalignmentcontextvalues },
- { "getbreakcontextvalues", texlib_getbreakcontextvalues },
- { "getbuildcontextvalues", texlib_getbuildcontextvalues },
- { "getvsplitcontextvalues", texlib_getvsplitcontextvalues },
- { "getpartriggervalues", texlib_getpartriggervalues },
- { "getparmodevalues", texlib_getparmodevalues },
- { "getautomigrationvalues", texlib_getautomigrationvalues },
- { "getflagvalues", texlib_getflagvalues },
- { "getprotrusionboundaryvalues", texlib_getprotrusionboundaryvalues },
- { "getlinebreakstatevalues", texlib_getlinebreakstatevalues },
- { "getmathclassoptionvalues", texlib_getmathclassoptionvalues },
- { "getnormalizelinevalues", texlib_getnormalizelinevalues },
- { "getnormalizeparvalues", texlib_getnormalizeparvalues },
- { "getdirectionvalues", texlib_getdirectionvalues },
- { "getparametermodevalues", texlib_getparametermodevalues },
- { "getcharactercontrolvalues", texlib_getcharactercontrolvalues },
- { "getfillvalues", texlib_getfillvalues },
- { "getunitclassvalues", texlib_getunitclassvalues },
- { "geterrorvalues", texlib_geterrorvalues },
- { "geterrorrecoverymodevalues", texlib_geterrorrecoverymodevalues },
- { "getinteractionmodes", texlib_getinteractionmodes },
- { "getbadnessmodevalues", texlib_getbadnessmodevalues },
+ { "write", texlib_write },
+ { "print", texlib_print },
+ { "sprint", texlib_sprint },
+ { "mprint", texlib_mprint },
+ { "tprint", texlib_tprint },
+ { "cprint", texlib_cprint },
+ { "isprintable", texlib_isprintable },
+ { "pushlocal", texlib_pushlocal },
+ { "poplocal", texlib_poplocal },
+ { "runlocal", texlib_runlocal },
+ { "runstring", texlib_runstring },
+ { "quitlocal", texlib_quitlocal },
+ { "expandasvalue", texlib_expandasvalue }, /* experiment */
+ { "error", texlib_error },
+ { "set", texlib_set },
+ { "get", texlib_get },
+ { "getregisterindex", texlib_getregisterindex },
+ { "isdimen", texlib_isdimen },
+ { "setdimen", texlib_setdimen },
+ { "getdimen", texlib_getdimen },
+ { "isfloat", texlib_isfloat },
+ { "setfloat", texlib_setfloat },
+ { "getfloat", texlib_getfloat },
+ { "isskip", texlib_isskip },
+ { "setskip", texlib_setskip },
+ { "getskip", texlib_getskip },
+ { "isglue", texlib_isglue },
+ { "setglue", texlib_setglue },
+ { "getglue", texlib_getglue },
+ { "ismuskip", texlib_ismuskip },
+ { "setmuskip", texlib_setmuskip },
+ { "getmuskip", texlib_getmuskip },
+ { "ismuglue", texlib_ismuglue },
+ { "setmuglue", texlib_setmuglue },
+ { "getmuglue", texlib_getmuglue },
+ { "trackedattribute", texlib_trackedattribute },
+ { "attributetracking", texlib_attributetracking },
+ { "isattribute", texlib_isattribute },
+ { "setattribute", texlib_setattribute },
+ { "getattribute", texlib_getattribute },
+ { "iscount", texlib_iscount },
+ { "setcount", texlib_setcount },
+ { "getcount", texlib_getcount },
+ { "istoks", texlib_istoks },
+ { "settoks", texlib_settoks },
+ { "scantoks", texlib_scantoks },
+ { "gettoks", texlib_gettoks },
+ { "getmark", texlib_getmark },
+ { "getmarknames", texlib_getmarknames },
+ { "isbox", texlib_isbox },
+ { "setbox", texlib_setbox },
+ { "getbox", texlib_getbox },
+ { "splitbox", texlib_splitbox },
+ { "setlist", texlib_setlist },
+ { "getlist", texlib_getlist },
+ { "getlistfields", texlib_getlistfields },
+ /* { "getspeciallistnames", texlib_getspeciallistnames }, */
+ { "setnest", texlib_setnest }, /* only a message */
+ { "getnest", texlib_getnest },
+ { "getnestlevel", texlib_getnestlevel },
+ { "getnestfields", texlib_getnestfields },
+ { "setcatcode", texlib_setcatcode },
+ { "getcatcode", texlib_getcatcode },
+ { "setcccode", texlib_setcccode },
+ { "getcccode", texlib_getcccode },
+ { "setdelcode", texlib_setdelcode },
+ { "getdelcode", texlib_getdelcode },
+ { "getdelcodes", texlib_getdelcodes },
+ { "sethccode", texlib_sethccode },
+ { "gethccode", texlib_gethccode },
+ { "sethmcode", texlib_sethmcode },
+ { "gethmcode", texlib_gethmcode },
+ { "setamcode", texlib_setamcode },
+ { "getamcode", texlib_getamcode },
+ { "setlccode", texlib_setlccode },
+ { "getlccode", texlib_getlccode },
+ { "setmathcode", texlib_setmathcode },
+ { "getmathcode", texlib_getmathcode },
+ { "getmathcodes", texlib_getmathcodes },
+ { "setsfcode", texlib_setsfcode },
+ { "getsfcode", texlib_getsfcode },
+ { "setspcode", texlib_setspcode },
+ { "getspcode", texlib_getspcode },
+ { "setuccode", texlib_setuccode },
+ { "getuccode", texlib_getuccode },
+ { "fontname", texlib_getfontname },
+ { "fontidentifier", texlib_getfontidentifier },
+ { "getfontoffamily", texlib_getfontoffamily },
+ { "getfontdimension", texlib_getfontdimension },
+ { "number", texlib_getnumber },
+ // { "dimension", texlib_getdimension },
+ { "romannumeral", texlib_getromannumeral },
+ { "definefont", texlib_definefont },
+ { "hashtokens", texlib_hashtokens },
+ { "primitives", texlib_primitives },
+ { "extraprimitives", texlib_extraprimitives },
+ { "enableprimitives", texlib_enableprimitives },
+ { "shipout", texlib_shipout },
+ { "badness", texlib_badness },
+ { "setmath", texlib_setmath },
+ { "getmath", texlib_getmath },
+ { "linebreak", texlib_linebreak },
+ { "getlinebreakparameterfields", texlib_getlinebreakparameterfields },
+ { "getlinebreakresultfields", texlib_getlinebreakresultfields },
+ { "preparelinebreak", texlib_preparelinebreak },
+ { "getbalanceparameterfields", texlib_getbalanceparameterfields },
+ { "getbalanceresultfields", texlib_getbalanceresultfields },
+ { "balance", texlib_balance },
+ { "resetparagraph", texlib_resetparagraph },
+ { "showcontext", texlib_showcontext },
+ { "triggerbuildpage", texlib_triggerbuildpage },
+ // { "checkdelayedglue", texlib_checkdelayedglue },
+ { "gethelptext", texlib_gethelptext },
+ { "getpagestate", texlib_getpagestate },
+ { "getpagestatevalues", texlib_getpagestatevalues },
+ { "getlocallevel", texlib_getlocallevel },
+ { "setinputstatemode", texlib_setinputstatemode },
+ { "getinputstatemode", texlib_getinputstatemode },
+ { "setinputstatefile", texlib_setinputstatefile },
+ { "getinputstatefile", texlib_getinputstatefile },
+ { "forceinputstatefile", texlib_forceinputstatefile },
+ { "forceinputstateline", texlib_forceinputstateline },
+ { "setinputstateline", texlib_setinputstateline },
+ { "getinputstateline", texlib_getinputstateline },
+ { "forcehmode", texlib_forcehmode },
+ { "gettextdir", texlib_gettextdir },
+ { "settextdir", texlib_settextdir },
+ { "getlinedir", texlib_gettextdir }, /* we're nice */
+ { "setlinedir", texlib_setlinedir },
+ { "getmathdir", texlib_getmathdir },
+ { "setmathdir", texlib_setmathdir },
+ { "getpardir", texlib_getpardir },
+ { "setpardir", texlib_setpardir },
+ { "getboxdir", texlib_getboxdir },
+ { "setboxdir", texlib_setboxdir },
+ { "getinteraction", texlib_getinteraction },
+ { "setinteraction", texlib_setinteraction },
+ { "getglyphdata", texlib_getglyphdata },
+ { "setglyphdata", texlib_setglyphdata },
+ { "getglyphstate", texlib_getglyphstate },
+ { "setglyphstate", texlib_setglyphstate },
+ { "getglyphscript", texlib_getglyphscript },
+ { "setglyphscript", texlib_setglyphscript },
+ { "getglyphscales", texlib_getglyphscales },
+ { "fatalerror", texlib_fatalerror },
+ { "lastnodetype", texlib_lastnodetype },
+ { "chardef", texlib_chardef },
+ { "mathchardef", texlib_mathchardef },
+ { "integerdef", texlib_setintegervalue },
+ { "setintegervalue", texlib_setintegervalue },
+ { "getintegervalue", texlib_getintegervalue },
+ { "positdef", texlib_setfloatvalue },
+ { "setpositvalue", texlib_setfloatvalue },
+ { "getpositvalue", texlib_getfloatvalue },
+ { "setcardinalvalue", texlib_setcardinalvalue },
+ { "getcardinalvalue", texlib_getintegervalue },
+ { "dimensiondef", texlib_setdimensionvalue },
+ { "setdimensionvalue", texlib_setdimensionvalue },
+ { "getdimensionvalue", texlib_getdimensionvalue },
+ { "getspecification", texlib_getspecification },
+ { "getmode", texlib_getmode },
+ { "getmodevalues", texlib_getmodevalues },
+ { "getrunstatevalues", texlib_getrunstatevalues },
+ { "setrunstate", texlib_setrunstate },
+ { "getrunstate", texlib_getrunstate },
+ { "setoverloadstate", texlib_setoverloadstate },
+ { "getoverloadstate", texlib_getoverloadstate },
+ { "gethyphenationvalues", texlib_gethyphenationvalues },
+ { "getglyphoptionvalues", texlib_getglyphoptionvalues },
+ { "getinsertoptionvalues", texlib_getinsertoptionvalues },
+ { "getinsertcategoryvalues", texlib_getinsertcategoryvalues },
+ { "getinsertsplitvalues", texlib_getinsertsplitvalues },
+ { "getglueoptionvalues", texlib_getglueoptionvalues },
+ { "getkernoptionvalues", texlib_getkernoptionvalues },
+ { "getmathoptionvalues", texlib_getmathoptionvalues },
+ { "getsnappingvalues", texlib_getsnappingvalues },
+ { "getpenaltyoptionvalues", texlib_getpenaltyoptionvalues },
+ { "getuleaderlocationvalues", texlib_getuleaderlocationvalues },
+ { "getnoadoptionvalues", texlib_getnoadoptionvalues },
+ { "getbalancestepoptionvalues", texlib_getbalancestepoptionvalues },
+ { "getparagraphoptionvalues", texlib_getparagraphoptionvalues },
+ { "getparagraphfillmodevalues", texlib_getparagraphfillmodevalues },
+ { "getdiscoptionvalues", texlib_getdiscoptionvalues },
+ { "getruleoptionvalues", texlib_getruleoptionvalues },
+ { "getboxoptionvalues", texlib_getboxoptionvalues },
+ { "getboxcontinuationvalues", texlib_getboxcontinuationvalues },
+ { "getmathsurroundvalues", texlib_getmathsurroundvalues },
+ { "getlistanchorvalues", texlib_getlistanchorvalues },
+ { "getlistsignvalues", texlib_getlistsignvalues },
+ { "getlistgeometryvalues", texlib_getlistgeometryvalues },
+ { "getmathgluevalues", texlib_getmathgluevalues },
+ { "getglyphprotectionvalues", texlib_getglyphprotectionvalues },
+ { "getdiscpartvalues", texlib_getdiscpartvalues },
+ { "getglyphdiscvalues", texlib_getglyphdiscvalues },
+ { "getspecificationoptionvalues", texlib_getspecificationoptionvalues },
+ { "getmathparametervalues", texlib_getmathparametervalues },
+ { "getmathstylenamevalues", texlib_getmathstylenamevalues },
+ { "getmathstylevalues", texlib_getmathstylevalues },
+ { "getmathvariantvalues", texlib_getmathvariantvalues },
+ { "getmathvariantpresets", texlib_getmathvariantpresets },
+ { "getvariablefamilyvalues", texlib_getvariablefamilyvalues },
+ { "getmathcontrolvalues", texlib_getmathcontrolvalues },
+ { "gettextcontrolvalues", texlib_gettextcontrolvalues },
+ { "getpardataspecifications", texlib_getpardataspecifications },
+ { "getprepoststatevalues", texlib_getprepoststatevalues },
+ { "getadjustoptionvalues", texlib_getadjustoptionvalues },
+ { "getnospacesmodevalues", texlib_getnospacesmodevalues },
+ { "getspaceskipvalues", texlib_getspaceskipvalues },
+ { "getspacefactorvalues", texlib_getspacefactorvalues },
+ { "getemptyparagraphmodevalues", texlib_getemptyparagraphmodevalues },
+ { "getpacktypevalues", texlib_getpacktypevalues },
+ { "getgroupvalues", texlib_getgroupvalues },
+ { "getparcontextvalues", texlib_getparcontextvalues },
+ { "getpagecontextvalues", texlib_getpagecontextvalues },
+ /* { "getappendlinecontextvalues", texlib_getappendlinecontextvalues }, */
+ { "getappendadjustcontextvalues", texlib_getappendadjustcontextvalues },
+ { "getappendmigratecontextvalues", texlib_getappendmigratecontextvalues },
+ { "getalignmentcontextvalues", texlib_getalignmentcontextvalues },
+ { "getbreakcontextvalues", texlib_getbreakcontextvalues },
+ { "getbuildcontextvalues", texlib_getbuildcontextvalues },
+ { "getvsplitcontextvalues", texlib_getvsplitcontextvalues },
+ { "getpartriggervalues", texlib_getpartriggervalues },
+ { "getparmodevalues", texlib_getparmodevalues },
+ { "getautomigrationvalues", texlib_getautomigrationvalues },
+ { "getflagvalues", texlib_getflagvalues },
+ { "getprotrusionboundaryvalues", texlib_getprotrusionboundaryvalues },
+ { "getlinebreakstatevalues", texlib_getlinebreakstatevalues },
+ { "getmathclassoptionvalues", texlib_getmathclassoptionvalues },
+ { "getnormalizelinevalues", texlib_getnormalizelinevalues },
+ { "getnormalizeparvalues", texlib_getnormalizeparvalues },
+ { "getdirectionvalues", texlib_getdirectionvalues },
+ { "getparametermodevalues", texlib_getparametermodevalues },
+ { "getcharactercontrolvalues", texlib_getcharactercontrolvalues },
+ { "getfillvalues", texlib_getfillvalues },
+ { "getunitclassvalues", texlib_getunitclassvalues },
+ { "geterrorvalues", texlib_geterrorvalues },
+ { "geterrorrecoverymodevalues", texlib_geterrorrecoverymodevalues },
+ { "getinteractionmodes", texlib_getinteractionmodes },
+ { "getbadnessmodevalues", texlib_getbadnessmodevalues },
# if (delayed_glue_supported == 1)
- { "getdelayedgluelocationvalues", texlib_getdelayedgluelocationvalues },
- { "getdelayedgluetargetvalues", texlib_getdelayedgluetargetvalues },
+ { "getdelayedgluelocationvalues", texlib_getdelayedgluelocationvalues },
+ { "getdelayedgluetargetvalues", texlib_getdelayedgluetargetvalues },
# endif
- { "getiftypes", texlib_getiftypes },
- { "getiovalues", texlib_getiovalues },
- { "getprimitiveorigins", texlib_getprimitiveorigins },
- { "getprimitivelegacies", texlib_getprimitivelegacies },
- { "getmissingcharactervalues", texlib_getmissingcharactervalues },
- { "getfrozenparvalues", texlib_getfrozenparvalues },
- { "getshapingpenaltiesvalues", texlib_getshapingpenaltiesvalues },
- { "getautoparagraphvalues", texlib_getautoparagraphvalues },
- { "getcharactertagvalues", texlib_getcharactertagvalues },
- { "getkerneloptionvalues", texlib_getkerneloptionvalues },
- { "getdoublescriptoptionvalues", texlib_getdoublescriptoptionvalues },
- { "getspecialmathclassvalues", texlib_getspecialmathclassvalues },
- { "getmathscriptordervalues", texlib_getmathscriptordervalues },
- { "getmathscriptsmodevalues", texlib_getmathscriptsmodevalues },
- { "getlargestusedmark", texlib_getlargestusedmark },
- { "getusedmarks", texlib_getusedmarks },
- { "getoutputactive", texlib_getoutputactive },
- { "getmvloptionvalues", texlib_getmvloptionvalues },
- { "getbalancecallbackvalues", texlib_getbalancecallbackvalues },
+ { "getiftypes", texlib_getiftypes },
+ { "getiovalues", texlib_getiovalues },
+ { "getprimitiveorigins", texlib_getprimitiveorigins },
+ { "getprimitivelegacies", texlib_getprimitivelegacies },
+ { "getmissingcharactervalues", texlib_getmissingcharactervalues },
+ { "getfrozenparvalues", texlib_getfrozenparvalues },
+ { "getshapingpenaltiesvalues", texlib_getshapingpenaltiesvalues },
+ { "getautoparagraphvalues", texlib_getautoparagraphvalues },
+ { "getcharactertagvalues", texlib_getcharactertagvalues },
+ { "getkerneloptionvalues", texlib_getkerneloptionvalues },
+ { "getdoublescriptoptionvalues", texlib_getdoublescriptoptionvalues },
+ { "getspecialmathclassvalues", texlib_getspecialmathclassvalues },
+ { "getmathscriptordervalues", texlib_getmathscriptordervalues },
+ { "getmathscriptsmodevalues", texlib_getmathscriptsmodevalues },
+ { "getlargestusedmark", texlib_getlargestusedmark },
+ { "getusedmarks", texlib_getusedmarks },
+ { "getoutputactive", texlib_getoutputactive },
+ { "getmvloptionvalues", texlib_getmvloptionvalues },
+ { "getbalancecallbackvalues", texlib_getbalancecallbackvalues },
/* experiment (metafun update) */
- { "shiftparshape", texlib_shiftparshape },
- { "snapshotpar", texlib_snapshotpar },
- { "getparstate", texlib_getparstate },
- { "getparstatefields", texlib_getparstatefields },
+ { "shiftparshape", texlib_shiftparshape },
+ { "snapshotpar", texlib_snapshotpar },
+ { "getparstate", texlib_getparstate },
+ { "getparstatefields", texlib_getparstatefields },
/* */
- { "getmathstylevariant", texlib_getmathstylevariant },
+ { "getmathstylevariant", texlib_getmathstylevariant },
/* */
- { "getinsertdistance", texlib_getinsertdistance },
- { "getinsertmultiplier", texlib_getinsertmultiplier },
- { "getinsertlimit", texlib_getinsertlimit },
- { "getinsertmaxplaced", texlib_getinsertmaxplaced },
- { "getinsertheight", texlib_getinsertheight },
- { "getinsertdepth", texlib_getinsertdepth },
- { "getinsertwidth", texlib_getinsertwidth },
- { "getinsertcontent", texlib_getinsertcontent },
- { "setinsertdistance", texlib_setinsertdistance },
- { "setinsertmultiplier", texlib_setinsertmultiplier },
- { "setinsertlimit", texlib_setinsertlimit },
- { "setinsertmaxplaced", texlib_setinsertmaxplaced },
- { "setinsertcontent", texlib_setinsertcontent },
- { "getlocalbox", texlib_getlocalbox },
- { "setlocalbox", texlib_setlocalbox },
- { "getlocalboxlocations", texlib_getlocalboxlocations },
+ { "getinsertdistance", texlib_getinsertdistance },
+ { "getinsertmultiplier", texlib_getinsertmultiplier },
+ { "getinsertlimit", texlib_getinsertlimit },
+ { "getinsertmaxplaced", texlib_getinsertmaxplaced },
+ { "getinsertheight", texlib_getinsertheight },
+ { "getinsertdepth", texlib_getinsertdepth },
+ { "getinsertwidth", texlib_getinsertwidth },
+ { "getinsertcontent", texlib_getinsertcontent },
+ { "setinsertdistance", texlib_setinsertdistance },
+ { "setinsertmultiplier", texlib_setinsertmultiplier },
+ { "setinsertlimit", texlib_setinsertlimit },
+ { "setinsertmaxplaced", texlib_setinsertmaxplaced },
+ { "setinsertcontent", texlib_setinsertcontent },
+ { "getlocalbox", texlib_getlocalbox },
+ { "setlocalbox", texlib_setlocalbox },
+ { "getlocalboxlocations", texlib_getlocalboxlocations },
/* */
- { "getcurrentmvl", texlib_getcurrentmvl },
- { "setbalanceshape", texlib_setbalanceshape },
+ { "getcurrentmvl", texlib_getcurrentmvl },
+ { "setbalanceshape", texlib_setbalanceshape },
/* */
- { "pushsavelevel", texlib_pushsavelevel },
- { "popsavelevel", texlib_popsavelevel },
+ { "pushsavelevel", texlib_pushsavelevel },
+ { "popsavelevel", texlib_popsavelevel },
/* */
- { "round", texlib_round },
- { "scale", texlib_scale },
- { "sp", texlib_toscaled },
- { "toscaled", texlib_toscaled },
- { "tonumber", texlib_tonumber },
- { "equal", texlib_equal },
- { "less", texlib_less },
- { "lessequal", texlib_lessequal },
+ { "round", texlib_round },
+ { "scale", texlib_scale },
+ { "sp", texlib_toscaled },
+ { "toscaled", texlib_toscaled },
+ { "tonumber", texlib_tonumber },
+ { "equal", texlib_equal },
+ { "less", texlib_less },
+ { "lessequal", texlib_lessequal },
/* */
- // { "savepagestate", texlib_savepagestate },
- // { "restorepagestate", texlib_restorepagestate },
+ // { "savepagestate", texlib_savepagestate },
+ // { "restorepagestate", texlib_restorepagestate },
/* */
# if (tracingonly)
- { "tracingonlygetqetb", texlib_geteqtb },
+ { "tracingonlygetqetb", texlib_geteqtb },
# endif
- { NULL, NULL },
+ { NULL, NULL },
};
# define defineindexers(name) \
diff --git a/source/luametatex/source/lua/lmttokenlib.c b/source/luametatex/source/lua/lmttokenlib.c
index 5069cb04b..9ee304b14 100644
--- a/source/luametatex/source/lua/lmttokenlib.c
+++ b/source/luametatex/source/lua/lmttokenlib.c
@@ -551,7 +551,7 @@ halfword lmt_token_list_from_lua(lua_State *L, int slot)
default:
{
int kl;
- int k = (int) aux_str2uni_len((const unsigned char *) (s + i), &kl);
+ int k = (int) aux_str2uni_len((const unsigned char *) (s + i), j - i, &kl);
i = i + kl - 1;
tok = token_val(other_char_cmd, k);
break;
@@ -818,10 +818,10 @@ static void tokenlib_aux_to_token(lua_State *L, int i, int m, int *head, int *ta
size_t l = 0;
const char *s = lua_tolstring(L, i, &l);
const unsigned char *p = (const unsigned char *) s;
- size_t n = aux_utf8len(s, l);
- for (size_t j = 0; j < n; j++) {
+ const unsigned char *end = p + l;
+ while (p < end) {
int xl;
- halfword x = tex_get_available_token(tokenlib_aux_to_token_val(aux_str2uni_len(p, &xl)));
+ halfword x = tex_get_available_token(tokenlib_aux_to_token_val(aux_str2uni_len(p, (size_t) (end - p), &xl)));
if (*head) {
token_link(*tail) = x;
} else {
@@ -1384,7 +1384,7 @@ static int tokenlib_scandimension(lua_State *L)
int mu = lua_toboolean(L, 2);
int eq = lua_toboolean(L, 3);
halfword order = normal_glue_order;
- halfword val = tex_scan_dimension(mu, inf, 0, eq, &order, NULL);
+ scaled val = tex_scan_dimension(mu, inf, 0, eq, &order, NULL);
lua_pushinteger(L, val);
tokenlib_aux_unsave_tex_scanner(texstate);
if (inf) {
@@ -2518,6 +2518,7 @@ static int tokenlib_future_expand(lua_State *L)
tokenlib_aux_unsave_tex_scanner(texstate);
return 0;
}
+ FALLTHROUGH
default:
tex_back_input(t);
if (spa && lua_toboolean(L, 2)) {
diff --git a/source/luametatex/source/luacore/lua55/src/lcode.c b/source/luametatex/source/luacore/lua55/src/lcode.c
index 8b61d5de9..791ec02ee 100644
--- a/source/luametatex/source/luacore/lua55/src/lcode.c
+++ b/source/luametatex/source/luacore/lua55/src/lcode.c
@@ -1542,15 +1542,19 @@ static void codebinK (FuncState *fs, BinOpr opr,
/* Try to code a binary operator negating its second operand.
** For the metamethod, 2nd operand must keep its original value.
+** As a special case, avoid the optimization for (exp - 0), because
+** (-0.0 - 0) is -0.0, while (-0.0 + 0) is +0.0.
*/
static int finishbinexpneg (FuncState *fs, expdesc *e1, expdesc *e2,
- OpCode op, int line, TMS event) {
+ OpCode op, int line, TMS event) {
if (!isKint(e2))
return 0; /* not an integer constant */
else {
lua_Integer i2 = e2->u.ival;
if (!(fitsC(i2) && fitsC(-i2)))
return 0; /* not in the proper range */
+ if (event == TM_SUB && i2 == 0)
+ return 0; /* do not optimize (exp - 0) */
else { /* operating a small integer constant */
int v2 = cast_int(i2);
finishbinexpval(fs, e1, e2, op, int2sC(-v2), 0, line, OP_MMBINI, event);
diff --git a/source/luametatex/source/luacore/lua55/src/lcorolib.c b/source/luametatex/source/luacore/lua55/src/lcorolib.c
index eb30bf4da..976ac6386 100644
--- a/source/luametatex/source/luacore/lua55/src/lcorolib.c
+++ b/source/luametatex/source/luacore/lua55/src/lcorolib.c
@@ -78,7 +78,8 @@ static int luaB_auxwrap (lua_State *L) {
int stat = lua_status(co);
if (stat != LUA_OK && stat != LUA_YIELD) { /* error in the coroutine? */
stat = lua_closethread(co, L); /* close its tbc variables */
- lua_assert(stat != LUA_OK);
+ if (stat == LUA_OK)
+ return 0; /* nothing to return */
lua_xmove(co, L, 1); /* move error message to the caller */
}
if (stat != LUA_ERRMEM && /* not a memory error and ... */
diff --git a/source/luametatex/source/luacore/lua55/src/ldebug.c b/source/luametatex/source/luacore/lua55/src/ldebug.c
index 61c527498..58d8731e2 100644
--- a/source/luametatex/source/luacore/lua55/src/ldebug.c
+++ b/source/luametatex/source/luacore/lua55/src/ldebug.c
@@ -202,7 +202,7 @@ const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, StkId *pos) {
if (n < 0) /* access to vararg values? */
return findvararg(ci, n, pos);
else
- name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci));
+ name = luaF_getlocalname(ci_func(ci)->p, cast_uint(n), currentpc(ci));
}
if (name == NULL) { /* no 'standard' name? */
StkId limit = (ci == L->ci) ? L->top.p : ci->next->func.p;
@@ -226,7 +226,7 @@ LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {
if (!isLfunction(s2v(L->top.p - 1))) /* not a Lua function? */
name = NULL;
else /* consider live variables at function start (parameters) */
- name = luaF_getlocalname(clLvalue(s2v(L->top.p - 1))->p, n, 0);
+ name = luaF_getlocalname(clLvalue(s2v(L->top.p - 1))->p, cast_uint(n), 0);
}
else { /* active function; get information through 'ar' */
StkId pos = NULL; /* to avoid warnings */
@@ -505,7 +505,7 @@ static const char *kname (const Proto *p, int index, const char **name) {
static const char *basicgetobjname (const Proto *p, int *ppc, int reg,
const char **name) {
int pc = *ppc;
- *name = luaF_getlocalname(p, reg + 1, pc);
+ *name = luaF_getlocalname(p, cast_uint(reg + 1), pc);
if (*name) /* is a local? */
return strlocal;
/* else try symbolic execution */
diff --git a/source/luametatex/source/luacore/lua55/src/lfunc.c b/source/luametatex/source/luacore/lua55/src/lfunc.c
index b6fd9ceb5..84a5b1861 100644
--- a/source/luametatex/source/luacore/lua55/src/lfunc.c
+++ b/source/luametatex/source/luacore/lua55/src/lfunc.c
@@ -300,7 +300,7 @@ void luaF_freeproto (lua_State *L, Proto *f) {
** Look for n-th local variable at line 'line' in function 'func'.
** Returns NULL if not found.
*/
-const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {
+const char *luaF_getlocalname (const Proto *f, unsigned local_number, int pc) {
int i;
for (i = 0; i<f->sizelocvars && f->locvars[i].startpc <= pc; i++) {
if (pc < f->locvars[i].endpc) { /* is variable active? */
diff --git a/source/luametatex/source/luacore/lua55/src/lfunc.h b/source/luametatex/source/luacore/lua55/src/lfunc.h
index d6aad3a6d..e53a4974d 100644
--- a/source/luametatex/source/luacore/lua55/src/lfunc.h
+++ b/source/luametatex/source/luacore/lua55/src/lfunc.h
@@ -58,8 +58,8 @@ LUAI_FUNC StkId luaF_close (lua_State *L, StkId level, TStatus status, int yy);
LUAI_FUNC void luaF_unlinkupval (UpVal *uv);
LUAI_FUNC lu_mem luaF_protosize (Proto *p);
LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f);
-LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number,
- int pc);
+LUAI_FUNC const char *luaF_getlocalname (const Proto *func,
+ unsigned local_number, int pc);
#endif
diff --git a/source/luametatex/source/luacore/lua55/src/lstate.c b/source/luametatex/source/luacore/lua55/src/lstate.c
index ada0b8566..08179357e 100644
--- a/source/luametatex/source/luacore/lua55/src/lstate.c
+++ b/source/luametatex/source/luacore/lua55/src/lstate.c
@@ -319,18 +319,36 @@ TStatus luaE_resetthread (lua_State *L, TStatus status) {
status = luaD_closeprotected(L, 1, status);
if (status != LUA_OK) /* errors? */
luaD_seterrorobj(L, status, L->stack.p + 1);
- else
+ else /* keep in the stack only the fake function-entry for basic ci */
L->top.p = L->stack.p + 1;
luaD_reallocstack(L, cast_int(L->ci->top.p - L->stack.p), 0);
return status;
}
+/*
+** Auxiliary function to call luaE_resetthread in protected mode.
+** That function closes all tbc variables in protected mode, so the
+** only possible "error" is when a tbc variable closes the thread being
+** closed and therefore calls 'luaD_throwbaselevel'; in that case,
+** control goes directly back to the first call to lua_closethread (not
+** to the second), to properly return it.
+*/
+static void resetthread_aux (lua_State *L, void *ud) {
+ TStatus status = *cast(TStatus*, ud);
+ status = luaE_resetthread(L, status);
+ if (status != LUA_OK)
+ luaD_throw(L, status);
+}
+
+
LUA_API int lua_closethread (lua_State *L, lua_State *from) {
TStatus status;
lua_lock(L);
L->nCcalls = (from) ? getCcalls(from) : 0;
- status = luaE_resetthread(L, L->status);
+ status = luaD_rawrunprotected(L, resetthread_aux, &L->status);
+ /* stack has error message iff there was an error */
+ lua_assert(L->top.p == L->stack.p + (status == LUA_OK ? 1 : 2));
if (L == from) /* closing itself? */
luaD_throwbaselevel(L, status);
lua_unlock(L);
diff --git a/source/luametatex/source/luacore/lua55/src/lua.c b/source/luametatex/source/luacore/lua55/src/lua.c
index 858a04c07..f07bb95e9 100644
--- a/source/luametatex/source/luacore/lua55/src/lua.c
+++ b/source/luametatex/source/luacore/lua55/src/lua.c
@@ -465,7 +465,8 @@ static int handle_luainit (lua_State *L) {
#include <readline/readline.h>
#include <readline/history.h>
-#define lua_initreadline(L) ((void)L, rl_readline_name="lua")
+#define lua_initreadline(L) \
+ ((void)L, *cast(const char **, &rl_readline_name)="lua")
#define lua_readline(buff,prompt) ((void)buff, readline(prompt))
#define lua_saveline(line) add_history(line)
#define lua_freeline(line) free(line)
diff --git a/source/luametatex/source/luacore/lua55/src/lundump.c b/source/luametatex/source/luacore/lua55/src/lundump.c
index d5fdc64b0..7ab340cb5 100644
--- a/source/luametatex/source/luacore/lua55/src/lundump.c
+++ b/source/luametatex/source/luacore/lua55/src/lundump.c
@@ -96,11 +96,12 @@ static lu_byte loadByte (LoadState *S) {
static lua_Unsigned loadVarint (LoadState *S, lua_Unsigned limit) {
lua_Unsigned x = 0;
+ lua_Unsigned limit_high = limit >> 7;
+ int limit_low = limit & 0x7f;
int b;
- limit >>= 7;
do {
b = loadByte(S);
- if (x > limit)
+ if (x >= limit_high && (x > limit_high || (b & 0x7f) > limit_low))
error(S, "integer overflow");
x = (x << 7) | (b & 0x7f);
} while ((b & 0x80) != 0);
@@ -108,11 +109,6 @@ static lua_Unsigned loadVarint (LoadState *S, lua_Unsigned limit) {
}
-static size_t loadSize (LoadState *S) {
- return cast_sizet(loadVarint(S, MAX_SIZE));
-}
-
-
static int loadInt (LoadState *S) {
return cast_int(loadVarint(S, cast_sizet(INT_MAX)));
}
@@ -137,16 +133,17 @@ static lua_Integer loadInteger (LoadState *S) {
/*
-** Load a nullable string into slot 'sl' from prototype 'p'. The
-** assignment to the slot and the barrier must be performed before any
-** possible GC activity, to anchor the string. (Both 'loadVector' and
-** 'luaH_setint' can call the GC.)
+** Load a nullable string into slot 'sl' from prototype 'p'. 'size' is
+** either the string length + 1 or zero for a previously saved string.
+** The assignment to the slot and the barrier must be performed before
+** any possible GC activity, to anchor the string. (Both 'loadVector'
+** and 'luaH_setint' can call the GC.)
*/
static void loadString (LoadState *S, Proto *p, TString **sl) {
lua_State *L = S->L;
TString *ts;
TValue sv;
- size_t size = loadSize(S);
+ size_t size = cast_sizet(loadVarint(S, MAX_SIZE - sizeof(TString) + 1));
if (size == 0) { /* previously saved string? */
lua_Unsigned idx = loadVarint(S, LUA_MAXUNSIGNED); /* get its index */
TValue stv;
@@ -160,7 +157,7 @@ static void loadString (LoadState *S, Proto *p, TString **sl) {
luaC_objbarrier(L, p, ts);
return; /* do not save it again */
}
- else if ((size -= 1) <= LUAI_MAXSHORTLEN) { /* short string? */
+ else if (--size <= LUAI_MAXSHORTLEN) { /* short string? */
char buff[LUAI_MAXSHORTLEN + 1]; /* extra space for '\0' */
loadVector(S, buff, size + 1); /* load string into buffer */
*sl = ts = luaS_newlstr(L, buff, size); /* create string */
diff --git a/source/luametatex/source/luacore/lua55/src/lvm.c b/source/luametatex/source/luacore/lua55/src/lvm.c
index 46170534c..cd3a36653 100644
--- a/source/luametatex/source/luacore/lua55/src/lvm.c
+++ b/source/luametatex/source/luacore/lua55/src/lvm.c
@@ -190,10 +190,11 @@ static int forlimit (lua_State *L, lua_Integer init, const TValue *lim,
if (step < 0) return 1; /* initial value must be less than it */
*p = LUA_MAXINTEGER; /* truncate */
}
- else { /* it is less than min integer */
+ else if (luai_numgt(0, flim)) { /* if it is negative, it is too small */
if (step > 0) return 1; /* initial value must be greater than it */
*p = LUA_MININTEGER; /* truncate */
}
+ else return 1; /* limit is NaN (neither 0 nor positive nor negative) */
}
return (step > 0 ? init > *p : init < *p); /* not to run? */
}
@@ -251,8 +252,8 @@ static int forprep (lua_State *L, StkId ra) {
luaG_forerror(L, pinit, "initial value");
if (step == 0)
luaG_runerror(L, "'for' step is zero");
- if (luai_numlt(0, step) ? luai_numlt(limit, init)
- : luai_numlt(init, limit))
+ if (!(luai_numge(0, step) ? luai_numge(init, limit)
+ : luai_numge(limit, init)))
return 1; /* skip the loop */
else {
/* make sure all values are floats */
diff --git a/source/luametatex/source/luametatex.c b/source/luametatex/source/luametatex.c
index 934e48cc8..b7ed19b4f 100644
--- a/source/luametatex/source/luametatex.c
+++ b/source/luametatex/source/luametatex.c
@@ -8,9 +8,13 @@ version_state_info lmt_version_state = {
.majorversion = luametatex_majorversion,
.minorversion = luametatex_minorversion,
.version = luametatex_version,
- .revision = luametatex_revision,
.release = luametatex_release,
- .developmentid = luametatex_development_id,
+ .functionality = luametatex_functionality,
+# if defined(LMT_DISTRIBUTION_USED)
+ .distribution = LMT_DISTRIBUTION_USED,
+# else
+ .distribution = "regular",
+# endif
.verbose = luametatex_version_string,
.banner = "This is " luametatex_name_camelcase ", Version " luametatex_version_string,
# if defined(LMT_COMPILER_USED)
@@ -25,7 +29,7 @@ version_state_info lmt_version_state = {
.luaversionmajor = LUA_VERSION_MAJOR_N,
.luaversionminor = LUA_VERSION_MINOR_N,
.luaversionrelease = LUA_VERSION_RELEASE_N,
- .luatexversion = (double) luametatex_version_number,
+ .luametatexversion = (double) luametatex_version_number,
.luaversion = (double) LUA_VERSION_MAJOR_N + (double) LUA_VERSION_MINOR_N / 10,
.luaformat = LUAC_FORMAT,
};
diff --git a/source/luametatex/source/luametatex.h b/source/luametatex/source/luametatex.h
index ae589b081..0ca9951da 100644
--- a/source/luametatex/source/luametatex.h
+++ b/source/luametatex/source/luametatex.h
@@ -87,6 +87,7 @@
2.11.07 : just after texlive 2025 code freeze
2.11.08 : just before the ctx 2025 meeting
2.11.09 : just after texlive 2026 code freeze
+ 2.11.10 : around the ctx 2026 meeting
At some point the \CONTEXT\ group will be responsible for guaranteeing that the official version
is what comes with \CONTEXT\ and that long term support and stability is guaranteed and that no
@@ -100,6 +101,8 @@
*/
+# define lmt_float_math 0
+
# include "utilities/auxcompiler.h"
# include "tex/textypes.h"
@@ -113,16 +116,19 @@
*/
-/*tex Currently LUAC_FORMAT is set to 5 awaiting an official version bump. */
+/*tex
+ We also set LUAC_FORMAT because we use the latest Lua version so there can be changes in
+ bytecode and we check for that in order to prevent cache crashes.
+*/
# define luametatex_majorversion 2
# define luametatex_minorversion 11
# define luametatex_version 211
-# define luametatex_revision 0
# define luametatex_release 10
# define luametatex_version_string "2.11.10"
# define luametatex_version_number 211.10
-# define luametatex_development_id 20260918
+# define luametatex_functionality 20261029
+# define luametatex_distribution "regular" /* LMT_DISTRIBUTION_USED */
# define luametatex_name_camelcase "LuaMetaTeX"
# define luametatex_name_lowercase "luametatex"
# define luametatex_copyright_holder "Taco Hoekwater, Hans Hagen, Wolfgang Schuster & Mikael Sundqvist"
@@ -146,7 +152,8 @@ typedef struct version_state_info {
int version;
int revision;
int release;
- int developmentid;
+ int functionality;
+ const char *distribution;
const char *verbose;
const char *banner;
const char *compiler;
@@ -158,7 +165,7 @@ typedef struct version_state_info {
int luaversionminor;
int luaversionrelease;
int luaformat;
- double luatexversion;
+ double luametatexversion;
double luaversion;
} version_state_info;
@@ -187,11 +194,15 @@ extern version_state_info lmt_version_state;
# include <sys/stat.h>
# include <stdbool.h>
# include <limits.h>
+# include <fcntl.h>
# ifdef _WIN32
+ /* no old stuff: */
+ # define WIN32_LEAN_AND_MEAN
+ // # include <winsock2.h> /* has to be done before <windows.h> */
+ // # include <ws2tcpip.h>
# include <windows.h>
# include <winerror.h>
- # include <fcntl.h>
# include <io.h>
# else
# include <unistd.h>
@@ -310,6 +321,7 @@ extern version_state_info lmt_version_state;
# include "utilities/auxsparsearray.h"
# include "utilities/auxunistring.h"
# include "utilities/auxfile.h"
+# include "utilities/auxserialize.h"
# include "libraries/hnj/hnjhyphen.h"
diff --git a/source/luametatex/source/luaoptional/cmake/mujs/CMakeLists.txt b/source/luametatex/source/luaoptional/cmake/mujs/CMakeLists.txt
index 83b6b48ac..cfe2ee2bf 100644
--- a/source/luametatex/source/luaoptional/cmake/mujs/CMakeLists.txt
+++ b/source/luametatex/source/luaoptional/cmake/mujs/CMakeLists.txt
@@ -1,107 +1,107 @@
-# This file is made by Mojca and Hans and is subjected to changes
-# as we proceed with luametatex and the contextgarden compile farm.
-
-cmake_minimum_required(VERSION 3.7)
-
-# Lucky us: only normal C is used:
-
-project (mujs
- VERSION 1.0.6
- DESCRIPTION "MuJS embeddable Javascript interpreter"
- LANGUAGES C)
-
-# The jsrepr.c is not needed and depends on utf.c as well has some function
-# pointer cast issue (accessing unknown name field).
-
-set (mujs_sources
- jsarray.c
- jsboolean.c
- jsbuiltin.c
- jscompile.c
- jsdate.c
- jsdtoa.c
- jsdump.c
- jserror.c
- jsfunction.c
- jsgc.c
- jsintern.c
- jslex.c
- jsmath.c
- jsnumber.c
- jsobject.c
- json.c
- jsparse.c
- jsproperty.c
- jsregexp.c
-# jsrepr.c
- jsrun.c
- jsstate.c
- jsstring.c
- jsvalue.c
- regexp.c
- utf.c
- utftype.c
-)
-
-set (mujs_headers
- jsbuiltin.h
- jscompile.h
- jsi.h
- jslex.h
- jsparse.h
- jsrun.h
- jsvalue.h
- mujs.h
- regexp.h
- utf.h
-)
-
-# We need this in order for msvc to export the symbols (which is default on
-# gcc). Otherwise we need this dllexport stuff.
-
-set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
-
-# The previous one has to come before the next one!
-
-if (MSVC)
-
- add_library(mujs SHARED ${mujs_headers} ${mujs_sources} )
-
-else()
-
- # Is this hack still needed or does the above work ok.?
-
- add_library(mujs SHARED ${mujs_headers} one.c)
-
-endif()
-
-# As per make file.
-
-set_property(TARGET mujs PROPERTY C_STANDARD 99)
-
-# We want consistent and predictable names:
-
-set_target_properties(mujs PROPERTIES OUTPUT_NAME "libmujs")
-
-# Some options based on what's in upstream's make file.
-
-if (NOT MSVC)
-
- target_compile_options(mujs
- PRIVATE
- -pedantic
- -Wall
- -Wextra
- -Wno-unused-parameter
- )
-
- if (CMAKE_C_COMPILER_ID STREQUAL "Clang")
-
- target_compile_options(mujs
- PRIVATE
- -Wunreachable-code
- )
-
- endif()
-
-endif()
+# This file is made by Mojca and Hans and is subjected to changes
+# as we proceed with luametatex and the contextgarden compile farm.
+
+cmake_minimum_required(VERSION 3.7)
+
+# Lucky us: only normal C is used:
+
+project (mujs
+ VERSION 1.0.6
+ DESCRIPTION "MuJS embeddable Javascript interpreter"
+ LANGUAGES C)
+
+# The jsrepr.c is not needed and depends on utf.c as well has some function
+# pointer cast issue (accessing unknown name field).
+
+set (mujs_sources
+ jsarray.c
+ jsboolean.c
+ jsbuiltin.c
+ jscompile.c
+ jsdate.c
+ jsdtoa.c
+ jsdump.c
+ jserror.c
+ jsfunction.c
+ jsgc.c
+ jsintern.c
+ jslex.c
+ jsmath.c
+ jsnumber.c
+ jsobject.c
+ json.c
+ jsparse.c
+ jsproperty.c
+ jsregexp.c
+# jsrepr.c
+ jsrun.c
+ jsstate.c
+ jsstring.c
+ jsvalue.c
+ regexp.c
+ utf.c
+ utftype.c
+)
+
+set (mujs_headers
+ jsbuiltin.h
+ jscompile.h
+ jsi.h
+ jslex.h
+ jsparse.h
+ jsrun.h
+ jsvalue.h
+ mujs.h
+ regexp.h
+ utf.h
+)
+
+# We need this in order for msvc to export the symbols (which is default on
+# gcc). Otherwise we need this dllexport stuff.
+
+set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
+
+# The previous one has to come before the next one!
+
+if (MSVC)
+
+ add_library(mujs SHARED ${mujs_headers} ${mujs_sources} )
+
+else()
+
+ # Is this hack still needed or does the above work ok.?
+
+ add_library(mujs SHARED ${mujs_headers} one.c)
+
+endif()
+
+# As per make file.
+
+set_property(TARGET mujs PROPERTY C_STANDARD 99)
+
+# We want consistent and predictable names:
+
+set_target_properties(mujs PROPERTIES OUTPUT_NAME "libmujs")
+
+# Some options based on what's in upstream's make file.
+
+if (NOT MSVC)
+
+ target_compile_options(mujs
+ PRIVATE
+ -pedantic
+ -Wall
+ -Wextra
+ -Wno-unused-parameter
+ )
+
+ if (CMAKE_C_COMPILER_ID STREQUAL "Clang")
+
+ target_compile_options(mujs
+ PRIVATE
+ -Wunreachable-code
+ )
+
+ endif()
+
+endif()
diff --git a/source/luametatex/source/luaoptional/cmake/mujs/CMakeSettings.json b/source/luametatex/source/luaoptional/cmake/mujs/CMakeSettings.json
index fc67a089b..f2d91f909 100644
--- a/source/luametatex/source/luaoptional/cmake/mujs/CMakeSettings.json
+++ b/source/luametatex/source/luaoptional/cmake/mujs/CMakeSettings.json
@@ -1,4 +1,4 @@
-{
+{
"configurations": [
{
"name": "msvc-x64-release",
diff --git a/source/luametatex/source/luaoptional/lmtcurl.c b/source/luametatex/source/luaoptional/lmtcurl.c
index 39d448941..a8bafa7f3 100644
--- a/source/luametatex/source/luaoptional/lmtcurl.c
+++ b/source/luametatex/source/luaoptional/lmtcurl.c
@@ -15,13 +15,14 @@ typedef enum curl_option_type {
curl_string = 2,
curl_function = 3, /* ignored */
curl_offset = 4, /* ignored */
+ curl_slist = 5, /* httpheaders, quote, etc., array of char pointers */
} curl_option_type;
/*tex At the \LUA\ end we can have a mapping of useful ones, */
static const int curl_options[] = {
curl_ignore, /* 0 */
- curl_string, /* 1 file | writedata */
+ curl_string, /* 1 file | writedata | response */
curl_string, /* 2 url */
curl_integer, /* 3 port */
curl_string, /* 4 proxy */
@@ -43,12 +44,12 @@ static const int curl_options[] = {
curl_integer, /* 20 low_speed_time */
curl_integer, /* 21 resume_from */
curl_string, /* 22 cookie */
- curl_string, /* 23 httpheader | rtspheader */
+ curl_slist, /* 23 httpheader | rtspheader */
curl_string, /* 24 httppost */
curl_string, /* 25 sslcert */
curl_string, /* 26 keypasswd */
curl_integer, /* 27 crlf */
- curl_string, /* 28 quote */
+ curl_slist, /* 28 quote */
curl_string, /* 29 writeheader | headerdata */
curl_ignore, /* 30 */
curl_string, /* 31 cookiefile */
@@ -59,7 +60,7 @@ static const int curl_options[] = {
curl_string, /* 36 customrequest */
curl_string, /* 37 stderr */
curl_ignore, /* 38 */
- curl_string, /* 39 postquote */
+ curl_slist, /* 39 postquote */
curl_string, /* 40 writeinfo */
curl_integer, /* 41 verbose */
curl_integer, /* 42 header */
@@ -90,7 +91,7 @@ static const int curl_options[] = {
curl_ignore, /* 67 */
curl_integer, /* 68 maxredirs */
curl_integer, /* 69 filetime */
- curl_string, /* 70 telnetoptions */
+ curl_slist, /* 70 telnetoptions */
curl_integer, /* 71 maxconnects */
curl_integer, /* 72 closepolicy */
curl_ignore, /* 73 */
@@ -113,7 +114,7 @@ static const int curl_options[] = {
curl_integer, /* 90 sslengine_default */
curl_integer, /* 91 dns_use_global_cache */
curl_integer, /* 92 dns_cache_timeout */
- curl_string, /* 93 prequote */
+ curl_slist, /* 93 prequote */
curl_function, /* 94 debugfunction */
curl_string, /* 95 debugdata */
curl_integer, /* 96 cookiesession */
@@ -124,7 +125,7 @@ static const int curl_options[] = {
curl_integer, /* 101 proxytype */
curl_string, /* 102 accept_encoding */
curl_string, /* 103 private */
- curl_string, /* 104 http200aliases */
+ curl_slist, /* 104 http200aliases */
curl_integer, /* 105 unrestricted_auth */
curl_integer, /* 106 ftp_use_eprt */
curl_integer, /* 107 httpauth */
@@ -207,7 +208,7 @@ static const int curl_options[] = {
curl_function, /* 184 ssh_keyfunction */
curl_string, /* 185 ssh_keydata */
curl_string, /* 186 mail_from */
- curl_string, /* 187 mail_rcpt */
+ curl_slist, /* 187 mail_rcpt */
curl_integer, /* 188 ftp_use_pret */
curl_integer, /* 189 rtsp_request */
curl_string, /* 190 rtsp_session_id */
@@ -223,7 +224,7 @@ static const int curl_options[] = {
curl_function, /* 200 fnmatch_function */
curl_string, /* 201 chunk_data */
curl_string, /* 202 fnmatch_data */
- curl_string, /* 203 resolve */
+ curl_slist, /* 203 resolve */
curl_string, /* 204 tlsauth_username */
curl_string, /* 205 tlsauth_password */
curl_string, /* 206 tlsauth_type */
@@ -320,20 +321,31 @@ typedef struct curllib_state_info {
curl_error_code errcode
);
+ void* (*curl_slist_append) (
+ void *list,
+ const char *string
+ );
+
+ void (*curl_slist_free_all) (
+ void *list
+ );
+
} curllib_state_info;
static curllib_state_info curllib_state = {
- .initialized = 0,
- .padding = 0,
- .curl_version = NULL,
- .curl_free = NULL,
- .curl_easy_init = NULL,
- .curl_easy_cleanup = NULL,
- .curl_easy_perform = NULL,
- .curl_easy_setopt = NULL,
- .curl_easy_escape = NULL,
- .curl_easy_unescape = NULL,
- .curl_easy_strerror = NULL,
+ .initialized = 0,
+ .padding = 0,
+ .curl_version = NULL,
+ .curl_free = NULL,
+ .curl_easy_init = NULL,
+ .curl_easy_cleanup = NULL,
+ .curl_easy_perform = NULL,
+ .curl_easy_setopt = NULL,
+ .curl_easy_escape = NULL,
+ .curl_easy_unescape = NULL,
+ .curl_easy_strerror = NULL,
+ .curl_slist_append = NULL,
+ .curl_slist_free_all = NULL,
};
static int curllib_initialize(lua_State * L)
@@ -344,15 +356,17 @@ static int curllib_initialize(lua_State * L)
lmt_library lib = lmt_library_load(L, filename);
- curllib_state.curl_version = lmt_library_find(lib, "curl_version");
- curllib_state.curl_free = lmt_library_find(lib, "curl_free");
- curllib_state.curl_easy_init = lmt_library_find(lib, "curl_easy_init");
- curllib_state.curl_easy_cleanup = lmt_library_find(lib, "curl_easy_cleanup");
- curllib_state.curl_easy_perform = lmt_library_find(lib, "curl_easy_perform");
- curllib_state.curl_easy_setopt = lmt_library_find(lib, "curl_easy_setopt");
- curllib_state.curl_easy_escape = lmt_library_find(lib, "curl_easy_escape");
- curllib_state.curl_easy_unescape = lmt_library_find(lib, "curl_easy_unescape");
- curllib_state.curl_easy_strerror = lmt_library_find(lib, "curl_easy_strerror");
+ curllib_state.curl_version = lmt_library_find(lib, "curl_version");
+ curllib_state.curl_free = lmt_library_find(lib, "curl_free");
+ curllib_state.curl_easy_init = lmt_library_find(lib, "curl_easy_init");
+ curllib_state.curl_easy_cleanup = lmt_library_find(lib, "curl_easy_cleanup");
+ curllib_state.curl_easy_perform = lmt_library_find(lib, "curl_easy_perform");
+ curllib_state.curl_easy_setopt = lmt_library_find(lib, "curl_easy_setopt");
+ curllib_state.curl_easy_escape = lmt_library_find(lib, "curl_easy_escape");
+ curllib_state.curl_easy_unescape = lmt_library_find(lib, "curl_easy_unescape");
+ curllib_state.curl_easy_strerror = lmt_library_find(lib, "curl_easy_strerror");
+ curllib_state.curl_slist_append = lmt_library_find(lib, "curl_slist_append");
+ curllib_state.curl_slist_free_all = lmt_library_find(lib, "curl_slist_free_all");
curllib_state.initialized = lmt_library_okay(lib);
}
@@ -377,7 +391,9 @@ static int curllib_fetch(lua_State * L)
if (lua_type(L, 1) == LUA_TTABLE) {
curl_instance *curl = curllib_state.curl_easy_init();
if (curl) {
- int result = 0;
+ int result = 0;
+ void *slists[16];
+ int num_slists = 0;
/*tex
We process the table options before initializing luaL_Buffer because luaL_Buffer
uses the Lua stack, so running lua_next while a buffer is active corrupts stack
@@ -407,6 +423,29 @@ static int curllib_fetch(lua_State * L)
break;
}
break;
+ case curl_slist:
+ if (curllib_state.curl_slist_append) {
+ void *slist = NULL;
+ if (lua_type(L, -1) == LUA_TTABLE) {
+ size_t len = lua_rawlen(L, -1);
+ for (size_t i = 1; i <= len; i++) {
+ lua_rawgeti(L, -1, i);
+ if (lua_type(L, -1) == LUA_TSTRING) {
+ slist = curllib_state.curl_slist_append(slist, lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+ }
+ } else if (lua_type(L, -1) == LUA_TSTRING) {
+ slist = curllib_state.curl_slist_append(slist, lua_tostring(L, -1));
+ }
+ if (slist) {
+ curllib_state.curl_easy_setopt(curl, curl_object_base + o, slist);
+ if (num_slists < 16) {
+ slists[num_slists++] = slist;
+ }
+ }
+ }
+ break;
}
}
}
@@ -430,6 +469,11 @@ static int curllib_fetch(lua_State * L)
luaL_pushresult(&writedata);
result = 1;
}
+ if (curllib_state.curl_slist_free_all) {
+ for (int i = 0; i < num_slists; i++) {
+ curllib_state.curl_slist_free_all(slists[i]);
+ }
+ }
curllib_state.curl_easy_cleanup(curl);
return result;
}
@@ -452,7 +496,7 @@ static int curllib_escape(lua_State * L)
curllib_state.curl_free(s);
ret = 1;
}
- /* FIX 2: Always cleanup the curl instance, regardless of escape success */
+ /* Always cleanup the curl instance, regardless of escape success */
curllib_state.curl_easy_cleanup(curl);
return ret;
}
@@ -510,4 +554,4 @@ int luaopen_curl(lua_State * L)
{
lmt_library_register(L, "curl", curllib_function_list);
return 0;
-}
+} \ No newline at end of file
diff --git a/source/luametatex/source/luaoptional/readme.txt b/source/luametatex/source/luaoptional/readme.txt
index 579433d61..31b489da9 100644
--- a/source/luametatex/source/luaoptional/readme.txt
+++ b/source/luametatex/source/luaoptional/readme.txt
@@ -1,30 +1,30 @@
-Nota bene,
-
-This is the directory where optional module support ends up. Optional modules have an interface but
-are not (nor will be) part of the binary. We might ship some at the context garden (like zint and
-mujs) but the large one (read: with many dependencies or written in c++) have to come from the
-operating system because if you use a library that is what you want: the external black box thing.
-No sources end up in the distribution either, athough we will archive some.
-
-There will be no user modules here, just those interfaces that we provide and maintain as part of
-standard ConTeXt LMTX. What users add themselves is up to them, including (long time !) support. So,
-this is the canonnical version of optional.
-
-We might at some point add some safeguards so that we can be sure that ConTeXt is run with the
-right binary because we want to prevent side effects (of any kind) resulting from a binary being
-used with the same name and different features ... just because one of the objective is to have
-a long term stable binary / macro package combination. Of course, what users do on their machines
-is up to them.
-
-It might take a while before the interfaces and way we do this is stable. Also, keep in mind that
-regular users never deal with these matters directly and only use the interfaces at the TeX and
-Lua end.
-
-PS. The socket library (and maybe cerf) are also candidates for optional although cerf needs to be
-compiled for windows which is not supported out of the box and sockets are way to large. We only
-do optional libs that add little to the binary, a few KB at most! I'll definitely try to stick to
-this principle!
-
-PS. Todo: move function pointers into state structures.
-
-Hans
+Nota bene,
+
+This is the directory where optional module support ends up. Optional modules have an interface but
+are not (nor will be) part of the binary. We might ship some at the context garden (like zint and
+mujs) but the large one (read: with many dependencies or written in c++) have to come from the
+operating system because if you use a library that is what you want: the external black box thing.
+No sources end up in the distribution either, athough we will archive some.
+
+There will be no user modules here, just those interfaces that we provide and maintain as part of
+standard ConTeXt LMTX. What users add themselves is up to them, including (long time !) support. So,
+this is the canonnical version of optional.
+
+We might at some point add some safeguards so that we can be sure that ConTeXt is run with the
+right binary because we want to prevent side effects (of any kind) resulting from a binary being
+used with the same name and different features ... just because one of the objective is to have
+a long term stable binary / macro package combination. Of course, what users do on their machines
+is up to them.
+
+It might take a while before the interfaces and way we do this is stable. Also, keep in mind that
+regular users never deal with these matters directly and only use the interfaces at the TeX and
+Lua end.
+
+PS. The socket library (and maybe cerf) are also candidates for optional although cerf needs to be
+compiled for windows which is not supported out of the box and sockets are way to large. We only
+do optional libs that add little to the binary, a few KB at most! I'll definitely try to stick to
+this principle!
+
+PS. Todo: move function pointers into state structures.
+
+Hans
diff --git a/source/luametatex/source/luarest/lmtclientlib.c b/source/luametatex/source/luarest/lmtclientlib.c
new file mode 100644
index 000000000..f58fab1f2
--- /dev/null
+++ b/source/luametatex/source/luarest/lmtclientlib.c
@@ -0,0 +1,869 @@
+/*
+ See license.txt in the root of this project.
+*/
+
+# include <luametatex.h>
+
+/*tex
+
+ When you search a bit you find plenty templates for downloading something. When we started with
+ \LUIATEX\ we decided to add |luasocket| and in \LUAMETATEX\ we have the optional curl support
+ library. However, because it looks like we can just assume that curl is available on \LINUX\
+ and \OSX\ and that the generic \MSWINDOWS\ interface will be around as long as this operating
+ system is there. Although \CURL\ is nowadays installed on \MSWINDOWS\ we cannot assume the
+ library to be there.
+
+ So, after investigating this a bit I settled for two code paths, something we need to have
+ anyway due to the wide filenames. We already had helpers for that so we could save some code
+ here. The first implementation was rather simple, apart from all these flags \unknown\ not
+ something you like to waste time on figuring them out.
+
+ This module is still kind of simple because we only need to fetch and delegate all other logic
+ to the \LUA\ end where we already have all in place anyway. The curl code path is a variant of
+ what we already had in the optional |lmtcurl| file but limited to |http(s)| usage.
+
+ After we had all in place a bit of checking with gemini about a potential speedup by writing
+ directly to the lua buffer (no intermediate buffer in the windows code path and larger socket
+ buffers) as well as checking the content length and preallocating the buffer at the start
+ gave a better saturation of the (1GB) connection I tested with. Before that, the socket
+ library performed better, after that code below won.
+
+ By adding the |supported| method we can fallback to other methods (when available) but the
+ assumption is that on posix systems we have libcurl installed. This module might evolve a bit
+ depending on usage. Because we no longer need |ftp|, |mail| and other features we might at
+ some point drop |luasocket| or come up with a simpler server option.
+
+*/
+
+/* tex
+
+ We need to occasionally check if the methods used here are still valid. It looks like the
+ api's has been stable for quite a while so we're probably good, but flags can evolve. Checking
+ is typically something that tools can help with because there isn't something spectacular
+ going on here. Of course we might want to improve performance. The reason why we pass so many
+ arguments to |clientlib_aux_http_request| is that we want to use the \LUA\ buffer mechanism
+ efficiently.
+
+ I decided to add th eoption to limit the size but it can be configured. After checking
+ with gemini (flash) and codex (luna) a few safeguards were added, like wiping forwarded
+ headers and such and makign sure we only handle http(s). There is plenty on the web about all
+ this stuff but \unknown\ how to find it and these are common coding patterns.
+
+ Because this is just some auxiliary module and no core engine functionality we can improve
+ matters over time. It doesn't impact how \LUAMETATEX\ and \CONTEXT\ work, apart from maybe
+ installation and occasional inclusion of images from the web or a server.
+
+*/
+
+# define default_timeout_connect 60
+# define default_timeout_receive 0
+# define default_maxsize (512 * 1024 * 1024)
+
+typedef struct {
+ const char *url;
+ const char *method;
+ const char **headers;
+ size_t length;
+ const char *body;
+ long timeout;
+ size_t maxsize;
+ int tolerant;
+} http_request_data;
+
+static inline void clientlib_aux_preset(http_request_data *data)
+{
+ data->url = NULL;
+ data->method = "GET";
+ data->headers = NULL;
+ data->length = 0;
+ data->body = NULL;
+ data->timeout = default_timeout_receive;
+ data->maxsize = default_maxsize;
+ data->tolerant = 0;
+}
+
+static inline void clientlib_aux_reset(http_request_data *data)
+{
+ lmt_memory_free(data->headers);
+}
+
+# if _WIN32
+
+ # include <stdint.h>
+ # include <windows.h>
+ # include <winhttp.h>
+
+ /*tex After checking this redirect callback was recommended: */
+
+ typedef struct {
+ LPCWSTR host;
+ DWORD scheme;
+ DWORD port;
+ const char **headers;
+ } winhttp_redirect_ctx;
+
+ static void CALLBACK WinHttpRedirectCallback(
+ HINTERNET hInternet,
+ DWORD_PTR dwContext,
+ DWORD dwInternetStatus,
+ LPVOID lpvStatusInformation,
+ DWORD dwStatusInformationLength
+ )
+ {
+ (void) dwStatusInformationLength;
+ if (dwInternetStatus == WINHTTP_CALLBACK_STATUS_REDIRECT) {
+ LPCWSTR redirect_url = (LPCWSTR) lpvStatusInformation;
+ winhttp_redirect_ctx *ctx = (winhttp_redirect_ctx *) dwContext;
+
+ URL_COMPONENTS target_comp;
+ memset(&target_comp, 0, sizeof(target_comp));
+ target_comp.dwStructSize = sizeof(target_comp);
+ target_comp.dwHostNameLength = (DWORD) -1;
+
+ if (WinHttpCrackUrl(redirect_url, 0, 0, &target_comp)) {
+ if (ctx && ctx->host && (
+ (DWORD) target_comp.nScheme != ctx->scheme ||
+ (DWORD) target_comp.nPort != ctx->port ||
+ target_comp.dwHostNameLength != wcslen(ctx->host) ||
+ _wcsnicmp(target_comp.lpszHostName, ctx->host, target_comp.dwHostNameLength) != 0))
+ {
+ // strip default sensitive headers
+ WinHttpAddRequestHeaders(hInternet, L"Authorization:", (DWORD) -1, WINHTTP_ADDREQ_FLAG_REPLACE);
+ WinHttpAddRequestHeaders(hInternet, L"Cookie:", (DWORD) -1, WINHTTP_ADDREQ_FLAG_REPLACE);
+ // strip all user-defined custom headers
+ if (ctx->headers) {
+ for (int i = 0; ctx->headers[i] != NULL; i++) {
+ const char *hdr = ctx->headers[i];
+ const char *colon = strchr(hdr, ':');
+ size_t name_len = colon ? (size_t) (colon - hdr) : strlen(hdr);
+ if (name_len > 0) {
+ if (name_len <= SIZE_MAX - 2) {
+ char *buf = (char *) lmt_memory_malloc(name_len + 2);
+ if (buf) {
+ memcpy(buf, hdr, name_len);
+ buf[name_len] = ':';
+ buf[name_len + 1] = '\0';
+ LPWSTR wname = aux_utf8_to_wide(buf);
+ if (wname) {
+ WinHttpAddRequestHeaders(hInternet, wname, (DWORD) -1, WINHTTP_ADDREQ_FLAG_REPLACE);
+ lmt_memory_free(wname);
+ }
+ lmt_memory_free(buf);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ static int clientlib_aux_http_request(
+ http_request_data *data,
+ luaL_Buffer *b,
+ int *status_code,
+ char **errormessage
+ )
+ {
+ LPWSTR wurl = aux_utf8_to_wide(data->url);
+ LPWSTR wmethod = aux_utf8_to_wide(data->method);
+
+ URL_COMPONENTS components;
+
+ memset(&components, 0, sizeof(components));
+
+ components.dwStructSize = sizeof(components);
+ components.dwHostNameLength = (DWORD) -1;
+ components.dwUrlPathLength = (DWORD) -1;
+ components.dwExtraInfoLength = (DWORD) -1;
+ components.dwSchemeLength = (DWORD) -1;
+
+ if (! WinHttpCrackUrl(wurl, 0, 0, &components)) {
+ *errormessage = lmt_memory_strdup("invalid url");
+ lmt_memory_free(wurl);
+ lmt_memory_free(wmethod);
+ return 0;
+ }
+
+ // if (components.nScheme != INTERNET_SCHEME_HTTP && components.nScheme != INTERNET_SCHEME_HTTPS) {
+ // *errormessage = lmt_memory_strdup("only http and https protocols are allowed");
+ // lmt_memory_free(wurl);
+ // lmt_memory_free(wmethod);
+ // return 0;
+ // }
+
+ DWORD host_len = components.dwHostNameLength;
+ WCHAR *host = (WCHAR *) lmt_memory_malloc((host_len + 1) * sizeof(WCHAR));
+ if (! host) {
+ *errormessage = lmt_memory_strdup("out of memory for host");
+ lmt_memory_free(wurl);
+ lmt_memory_free(wmethod);
+ return 0;
+ }
+ wcsncpy(host, components.lpszHostName, host_len);
+ host[host_len] = L'\0';
+
+ DWORD path_len = components.dwUrlPathLength + components.dwExtraInfoLength;
+ WCHAR *path = (WCHAR *) lmt_memory_malloc((path_len + 1) * sizeof(WCHAR));
+ if (! path) {
+ *errormessage = lmt_memory_strdup("out of memory for path");
+ lmt_memory_free(host);
+ lmt_memory_free(wurl);
+ lmt_memory_free(wmethod);
+ return 0;
+ }
+
+ if (components.lpszUrlPath && path_len > 0) {
+ wcsncpy(path, components.lpszUrlPath, path_len);
+ path[path_len] = L'\0';
+ } else {
+ path[0] = L'\0';
+ }
+
+ HINTERNET session = WinHttpOpen(L"LMTHTTP/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
+ HINTERNET connection = session ? WinHttpConnect(session, host, components.nPort, 0) : NULL;
+
+ DWORD flags = (components.nScheme == INTERNET_SCHEME_HTTPS) ? WINHTTP_FLAG_SECURE : 0;
+ HINTERNET request = connection ? WinHttpOpenRequest(connection, wmethod, path, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, flags) : NULL;
+
+ int success = 0;
+
+ if (! request) {
+ *errormessage = lmt_memory_strdup("http(s) connection failed");
+ if (connection) {
+ WinHttpCloseHandle(connection);
+ }
+ if (session) {
+ WinHttpCloseHandle(session);
+ }
+ lmt_memory_free(host);
+ lmt_memory_free(path);
+ lmt_memory_free(wurl);
+ lmt_memory_free(wmethod);
+ return 0;
+ }
+
+ if (data->tolerant) {
+ DWORD security_flags = SECURITY_FLAG_IGNORE_UNKNOWN_CA
+ | SECURITY_FLAG_IGNORE_CERT_CN_INVALID
+ | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
+ | SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE;
+ WinHttpSetOption(
+ request,
+ WINHTTP_OPTION_SECURITY_FLAGS,
+ &security_flags,
+ sizeof(security_flags)
+ );
+ }
+
+ if (data->headers) {
+ for (int i = 0; data->headers[i] != NULL; i++) {
+ LPWSTR wheader = aux_utf8_to_wide(data->headers[i]);
+ WinHttpAddRequestHeaders(request, wheader, (DWORD) -1, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE);
+ lmt_memory_free(wheader);
+ }
+ }
+
+ winhttp_redirect_ctx redirect_ctx = {
+ .host = host,
+ .scheme = (DWORD) components.nScheme,
+ .port = (DWORD) components.nPort,
+ .headers = data->headers
+ };
+
+ DWORD_PTR redirect_context = (DWORD_PTR) &redirect_ctx;
+ if (! WinHttpSetOption(
+ request,
+ WINHTTP_OPTION_CONTEXT_VALUE,
+ &redirect_context,
+ sizeof(redirect_context)))
+ {
+ *errormessage = lmt_memory_strdup("http(s) redirect context setup failed");
+ goto winhttp_cleanup;
+ }
+
+ if (WinHttpSetStatusCallback(
+ request,
+ WinHttpRedirectCallback,
+ WINHTTP_CALLBACK_FLAG_REDIRECT,
+ 0
+ ) == WINHTTP_INVALID_STATUS_CALLBACK) {
+ *errormessage = lmt_memory_strdup("https(s) redirect callback setup failed");
+ goto winhttp_cleanup;
+ }
+
+ if (data->timeout > 0) {
+ if (data->timeout > (long) (INT_MAX / 1000) || ! WinHttpSetTimeouts(
+ request, // times ln ms:
+ 1000 * default_timeout_connect, // resolveTimeout
+ 1000 * default_timeout_connect, // connectTimeout
+ 1000 * default_timeout_connect, // sendTimeout
+ 1000 * data->timeout // receiveTimeout
+ ))
+ {
+ *errormessage = lmt_memory_strdup("https(s) timeout setup failed");
+ goto winhttp_cleanup;
+ }
+ }
+
+ if (data->length > (size_t) ((DWORD) -1)) {
+ *errormessage = lmt_memory_strdup("https(s) request body is too large");
+ goto winhttp_cleanup;
+ }
+
+ if (WinHttpSendRequest(request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, (LPVOID) (uintptr_t) data->body, (DWORD) data->length, (DWORD) data->length, 0)) {
+ if (! WinHttpReceiveResponse(request, NULL)) {
+ *errormessage = lmt_memory_strdup("https(s) receive response failed");
+ } else {
+ DWORD status = 0;
+ DWORD statussize = sizeof(status);
+
+ WinHttpQueryHeaders(
+ request,
+ WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
+ WINHTTP_HEADER_NAME_BY_INDEX,
+ &status,
+ &statussize,
+ WINHTTP_NO_HEADER_INDEX
+ );
+
+ *status_code = (int) status;
+
+ DWORD available = 0;
+ DWORD downloaded = 0;
+ size_t totalread = 0;
+ int read_ok = 1;
+
+ DWORD content_length = 0;
+ DWORD cl_size = sizeof(content_length);
+ if (WinHttpQueryHeaders(
+ request,
+ WINHTTP_QUERY_CONTENT_LENGTH | WINHTTP_QUERY_FLAG_NUMBER,
+ WINHTTP_HEADER_NAME_BY_INDEX,
+ &content_length,
+ &cl_size,
+ WINHTTP_NO_HEADER_INDEX)
+ ) {
+ if (content_length > data->maxsize) {
+ read_ok = 0;
+ *errormessage = lmt_memory_strdup("content length exceeded size limit");
+ } else {
+ luaL_prepbuffsize(b, content_length);
+ }
+ }
+
+ while (read_ok) {
+ if (! WinHttpQueryDataAvailable(request, &available)) {
+ *errormessage = lmt_memory_strdup("https(s) query data available failed");
+ read_ok = 0;
+ break;
+ }
+ if (available == 0) {
+ break; /* end of response */
+ }
+ if (totalread > data->maxsize || (size_t) available > data->maxsize - totalread) {
+ *errormessage = lmt_memory_strdup("response body exceeded size limit");
+ read_ok = 0;
+ break;
+ }
+ char *dest = luaL_prepbuffsize(b, available);
+ if (! WinHttpReadData(request, dest, available, &downloaded) || downloaded == 0) {
+ *errormessage = lmt_memory_strdup("https(s) read data failed");
+ read_ok = 0;
+ break;
+ }
+ luaL_addsize(b, downloaded);
+ totalread += downloaded;
+ }
+ if (read_ok) {
+ success = 1;
+ }
+ }
+ } else {
+ *errormessage = lmt_memory_strdup("https(s) request failed");
+ }
+
+ winhttp_cleanup:
+ WinHttpCloseHandle(request);
+ WinHttpCloseHandle(connection);
+ WinHttpCloseHandle(session);
+ lmt_memory_free(host);
+ lmt_memory_free(path);
+ lmt_memory_free(wurl);
+ lmt_memory_free(wmethod);
+ return success;
+ }
+
+ static int clientlib_aux_supported(void)
+ {
+ return 1;
+ }
+
+# else
+
+ # include <dlfcn.h>
+ # include <strings.h>
+
+ typedef void* (*fn_curl_easy_init) (void);
+ typedef void (*fn_curl_easy_cleanup) (void*);
+ typedef int (*fn_curl_easy_perform) (void*);
+ typedef int (*fn_curl_easy_setopt) (void*, int, ...);
+ typedef int (*fn_curl_easy_getinfo) (void*, int, ...);
+ typedef const char* (*fn_curl_easy_strerror) (int);
+ typedef void* (*fn_curl_slist_append) (void*, const char*);
+ typedef void (*fn_curl_slist_free_all) (void*);
+
+ static void *curl_handle = NULL;
+ static int curl_loaded = -1; /* not yet checked */
+
+ static fn_curl_easy_init curl_easy_init = NULL;
+ static fn_curl_easy_cleanup curl_easy_cleanup = NULL;
+ static fn_curl_easy_perform curl_easy_perform = NULL;
+ static fn_curl_easy_setopt curl_easy_setopt = NULL;
+ static fn_curl_easy_getinfo curl_easy_getinfo = NULL;
+ static fn_curl_easy_strerror curl_easy_strerror = NULL;
+ static fn_curl_slist_append curl_slist_append = NULL;
+ static fn_curl_slist_free_all curl_slist_free_all = NULL;
+
+ /*tex The complete list is in the |lmtcurl.c| file. */
+
+ # define curl_option_writedata 1
+ # define curl_option_url 2
+ # define curl_option_readdata 9
+ # define curl_option_writefunction 11
+ # define curl_option_timeout 13
+ # define curl_option_postfields 15
+ # define curl_option_httpheader 23
+ # define curl_option_headerdata 29
+ # define curl_option_customrequest 36
+ # define curl_option_header 42
+ # define curl_option_post 47
+ # define curl_option_followlocation 52
+ # define curl_option_postfieldsize 60
+ # define curl_option_ssl_verifypeer 64
+ # define curl_option_maxredirs 68
+ # define curl_option_connecttimeout 78
+ # define curl_option_headerfunction 79
+ # define curl_option_httpget 80
+ # define curl_option_ssl_verifyhost 81
+ # define curl_option_buffersize 98
+ # define curl_option_nosignal 99
+ # define curl_option_protocols 181
+ # define curl_option_redir_protocols 182
+
+ # define curl_proto_http (1L << 0)
+ # define curl_proto_https (1L << 1)
+
+ # define curl_integer_base 0 /* long */
+ # define curl_string_base 10000
+ # define curl_object_base 10000
+ # define curl_function_base 20000
+ # define curl_offset_base 30000
+ # define curl_blob_base 40000
+
+ # define curl_info_long 0x200000
+ # define curl_info_double 0x300000
+
+ # define curl_responsecode 2
+ # define curl_content_length_download 15
+
+ /*tex Because we know we're on \UNIX\ we can do this: */
+
+ static void *clientlib_aux_load_curl_library(void)
+ {
+ static const char *names[] = {
+ "libcurl.so.4",
+ "libcurl.so",
+ "libcurl.4.dylib",
+ "libcurl.dylib",
+ NULL
+ };
+ for (int i = 0; names[i]; i++) {
+ void *handle = dlopen(names[i], RTLD_LAZY | RTLD_GLOBAL);
+ if (handle) {
+ return handle;
+ }
+ }
+ return NULL;
+ }
+
+ static int clientlib_aux_curl_loaded(void)
+ {
+ if (curl_loaded >= 0) {
+ return curl_loaded;
+ }
+ curl_handle = clientlib_aux_load_curl_library();
+ if (curl_handle) {
+ curl_easy_init = (fn_curl_easy_init) dlsym(curl_handle, "curl_easy_init");
+ curl_easy_cleanup = (fn_curl_easy_cleanup) dlsym(curl_handle, "curl_easy_cleanup");
+ curl_easy_perform = (fn_curl_easy_perform) dlsym(curl_handle, "curl_easy_perform");
+ curl_easy_setopt = (fn_curl_easy_setopt) dlsym(curl_handle, "curl_easy_setopt");
+ curl_easy_getinfo = (fn_curl_easy_getinfo) dlsym(curl_handle, "curl_easy_getinfo");
+ curl_easy_strerror = (fn_curl_easy_strerror) dlsym(curl_handle, "curl_easy_strerror");
+ curl_slist_append = (fn_curl_slist_append) dlsym(curl_handle, "curl_slist_append");
+ curl_slist_free_all = (fn_curl_slist_free_all) dlsym(curl_handle, "curl_slist_free_all");
+ if ( ! curl_easy_init || ! curl_easy_cleanup || ! curl_easy_setopt
+ || ! curl_easy_perform || ! curl_easy_getinfo || ! curl_easy_strerror
+ || ! curl_slist_append || ! curl_slist_free_all) {
+ dlclose(curl_handle);
+ curl_handle = NULL;
+ }
+ }
+ curl_loaded = curl_handle != NULL;
+ return curl_loaded;
+ }
+
+ typedef struct {
+ luaL_Buffer *buffer;
+ size_t maxsize;
+ size_t bytesread;
+ int exceeded;
+ } curl_stream_context;
+
+ static size_t write_callback(
+ void *buffer,
+ size_t size,
+ size_t nitems,
+ void *userdata
+ )
+ {
+ size_t total = size * nitems;
+ curl_stream_context *ctx = (curl_stream_context *) userdata;
+ if (ctx->bytesread > ctx->maxsize || total > ctx->maxsize - ctx->bytesread) {
+ ctx->exceeded = 1;
+ return 0; /* Returning 0 causes libcurl to abort with CURLE_WRITE_ERROR */
+ } else {
+ luaL_addlstring(ctx->buffer, (const char*) buffer, total);
+ ctx->bytesread += total;
+ return total;
+ }
+ }
+
+ static int parse_content_length(const char *data, size_t length, size_t *value)
+ {
+ size_t i = 0;
+ size_t result = 0;
+ while (i < length && (data[i] == ' ' || data[i] == '\t')) {
+ i++;
+ }
+ if (i == length || data[i] < '0' || data[i] > '9') {
+ return 0;
+ }
+ while (i < length && data[i] >= '0' && data[i] <= '9') {
+ size_t digit = (size_t) (data[i] - '0');
+ if (result > (SIZE_MAX - digit) / 10) {
+ return 0;
+ }
+ result = result * 10 + digit;
+ i++;
+ }
+ while (i < length && (data[i] == ' ' || data[i] == '\t' || data[i] == '\r' || data[i] == '\n')) {
+ i++;
+ }
+ if (i != length) {
+ return 0;
+ }
+ *value = result;
+ return 1;
+ }
+
+ static size_t header_callback(
+ char *buffer,
+ size_t size,
+ size_t nitems,
+ void *userdata
+ )
+ {
+ size_t total = size * nitems;
+ curl_stream_context *ctx = (curl_stream_context *) userdata;
+ if (total > 15 && strncasecmp(buffer, "Content-Length:", 15) == 0) {
+ size_t val_len = total - 15;
+ size_t len = 0;
+ if (parse_content_length(buffer + 15, val_len, &len)) {
+ if (len > ctx->maxsize) {
+ ctx->exceeded = 1;
+ return 0; /* Abort request on header processing */
+ } else if (len > 0) {
+ luaL_prepbuffsize(ctx->buffer, len);
+ }
+ }
+ }
+ return total;
+ }
+
+ static int clientlib_aux_http_request(
+ http_request_data *data,
+ luaL_Buffer *buffer,
+ int *status_code,
+ char **errormessage
+ )
+ {
+ if (! clientlib_aux_curl_loaded()) {
+ *errormessage = lmt_memory_strdup("libcurl is not available on this system");
+ return 0;
+ }
+
+ void *curl = curl_easy_init();
+ if (! curl) {
+ *errormessage = lmt_memory_strdup("initializing dynamic curl failed");
+ return 0;
+ }
+
+ void *slist = NULL;
+ if (data->headers) {
+ for (int i = 0; data->headers[i] != NULL; i++) {
+ void *next = curl_slist_append(slist, data->headers[i]);
+ if (! next) {
+ *errormessage = lmt_memory_strdup("adding https(s) request header failed");
+ if (slist) {
+ curl_slist_free_all(slist);
+ }
+ curl_easy_cleanup(curl);
+ return 0;
+ }
+ slist = next;
+ }
+ }
+
+ curl_stream_context ctx = {
+ .buffer = buffer,
+ .maxsize = data->maxsize,
+ .bytesread = 0,
+ .exceeded = 0
+ };
+
+ int code = 0;
+
+ # define curl_setopt_checked(...) \
+ do { \
+ if (curl_easy_setopt(__VA_ARGS__) != 0) { \
+ *errormessage = lmt_memory_strdup("configuring libcurl failed"); \
+ goto curl_cleanup; \
+ } \
+ } while (0)
+
+ curl_setopt_checked(curl, curl_integer_base + curl_option_nosignal, 1L);
+ curl_setopt_checked(curl, curl_integer_base + curl_option_protocols, (long) (curl_proto_http | curl_proto_https));
+ curl_setopt_checked(curl, curl_integer_base + curl_option_redir_protocols, (long) (curl_proto_http | curl_proto_https));
+ curl_setopt_checked(curl, curl_integer_base + curl_option_followlocation, 1L);
+ curl_setopt_checked(curl, curl_integer_base + curl_option_maxredirs, 10L); /* plenty */
+
+ if (data->timeout > 0) {
+ curl_setopt_checked(curl, curl_integer_base + curl_option_connecttimeout, (long) default_timeout_connect);
+ curl_setopt_checked(curl, curl_integer_base + curl_option_timeout, data->timeout);
+ }
+
+ curl_setopt_checked(curl, curl_string_base + curl_option_url, (const void*) data->url);
+
+ if (strcasecmp(data->method, "GET") == 0) {
+ curl_setopt_checked(curl, curl_integer_base + curl_option_httpget, 1L);
+ } else if (strcasecmp(data->method, "POST") == 0) {
+ curl_setopt_checked(curl, curl_integer_base + curl_option_post, 1L);
+ } else {
+ curl_setopt_checked(curl, curl_string_base + curl_option_customrequest, (const void*) data->method);
+ }
+
+ if (slist) {
+ curl_setopt_checked(curl, curl_object_base + curl_option_httpheader, (const void*) slist);
+ }
+
+ if (data->body && data->length > 0) {
+ if (data->length > (size_t) LONG_MAX) {
+ *errormessage = lmt_memory_strdup("https(s) request body is too large");
+ goto curl_cleanup;
+ }
+ curl_setopt_checked(curl, curl_string_base + curl_option_postfields, (const void*) data->body);
+ curl_setopt_checked(curl, curl_integer_base + curl_option_postfieldsize, (long) data->length);
+ }
+
+ if (data->tolerant) {
+ curl_setopt_checked(curl, curl_integer_base + curl_option_ssl_verifypeer, 0L);
+ curl_setopt_checked(curl, curl_integer_base + curl_option_ssl_verifyhost, 0L);
+ }
+
+ curl_setopt_checked(curl, curl_function_base + curl_option_headerfunction, header_callback);
+ curl_setopt_checked(curl, curl_object_base + curl_option_headerdata, (const void*) &ctx);
+
+ curl_setopt_checked(curl, curl_function_base + curl_option_writefunction, write_callback);
+ curl_setopt_checked(curl, curl_object_base + curl_option_writedata, (const void*) &ctx);
+
+ curl_setopt_checked(curl, curl_integer_base + curl_option_buffersize, 1024L * 1024L);
+ curl_setopt_checked(curl, curl_integer_base + curl_option_header, 0L);
+
+ code = curl_easy_perform(curl);
+ if (code == 0) {
+ long status = 0;
+ if (curl_easy_getinfo(curl, curl_info_long + curl_responsecode, &status) != 0) {
+ *errormessage = lmt_memory_strdup("getting https(s) response status failed");
+ code = 1;
+ } else {
+ *status_code = (int) status;
+ }
+ } else if (ctx.exceeded) {
+ *errormessage = lmt_memory_strdup("response body exceeded size limit");
+ } else {
+ *errormessage = lmt_memory_strdup(curl_easy_strerror(code));
+ }
+
+ # undef curl_setopt_checked
+
+ curl_cleanup:
+
+ if (slist) {
+ curl_slist_free_all(slist);
+ }
+ curl_easy_cleanup(curl);
+ return (code == 0 && *errormessage == NULL);
+ }
+
+ static int clientlib_aux_supported(void)
+ {
+ return clientlib_aux_curl_loaded();
+ }
+
+# endif
+
+/*tex
+
+ Currently this is what goes in and out. Often just an \URL\ is enough which is why
+ it comes first while checking the boolean is easy too.
+
+ \starttabulate[|l|l|]
+ \NC url \EQ string (mandate) \NC \NR
+ \NC method \EQ string (optional, default: GET) \NC \NR
+ \NC headers \EQ table (optional) \NC \NR
+ \NC body \EQ string (optional) \NC \NR
+ \NC timeout \EQ number (optional, default: 0) \NC \NR
+ \NC maxsize \EQ number (optional, default: 512MB) \NC \NR
+ \NC tolerant \EQ boolean (optional, default: false) \NC \NR
+ \HL
+ \NC result \EQ integer + string \NC \NR
+ \NC error \EQ false + string \NC \NR
+ \stoptabulate
+
+ When |tolerant| is |true| an \HTTPS\ request will not fail on an expired certificate,
+ something that can make sense when we have an installer that gets from an okay site
+ where keeping certifiates up-to-date can be a bit a pain.
+
+*/
+
+/*tex
+ When we want to be more efficient we can use keys and/ur userdata with defaults
+ but for now we are okay.
+*/
+
+/*tex
+ Watch out: these string have to live till we return from the caller!
+*/
+
+static const char** lmt_tostrings(lua_State *L, int index)
+{
+ if (lua_istable(L, index)) {
+ size_t len = lua_rawlen(L, index);
+ const char **list = (const char**) lmt_memory_calloc(len + 1, sizeof(char*));
+ for (size_t i = 1; i <= len; i++) {
+ lua_rawgeti(L, index, i);
+ list[i - 1] = lua_tostring(L, -1);
+ lua_pop(L, 1);
+ }
+ return list;
+ } else {
+ return NULL;
+ }
+}
+
+# if defined(_WIN32) || defined(_MSC_VER)
+ # include <string.h>
+ # define strcasecmp _stricmp
+ # define strncasecmp _strnicmp
+# else
+ # include <strings.h>
+# endif
+
+static int clientlib_httprequest(lua_State *L)
+{
+ http_request_data data;
+ clientlib_aux_preset(&data);
+
+ if (lua_type(L, 1) == LUA_TTABLE) {
+ if (lua_getfield(L, 1, "url") == LUA_TSTRING) { data.url = lua_tostring (L, -1); } lua_pop(L, 1);
+ if (lua_getfield(L, 1, "method") == LUA_TSTRING) { data.method = lua_tostring (L, -1); } lua_pop(L, 1);
+ if (lua_getfield(L, 1, "body") == LUA_TSTRING) { data.body = lua_tolstring(L, -1, &data.length); } lua_pop(L, 1);
+ if (lua_getfield(L, 1, "timeout") == LUA_TNUMBER) { data.timeout = lmt_toulong (L, -1); } lua_pop(L, 1);
+ if (lua_getfield(L, 1, "maxsize") == LUA_TNUMBER) { data.maxsize = lmt_tosizet (L, -1); } lua_pop(L, 1);
+ if (lua_getfield(L, 1, "tolerant") == LUA_TBOOLEAN) { data.tolerant = lua_toboolean(L, -1); } lua_pop(L, 1);
+ if (lua_getfield(L, 1, "headers") == LUA_TTABLE) { data.headers = lmt_tostrings(L, -1); } lua_pop(L, 1);
+ } else {
+ data.url = luaL_checkstring(L, 1);
+ /* We keep this for now. */
+ data.method = luaL_optstring (L, 2, data.method);
+ data.headers = lmt_tostrings (L, 3);
+ data.body = lua_tolstring (L, 4, &data.length);
+ data.timeout = lmt_optulong (L, 5, data.timeout);
+ data.maxsize = lmt_optsizet (L, 6, data.maxsize);
+ data.tolerant = lua_toboolean (L, 7);
+ }
+ if (data.timeout < 0) {
+ data.timeout = 0;
+ }
+
+ if (strncasecmp(data.url, "http://", 7) != 0 && strncasecmp(data.url, "https://", 8) != 0) {
+
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "only http and https protocols are allowed");
+
+ } else if (! lmt_valid_target(L, security_client, data.url, security_http_request)) {
+
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, "the http(s) request is blocked");
+
+ } else {
+
+ luaL_Buffer buffer;
+ luaL_buffinit(L, &buffer);
+
+ int status = 0;
+ char *errormessage = NULL;
+
+ int success = clientlib_aux_http_request(
+ &data, &buffer, &status, &errormessage
+ );
+
+ if (! success || errormessage) {
+ lua_pushboolean(L, 0);
+ lua_pushstring(L, errormessage ? errormessage : "the http(s) request failed");
+ lmt_memory_free(errormessage);
+ } else {
+ /*tex
+ We need to finish the buffer first, and as that can involve pushing stuff on the stack
+ we need to keep the order right. Which in turn means pushing the status after that is
+ done and then move it up (swap places).
+ */
+ luaL_pushresult(&buffer);
+ lua_pushinteger(L, status);
+ lua_insert(L, -2);
+ }
+ }
+
+ clientlib_aux_reset(&data);
+ return 2;
+}
+
+static int clientlib_supported(lua_State *L)
+{
+ lua_pushboolean(L, clientlib_aux_supported());
+ return 1;
+}
+
+static const struct luaL_Reg clientlib_function_list[] = {
+ { "httprequest", clientlib_httprequest },
+ { "supported", clientlib_supported },
+ { NULL, NULL },
+};
+
+int luaopen_client(lua_State *L)
+{
+ luaL_newlib(L, clientlib_function_list);
+ return 1;
+}
diff --git a/source/luametatex/source/luarest/lmteffectslib.c b/source/luametatex/source/luarest/lmteffectslib.c
index c78cd0e32..8a62289ee 100644
--- a/source/luametatex/source/luarest/lmteffectslib.c
+++ b/source/luametatex/source/luarest/lmteffectslib.c
@@ -1,4 +1,4 @@
-/*
+/*
See license.txt in the root of this project.
*/
diff --git a/source/luametatex/source/luarest/lmtfilelib.c b/source/luametatex/source/luarest/lmtfilelib.c
index 7e993b546..902432b9c 100644
--- a/source/luametatex/source/luarest/lmtfilelib.c
+++ b/source/luametatex/source/luarest/lmtfilelib.c
@@ -77,14 +77,6 @@
tens of thousands iterations.
*/
-# if defined(PATH_MAX)
- # define MY_MAXPATHLEN PATH_MAX
-# elif defined(MAXPATHLEN)
- # define MY_MAXPATHLEN MAXPATHLEN
-# else
- # define MY_MAXPATHLEN 255
-# endif
-
# ifdef _WIN32
# include <direct.h>
@@ -95,6 +87,31 @@
# include <sys/utime.h>
# include <fcntl.h>
+# else
+
+ # include <unistd.h>
+ # include <dirent.h>
+ # include <fcntl.h>
+ # include <sys/types.h>
+ # include <utime.h>
+ # include <sys/param.h>
+
+# endif
+
+/*tex
+ After the included these can be known:
+*/
+
+# if defined(PATH_MAX)
+ # define MY_MAXPATHLEN PATH_MAX
+# elif defined(MAXPATHLEN)
+ # define MY_MAXPATHLEN MAXPATHLEN
+# else
+ # define MY_MAXPATHLEN 255
+# endif
+
+# ifdef _WIN32
+
# ifndef FIND_FIRST_EX_LARGE_FETCH
# define FIND_FIRST_EX_LARGE_FETCH 0x02
# endif
@@ -124,34 +141,68 @@
static const int exec_mode_flag = _S_IEXEC;
- static inline int get_stat(const char *s, info_struct *i)
+ static inline LPWSTR aux_utf8_to_wide_path(const char *s)
{
LPWSTR w = aux_utf8_to_wide(s);
- int r = _wstati64(w, i);
+ if (! w) {
+ return NULL;
+ }
+ size_t wlen = wcslen(w);
+ /* trim trailing slashes safely (except for roots like "C:\" or "\") */
+ while (wlen > 1 && (w[wlen - 1] == L'/' || w[wlen - 1] == L'\\')) {
+ if (wlen == 3 && w[1] == L':' ) { break; } /* Keeps "C:\" intact */
+ if (wlen == 1 && (w[0] == L'/' || w[0] == L'\\')) { break; } /* keeps "\" intact */
+ w[--wlen] = L'\0';
+ }
+ /* if it's already an extended path or too short to matter, return as-is */
+ if (wlen <= 240 || (w[0] == L'\\' && w[1] == L'?' && w[2] == L'\\' && w[3] == L'?')) {
+ return w;
+ }
+ /* allocate space for "\\?\" (or "\\?\UNC\") plus the original path */
+ size_t extra = (w[0] == L'\\' && w[1] == L'\\') ? 8 : 4;
+ LPWSTR extended = lmt_memory_malloc((wlen + extra + 1) * sizeof(WCHAR));
+ if (! extended) {
+ return w;
+ }
+ if (extra == 8) {
+ wcscpy(extended, L"\\\\?\\UNC\\");
+ wcscpy(extended + 8, w + 2);
+ } else {
+ wcscpy(extended, L"\\\\?\\");
+ wcscpy(extended + 4, w);
+ }
+ lmt_memory_free(w);
+ return extended;
+ }
+
+ static inline int get_stat(const char *s, info_struct *i)
+ {
+ LPWSTR w = aux_utf8_to_wide_path(s);
+ int r = w ? _wstati64(w, i) : -1;
lmt_memory_free(w);
return r == 0;
}
static inline int mk_dir(const char *s)
{
- LPWSTR w = aux_utf8_to_wide(s);
- int r = _wmkdir(w);
+ LPWSTR w = aux_utf8_to_wide_path(s);
+ int r = w ? _wmkdir(w) : -1;
lmt_memory_free(w);
return r == 0;
}
- static inline int ch_dir(const char *s)
+ static inline int rm_dir(const char *s)
{
- LPWSTR w = aux_utf8_to_wide(s);
- int r = _wchdir(w);
+ LPWSTR w = aux_utf8_to_wide_path(s);
+ int r = w ? _wrmdir(w) : -1;
lmt_memory_free(w);
return r == 0;
}
- static inline int rm_dir(const char *s)
+ static inline int ch_dir(const char *s)
{
- LPWSTR w = aux_utf8_to_wide(s);
- int r = _wrmdir(w);
+ LPWSTR w = aux_utf8_to_wide_path(s);
+ int r = w ? _wchdir(w) : -1;
lmt_memory_free(w);
return r == 0;
}
@@ -160,27 +211,36 @@
static inline int mk_symlink(const char *t, const char *f)
{
- LPWSTR wt = aux_utf8_to_wide(t); /* Existing Target */
- LPWSTR wf = aux_utf8_to_wide(f); /* New Link Name */
- /* Win32 takes (NewLink, ExistingTarget, Flags) */
- /* 0x2 = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE */
- int r = CreateSymbolicLinkW(wf, wt, 0x2) != 0;
+ LPWSTR wt = aux_utf8_to_wide(t);
+ LPWSTR wf = aux_utf8_to_wide(f);
+ int r = 0;
+ if (wt && wf) {
+ DWORD flags = 0x2; /* SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE */
+ DWORD attr = GetFileAttributesW(wt);
+ if (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY)) {
+ flags |= 0x1; /* SYMBOLIC_LINK_FLAG_DIRECTORY */
+ }
+ /* Win32 takes (NewLink, ExistingTarget, Flags) */
+ r = CreateSymbolicLinkW(wf, wt, flags) != 0;
+ if (! r && GetLastError() == ERROR_INVALID_PARAMETER && (flags & 0x2)) {
+ r = CreateSymbolicLinkW(wf, wt, flags & ~0x2) != 0;
+ }
+ }
lmt_memory_free(wt);
lmt_memory_free(wf);
- return r == 0;
+ return r;
}
-
+
/* POSIX link(target, linkpath) -> Hard Link */
static inline int mk_link(const char *t, const char *f)
{
- LPWSTR wt = aux_utf8_to_wide(t); /* Existing Target */
- LPWSTR wf = aux_utf8_to_wide(f); /* New Link Name */
- /* Win32 takes (NewLink, ExistingTarget, Reserved) */
- int r = CreateHardLinkW(wf, wt, NULL) != 0;
+ LPWSTR wt = aux_utf8_to_wide(t);
+ LPWSTR wf = aux_utf8_to_wide(f);
+ int r = (wt && wf) ? (CreateHardLinkW(wf, wt, NULL) != 0) : 0;
lmt_memory_free(wt);
lmt_memory_free(wf);
- return r == 0;
+ return r;
}
static inline int ch_to_exec(const char *s, mode_t n)
@@ -211,13 +271,6 @@
/* POSIX */
- # include <unistd.h>
- # include <dirent.h>
- # include <fcntl.h>
- # include <sys/types.h>
- # include <utime.h>
- # include <sys/param.h>
-
typedef struct stat info_struct;
typedef struct utimbuf utime_struct;
@@ -258,16 +311,100 @@
return chmod(s, mode) == 0;
}
+ // static inline int set_utime(const char *s, utime_struct *b)
+ // {
+ // return utime(s, b) == 0;
+ // }
+
static inline int set_utime(const char *s, utime_struct *b)
{
- return utime(s, b) == 0;
+ int r = utime(s, b);
+ if (r != 0 && errno == ENOENT) {
+ FILE *f = fopen(s, "ab");
+ if (f) {
+ fclose(f);
+ r = utime(s, b);
+ }
+ }
+ return r == 0;
}
# endif
-# include <lua.h>
-# include <lauxlib.h>
-# include <lualib.h>
+/*tex
+
+ This one is common. We used to do this in \LUA\ but it is more reliable here, also because
+ when we interface to \LUA\ we have to apply the sandbox feature. We step through the path
+ by replacing the slash by a zero. We also want to quit on a failure, but keep the already
+ created subpaths. Duplicate path seperators are ignored. So in the end less messy that doing
+ all this in \LUA.
+
+*/
+
+static inline int aux_isdir(const char *s)
+{
+ info_struct info;
+ return get_stat(s, &info) && S_ISDIR(info.st_mode);
+}
+
+static inline int mk_dirs(const char *s)
+{
+ /* sanity checks */
+ if (! s || ! *s) {
+ return 0;
+ }
+ /* we need a mutable path */
+ char *path = lmt_memory_strdup(s);
+ if (! path) {
+ return 0;
+ }
+ /* the pointer in path */
+ char *p = path;
+# ifdef _WIN32
+ /* skip a windows drive letter if present (e.g., "c:") */
+ if (isalpha((unsigned char) path[0]) && path[1] == ':') {
+ p += 2;
+ }
+# endif
+ /* skip leading slashes / root indicators */
+ while (*p == '/' || *p == '\\') {
+ p++;
+ }
+ /* walk through the path and create directories incrementally */
+ while (*p) {
+ if (*p == '/' || *p == '\\') {
+ /* save the slash and temporary end the path */
+ char slash = *p;
+ *p = '\0';
+ /* try to create the intermediate directory: /a /a/b /a/b/c etc */
+ if (! mk_dir(path)) {
+ /* only quit when the path doesn't exist afterward */
+ if (errno != EEXIST) {
+ lmt_memory_free(path);
+ return 0;
+ }
+ }
+ /* restore the slash */
+ *p = slash;
+ /* skip duplicate separators */
+ while (*p == '/' || *p == '\\') {
+ p++;
+ }
+ } else {
+ p++;
+ }
+ }
+ /* create the final directory */
+ int result = mk_dir(path);
+ if (! result && errno != EEXIST) {
+ lmt_memory_free(path);
+ return 0;
+ }
+ /* ensure it actually exists and is a directory */
+ int success = aux_isdir(path);
+ lmt_memory_free(path);
+ return success ? 1 : 0;
+}
/*
This function changes the current directory.
@@ -300,11 +437,13 @@ static int filelib_chdir(lua_State *L)
int size = 256;
while (1) {
LPWSTR temp = lmt_memory_realloc(wpath, size * sizeof(WCHAR));
- wpath = temp;
- if (! wpath) {
+ if (! temp) {
+ lmt_memory_free(wpath);
lua_pushboolean(L, 0);
- break;
- } else if (_wgetcwd(wpath, size)) {
+ return 1;
+ }
+ wpath = temp;
+ if (_wgetcwd(wpath, size)) {
char *path = aux_utf8_from_wide(wpath);
lua_pushstring(L, path);
lmt_memory_free(path);
@@ -327,16 +466,15 @@ static int filelib_chdir(lua_State *L)
char *path = NULL;
size_t size = MY_MAXPATHLEN;
while (1) {
- char *next_path = lmt_memory_realloc(path, size);
- if (! next_path) {
+ char *temp = lmt_memory_realloc(path, size);
+ if (! temp) {
if (path) {
lmt_memory_free(path); /* Free original buffer if realloc fails */
}
lua_pushboolean(L, 0);
return 1;
}
- path = next_path;
-
+ path = temp;
if (getcwd(path, size)) {
lua_pushstring(L, path);
lmt_memory_free(path); /* Clean up allocated buffer before returning */
@@ -367,7 +505,7 @@ static int filelib_link(lua_State *L)
if (lua_type(L, 1) == LUA_TSTRING && lua_type(L, 2) == LUA_TSTRING) {
const char *oldpath = lua_tostring(L, 1);
const char *newpath = lua_tostring(L, 2);
- if (oldpath && newpath && lmt_valid_target(L, security_writeable, newpath, security_link_object)) {
+ if (oldpath && newpath && lmt_valid_target(L, security_writable, newpath, security_link_object)) {
okay = lua_toboolean(L, 3) ? mk_symlink(oldpath, newpath) : mk_link(oldpath, newpath);
}
}
@@ -381,7 +519,7 @@ static int filelib_symlink(lua_State *L)
if (lua_type(L, 1) == LUA_TSTRING && lua_type(L, 2) == LUA_TSTRING) {
const char *oldpath = lua_tostring(L, 1);
const char *newpath = lua_tostring(L, 2);
- if (oldpath && newpath && lmt_valid_target(L, security_writeable, newpath, security_link_object)) {
+ if (oldpath && newpath && lmt_valid_target(L, security_writable, newpath, security_link_object)) {
okay = mk_symlink(oldpath, newpath);
}
}
@@ -400,16 +538,55 @@ static int filelib_mkdir(lua_State *L)
int okay = 0;
if (lua_type(L, 1) == LUA_TSTRING) {
const char * name = lua_tostring(L, 1);
- okay = (name && lmt_valid_target(L, security_writeable, name, security_create_directory)) ? mk_dir(name) : 0;
+ okay = (name && lmt_valid_target(L, security_writable, name, security_create_directory)) ? mk_dir(name) : 0;
}
lua_pushboolean(L, okay);
return 1;
}
+static int filelib_mkdirs(lua_State *L)
+{
+ int n = lua_gettop(L);
+ if (n <= 0) {
+ lua_pushboolean(L, 0);
+ return 1;
+ }
+ const char *name = NULL;
+ if (n > 1) {
+ /* concatenate arguments with '/' just like the original \LUA\ variant */
+ luaL_Buffer b;
+ luaL_buffinit(L, &b);
+ int done = 0;
+ for (int i = 1; i <= n; i++) {
+ size_t len;
+ const char *str = lua_tolstring(L, i, &len);
+ if (str && len > 0) {
+ if (done) {
+ luaL_addchar(&b, '/');
+ }
+ luaL_addlstring(&b, str, len);
+ done = 1;
+ }
+ }
+ /* pushes the combined path string onto the stack */
+ luaL_pushresult(&b);
+ name = lua_tostring(L, -1);
+ } else {
+ name = lua_tostring(L, 1);
+ }
+ int okay = 0;
+ if (name && lmt_valid_target(L, security_writable, name, security_create_directory)) {
+ okay = aux_isdir(name) ? 1 : mk_dirs(name);
+ }
+ /* push the success boolean on top of the path string, returning path, success */
+ lua_pushboolean(L, okay);
+ return 2;
+}
+
/*
This function removes a directory (non-recursive).
- success = mkdir(name)
+ success = rmdir(name)
*/
static int filelib_rmdir(lua_State *L)
@@ -417,7 +594,7 @@ static int filelib_rmdir(lua_State *L)
int okay = 0;
if (lua_type(L, 1) == LUA_TSTRING) {
const char * name = lua_tostring(L, 1);
- okay = (name && lmt_valid_target(L, security_writeable, name, security_remove_directory)) ? rm_dir(name) : 0;
+ okay = (name && lmt_valid_target(L, security_writable, name, security_remove_directory)) ? rm_dir(name) : 0;
}
lua_pushboolean(L, okay);
return 1;
@@ -433,7 +610,7 @@ static int filelib_moreweird(lua_State *L)
static int filelib_lessweird(lua_State *L)
{
- static const char *weird = "~`#$%^&*:;\"\'||<>,?\n\r\t";
+ static const char *weird = "~`#$%^&*:;\"\'|<>,?\n\r\t";
const char *str = lua_tostring(L, 1);
lua_pushboolean(L, str ? str[0] == '.' || strpbrk(str, weird) != NULL : 1);
return 1;
@@ -525,10 +702,12 @@ static int filelib_lessweird(lua_State *L)
if (details) {
/* convert FILETIME to 64-bit Unix epoch time */
ULARGE_INTEGER ull;
- ull.LowPart = fd->ftLastWriteTime.dwLowDateTime;
+ ull.LowPart = fd->ftLastWriteTime.dwLowDateTime;
ull.HighPart = fd->ftLastWriteTime.dwHighDateTime;
/* the magic number is 100 nanoseconds between 1601 and 1970 */
- lua_Integer mtime = (lua_Integer) ((ull.QuadPart - 116444736000000000ULL) / 10000000ULL);
+ lua_Integer mtime = ull.QuadPart >= 116444736000000000ULL
+ ? (lua_Integer) ((ull.QuadPart - 116444736000000000ULL) / 10000000ULL)
+ : 0;
lua_Integer size = ((lua_Integer)fd->nFileSizeHigh << 32) | fd->nFileSizeLow;
lua_pushinteger(L, size);
lua_pushinteger(L, mtime);
@@ -581,12 +760,16 @@ static int filelib_lessweird(lua_State *L)
static inline dir_data *filelib_aux_valid_dir(lua_State *L)
{
dir_data *d = (dir_data *) lua_touserdata(L, 1);
- if (d && lua_getmetatable(L, 1)) {
- lua_get_metatablelua(dir_handle_instance);
- if (! lua_rawequal(L, -1, -2)) {
+ if (d) {
+ if (lua_getmetatable(L, 1)) {
+ lua_get_metatablelua(dir_handle_instance);
+ if (! lua_rawequal(L, -1, -2)) {
+ d = NULL;
+ }
+ lua_pop(L, 2);
+ } else {
d = NULL;
}
- lua_pop(L, 2);
}
return d;
}
@@ -600,14 +783,14 @@ static int filelib_lessweird(lua_State *L)
static int filelib_aux_dir_method(lua_State *L)
{
dir_data *d = (dir_data *) luaL_checkudata(L, 1, DIR_HANDLE_INSTANCE);
- // dir_data *d = filelib_aux_valid_dir(L);
+ /* dir_data *d = filelib_aux_valid_dir(L); */ /* faster */
return d ? filelib_aux_dir_next(L, d) : 0;
}
static int filelib_aux_dir_close(lua_State *L)
{
dir_data *d = (dir_data *) luaL_checkudata(L, 1, DIR_HANDLE_INSTANCE);
- // dir_data *d = filelib_aux_valid_dir(L);
+ /* dir_data *d = filelib_aux_valid_dir(L); */ /* faster */
if (d && ! d->closed && d->handle != INVALID_HANDLE_VALUE) {
FindClose(d->handle);
d->handle = INVALID_HANDLE_VALUE;
@@ -622,25 +805,32 @@ static int filelib_lessweird(lua_State *L)
{
const char *path = luaL_checkstring(L, 1);
int details = (lua_type(L, 2) == LUA_TBOOLEAN) ? lua_toboolean(L, 2) : 1;
+ if (! path || path[0] == '\0') {
+ path = ".";
+ }
dir_data *d = (dir_data *) lua_newuserdatauv(L, sizeof(dir_data), 0);
lua_get_metatablelua(dir_handle_instance);
lua_setmetatable(L, -2);
d->closed = 0;
d->details = details;
d->handle = INVALID_HANDLE_VALUE;
- if (!path) {
- path = ".";
- }
- /* Convert path directly to wide string */
+ /* Convert path to wide string */
int len = MultiByteToWideChar(CP_UTF8, 0, path, -1, d->pattern, MY_MAXPATHLEN);
if (len <= 0) {
luaL_error(L, "path conversion failed or too long: %s", path);
return 0;
}
- /* Remove trailing slashes (e.g., "foo/" or "foo\") before appending "\*" */
- while (len > 1 && (d->pattern[len - 2] == L'/' || d->pattern[len - 2] == L'\\')) {
+ /* Trim trailing slashes (except for root like "C:\" or "\") */
+ while (len > 2 && (d->pattern[len - 2] == L'/' || d->pattern[len - 2] == L'\\') && d->pattern[len - 3] != L':') {
len--;
}
+ d->pattern[len - 1] = L'\0';
+ /* Validate directory existence and type (matches POSIX opendir check) */
+ DWORD attr = GetFileAttributesW(d->pattern);
+ if (attr == INVALID_FILE_ATTRIBUTES || ! (attr & FILE_ATTRIBUTE_DIRECTORY)) {
+ luaL_error(L, "cannot open %s: %s", path, (attr == INVALID_FILE_ATTRIBUTES) ? "no such directory" : "not a directory");
+ return 0;
+ }
/* Append "\*" for FindFirstFileExW */
d->pattern[len - 1] = L'\\';
d->pattern[len] = L'*';
@@ -678,8 +868,9 @@ static int filelib_lessweird(lua_State *L)
DIR *handle;
int closed;
int details;
+ # if HAVE_FSTATAT
int dfd;
- # if ! HAVE_FSTATAT
+ # else
char path[MY_MAXPATHLEN]; /* Only allocated on older OS/SDK targets */
# endif
} dir_data;
@@ -701,7 +892,9 @@ static int filelib_lessweird(lua_State *L)
closedir(d->handle);
d->closed = 1;
d->handle = NULL;
+ # if HAVE_FSTATAT
d->dfd = -1;
+ # endif
return 0;
}
lua_pushstring(L, entry->d_name);
@@ -752,12 +945,16 @@ static int filelib_lessweird(lua_State *L)
static inline dir_data *filelib_aux_valid_dir(lua_State *L)
{
dir_data *d = (dir_data *) lua_touserdata(L, 1);
- if (d && lua_getmetatable(L, 1)) {
- lua_get_metatablelua(dir_handle_instance);
- if (! lua_rawequal(L, -1, -2)) {
+ if (d) {
+ if (lua_getmetatable(L, 1)) {
+ lua_get_metatablelua(dir_handle_instance);
+ if (! lua_rawequal(L, -1, -2)) {
+ d = NULL;
+ }
+ lua_pop(L, 2);
+ } else {
d = NULL;
}
- lua_pop(L, 2);
}
return d;
}
@@ -771,21 +968,23 @@ static int filelib_lessweird(lua_State *L)
static int filelib_aux_dir_method(lua_State *L)
{
dir_data *d = (dir_data *) luaL_checkudata(L, 1, DIR_HANDLE_INSTANCE);
- // dir_data *d = filelib_aux_valid_dir(L);
+ /* dir_data *d = filelib_aux_valid_dir(L); */ /* faster */
return d ? filelib_aux_dir_next(L, d) : 0;
}
static int filelib_aux_dir_close(lua_State *L)
{
dir_data *d = (dir_data *) luaL_checkudata(L, 1, DIR_HANDLE_INSTANCE);
- // dir_data *d = filelib_aux_valid_dir(L);
+ /* dir_data *d = filelib_aux_valid_dir(L); */ /* faster */
if (d && ! d->closed && d->handle) {
closedir(d->handle);
}
if (d) {
d->closed = 1;
d->handle = NULL;
+ # if HAVE_FSTATAT
d->dfd = -1;
+ # endif
}
return 0;
}
@@ -808,7 +1007,9 @@ static int filelib_lessweird(lua_State *L)
if (! d->handle) {
luaL_error(L, "cannot open %s: %s", path, strerror(errno));
}
+ # if HAVE_FSTATAT
d->dfd = dirfd(d->handle);
+ # endif
lua_pushvalue(L, -1);
lua_pushcclosure(L, filelib_aux_dir_iterator, 1);
lua_insert(L, -2);
@@ -817,7 +1018,7 @@ static int filelib_lessweird(lua_State *L)
# endif
-static int dir_create_meta(lua_State *L)
+static int dir_create_metatable(lua_State *L)
{
luaL_newmetatable(L, DIR_HANDLE_INSTANCE);
lua_newtable(L);
@@ -828,6 +1029,7 @@ static int dir_create_meta(lua_State *L)
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, filelib_aux_dir_close);
lua_setfield(L, -2, "__gc");
+ lua_pop(L, 1);
return 1;
}
@@ -901,7 +1103,7 @@ static int filelib_touch(lua_State *L)
utb.modtime = (time_t) luaL_optinteger(L, 3, utb.actime);
buf = &utb;
}
- okay = (name && lmt_valid_target(L, security_writeable, name, security_touch_object)) ? set_utime(name, buf) : 0;
+ okay = (name && lmt_valid_target(L, security_writable, name, security_touch_object)) ? set_utime(name, buf) : 0;
}
lua_pushboolean(L, okay);
return 1;
@@ -1010,7 +1212,33 @@ static int filelib_attributes(lua_State *L)
const char *name = lua_tostring(L, 1);
if (get_stat(name, &info)) {
int match = check_dir ? S_ISDIR(info.st_mode) : (S_ISREG(info.st_mode) || S_ISLNK(info.st_mode));
- okay = match && (access(name, access_mode) == 0);
+ /* okay = match && (access(name, access_mode) == 0); */ /* avoid access: */
+ if (match) {
+ if (access_mode == F_OK) {
+ okay = 1;
+ } else {
+ /* gemini: check permissions directly from st_mode bits to avoid redundant system calls */
+ uid_t uid = getuid();
+ gid_t gid = getgid();
+ int allowed = 0;
+ if (uid == 0) {
+ allowed = 1; /* root has access to everything */
+ } else if (info.st_uid == uid) {
+ if ((access_mode & R_OK) && ! (info.st_mode & S_IRUSR)) allowed = -1;
+ if ((access_mode & W_OK) && ! (info.st_mode & S_IWUSR)) allowed = -1;
+ if (allowed != -1) allowed = 1;
+ } else if (info.st_gid == gid) {
+ if ((access_mode & R_OK) && ! (info.st_mode & S_IRGRP)) allowed = -1;
+ if ((access_mode & W_OK) && ! (info.st_mode & S_IWGRP)) allowed = -1;
+ if (allowed != -1) allowed = 1;
+ } else {
+ if ((access_mode & R_OK) && ! (info.st_mode & S_IROTH)) allowed = -1;
+ if ((access_mode & W_OK) && ! (info.st_mode & S_IWOTH)) allowed = -1;
+ if (allowed != -1) allowed = 1;
+ }
+ okay = (allowed == 1);
+ }
+ }
}
}
lua_pushboolean(L, okay);
@@ -1021,18 +1249,18 @@ static int filelib_attributes(lua_State *L)
static int filelib_isdir (lua_State *L) { return filelib_check_path_type(L, F_OK, 1); }
static int filelib_isreadabledir (lua_State *L) { return filelib_check_path_type(L, R_OK, 1); }
-static int filelib_iswriteabledir (lua_State *L) { return filelib_check_path_type(L, W_OK, 1); }
+static int filelib_iswritabledir (lua_State *L) { return filelib_check_path_type(L, W_OK, 1); }
static int filelib_isfile (lua_State *L) { return filelib_check_path_type(L, F_OK, 0); }
static int filelib_isreadablefile (lua_State *L) { return filelib_check_path_type(L, R_OK, 0); }
-static int filelib_iswriteablefile(lua_State *L) { return filelib_check_path_type(L, W_OK, 0); }
+static int filelib_iswritablefile (lua_State *L) { return filelib_check_path_type(L, W_OK, 0); }
static int filelib_setexecutable(lua_State *L)
{
int okay = 0;
if (lua_type(L, 1) == LUA_TSTRING) {
const char *name = lua_tostring(L, 1);
- if (name && lmt_valid_target(L, security_writeable, name, security_set_executable)) {
+ if (name && lmt_valid_target(L, security_writable, name, security_set_executable)) {
info_struct info;
if (get_stat(name, &info) && S_ISREG(info.st_mode)) {
okay = ch_to_exec(name, info.st_mode | exec_mode_flag);
@@ -1045,9 +1273,10 @@ static int filelib_setexecutable(lua_State *L)
static int filelib_symlinktarget(lua_State *L)
{
- const char *file = aux_utf8_readlink(luaL_checkstring(L, 1));
+ char *file = aux_utf8_readlink(luaL_checkstring(L, 1));
if (file) {
lua_pushstring(L, file);
+ lmt_memory_free(file);
} else {
lua_pushnil(L);
}
@@ -1056,9 +1285,10 @@ static int filelib_symlinktarget(lua_State *L)
static int filelib_expandpath(lua_State *L)
{
- const char *file = aux_utf8_expandpath(luaL_checkstring(L, 1));
+ char *file = aux_utf8_expandpath(luaL_checkstring(L, 1));
if (file) {
lua_pushstring(L, file);
+ lmt_memory_free(file);
} else {
lua_pushnil(L);
}
@@ -1067,9 +1297,10 @@ static int filelib_expandpath(lua_State *L)
static int filelib_canonicalize(lua_State *L)
{
- const char *file = aux_utf8_canonicalize(luaL_checkstring(L, 1));
+ char *file = aux_utf8_canonicalize(luaL_checkstring(L, 1));
if (file) {
lua_pushstring(L, file);
+ lmt_memory_free(file);
} else {
lua_pushnil(L);
}
@@ -1185,7 +1416,7 @@ int filelib_loadfilex(
static int filelib_setloadshebang(lua_State *L)
{
if (lmt_engine_state.permit_shebang != load_shebang_blocked) {
- int permission = lua_tointeger(L, 1);
+ int permission = lmt_tointeger(L, 1);
switch (permission) {
case load_shebang_disabled:
case load_shebang_enabled:
@@ -1241,20 +1472,35 @@ static const char *filelib_searchpath(
name = luaL_gsub(L, name, sep, dirsep);
}
while (*path != '\0') {
- const char *sub = strchr(path, '?');
+ // const char *sub = strchr(path, '?');
+ // if (sub != NULL) {
+ // luaL_addlstring(&b, path, sub - path);
+ // luaL_addstring(&b, name);
+ // path = sub + 1;
+ // }
+ // const char *next = strchr(path, ';');
+ // if (next == NULL) {
+ // luaL_addstring(&b, path);
+ // path = ""; /* ends the loop on the next iteration */
+ // } else {
+ // luaL_addlstring(&b, path, next - path);
+ // path = next + 1; /* jumps past the semicolon */
+ // }
+ const char *next = strchr(path, ';');
+ size_t templen = next ? (size_t) (next - path) : strlen(path);
+ const char *sub = memchr(path, '?', templen);
if (sub != NULL) {
luaL_addlstring(&b, path, sub - path);
luaL_addstring(&b, name);
- path = sub + 1;
- }
- const char *next = strchr(path, ';');
- if (next == NULL) {
- luaL_addstring(&b, path);
- path = ""; /* ends the loop on the next iteration */
+ luaL_addlstring(&b, sub + 1, (path + templen) - (sub + 1));
} else {
- luaL_addlstring(&b, path, next - path);
- path = next + 1; /* jumps past the semicolon */
+ luaL_addlstring(&b, path, templen);
+ }
+ path += templen;
+ if (*path == ';') {
+ path++;
}
+ /* */
luaL_pushresult(&b);
const char *filename = lua_tostring(L, -1);
# if defined(_WIN32)
@@ -1289,7 +1535,7 @@ static int filelib_package_searcher_file(lua_State *L)
lua_pushfstring(L, "no 'package.path'");
return 1;
} else {
- const char *filename = filelib_searchpath(L, name, lua_tostring(L, -1), "-", "/");
+ const char *filename = filelib_searchpath(L, name, lua_tostring(L, -1), ".", "/");
if (filename == NULL) {
return 1; /* error message */
} else if (filelib_loadfilex(L, filename, "bt") == LUA_OK) {
@@ -1303,28 +1549,74 @@ static int filelib_package_searcher_file(lua_State *L)
/* */
+static int filelib_isready(lua_State *L)
+{
+ const char *filename = luaL_checkstring(L, 1);
+ int ready = 0;
+
+ # if defined(_WIN32)
+
+ // open the file with zero share mode (exclusive lock)
+ HANDLE hFile = CreateFileA(
+ filename,
+ GENERIC_READ | GENERIC_WRITE,
+ 0, // no sharing -> fails if another process has it open
+ NULL,
+ OPEN_EXISTING,
+ FILE_ATTRIBUTE_NORMAL,
+ NULL
+ );
+ if (hFile != INVALID_HANDLE_VALUE) {
+ CloseHandle(hFile);
+ ready = 1;
+ }
+
+ # else
+
+ // try opening for read/write and check for locking/busy errors
+ int fd = open(filename, O_RDWR);
+ if (fd == -1) {
+ // if file exists and opened, check if we can acquire an advisory lock (ensures no one else is writing)
+ if (lockf(fd, F_TLOCK, 0) != -1) {
+ // unlock immediately
+ lockf(fd, F_ULOCK, 0);
+ ready = 1;
+ }
+ close(fd);
+ }
+
+ # endif
+
+ lua_pushboolean(L, ready);
+ return 1;
+}
+
+/* */
+
static const struct luaL_Reg filelib_function_list[] = {
{ "attributes", filelib_attributes },
{ "currentdir", filelib_currentdir },
{ "dir", filelib_dir },
{ "chdir", filelib_chdir }, /* security : readable */
- { "mkdir", filelib_mkdir }, /* security : writeable */
- { "rmdir", filelib_rmdir }, /* security : writeable */
- { "touch", filelib_touch }, /* security : writeable */
+ { "mkdir", filelib_mkdir }, /* security : writable */
+ { "mkdirs", filelib_mkdirs }, /* security : writable */
+ { "rmdir", filelib_rmdir }, /* security : writable */
+ { "touch", filelib_touch }, /* security : writable */
{ "expandpath", filelib_expandpath },
{ "canonicalize", filelib_canonicalize },
/* */
- { "link", filelib_link }, /* security : writeable */
- { "symlink", filelib_symlink }, /* security : writeable */
- { "setexecutable", filelib_setexecutable }, /* security : writeable */
+ { "link", filelib_link }, /* security : writable */
+ { "symlink", filelib_symlink }, /* security : writable */
+ { "setexecutable", filelib_setexecutable }, /* security : writable */
{ "symlinktarget", filelib_symlinktarget },
/* */
{ "isdir", filelib_isdir },
{ "isfile", filelib_isfile },
- { "iswriteabledir", filelib_iswriteabledir }, /* security */
- { "iswriteablefile", filelib_iswriteablefile }, /* security */
+ { "iswritabledir", filelib_iswritabledir }, /* security */
+ { "iswritablefile", filelib_iswritablefile }, /* security */
{ "isreadabledir", filelib_isreadabledir }, /* security */
{ "isreadablefile", filelib_isreadablefile }, /* security */
+ { "isready", filelib_isready },
/* */
{ "lessweird", filelib_lessweird },
{ "moreweird", filelib_moreweird },
@@ -1338,14 +1630,14 @@ int luaopen_filelib(lua_State *L)
{
/* */
lua_pushcfunction(L, filelib_loadfile);
- lua_setglobal(L, "loadfile"); /* security: loadable */
+ lua_setglobal(L, "loadfile"); /* security: loadable */
/* */
lua_pushcfunction(L, filelib_dofile);
- lua_setglobal(L, "dofile"); /* security: loadable */
+ lua_setglobal(L, "dofile"); /* security: loadable */
/* */
lua_getglobal(L, "package");
if (lua_istable(L, -1)) {
- lua_getfield(L, -1, "searchers"); /* security: loadable */
+ lua_getfield(L, -1, "searchers"); /* security: loadable */
if (lua_istable(L, -1)) {
lua_pushvalue(L, -2);
lua_pushcclosure(L, filelib_package_searcher_file, 1);
@@ -1355,7 +1647,7 @@ int luaopen_filelib(lua_State *L)
}
lua_pop(L, 1); // package
/* */
- dir_create_meta(L);
+ dir_create_metatable(L);
luaL_newlib(L, filelib_function_list);
return 1;
}
diff --git a/source/luametatex/source/luarest/lmtiolibext.c b/source/luametatex/source/luarest/lmtiolibext.c
index 91e93284d..fc78118dd 100644
--- a/source/luametatex/source/luarest/lmtiolibext.c
+++ b/source/luametatex/source/luarest/lmtiolibext.c
@@ -48,6 +48,26 @@
# define uchar(c) ((unsigned char)(c))
+static inline int8_t siolib_signed8(uint32_t n)
+{
+ return (n & 0x80u) ? (int8_t) ((int32_t) n - 0x100) : (int8_t) n;
+}
+
+static inline int16_t siolib_signed16(uint32_t n)
+{
+ return (n & 0x8000u) ? (int16_t) ((int32_t) n - 0x10000) : (int16_t) n;
+}
+
+static inline int32_t siolib_signed24(uint32_t n)
+{
+ return (n & 0x800000u) ? (int32_t) n - 0x1000000 : (int32_t) n;
+}
+
+static inline int32_t siolib_signed32(uint32_t n)
+{
+ return (n & 0x80000000u) ? (int32_t) ((int64_t) n - INT64_C(0x100000000)) : (int32_t) n;
+}
+
/*tex
We can delegate some management to here (the stream code in \CONTEXT) so let's do that
@@ -77,16 +97,19 @@ static const char * siolib_okay(lua_State *L, int len, size_t *p, size_t *l, int
const char *s = lua_tolstring(L, -1, &ls);
lua_pop(L, 1);
if (lua_rawgeti(L, 1, 2) == LUA_TNUMBER) {
- *p = lua_tointeger(L, -1) - 1;
+ lua_Integer position = lua_tointeger(L, -1);
lua_pop(L, 1);
- lua_pushinteger(L, *p + len + 1);
- lua_rawseti(L, 1, 2);
- if (l) {
- /* checking happens elsewhere */
- *l = ls;
- return s;
- } else if ((*p + 1) < ls) {
- return s;
+ if (position >= 1 && (uintmax_t) (position - 1) <= (uintmax_t) ls) {
+ *p = (size_t) (position - 1);
+ if (l) {
+ /* checking happens elsewhere */
+ *l = ls;
+ return s;
+ } else if (len >= 0 && (size_t) len <= (ls - *p)) {
+ lua_pushinteger(L, (lua_Integer) (*p + (size_t) len + 1));
+ lua_rawseti(L, 1, 2);
+ return s;
+ }
}
} else {
lua_pop(L, 1);
@@ -102,12 +125,15 @@ static const char * siolib_okay(lua_State *L, int len, size_t *p, size_t *l, int
if (lua_type(L, 2) == LUA_TNUMBER) {
size_t ls = 0;
const char *s = lua_tolstring(L, 1, &ls);
- *p = lua_tointeger(L, 2) - 1;
- if (l) {
- *l = ls;
- }
- if ((*p + 1) < ls) {
- return s;
+ lua_Integer position = lua_tointeger(L, 2);
+ if (position >= 1 && (uintmax_t) (position - 1) <= (uintmax_t) ls) {
+ *p = (size_t) (position - 1);
+ if (l) {
+ *l = ls;
+ return s;
+ } else if (len >= 0 && (size_t) len <= (ls - *p)) {
+ return s;
+ }
}
}
break;
@@ -145,7 +171,7 @@ static int fiolib_readcardinal1(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer a = getc(f);
+ int a = getc(f);
if (a == EOF) {
lua_pushnil(L);
} else {
@@ -174,13 +200,15 @@ static int fiolib_readcardinal2(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer a = getc(f);
- lua_Integer b = getc(f);
- if (b == EOF) {
- lua_pushnil(L);
- } else {
- lua_pushinteger(L, (a << 8) | b);
+ int a = getc(f);
+ if (a != EOF) {
+ int b = getc(f);
+ if (b != EOF) {
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 8) | (uint32_t) b));
+ return 1;
+ }
}
+ lua_pushnil(L);
return 1;
} else {
return 0;
@@ -191,13 +219,15 @@ static int fiolib_readcardinal2_le(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer b = getc(f);
- lua_Integer a = getc(f);
- if (a == EOF) {
- lua_pushnil(L);
- } else {
- lua_pushinteger(L, (a << 8) | b);
+ int b = getc(f);
+ if (b != EOF) {
+ int a = getc(f);
+ if (a != EOF) {
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 8) | (uint32_t) b));
+ return 1;
+ }
}
+ lua_pushnil(L);
return 1;
} else {
return 0;
@@ -211,7 +241,7 @@ static int siolib_readcardinal2(lua_State *L)
if (s) {
lua_Integer a = uchar(s[p++]);
lua_Integer b = uchar(s[p]);
- lua_pushinteger(L, (a << 8) | b);
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 8) | (uint32_t) b));
} else {
lua_pushnil(L);
}
@@ -223,9 +253,9 @@ static int siolib_readcardinal2_le(lua_State *L)
size_t p;
const char *s = siolib_okay(L, 2, &p, NULL, NULL);
if (s) {
- lua_Integer b = uchar(s[p]);
- lua_Integer a = uchar(s[p++]);
- lua_pushinteger(L, (a << 8) | b);
+ lua_Integer b = uchar(s[p++]);
+ lua_Integer a = uchar(s[p]);
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 8) | (uint32_t) b));
} else {
lua_pushnil(L);
}
@@ -236,14 +266,18 @@ static int fiolib_readcardinal3(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer a = getc(f);
- lua_Integer b = getc(f);
- lua_Integer c = getc(f);
- if (c == EOF) {
- lua_pushnil(L);
- } else {
- lua_pushinteger(L, (a << 16) | (b << 8) | c);
+ int a = getc(f);
+ if (a != EOF) {
+ int b = getc(f);
+ if (b != EOF) {
+ int c = getc(f);
+ if (c != EOF) {
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 16) | ((uint32_t) b << 8) | (uint32_t) c));
+ return 1;
+ }
+ }
}
+ lua_pushnil(L);
return 1;
} else {
return 0;
@@ -254,14 +288,18 @@ static int fiolib_readcardinal3_le(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer c = getc(f);
- lua_Integer b = getc(f);
- lua_Integer a = getc(f);
- if (a == EOF) {
- lua_pushnil(L);
- } else {
- lua_pushinteger(L, (a << 16) | (b << 8) | c);
+ int c = getc(f);
+ if (c != EOF) {
+ int b = getc(f);
+ if (b != EOF) {
+ int a = getc(f);
+ if (a != EOF) {
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 16) | ((uint32_t) b << 8) | (uint32_t) c));
+ return 1;
+ }
+ }
}
+ lua_pushnil(L);
return 1;
} else {
return 0;
@@ -276,7 +314,7 @@ static int siolib_readcardinal3(lua_State *L)
lua_Integer a = uchar(s[p++]);
lua_Integer b = uchar(s[p++]);
lua_Integer c = uchar(s[p]);
- lua_pushinteger(L, (a << 16) | (b << 8) | c);
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 16) | ((uint32_t) b << 8) | (uint32_t) c));
} else {
lua_pushnil(L);
}
@@ -291,7 +329,7 @@ static int siolib_readcardinal3_le(lua_State *L)
lua_Integer c = uchar(s[p++]);
lua_Integer b = uchar(s[p++]);
lua_Integer a = uchar(s[p]);
- lua_pushinteger(L, (a << 16) | (b << 8) | c);
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 16) | ((uint32_t) b << 8) | (uint32_t) c));
} else {
lua_pushnil(L);
}
@@ -302,15 +340,21 @@ static int fiolib_readcardinal4(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer a = getc(f);
- lua_Integer b = getc(f);
- lua_Integer c = getc(f);
- lua_Integer d = getc(f);
- if (d == EOF) {
- lua_pushnil(L);
- } else {
- lua_pushinteger(L, (a << 24) | (b << 16) | (c << 8) | d);
+ int a = getc(f);
+ if (a != EOF) {
+ int b = getc(f);
+ if (b != EOF) {
+ int c = getc(f);
+ if (c != EOF) {
+ int d = getc(f);
+ if (d != EOF) {
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d));
+ return 1;
+ }
+ }
+ }
}
+ lua_pushnil(L);
return 1;
} else {
return 0;
@@ -321,15 +365,21 @@ static int fiolib_readcardinal4_le(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer d = getc(f);
- lua_Integer c = getc(f);
- lua_Integer b = getc(f);
- lua_Integer a = getc(f);
- if (a == EOF) {
- lua_pushnil(L);
- } else {
- lua_pushinteger(L, (a << 24) | (b << 16) | (c << 8) | d);
+ int d = getc(f);
+ if (d != EOF) {
+ int c = getc(f);
+ if (c != EOF) {
+ int b = getc(f);
+ if (b != EOF) {
+ int a = getc(f);
+ if (a != EOF) {
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d));
+ return 1;
+ }
+ }
+ }
}
+ lua_pushnil(L);
return 1;
} else {
return 0;
@@ -345,7 +395,7 @@ static int siolib_readcardinal4(lua_State *L)
lua_Integer b = uchar(s[p++]);
lua_Integer c = uchar(s[p++]);
lua_Integer d = uchar(s[p]);
- lua_pushinteger(L, (a << 24) | (b << 16) | (c << 8) | d);
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d));
} else {
lua_pushnil(L);
}
@@ -361,7 +411,7 @@ static int siolib_readcardinal4_le(lua_State *L)
lua_Integer c = uchar(s[p++]);
lua_Integer b = uchar(s[p++]);
lua_Integer a = uchar(s[p]);
- lua_pushinteger(L, (a << 24) | (b << 16) | (c << 8) | d);
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d));
} else {
lua_pushnil(L);
}
@@ -378,7 +428,7 @@ static int fiolib_readcardinaltable(lua_State *L)
switch (m) {
case 1:
for (lua_Integer i = 1; i <= n; i++) {
- lua_Integer a = getc(f);
+ int a = getc(f);
if (a == EOF) {
break;
} else {
@@ -389,41 +439,38 @@ static int fiolib_readcardinaltable(lua_State *L)
break;
case 2:
for (lua_Integer i = 1; i <= n; i++) {
- lua_Integer a = getc(f);
- lua_Integer b = getc(f);
- if (b == EOF) {
- break;
- } else {
- lua_pushinteger(L, (a << 8) | b);
- lua_rawseti(L, -2, i);
- }
+ int a = getc(f);
+ if (a == EOF) break;
+ int b = getc(f);
+ if (b == EOF) break;
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 8) | (uint32_t) b));
+ lua_rawseti(L, -2, i);
}
break;
case 3:
for (lua_Integer i = 1; i <= n; i++) {
- lua_Integer a = getc(f);
- lua_Integer b = getc(f);
- lua_Integer c = getc(f);
- if (c == EOF) {
- break;
- } else {
- lua_pushinteger(L, (a << 16) | (b << 8) | c);
- lua_rawseti(L, -2, i);
- }
+ int a = getc(f);
+ if (a == EOF) break;
+ int b = getc(f);
+ if (b == EOF) break;
+ int c = getc(f);
+ if (c == EOF) break;
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 16) | ((uint32_t) b << 8) | (uint32_t) c));
+ lua_rawseti(L, -2, i);
}
break;
case 4:
for (lua_Integer i = 1; i <= n; i++) {
- lua_Integer a = getc(f);
- lua_Integer b = getc(f);
- lua_Integer c = getc(f);
- lua_Integer d = getc(f);
- if (d == EOF) {
- break;
- } else {
- lua_pushinteger(L, (a << 24) | (b << 16) | (c << 8) | d);
- lua_rawseti(L, -2, i);
- }
+ int a = getc(f);
+ if (a == EOF) break;
+ int b = getc(f);
+ if (b == EOF) break;
+ int c = getc(f);
+ if (c == EOF) break;
+ int d = getc(f);
+ if (d == EOF) break;
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d));
+ lua_rawseti(L, -2, i);
}
break;
default:
@@ -438,6 +485,7 @@ static int fiolib_readcardinaltable(lua_State *L)
static int siolib_readcardinaltable(lua_State *L)
{
size_t p, l;
+ size_t start;
int mode;
const char *s = siolib_okay(L, 0, &p, &l, &mode);
/*tex We need to know the mode so we delay updating the advance. */
@@ -445,6 +493,7 @@ static int siolib_readcardinaltable(lua_State *L)
lua_Integer m = lua_tointeger(L, mode == mode_table ? 3 : 4);
lua_createtable(L, (int) n, 0);
if (s) {
+ start = p;
switch (m) {
case 1:
for (lua_Integer i = 1; i <= n; i++) {
@@ -459,39 +508,39 @@ static int siolib_readcardinaltable(lua_State *L)
break;
case 2:
for (lua_Integer i = 1; i <= n; i++) {
- if ((p + 1) >= l) {
+ if (l - p < 2) {
break;
} else {
lua_Integer a = uchar(s[p++]);
lua_Integer b = uchar(s[p++]);
- lua_pushinteger(L, (a << 8) | b);
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 8) | (uint32_t) b));
lua_rawseti(L, -2, i);
}
}
break;
case 3:
for (lua_Integer i = 1; i <= n; i++) {
- if ((p + 2) >= l) {
+ if (l - p < 3) {
break;
} else {
lua_Integer a = uchar(s[p++]);
lua_Integer b = uchar(s[p++]);
lua_Integer c = uchar(s[p++]);
- lua_pushinteger(L, (a << 16) | (b << 8) | c);
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 16) | ((uint32_t) b << 8) | (uint32_t) c));
lua_rawseti(L, -2, i);
}
}
break;
case 4:
for (lua_Integer i = 1; i <= n; i++) {
- if ((p + 3) >= l) {
+ if (l - p < 4) {
break;
} else {
lua_Integer a = uchar(s[p++]);
lua_Integer b = uchar(s[p++]);
lua_Integer c = uchar(s[p++]);
lua_Integer d = uchar(s[p++]);
- lua_pushinteger(L, (a << 24) | (b << 16) | (c << 8) | d);
+ lua_pushinteger(L, (lua_Integer) (((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d));
lua_rawseti(L, -2, i);
}
}
@@ -499,7 +548,7 @@ static int siolib_readcardinaltable(lua_State *L)
default:
break;
}
- siolib_done(L, mode, n * m);
+ siolib_done(L, mode, (lua_Integer) (p - start));
}
return 1;
}
@@ -508,11 +557,11 @@ static int fiolib_readinteger1(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer a = getc(f);
+ int a = getc(f);
if (a == EOF) {
lua_pushnil(L);
} else {
- lua_pushinteger(L, (int8_t) a);
+ lua_pushinteger(L, siolib_signed8((uint32_t) a));
}
return 1;
} else {
@@ -526,7 +575,7 @@ static int siolib_readinteger1(lua_State *L)
const char *s = siolib_okay(L, 1, &p, NULL, NULL);
if (s) {
lua_Integer a = uchar(s[p]);
- lua_pushinteger(L, (int8_t) a);
+ lua_pushinteger(L, siolib_signed8((uint32_t) a));
} else {
lua_pushnil(L);
}
@@ -537,13 +586,15 @@ static int fiolib_readinteger2(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer a = getc(f);
- lua_Integer b = getc(f);
- if (b == EOF) {
- lua_pushnil(L);
- } else {
- lua_pushinteger(L, (int16_t) ((a << 8) | b));
+ int a = getc(f);
+ if (a != EOF) {
+ int b = getc(f);
+ if (b != EOF) {
+ lua_pushinteger(L, siolib_signed16(((uint32_t) a << 8) | (uint32_t) b));
+ return 1;
+ }
}
+ lua_pushnil(L);
return 1;
} else {
return 0;
@@ -554,13 +605,15 @@ static int fiolib_readinteger2_le(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer b = getc(f);
- lua_Integer a = getc(f);
- if (a == EOF) {
- lua_pushnil(L);
- } else {
- lua_pushinteger(L, (int16_t) ((a << 8) | b));
+ int b = getc(f);
+ if (b != EOF) {
+ int a = getc(f);
+ if (a != EOF) {
+ lua_pushinteger(L, siolib_signed16(((uint32_t) a << 8) | (uint32_t) b));
+ return 1;
+ }
}
+ lua_pushnil(L);
return 1;
} else {
return 0;
@@ -574,7 +627,7 @@ static int siolib_readinteger2(lua_State *L)
if (s) {
lua_Integer a = uchar(s[p++]);
lua_Integer b = uchar(s[p]);
- lua_pushinteger(L, (int16_t) ((a << 8) | b));
+ lua_pushinteger(L, siolib_signed16(((uint32_t) a << 8) | (uint32_t) b));
} else {
lua_pushnil(L);
}
@@ -588,7 +641,7 @@ static int siolib_readinteger2_le(lua_State *L)
if (s) {
lua_Integer b = uchar(s[p++]);
lua_Integer a = uchar(s[p]);
- lua_pushinteger(L, (int16_t) ((a << 8) | b));
+ lua_pushinteger(L, siolib_signed16(((uint32_t) a << 8) | (uint32_t) b));
} else {
lua_pushnil(L);
}
@@ -599,15 +652,19 @@ static int fiolib_readinteger3(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer a = getc(f);
- lua_Integer b = getc(f);
- lua_Integer c = getc(f);
- if (c == EOF) {
- lua_pushnil(L);
- } else {
- int32_t n = (int32_t) ((a << 24) | (b << 16) | (c << 8)) >> 8;
- lua_pushinteger(L, n);
+ int a = getc(f);
+ if (a != EOF) {
+ int b = getc(f);
+ if (b != EOF) {
+ int c = getc(f);
+ if (c != EOF) {
+ uint32_t u = ((uint32_t) a << 16) | ((uint32_t) b << 8) | (uint32_t) c;
+ lua_pushinteger(L, siolib_signed24(u));
+ return 1;
+ }
+ }
}
+ lua_pushnil(L);
return 1;
} else {
return 0;
@@ -618,15 +675,19 @@ static int fiolib_readinteger3_le(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer c = getc(f);
- lua_Integer b = getc(f);
- lua_Integer a = getc(f);
- if (a == EOF) {
- lua_pushnil(L);
- } else {
- int32_t n = (int32_t) ((a << 24) | (b << 16) | (c << 8)) >> 8;
- lua_pushinteger(L, n);
+ int c = getc(f);
+ if (c != EOF) {
+ int b = getc(f);
+ if (b != EOF) {
+ int a = getc(f);
+ if (a != EOF) {
+ uint32_t u = ((uint32_t) a << 16) | ((uint32_t) b << 8) | (uint32_t) c;
+ lua_pushinteger(L, siolib_signed24(u));
+ return 1;
+ }
+ }
}
+ lua_pushnil(L);
return 1;
} else {
return 0;
@@ -638,12 +699,10 @@ static int siolib_readinteger3(lua_State *L)
size_t p;
const char *s = siolib_okay(L, 3, &p, NULL, NULL);
if (s) {
- lua_Integer a = uchar(s[p++]);
- lua_Integer b = uchar(s[p++]);
- lua_Integer c = uchar(s[p]);
- // Shift to bit 31, then arithmetic right-shift back to bit 0
- int32_t n = (int32_t) ((a << 24) | (b << 16) | (c << 8)) >> 8;
- lua_pushinteger(L, n);
+ uint32_t a = uchar(s[p++]);
+ uint32_t b = uchar(s[p++]);
+ uint32_t c = uchar(s[p]);
+ lua_pushinteger(L, siolib_signed24((a << 16) | (b << 8) | c));
} else {
lua_pushnil(L);
}
@@ -655,11 +714,10 @@ static int siolib_readinteger3_le(lua_State *L)
size_t p;
const char *s = siolib_okay(L, 3, &p, NULL, NULL);
if (s) {
- lua_Integer c = uchar(s[p++]);
- lua_Integer b = uchar(s[p++]);
- lua_Integer a = uchar(s[p]);
- int32_t n = (int32_t) ((a << 24) | (b << 16) | (c << 8)) >> 8;
- lua_pushinteger(L, n);
+ uint32_t c = uchar(s[p++]);
+ uint32_t b = uchar(s[p++]);
+ uint32_t a = uchar(s[p]);
+ lua_pushinteger(L, siolib_signed24((a << 16) | (b << 8) | c));
} else {
lua_pushnil(L);
}
@@ -670,16 +728,21 @@ static int fiolib_readinteger4(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer a = getc(f);
- lua_Integer b = getc(f);
- lua_Integer c = getc(f);
- lua_Integer d = getc(f);
- if (d == EOF) {
- lua_pushnil(L);
- } else {
- int32_t n = (int32_t) (((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d);
- lua_pushinteger(L, n);
+ int a = getc(f);
+ if (a != EOF) {
+ int b = getc(f);
+ if (b != EOF) {
+ int c = getc(f);
+ if (c != EOF) {
+ int d = getc(f);
+ if (d != EOF) {
+ lua_pushinteger(L, siolib_signed32(((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d));
+ return 1;
+ }
+ }
+ }
}
+ lua_pushnil(L);
return 1;
} else {
return 0;
@@ -690,16 +753,21 @@ static int fiolib_readinteger4_le(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer d = getc(f);
- lua_Integer c = getc(f);
- lua_Integer b = getc(f);
- lua_Integer a = getc(f);
- if (a == EOF) {
- lua_pushnil(L);
- } else {
- int32_t n = (int32_t) (((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d);
- lua_pushinteger(L, n);
+ int d = getc(f);
+ if (d != EOF) {
+ int c = getc(f);
+ if (c != EOF) {
+ int b = getc(f);
+ if (b != EOF) {
+ int a = getc(f);
+ if (a != EOF) {
+ lua_pushinteger(L, siolib_signed32(((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d));
+ return 1;
+ }
+ }
+ }
}
+ lua_pushnil(L);
return 1;
} else {
return 0;
@@ -715,8 +783,7 @@ static int siolib_readinteger4(lua_State *L)
lua_Integer b = uchar(s[p++]);
lua_Integer c = uchar(s[p++]);
lua_Integer d = uchar(s[p]);
- int32_t n = (int32_t) (((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d);
- lua_pushinteger(L, n);
+ lua_pushinteger(L, siolib_signed32(((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d));
} else {
lua_pushnil(L);
}
@@ -732,8 +799,7 @@ static int siolib_readinteger4_le(lua_State *L)
lua_Integer c = uchar(s[p++]);
lua_Integer b = uchar(s[p++]);
lua_Integer a = uchar(s[p]);
- int32_t n = (int32_t) (((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d);
- lua_pushinteger(L, n);
+ lua_pushinteger(L, siolib_signed32(((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d));
} else {
lua_pushnil(L);
}
@@ -750,53 +816,49 @@ static int fiolib_readintegertable(lua_State *L)
switch (m) {
case 1:
for (lua_Integer i = 1; i <= n; i++) {
- lua_Integer a = getc(f);
+ int a = getc(f);
if (a == EOF) {
break;
} else {
- lua_pushinteger(L, (int8_t) a);
+ lua_pushinteger(L, siolib_signed8((uint32_t) a));
+ lua_rawseti(L, -2, i);
}
- lua_rawseti(L, -2, i);
}
break;
case 2:
for (lua_Integer i = 1; i <= n; i++) {
- lua_Integer a = getc(f);
- lua_Integer b = getc(f);
- if (b == EOF) {
- break;
- } else {
- lua_pushinteger(L, (int16_t) ((a << 8) | b));
- }
+ int a = getc(f);
+ if (a == EOF) break;
+ int b = getc(f);
+ if (b == EOF) break;
+ lua_pushinteger(L, siolib_signed16(((uint32_t) a << 8) | (uint32_t) b));
lua_rawseti(L, -2, i);
}
break;
case 3:
for (lua_Integer i = 1; i <= n; i++) {
- lua_Integer a = getc(f);
- lua_Integer b = getc(f);
- lua_Integer c = getc(f);
- if (c == EOF) {
- break;
- } else {
- int32_t val = (int32_t) ((a << 24) | (b << 16) | (c << 8)) >> 8;
- lua_pushinteger(L, val);
- }
+ int a = getc(f);
+ if (a == EOF) break;
+ int b = getc(f);
+ if (b == EOF) break;
+ int c = getc(f);
+ if (c == EOF) break;
+ uint32_t u = ((uint32_t) a << 16) | ((uint32_t) b << 8) | (uint32_t) c;
+ lua_pushinteger(L, siolib_signed24(u));
lua_rawseti(L, -2, i);
}
break;
case 4:
for (lua_Integer i = 1; i <= n; i++) {
- lua_Integer a = getc(f);
- lua_Integer b = getc(f);
- lua_Integer c = getc(f);
- lua_Integer d = getc(f);
- if (d == EOF) {
- break;
- } else {
- int32_t val = (int32_t) (((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d);
- lua_pushinteger(L, val);
- }
+ int a = getc(f);
+ if (a == EOF) break;
+ int b = getc(f);
+ if (b == EOF) break;
+ int c = getc(f);
+ if (c == EOF) break;
+ int d = getc(f);
+ if (d == EOF) break;
+ lua_pushinteger(L, siolib_signed32(((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d));
lua_rawseti(L, -2, i);
}
break;
@@ -812,126 +874,88 @@ static int fiolib_readintegertable(lua_State *L)
static int siolib_readintegertable(lua_State *L)
{
size_t p, l;
+ size_t start;
int mode;
const char *s = siolib_okay(L, 0, &p, &l, &mode);
/*tex We need to know the mode so we delay updating the advance. */
lua_Integer n = lua_tointeger(L, mode == mode_table ? 2 : 3);
- lua_Integer m = lua_tointeger(L, mode == mode_table ? 1 : 4);
+ lua_Integer m = lua_tointeger(L, mode == mode_table ? 3 : 4);
lua_createtable(L, (int) n, 0);
- switch (m) {
- case 1:
- for (lua_Integer i = 1; i <= n; i++) {
- if (p >= l) {
- break;
- } else {
- lua_Integer a = uchar(s[p++]);
- lua_pushinteger(L, (int8_t) a);
- lua_rawseti(L, -2, i);
+ if (s) {
+ start = p;
+ switch (m) {
+ case 1:
+ for (lua_Integer i = 1; i <= n; i++) {
+ if (p >= l) {
+ break;
+ } else {
+ lua_Integer a = uchar(s[p++]);
+ lua_pushinteger(L, siolib_signed8((uint32_t) a));
+ lua_rawseti(L, -2, i);
+ }
}
- }
- break;
- case 2:
- for (lua_Integer i = 1; i <= n; i++) {
- if ((p + 1) >= l) {
- break;
- } else {
- lua_Integer a = uchar(s[p++]);
- lua_Integer b = uchar(s[p++]);
- lua_pushinteger(L, (int16_t) ((a << 8) | b));
- lua_rawseti(L, -2, i);
+ break;
+ case 2:
+ for (lua_Integer i = 1; i <= n; i++) {
+ if (l - p < 2) {
+ break;
+ } else {
+ lua_Integer a = uchar(s[p++]);
+ lua_Integer b = uchar(s[p++]);
+ lua_pushinteger(L, siolib_signed16(((uint32_t) a << 8) | (uint32_t) b));
+ lua_rawseti(L, -2, i);
+ }
}
- }
- break;
- case 3:
- for (lua_Integer i = 1; i <= n; i++) {
- if ((p + 2) >= l) {
- break;
- } else {
- lua_Integer a = uchar(s[p++]);
- lua_Integer b = uchar(s[p++]);
- lua_Integer c = uchar(s[p++]);
- int32_t val = (int32_t) ((a << 24) | (b << 16) | (c << 8)) >> 8;
- lua_pushinteger(L, val);
- lua_rawseti(L, -2, i);
+ break;
+ case 3:
+ for (lua_Integer i = 1; i <= n; i++) {
+ if (l - p < 3) {
+ break;
+ } else {
+ uint32_t a = uchar(s[p++]);
+ uint32_t b = uchar(s[p++]);
+ uint32_t c = uchar(s[p++]);
+ lua_pushinteger(L, siolib_signed24((a << 16) | (b << 8) | c));
+ lua_rawseti(L, -2, i);
+ }
}
- }
- break;
- case 4:
- for (lua_Integer i = 1; i <= n; i++) {
- if ((p + 3) >= l) {
- break;
- } else {
- lua_Integer a = uchar(s[p++]);
- lua_Integer b = uchar(s[p++]);
- lua_Integer c = uchar(s[p++]);
- lua_Integer d = uchar(s[p++]);
- int32_t val = (int32_t) (((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d);
- lua_pushinteger(L, val);
- lua_rawseti(L, -2, i);
+ break;
+ case 4:
+ for (lua_Integer i = 1; i <= n; i++) {
+ if (l - p < 4) {
+ break;
+ } else {
+ lua_Integer a = uchar(s[p++]);
+ lua_Integer b = uchar(s[p++]);
+ lua_Integer c = uchar(s[p++]);
+ lua_Integer d = uchar(s[p++]);
+ lua_pushinteger(L, siolib_signed32(((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d));
+ lua_rawseti(L, -2, i);
+ }
}
- }
- break;
- default:
- break;
+ break;
+ default:
+ break;
+ }
+ siolib_done(L, mode, (lua_Integer) (p - start));
}
- siolib_done(L, mode, n * m);
return 1;
}
-/* from ff */
-
-/*
-
- signed :
-
- // assemble bytes into a signed 16-bit integer/
- int16_t n = (int16_t)((a << 8) | b);
- // direct division by 256.0 handles integer and fractional parts together
- lua_pushnumber(L, (double) n / 256.0);
-
- unsigned :
-
- // assemble bytes into an unsigned 16-bit integer
- uint16_t n = (uint16_t)((a << 8) | b);
- lua_pushnumber(L, (double) n / 256.0);
-
-*/
-
-// static int fiolib_readfixed2_unsigned(lua_State *L)
-// {
-// FILE *f = lmt_valid_file(L);
-// if (f) {
-// int a = getc(f);
-// int b = getc(f);
-// if (b == EOF) {
-// lua_pushnil(L);
-// } else {
-// /* assemble bytes into an unsigned 16-bit integer */
-// uint16_t n = (uint16_t) ((a << 8) | b);
-// lua_pushnumber(L, (double) n / 256.0);
-// }
-// return 1;
-// } else {
-// return 0;
-// }
-// }
-
static int fiolib_readfixed2(lua_State *L) // signed
{
FILE *f = lmt_valid_file(L);
if (f) {
int a = getc(f);
- int b = getc(f);
- if (b == EOF) {
- lua_pushnil(L);
- } else {
- // int n = (a << 8) | b; /* really an int because we shift */
- // lua_pushnumber(L, (double) ((n >> 8) + ((n & 0xFF) / 256.0)));
- /* assemble bytes into a signed 16-bit integer */
- int16_t n = (int16_t) ((a << 8) | b);
- /* direct division by 256.0 handles integer and fractional parts together */
- lua_pushnumber(L, (double) n / 256.0);
+ if (a != EOF) {
+ int b = getc(f);
+ if (b != EOF) {
+ int16_t n = siolib_signed16(((uint32_t) a << 8) | (uint32_t) b);
+ lua_pushnumber(L, (double) n / 256.0);
+ return 1;
+ }
}
+ lua_pushnil(L);
return 1;
} else {
return 0;
@@ -945,10 +969,7 @@ static int siolib_readfixed2(lua_State *L) // signed
if (s) {
int a = uchar(s[p++]);
int b = uchar(s[p]);
- // int n = (a << 8) | b; /* really an int because we shift */
- // lua_pushnumber(L, (double) ((n >> 8) + ((n & 0xFF) / 256.0)));
- int16_t n = (int16_t) ((a << 8) | b);
- /* direct division by 256.0 handles integer and fractional parts together */
+ int16_t n = siolib_signed16(((uint32_t) a << 8) | (uint32_t) b);
lua_pushnumber(L, (double) n / 256.0);
} else {
lua_pushnil(L);
@@ -956,46 +977,27 @@ static int siolib_readfixed2(lua_State *L) // signed
return 1;
}
-// static int fiolib_readfixed4_unsigned(lua_State *L)
-// {
-// FILE *f = lmt_valid_file(L);
-// if (f) {
-// int a = getc(f);
-// int b = getc(f);
-// int c = getc(f);
-// int d = getc(f);
-// if (d == EOF) {
-// lua_pushnil(L);
-// } else {
-// uint32_t u = ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d;
-// lua_pushnumber(L, (double) u / 65536.0);
-// }
-// return 1;
-// } else {
-// return 0;
-// }
-// }
-
static int fiolib_readfixed4(lua_State *L) // signed
{
FILE *f = lmt_valid_file(L);
if (f) {
int a = getc(f);
- int b = getc(f);
- int c = getc(f);
- int d = getc(f);
- if (d == EOF) {
- lua_pushnil(L);
- } else {
- // int n = (a << 24) | (b << 16) | (c << 8) | d; /* really an int because we shift */
- // lua_pushnumber(L, (double) ((n >> 16) + ((n & 0xFFFF) / 65536.0)));
- /* assemble using uint32_t to safely prevent undefined behavior during shifting */
- uint32_t u = ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d;
- /* cast to signed int32_t to correctly preserve two's complement negative values */
- int32_t n = (int32_t) u;
- /* dividing the entire 32-bit signed value by 65536.0 correctly converts integer & fraction */
- lua_pushnumber(L, (double) n / 65536.0);
+ if (a != EOF) {
+ int b = getc(f);
+ if (b != EOF) {
+ int c = getc(f);
+ if (c != EOF) {
+ int d = getc(f);
+ if (d != EOF) {
+ uint32_t u = ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d;
+ int32_t n = siolib_signed32(u);
+ lua_pushnumber(L, (double) n / 65536.0);
+ return 1;
+ }
+ }
+ }
}
+ lua_pushnil(L);
return 1;
} else {
return 0;
@@ -1011,13 +1013,8 @@ static int siolib_readfixed4(lua_State *L)
int b = uchar(s[p++]);
int c = uchar(s[p++]);
int d = uchar(s[p]);
- // int n = (a << 24) | (b << 16) | (c << 8) | d; /* really an int because we shift */
- // lua_pushnumber(L, (double) ((n >> 16) + ((n & 0xFFFF) / 65536.0)));
- /* assemble using uint32_t to safely prevent undefined behavior during shifting */
uint32_t u = ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | (uint32_t) d;
- /* cast to signed int32_t to correctly preserve two's complement negative values */
- int32_t n = (int32_t) u;
- /* dividing the entire 32-bit signed value by 65536.0 correctly converts integer & fraction */
+ int32_t n = siolib_signed32(u);
lua_pushnumber(L, (double) n / 65536.0);
} else {
lua_pushnil(L);
@@ -1030,17 +1027,15 @@ static int fiolib_read2dot14(lua_State *L)
FILE *f = lmt_valid_file(L);
if (f) {
int a = getc(f);
- int b = getc(f);
- if (b == EOF) {
- lua_pushnil(L);
- } else {
- // int n = (a << 8) | b; /* really an int because we shift */
- // lua_pushnumber(L, (double) (((n << 16) >> (16 + 14)) + ((n & 0x3FFF) / 16384.0)));
- /* assemble bytes and cast to signed 16-bit integer */
- int16_t n = (int16_t) ((a << 8) | b);
- /* dividing by 16384.0 (2^14) converts both integer and fractional parts seamlessly */
- lua_pushnumber(L, (double) n / 16384.0);
+ if (a != EOF) {
+ int b = getc(f);
+ if (b != EOF) {
+ int16_t n = siolib_signed16(((uint32_t) a << 8) | (uint32_t) b);
+ lua_pushnumber(L, (double) n / 16384.0);
+ return 1;
+ }
}
+ lua_pushnil(L);
return 1;
} else {
return 0;
@@ -1050,15 +1045,11 @@ static int fiolib_read2dot14(lua_State *L)
static int siolib_read2dot14(lua_State *L)
{
size_t p;
- const char *s = siolib_okay(L, 4, &p, NULL, NULL);
+ const char *s = siolib_okay(L, 2, &p, NULL, NULL);
if (s) {
int a = uchar(s[p++]);
int b = uchar(s[p]);
- // int n = (a << 8) | b; /* really an int because we shift */
- // lua_pushnumber(L, (double) (((n << 16) >> (16 + 14)) + ((n & 0x3FFF) / 16384.0)));
- /* assemble bytes and cast to signed 16-bit integer */
- int16_t n = (int16_t) ((a << 8) | b);
- /* dividing by 16384.0 (2^14) converts both integer and fractional parts seamlessly */
+ int16_t n = siolib_signed16(((uint32_t) a << 8) | (uint32_t) b);
lua_pushnumber(L, (double) n / 16384.0);
} else {
lua_pushnil(L);
@@ -1088,24 +1079,48 @@ static inline void copywithendian(char *dest, const char *src, unsigned size, in
}
}
-static inline void readwithendian4(char *dest, FILE *f, int islittle) /* taken from lua */
+static inline int readwithendian4(char *dest, FILE *f, int islittle) /* taken from lua */
{
if (islittle == nativeendian.little) {
- dest[0] = (char) getc(f); dest[1] = (char) getc(f); dest[2] = (char) getc(f); dest[3] = (char) getc(f);
+ for (unsigned i = 0; i < 4; i++) {
+ int c = getc(f);
+ if (c == EOF) {
+ return 0;
+ }
+ dest[i] = (char) c;
+ }
} else {
- dest[3] = (char) getc(f); dest[2] = (char) getc(f); dest[1] = (char) getc(f); dest[0] = (char) getc(f);
+ for (unsigned i = 0; i < 4; i++) {
+ int c = getc(f);
+ if (c == EOF) {
+ return 0;
+ }
+ dest[3 - i] = (char) c;
+ }
}
+ return 1;
}
-static inline void readwithendian8(char *dest, FILE *f, int islittle) /* taken from lua */
+static inline int readwithendian8(char *dest, FILE *f, int islittle) /* taken from lua */
{
if (islittle == nativeendian.little) {
- dest[0] = (char) getc(f); dest[1] = (char) getc(f); dest[2] = (char) getc(f); dest[3] = (char) getc(f);
- dest[4] = (char) getc(f); dest[5] = (char) getc(f); dest[6] = (char) getc(f); dest[7] = (char) getc(f);
+ for (unsigned i = 0; i < 8; i++) {
+ int c = getc(f);
+ if (c == EOF) {
+ return 0;
+ }
+ dest[i] = (char) c;
+ }
} else {
- dest[7] = (char) getc(f); dest[6] = (char) getc(f); dest[5] = (char) getc(f); dest[4] = (char) getc(f);
- dest[3] = (char) getc(f); dest[2] = (char) getc(f); dest[1] = (char) getc(f); dest[0] = (char) getc(f);
+ for (unsigned i = 0; i < 8; i++) {
+ int c = getc(f);
+ if (c == EOF) {
+ return 0;
+ }
+ dest[7 - i] = (char) c;
+ }
}
+ return 1;
}
static inline void writewithendian(char *dest, FILE *f, unsigned size, int islittle)
@@ -1131,8 +1146,11 @@ static int fiolib_readfloat(lua_State *L)
FILE *f = lmt_valid_file(L);
if (f) {
floatcast flt;
- readwithendian4(&flt.c[0], f, 0);
- lua_pushnumber(L, (double) flt.f);
+ if (readwithendian4(&flt.c[0], f, 0)) {
+ lua_pushnumber(L, (double) flt.f);
+ } else {
+ lua_pushnil(L);
+ }
return 1;
} else {
return 0;
@@ -1157,8 +1175,11 @@ static int fiolib_readfloatle(lua_State *L)
FILE *f = lmt_valid_file(L);
if (f) {
floatcast flt;
- readwithendian4(&flt.c[0], f, 1);
- lua_pushnumber(L, (double) flt.f);
+ if (readwithendian4(&flt.c[0], f, 1)) {
+ lua_pushnumber(L, (double) flt.f);
+ } else {
+ lua_pushnil(L);
+ }
return 1;
} else {
return 0;
@@ -1207,7 +1228,7 @@ static int siolib_readfloatle(lua_State *L)
}
/*tex
- These two are for stl files and they are not offcial and might go away again.
+ These two are for stl files and they are not official and might go away again.
*/
static int siolib_readfloatle6(lua_State *L)
@@ -1223,7 +1244,7 @@ static int siolib_readfloatle6(lua_State *L)
}
return 6;
} else {
- lua_pushnil(L); // 12 nils
+ lua_pushnil(L);
}
return 1;
}
@@ -1241,7 +1262,7 @@ static int siolib_readfloatle12(lua_State *L)
}
return 12;
} else {
- lua_pushnil(L); // 12 nils
+ lua_pushnil(L);
}
return 1;
}
@@ -1253,8 +1274,11 @@ static int fiolib_readdouble(lua_State *L)
FILE *f = lmt_valid_file(L);
if (f) {
doublecast dbl;
- readwithendian8(&dbl.c[0], f, 0);
- lua_pushnumber(L, dbl.d);
+ if (readwithendian8(&dbl.c[0], f, 0)) {
+ lua_pushnumber(L, dbl.d);
+ } else {
+ lua_pushnil(L);
+ }
return 1;
} else {
return 0;
@@ -1279,8 +1303,11 @@ static int fiolib_readdoublele(lua_State *L)
FILE *f = lmt_valid_file(L);
if (f) {
doublecast dbl;
- readwithendian8(&dbl.c[0], f, 1);
- lua_pushnumber(L, dbl.d);
+ if (readwithendian8(&dbl.c[0], f, 1)) {
+ lua_pushnumber(L, dbl.d);
+ } else {
+ lua_pushnil(L);
+ }
return 1;
} else {
return 0;
@@ -1334,11 +1361,11 @@ static int fiolib_getposition(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- long p = ftell(f);
+ l_seeknum p = l_ftell(f);
if (p < 0) {
lua_pushnil(L);
} else {
- lua_pushinteger(L, p);
+ lua_pushinteger(L, (lua_Integer) p);
}
return 1;
} else {
@@ -1350,12 +1377,11 @@ static int fiolib_setposition(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- long p = lmt_tolong(L, 2);
- p = fseek(f, p, SEEK_SET);
- if (p < 0) {
- lua_pushnil(L);
+ l_seeknum p = (l_seeknum) lua_tointeger(L, 2);
+ if (l_fseek(f, p, SEEK_SET) == 0) {
+ lua_pushinteger(L, (lua_Integer) l_ftell(f));
} else {
- lua_pushinteger(L, p);
+ lua_pushnil(L);
}
return 1;
} else {
@@ -1367,12 +1393,11 @@ static int fiolib_skipposition(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- long p = lmt_tolong(L, 2);
- p = fseek(f, ftell(f) + p, SEEK_SET);
- if (p < 0) {
- lua_pushnil(L);
+ l_seeknum p = (l_seeknum) lua_tointeger(L, 2);
+ if (l_fseek(f, p, SEEK_CUR) == 0) {
+ lua_pushinteger(L, (lua_Integer) l_ftell(f));
} else {
- lua_pushinteger(L, p);
+ lua_pushnil(L);
}
return 1;
} else {
@@ -1387,15 +1412,10 @@ static int fiolib_readbytetable(lua_State *L)
lua_Integer n = lua_tointeger(L, 2);
lua_createtable(L, (int) n, 0);
for (lua_Integer i = 1; i <= n; i++) {
- lua_Integer a = getc(f);
+ int a = getc(f);
if (a == EOF) {
break;
} else {
- /*
- lua_pushinteger(L, i);
- lua_pushinteger(L, a);
- lua_rawset(L, -3);
- */
lua_pushinteger(L, a);
lua_rawseti(L, -2, i);
}
@@ -1408,18 +1428,19 @@ static int fiolib_readbytetable(lua_State *L)
static int siolib_readbytetable(lua_State *L)
{
- size_t p;
+ size_t p, l;
int mode;
- const char *s = siolib_okay(L, 0, &p, NULL, &mode);
+ const char *s = siolib_okay(L, 0, &p, &l, &mode);
int n = lmt_tointeger(L, mode == mode_table ? 2 : 3);
if (s) {
lua_createtable(L, (int) n, 0);
- for (int i = 1; i <= n; i++) {
+ int i = 1;
+ for (; i <= n && p < l; i++) {
int a = uchar(s[p++]);
lua_pushinteger(L, a);
lua_rawseti(L, -2, i);
}
- siolib_done(L, mode, n);
+ siolib_done(L, mode, i - 1);
} else {
lua_pushnil(L);
}
@@ -1432,7 +1453,7 @@ static int fiolib_readbytes(lua_State *L)
if (f) {
lua_Integer n = lua_tointeger(L, 2);
for (lua_Integer i = 1; i <= n; i++) {
- lua_Integer a = getc(f);
+ int a = getc(f);
if (a == EOF) {
return (int) (i - 1);
} else {
@@ -1447,22 +1468,27 @@ static int fiolib_readbytes(lua_State *L)
static int siolib_readbytes(lua_State *L)
{
- size_t p;
+ size_t p, l;
int mode;
- const char *s = siolib_okay(L, 0, &p, NULL, &mode);
- int n = lmt_tointeger(L, mode ? 2 : 3);
+ const char *s = siolib_okay(L, 0, &p, &l, &mode);
+ int n = lmt_tointeger(L, mode == mode_table ? 2 : 3);
if (s) {
- for (int i = 1; i <= n; i++) {
+ int i = 1;
+ for (; i <= n && p < l; i++) {
int a = uchar(s[p++]);
lua_pushinteger(L, a);
}
- siolib_done(L, mode, n);
- return (int) n;
+ siolib_done(L, mode, i - 1);
+ return i - 1;
} else {
return 0;
}
}
+/*tex
+ When we fail, we return nil.
+*/
+
static int fiolib_readcline(lua_State *L)
{
FILE *f = lmt_valid_file(L);
@@ -1481,24 +1507,29 @@ static int fiolib_readcline(lua_State *L)
} else if (c == '\r') {
c = fgetc(f);
if (c != EOF && c != '\n') {
- ungetc((int) c, f);
+ ungetc(c, f);
}
goto GOOD;
+ } else if (c == EOF) {
+ if (n > 0) {
+ goto GOOD;
+ } else {
+ goto BAD;
+ }
} else {
n++;
b[i++] = (char) c;
}
}
- } while (c != EOF);
+ } while (c != EOF);
goto BAD;
- GOOD:
- if (n > 0) {
- luaL_addsize(&buf, n);
- luaL_pushresult(&buf);
- } else {
- lua_pushnil(L);
+ if (n == 0) {
+ goto BAD;
}
- lua_pushinteger(L, ftell(f));
+ GOOD:
+ luaL_addsize(&buf, n);
+ luaL_pushresult(&buf);
+ lua_pushinteger(L, (lua_Integer) l_ftell(f));
return 2;
}
BAD:
@@ -1512,7 +1543,7 @@ static int siolib_readcline(lua_State *L)
int mode;
const char *s = siolib_okay(L, 0, &p, &l, &mode);
if (s) {
- lua_Integer i = p;
+ size_t i = p;
int n = 0;
while (p < l) {
int c = uchar(s[p++]);
@@ -1520,9 +1551,9 @@ static int siolib_readcline(lua_State *L)
goto GOOD;
} else if (c == '\r') {
if (p < l) {
- c = uchar(s[p++]);
- if (c != EOF && c != '\n') {
- --p;
+ c = uchar(s[p]);
+ if (c == '\n') {
+ p++;
}
}
goto GOOD;
@@ -1530,20 +1561,22 @@ static int siolib_readcline(lua_State *L)
n++;
}
}
- goto BAD;
- GOOD:
if (n > 0) {
- siolib_done(L, mode, n + 1);
- lua_pushlstring(L, &s[i], n);
- lua_pushinteger(L, p);
- return 2;
+ goto GOOD;
}
+ goto BAD;
+ GOOD:
+ siolib_done(L, mode, p - i);
+ lua_pushlstring(L, &s[i], n);
+ lua_pushinteger(L, p + 1);
+ return 2;
}
BAD:
siolib_done(L, mode, 1);
lua_pushnil(L);
- lua_pushinteger(L, p + 1);
- return 2;
+ // lua_pushinteger(L, p + 1);
+ // return 2;
+ return 1;
}
static int fiolib_readcstring(lua_State *L)
@@ -1561,21 +1594,27 @@ static int fiolib_readcstring(lua_State *L)
c = fgetc(f);
if (c == '\0') {
goto GOOD;
+ } else if (c == EOF) {
+ if (n > 0) {
+ goto GOOD;
+ } else {
+ goto BAD;
+ }
} else {
n++;
b[i++] = (char) c;
}
}
- } while (c != EOF);
+ } while (c != EOF);
goto BAD;
GOOD:
if (n > 0) {
luaL_addsize(&buf, n);
luaL_pushresult(&buf);
} else {
- lua_pushliteral(L,"");
+ lua_pushliteral(L, "");
}
- lua_pushinteger(L, ftell(f));
+ lua_pushinteger(L, (lua_Integer) l_ftell(f));
return 2;
}
BAD:
@@ -1589,7 +1628,7 @@ static int siolib_readcstring(lua_State *L)
int mode;
const char *s = siolib_okay(L, 0, &p, &l, &mode);
if (s) {
- lua_Integer i = p;
+ size_t i = p;
int n = 0;
while (p < l) {
int c = uchar(s[p++]);
@@ -1598,7 +1637,7 @@ static int siolib_readcstring(lua_State *L)
} else {
n++;
}
- };
+ }
goto BAD;
GOOD:
if (n > 0) {
@@ -1606,7 +1645,7 @@ static int siolib_readcstring(lua_State *L)
lua_pushlstring(L, &s[i], n);
} else {
siolib_done(L, mode, 1);
- lua_pushliteral(L,"");
+ lua_pushliteral(L, "");
}
lua_pushinteger(L, p + 1);
return 2;
@@ -1614,17 +1653,80 @@ static int siolib_readcstring(lua_State *L)
BAD:
siolib_done(L, mode, 1);
lua_pushnil(L);
- lua_pushinteger(L, p + 1);
+ // lua_pushinteger(L, p + 1);
+ // return 2;
+ return 1;
+}
+
+/* */
+
+static int fiolib_readnstring(lua_State *L)
+{
+ FILE *f = lmt_valid_file(L);
+ size_t n = (size_t) luaL_checkinteger(L, 2);
+ if (! f) {
+ lua_pushnil(L);
+ return 1;
+ }
+ luaL_Buffer buf;
+ char *b = luaL_buffinitsize(L, &buf, n);
+ size_t bytes_read = fread(b, 1, n, f);
+ if (bytes_read == 0) {
+ lua_pushliteral(L, "");
+ lua_pushinteger(L, (lua_Integer) l_ftell(f));
+ return 2;
+ }
+ char *nul = memchr(b, '\0', bytes_read);
+ size_t len = nul ? (size_t) (nul - b) : bytes_read;
+ luaL_addsize(&buf, len);
+ luaL_pushresult(&buf);
+ lua_pushinteger(L, (lua_Integer) l_ftell(f));
return 2;
}
+static int siolib_readnstring(lua_State *L)
+{
+ size_t p, l;
+ int mode;
+ const char *s = siolib_okay(L, 0, &p, &l, &mode);
+ lua_Integer max_n = luaL_checkinteger(L, 2);
+ if (s) {
+ size_t i = p;
+ size_t n = 0;
+ int found_nul = 0;
+ while (p < l && (lua_Integer)n < max_n) {
+ int c = uchar(s[p++]);
+ if (c == '\0') {
+ found_nul = 1;
+ break;
+ } else {
+ n++;
+ }
+ }
+ if (n > 0 || found_nul) {
+ /* also skip the nul when found */
+ size_t consumed = found_nul ? n + 1 : n;
+ siolib_done(L, mode, consumed);
+ lua_pushlstring(L, &s[i], n);
+ } else {
+ siolib_done(L, mode, 1);
+ lua_pushliteral(L, "");
+ }
+ lua_pushinteger(L, p + 1);
+ return 2;
+ }
+ siolib_done(L, mode, 1);
+ lua_pushnil(L);
+ return 1;
+}
+
/* will be completed */
static int fiolib_writecardinal1(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer n = lua_tointeger(L, 2);
+ uint64_t n = (uint64_t) lua_tointeger(L, 2);
putc((char) (n & 0xFF), f);
}
return 0;
@@ -1632,7 +1734,7 @@ static int fiolib_writecardinal1(lua_State *L)
static int siolib_tocardinal1(lua_State *L)
{
- lua_Integer n = lua_tointeger(L, 1);
+ uint64_t n = (uint64_t) lua_tointeger(L, 1);
char buffer[1] = { (char) (n & 0xFF) };
lua_pushlstring(L, buffer, 1);
return 1;
@@ -1642,7 +1744,7 @@ static int fiolib_writecardinal2(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer n = lua_tointeger(L, 2);
+ uint64_t n = (uint64_t) lua_tointeger(L, 2);
putc((char) ((n >> 8) & 0xFF), f);
putc((char) ( n & 0xFF), f);
}
@@ -1651,7 +1753,7 @@ static int fiolib_writecardinal2(lua_State *L)
static int siolib_tocardinal2(lua_State *L)
{
- lua_Integer n = lua_tointeger(L, 1);
+ uint64_t n = (uint64_t) lua_tointeger(L, 1);
char buffer[2] = {
(char) ((n >> 8) & 0xFF),
(char) ( n & 0xFF)
@@ -1660,22 +1762,11 @@ static int siolib_tocardinal2(lua_State *L)
return 1;
}
-// static int siolib_tocardinal2(lua_State *L)
-// {
-// uint16_t n = lmt_tounsignedshort(L, 1);
-// char buffer[2] = {
-// (char) (n >> 8),
-// (char) (n & 0xFF)
-// };
-// lua_pushlstring(L, buffer, 2);
-// return 1;
-// }
-
static int fiolib_writecardinal2_le(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer n = lua_tointeger(L, 2);
+ uint64_t n = (uint64_t) lua_tointeger(L, 2);
putc((char) ( n & 0xFF), f);
putc((char) ((n >> 8) & 0xFF), f);
}
@@ -1684,7 +1775,7 @@ static int fiolib_writecardinal2_le(lua_State *L)
static int siolib_tocardinal2_le(lua_State *L)
{
- lua_Integer n = lua_tointeger(L, 1);
+ uint64_t n = (uint64_t) lua_tointeger(L, 1);
char buffer[2] = {
(char) ( n & 0xFF),
(char) ((n >> 8) & 0xFF)
@@ -1697,7 +1788,7 @@ static int fiolib_writecardinal3(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer n = lua_tointeger(L, 2);
+ uint64_t n = (uint64_t) lua_tointeger(L, 2);
putc((char) ((n >> 16) & 0xFF), f);
putc((char) ((n >> 8) & 0xFF), f);
putc((char) ( n & 0xFF), f);
@@ -1707,7 +1798,7 @@ static int fiolib_writecardinal3(lua_State *L)
static int siolib_tocardinal3(lua_State *L)
{
- lua_Integer n = lua_tointeger(L, 1);
+ uint64_t n = (uint64_t) lua_tointeger(L, 1);
char buffer[3] = {
(char) ((n >> 16) & 0xFF),
(char) ((n >> 8) & 0xFF),
@@ -1717,12 +1808,11 @@ static int siolib_tocardinal3(lua_State *L)
return 1;
}
-
static int fiolib_writecardinal3_le(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer n = lua_tointeger(L, 2);
+ uint64_t n = (uint64_t) lua_tointeger(L, 2);
putc((char) ( n & 0xFF), f);
putc((char) ((n >> 8) & 0xFF), f);
putc((char) ((n >> 16) & 0xFF), f);
@@ -1732,7 +1822,7 @@ static int fiolib_writecardinal3_le(lua_State *L)
static int siolib_tocardinal3_le(lua_State *L)
{
- lua_Integer n = lua_tointeger(L, 1);
+ uint64_t n = (uint64_t) lua_tointeger(L, 1);
char buffer[3] = {
(char) ( n & 0xFF),
(char) ((n >> 8) & 0xFF),
@@ -1746,7 +1836,7 @@ static int fiolib_writecardinal4(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer n = lua_tointeger(L, 2);
+ uint64_t n = (uint64_t) lua_tointeger(L, 2);
putc((char) ((n >> 24) & 0xFF), f);
putc((char) ((n >> 16) & 0xFF), f);
putc((char) ((n >> 8) & 0xFF), f);
@@ -1757,7 +1847,7 @@ static int fiolib_writecardinal4(lua_State *L)
static int siolib_tocardinal4(lua_State *L)
{
- lua_Integer n = lua_tointeger(L, 1);
+ uint64_t n = (uint64_t) lua_tointeger(L, 1);
char buffer[4] = {
(char) ((n >> 24) & 0xFF),
(char) ((n >> 16) & 0xFF),
@@ -1772,7 +1862,7 @@ static int fiolib_writecardinal4_le(lua_State *L)
{
FILE *f = lmt_valid_file(L);
if (f) {
- lua_Integer n = lua_tointeger(L, 2);
+ uint64_t n = (uint64_t) lua_tointeger(L, 2);
putc((char) ( n & 0xFF), f);
putc((char) ((n >> 8) & 0xFF), f);
putc((char) ((n >> 16) & 0xFF), f);
@@ -1783,7 +1873,7 @@ static int fiolib_writecardinal4_le(lua_State *L)
static int siolib_tocardinal4_le(lua_State *L)
{
- lua_Integer n = lua_tointeger(L, 1);
+ uint64_t n = (uint64_t) lua_tointeger(L, 1);
char buffer[4] = {
(char) ( n & 0xFF),
(char) ((n >> 8) & 0xFF),
@@ -1864,8 +1954,6 @@ static const luaL_Reg fiolib_function_list[] = {
{ "readfloatle", fiolib_readfloatle },
{ "readdoublele", fiolib_readdoublele },
- /* { "readfloatle12", fiolib_readfloatle12 }, */
-
{ "read2dot14", fiolib_read2dot14 },
{ "setposition", fiolib_setposition },
@@ -1877,6 +1965,7 @@ static const luaL_Reg fiolib_function_list[] = {
{ "readcline", fiolib_readcline },
{ "readcstring", fiolib_readcstring },
+ { "readnstring", fiolib_readnstring },
{ "writecardinal1", fiolib_writecardinal1 },
{ "writecardinal2", fiolib_writecardinal2 },
@@ -1939,6 +2028,7 @@ static const luaL_Reg siolib_function_list[] = {
{ "readcline", siolib_readcline },
{ "readcstring", siolib_readcstring },
+ { "readnstring", siolib_readnstring },
{ "tocardinal1", siolib_tocardinal1 },
{ "tocardinal2", siolib_tocardinal2 },
@@ -2077,7 +2167,7 @@ static inline int io_aux_check_open(lua_State *L, const char **filename, const c
errno = EACCES;
return 0;
}
- if (is_write && ! lmt_valid_target(L, security_writeable, *filename, security_open_file)) {
+ if (is_write && ! lmt_valid_target(L, security_writable, *filename, security_open_file)) {
errno = EACCES;
return 0;
}
@@ -2096,20 +2186,111 @@ static inline int io_aux_check_popen(lua_State *L, const char **filename, const
return 1;
}
-static int io_open(lua_State *L)
-{
- const char *filename, *mode;
- if (! io_aux_check_open(L, &filename, &mode)) {
- return luaL_fileresult(L, 0, filename);
+/*tex
+
+ This is just a proof of concept. There are more places where this should happen but we only
+ show it here.
+
+ \starttyping
+ io.savedata("Knäckebröd-NFC.log","nfc")
+ io.savedata("Knäckebröd-NFD.log","nfd")
+
+ print("NFC",io.loaddata("Knäckebröd-NFC.log"))
+ print("NFD",io.loaddata("Knäckebröd-NFD.log"))
+ print("NFC",io.loaddata("Knäckebröd-NFC.log"))
+ print("NFD",io.loaddata("Knäckebröd-NFD.log"))
+ \stoptyping
+
+ On Windows and Linux these are different, on OSX (de)composition is kind of handled but the
+ file system stores decomposed. We assume that users are consistent so we will not introduce
+ the overhead. If we ever do, we will likely only check validity (sandbox) for the given
+ name.
+
+*/
+
+# define default_name_check 1
+
+# if default_name_check
+
+ static int io_open(lua_State *L)
+ {
+ const char *filename, *mode;
+ if (! io_aux_check_open(L, &filename, &mode)) {
+ return luaL_fileresult(L, 0, filename);
+ }
+ LStream *p = newfile(L);
+ # ifdef _WIN32
+ p->f = aux_utf8_fopen(filename, mode);
+ # else
+ p->f = fopen(filename, mode);
+ # endif
+ return (p->f) ? 1 : luaL_fileresult(L, 0, filename);
}
- LStream *p = newfile(L);
-# ifdef _WIN32
- p->f = aux_utf8_fopen(filename, mode);
+
# else
- p->f = fopen(filename, mode);
+
+ static int io_open(lua_State *L)
+ {
+ const char *filename, *mode;
+ if (! io_aux_check_open(L, &filename, &mode)) {
+ return luaL_fileresult(L, 0, filename);
+ }
+ LStream *p = newfile(L);
+ # ifdef _WIN32
+ p->f = aux_utf8_fopen(filename, mode);
+ # else
+ p->f = fopen(filename, mode);
+ # endif
+ if (! p->f && ! aux_onlyascii(filename, strlen(filename))) {
+ lua_pushvalue(L, lua_upvalueindex(1));
+ if (lua_isfunction(L, -1)) {
+ lua_pushstring(L, filename);
+ if (lua_pcall(L, 1, 1, 0) == LUA_OK) {
+ if (lua_isstring(L, -1)) {
+ const char *alternative = lua_tostring(L, -1);
+ // if (! io_aux_check_open(L, &alternative, &mode)) {
+ // return luaL_fileresult(L, 0, alternative);
+ // }
+ # ifdef _WIN32
+ p->f = aux_utf8_fopen(alternative, mode);
+ # else
+ p->f = fopen(alternative, mode);
+ # endif
+ if (p->f) {
+ lua_pop(L, 1); // pop alternative
+ return 1;
+ }
+ }
+ } else {
+ tex_formatted_warning("io.open", "alternative: %s\n", lua_tostring(L, -1));
+ }
+ lua_pop(L, 1); // pop result/error from pcall
+ } else {
+ lua_pop(L, 1); // pop pushed upvalue
+ }
+ }
+ return (p->f) ? 1 : luaL_fileresult(L, 0, filename);
+ }
+
+ static int io_filenamevariant(lua_State *L)
+ {
+ luaL_checktype(L, 1, LUA_TFUNCTION);
+ lua_getglobal(L, "io");
+ lua_getfield(L, -1, "open"); // stack: -2 = io, -1 = io.open
+ lua_getupvalue(L, -1, 1); // pushes the upvalue onto the stack
+ if (! lua_isnil(L, -1)) {
+ return luaL_error(L, "io.filenamevariant can already been set");
+ }
+ lua_pop(L, 1); // pop the nil upvalue
+ // move the new function into position, then set it as io_open's upvalue
+ lua_pushvalue(L, 1); // duplicate user's function to top of stack
+ // lua_setupvalue pops the value from the top of the stack and assigns it to upvalue #1 of io.open (at index -2)
+ lua_setupvalue(L, -2, 1);
+ lua_pop(L, 2); // pop io.open and io table
+ return 0;
+ }
+
# endif
- return (p->f) ? 1 : luaL_fileresult(L, 0, filename);
-}
static int io_pclose(lua_State *L)
{
@@ -2161,9 +2342,25 @@ static int io_popen(lua_State *L)
int luaextend_io(lua_State *L)
{
lua_getglobal(L, "io");
+
+# if default_name_check
+
lua_pushcfunction(L, io_open); lua_setfield(L, -2, "open");
+
+# else
+
+ lua_pushnil(L);
+ lua_pushcclosure(L, io_open, 1);
+ lua_setfield(L, -2, "open");
+ lua_pushcfunction(L, io_filenamevariant);
+ lua_setfield(L, -2, "filenamevariant");
+
+# endif
+
lua_pushcfunction(L, io_popen); lua_setfield(L, -2, "popen");
+
lua_pushcfunction(L, io_gobble); lua_setfield(L, -2, "gobble");
+
lua_pop(L, 1);
# ifdef _WIN32
if (_setmaxstdio(2048) < 0) {
@@ -2188,4 +2385,4 @@ int luaextend_io(lua_State *L)
}
# endif
return 1;
-} \ No newline at end of file
+}
diff --git a/source/luametatex/source/luarest/lmtoslibext.c b/source/luametatex/source/luarest/lmtoslibext.c
index 578e232b2..79585c317 100644
--- a/source/luametatex/source/luarest/lmtoslibext.c
+++ b/source/luametatex/source/luarest/lmtoslibext.c
@@ -10,6 +10,12 @@
# define MKDIR(a,b) mkdir(a,b)
# endif
+# ifndef _WIN32
+ extern char **environ;
+# else
+ # define environ _environ
+# endif
+
/*tex
An attempt to figure out the basic platform, does not care about niceties like version numbers
@@ -300,14 +306,14 @@ static int oslib_execute(lua_State *L)
static int oslib_remove(lua_State *L)
{
const char *filename = luaL_checkstring(L, 1);
- return luaL_fileresult(L, lmt_valid_target(L, security_writeable, filename, security_remove_file) ? aux_utf8_remove(filename) == 0 : 0, filename);
+ return luaL_fileresult(L, lmt_valid_target(L, security_writable, filename, security_remove_file) ? aux_utf8_remove(filename) == 0 : 0, filename);
}
static int oslib_rename(lua_State *L)
{
const char *fromname = luaL_checkstring(L, 1);
const char *toname = luaL_checkstring(L, 2);
- return luaL_fileresult(L, lmt_valid_target(L, security_writeable, toname, security_rename_file) ? aux_utf8_rename(fromname, toname) == 0 : 0, NULL);
+ return luaL_fileresult(L, lmt_valid_target(L, security_writable, toname, security_rename_file) ? aux_utf8_rename(fromname, toname) == 0 : 0, NULL);
}
# ifdef _WIN32
@@ -418,23 +424,233 @@ static int oslib_setlocale(lua_State *L)
return 0;
}
+/*tex
+
+ This one is not that important but cheap to implement, we assume some sanity check
+ at the \LUA\ end. For instance, we can go to a website or url.
+
+*/
+
+# if defined(_WIN32) || defined(_WIN64)
+ # include <shellapi.h>
+# else
+ # include <spawn.h>
+ # include <sys/wait.h>
+# endif
+
+# define max_command_length 2048
+
+typedef enum {
+ launcher_state_success,
+ launcher_state_blocked,
+ launcher_state_no_command,
+ launcher_state_bad_command,
+ launcher_state_long_command,
+ launcher_state_not_found,
+ launcher_state_failure,
+ launcher_state_unsupported
+} launcher_states;
+
+static int oslib_aux_valid_launch(const char *cmd, size_t len)
+{
+ if (! cmd || len == 0) {
+ return launcher_state_no_command;
+ } else if (len >= max_command_length) {
+ return launcher_state_long_command;
+ } else {
+ for (size_t i = 0; i < len; i++) {
+ unsigned char c = (unsigned char) cmd[i];
+ if (c <= 32 || c >= 127) {
+ return launcher_state_bad_command;
+ }
+ }
+ return launcher_state_success;
+ }
+}
+
+# if defined(_WIN32) || defined(_WIN64)
+
+ /*tex Not really spawn but kind of. */
+
+ static int oslib_aux_spawn_process(const char *executable, const char * cmd)
+ {
+ INT_PTR result = (INT_PTR) ShellExecuteA(NULL, executable, cmd, NULL, NULL, SW_SHOWNORMAL);
+ if (result > 32) {
+ return launcher_state_success;
+ } else {
+ return (result == SE_ERR_FNF || result == SE_ERR_PNF)
+ ? launcher_state_not_found : launcher_state_failure;
+ }
+ }
+
+# else
+
+ /*tex
+
+ This variant intercepts errors in case of an indirect. As I tested the posix variant
+ in WSL, after consulting Gemini instead of a redirect to wslview after a failure some
+ magic commands (installation) did that automatically so we keep things simple and don't
+ rely on a shell.
+
+ */ /*
+
+ static int oslib_aux_spawn_process(const char *executable, const char * cmd)
+ {
+ char buffer[max_command_length * 2];
+ snprintf(buffer, sizeof(buffer), "%s \"%s\" > /dev/null 2>&1 &", executable, cmd);
+ char *const argv[] = {
+ (char *) "/bin/sh",
+ (char *) "-c",
+ buffer,
+ NULL
+ };
+ posix_spawn_file_actions_t actions;
+ posix_spawn_file_actions_init(&actions);
+ pid_t pid;
+ int status = posix_spawnp(&pid, "/bin/sh", &actions, NULL, argv, environ);
+ posix_spawn_file_actions_destroy(&actions);
+ if (status != 0) {
+ return (status == ENOENT) ? launcher_state_not_found : launcher_state_failure;
+ }
+ int exit_code;
+ waitpid(pid, &exit_code, 0);
+ return (WIFEXITED(exit_code) && WEXITSTATUS(exit_code) == 0)
+ ? launcher_state_success
+ : launcher_state_failure;
+ }
+
+ */
+
+ static int oslib_aux_spawn_process(const char *executable, const char * cmd)
+ {
+ char *const argv[] = {
+ (char *) (uintptr_t) executable,
+ (char *) (uintptr_t) cmd,
+ NULL
+ };
+ posix_spawn_file_actions_t actions;
+ posix_spawn_file_actions_init(&actions);
+ int dev_null = open("/dev/null", O_WRONLY);
+ if (dev_null >= 0) {
+ posix_spawn_file_actions_adddup2(&actions, dev_null, STDOUT_FILENO);
+ posix_spawn_file_actions_adddup2(&actions, dev_null, STDERR_FILENO);
+ posix_spawn_file_actions_addclose(&actions, dev_null);
+ }
+ pid_t pid;
+ int status = posix_spawnp(&pid, executable, &actions, NULL, argv, environ);
+ posix_spawn_file_actions_destroy(&actions);
+ if (dev_null >= 0) {
+ close(dev_null);
+ }
+ if (status != 0) {
+ return (status == ENOENT) ? launcher_state_not_found : launcher_state_failure;
+ }
+ return launcher_state_success;
+ }
+
+# endif
+
+static int oslib_launch(lua_State *L)
+{
+ size_t len = 0;
+ const char *cmd = luaL_checklstring(L, 1, &len);
+ int status = oslib_aux_valid_launch(cmd, len);
+
+ if (status == launcher_state_success && ! lmt_valid_target(L, security_launchable, cmd, security_launch_command)) {
+ status = launcher_state_blocked;
+ }
+ if (status == launcher_state_success) {
+ # if defined(_WIN32) || defined(_WIN64)
+ status = oslib_aux_spawn_process("open", cmd);
+ # elif defined(__APPLE__)
+ status = oslib_aux_spawn_process("open", cmd);
+ # elif defined(__unix__) || defined(__linux__)
+ status = oslib_aux_spawn_process("xdg-open", cmd);
+ // /* WSL Fallback 1: wslview */
+ // if (status != launcher_state_success) {
+ // status = oslib_aux_spawn_process("wslview", cmd);
+ // }
+ // /* WSL Fallback 2: Direct Windows command interop */
+ // if (status != launcher_state_success) {
+ // status = oslib_aux_spawn_process("cmd.exe /c start", cmd);
+ // }
+ # else
+ status = launcher_state_unsupported;
+ # endif
+ }
+ lua_pushinteger(L, status);
+ return 1;
+}
+
+# if defined(_WIN32) || defined(_WIN64)
+
+ static int oslib_getseparators(lua_State *L)
+ {
+ lua_pushstring(L, "\\");
+ lua_pushstring(L, ";");
+ return 2;
+ }
+
+# else
+
+ static int oslib_getseparators(lua_State *L)
+ {
+ lua_pushstring(L, "/");
+ lua_pushstring(L, ":");
+ return 2;
+ }
+
+# endif
+
+# if defined(_WIN32)
+
+ static int oslib_getcpucount(lua_State *L)
+ {
+ SYSTEM_INFO sysinfo;
+ GetSystemInfo(&sysinfo);
+ lua_pushinteger(L, (int) sysinfo.dwNumberOfProcessors);
+ return 1;
+ }
+
+# elif defined(__unix__) || defined(__APPLE__)
+
+ static int oslib_getcpucount(lua_State *L)
+ {
+ long n = sysconf(_SC_NPROCESSORS_ONLN);
+ lua_pushinteger(L, (n < 1) ? 1 : (int) n);
+ return 1;
+ }
+
+# else
+
+ static int oslib_getcpucount(lua_State *L)
+ {
+ lua_pushinteger(L, 1);
+ return 1;
+ }
+
+# endif
+
static const luaL_Reg oslib_function_list[] = {
{ "sleep", oslib_sleep },
{ "uname", oslib_uname },
{ "gettimeofday", oslib_gettimeofday },
- { "setenv", oslib_setenv }, /* security : todo */
- { "execute", oslib_execute }, /* security : todo */
- { "rename", oslib_rename }, /* security : writeable */
- { "remove", oslib_remove }, /* security : writeable */
+ { "setenv", oslib_setenv },
+ { "execute", oslib_execute },
+ { "launch", oslib_launch },
+ { "rename", oslib_rename },
+ { "remove", oslib_remove },
{ "setlocale", oslib_setlocale },
# ifdef _WIN32
{ "getenv", oslib_getenv },
# endif
+ { "getseparators", oslib_getseparators },
{ "enableansi", oslib_enableansi },
{ "getcodepage", oslib_getcodepage },
{ "getnamevalues", oslib_getnamevalues },
{ "gettypevalues", oslib_gettypevalues },
{ "getunamefields", oslib_getunamefields },
+ { "getcpucount", oslib_getcpucount },
/* */
{ NULL, NULL },
};
@@ -444,12 +660,6 @@ static const luaL_Reg oslib_function_list[] = {
feature.
*/
-# ifndef _WIN32
- extern char **environ;
-# else
- # define environ _environ
-# endif
-
int luaextend_os(lua_State *L)
{
/*tex We locate the library: */
diff --git a/source/luametatex/source/luarest/lmtprocesslib.c b/source/luametatex/source/luarest/lmtprocesslib.c
index 3fa208621..b172ebf55 100644
--- a/source/luametatex/source/luarest/lmtprocesslib.c
+++ b/source/luametatex/source/luarest/lmtprocesslib.c
@@ -971,3 +971,368 @@ int luaopen_process(lua_State *L)
lua_settable(L, -3);
return 1;
}
+
+/*tex
+
+ For now we put this code here because processes and watchdogs kind of relate (or can be
+ combined). As usual with this low level hackery, the operating specific code was the
+ result of some querying on the web and from that we moved on.
+
+ We use a simple model: we create a watchdog and bind a callback function to it that we
+ register in the \LUA\ registry. We limits the functionality here because the (various)
+ applications can best be done at the \LUA\ end (which is also more fun). We can quit
+ am event handler explicitly because the garbage collector can take a while to kick in
+ because we use little memory.
+
+ Because this is not a POSIX feature we need a seperate branch for linux and the bsd
+ operating systems. We could also trigger on a change in file but that feature is not
+ available on osx so not portable. In practice we should work with a job ticket (at
+ leat that's what I always did) and those are unique (and later cleaned up). Anyway, the
+ intelligence sits at the \LUA\ end.
+
+*/
+
+# if defined(_WIN32)
+
+ // already ok
+
+# elif defined(__linux__)
+
+ /* It is actually a kernel feature, so the library is basically a wrapper. */
+
+ # include <sys/inotify.h>
+
+# elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
+
+ # include <sys/types.h>
+ # include <sys/event.h>
+
+# endif
+
+typedef struct watch_data {
+ int lua_ref;
+ char *path;
+
+# if defined(_WIN32)
+
+ HANDLE hDir;
+ OVERLAPPED overlapped;
+ char buffer[4096];
+ DWORD bytesReturned;
+
+# elif defined(__linux__)
+
+ int fd;
+ int wd;
+
+# elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
+
+ int fd;
+ int kq;
+
+# endif
+} watch_data;
+
+// /* todo (when we add more features) */
+//
+// static inline watch_data * watchlib_aux_valid(lua_State *L)
+// {
+// watch_data * w = lua_touserdata(L, 1);
+// if (w && lua_getmetatable(L, i)) {
+// lua_get_metatablelua(watch_instance);
+// if (! lua_rawequal(L, -1, -2)) {
+// w = NULL;
+// }
+// lua_pop(L, 2);
+// }
+// return w;
+// }
+
+static void watchlib_aux_callback(lua_State *L, int lua_ref, const char *filename)
+{
+ lua_rawgeti(L, LUA_REGISTRYINDEX, lua_ref);
+ lua_pushstring(L, filename ? filename : "");
+ /*tex We might at some point pass more details. */
+ if (lua_pcall(L, 1, 0, 0) != LUA_OK) {
+ tex_formatted_warning("watcher","error in callback: %s", lua_tostring(L, -1));
+ lua_pop(L, 1);
+ }
+}
+
+static int watchlib_register(lua_State *L)
+{
+ const char *path = luaL_checkstring(L, 1);
+ luaL_checktype(L, 2, LUA_TFUNCTION);
+
+ watch_data *w = (watch_data *) lua_newuserdata(L, sizeof(watch_data));
+ memset(w, 0, sizeof(watch_data));
+
+ w->path = lmt_memory_strdup(path);
+
+ lua_pushvalue(L, 2);
+ w->lua_ref = luaL_ref(L, LUA_REGISTRYINDEX);
+
+ luaL_getmetatable(L, WATCHER_METATABLE_INSTANCE);
+ lua_setmetatable(L, -2); /* so we gc on error */
+
+ # if defined(_WIN32)
+
+ w->hDir = CreateFileA(
+ path,
+ FILE_LIST_DIRECTORY,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ NULL,
+ OPEN_EXISTING,
+ FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
+ NULL
+ );
+ if (w->hDir == INVALID_HANDLE_VALUE) {
+ return luaL_error(L, "watcher: failed to open directory for monitoring");
+ }
+ memset(&w->overlapped, 0, sizeof(OVERLAPPED));
+ w->overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
+ ReadDirectoryChangesW(
+ w->hDir, w->buffer, sizeof(w->buffer),
+ FALSE,
+ FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME,
+ // FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_ATTRIBUTES;
+ &w->bytesReturned,
+ &w->overlapped,
+ NULL
+ );
+
+ # elif defined(__linux__)
+
+ w->fd = inotify_init1(IN_NONBLOCK);
+ if (w->fd < 0) {
+ return luaL_error(L, "watcher: failed to initialize inotify");
+ }
+ w->wd = inotify_add_watch(w->fd, path, IN_CREATE | IN_MOVED_TO);
+ // w->wd = inotify_add_watch(w->fd, path, IN_CREATE | IN_MOVED_TO | IN_MODIFY | IN_ATTRIB);
+ if (w->wd < 0) {
+ close(w->fd);
+ return luaL_error(L, "watcher: failed to add watch for path: %s", path);
+ }
+
+ # elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
+
+ w->kq = kqueue();
+ if (w->kq == -1) {
+ return luaL_error(L, "watcher: failed to create kqueue");
+ }
+ w->fd = open(path, O_RDONLY);
+ if (w->fd == -1) {
+ close(w->kq);
+ return luaL_error(L, "watcher: failed to open directory for kqueue");
+ }
+ struct kevent ev;
+ EV_SET(
+ &ev,
+ w->fd,
+ EVFILT_VNODE,
+ EV_ADD | EV_ENABLE | EV_CLEAR,
+ NOTE_WRITE | NOTE_EXTEND | NOTE_RENAME | NOTE_DELETE,
+ 0,
+ NULL
+ );
+ if (kevent(w->kq, &ev, 1, NULL, 0, NULL) == -1) {
+ close(w->fd);
+ close(w->kq);
+ return luaL_error(L, "watcher: failed to register kqueue event");
+ }
+
+ # endif
+
+ return 1;
+}
+
+static int watchlib_check(lua_State *L)
+{
+ watch_data *w = (watch_data *) luaL_checkudata(L, 1, WATCHER_METATABLE_INSTANCE);
+
+ if (! w->path) {
+ return 0;
+ }
+
+ # if defined(_WIN32)
+
+ DWORD transferred = 0;
+ if (GetOverlappedResult(w->hDir, &w->overlapped, &transferred, FALSE)) {
+ if (transferred > 0) {
+ char *p = w->buffer;
+ for (;;) {
+ FILE_NOTIFY_INFORMATION *fni = (FILE_NOTIFY_INFORMATION *)p;
+ if (fni->Action == FILE_ACTION_ADDED || fni->Action == FILE_ACTION_RENAMED_NEW_NAME) {
+ char filename[MAX_PATH];
+ int size = WideCharToMultiByte(CP_UTF8, 0, fni->FileName, fni->FileNameLength / sizeof(WCHAR), filename, sizeof(filename) - 1, NULL, NULL);
+ filename[size] = '\0';
+ watchlib_aux_callback(L, w->lua_ref, filename);
+ }
+ if (fni->NextEntryOffset == 0) break;
+ p += fni->NextEntryOffset;
+ }
+ }
+ // re-arm asynchronous read
+ memset(&w->overlapped, 0, sizeof(OVERLAPPED));
+ w->overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
+ ReadDirectoryChangesW(
+ w->hDir,
+ w->buffer,
+ sizeof(w->buffer),
+ FALSE,
+ FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME,
+ &w->bytesReturned,
+ &w->overlapped,
+ NULL
+ );
+ }
+
+ # elif defined(__linux__)
+
+ char buf[4096] __attribute__ ((aligned(__alignof__(struct inotify_event))));
+ ssize_t len = read(w->fd, buf, sizeof(buf));
+ if (len < 0) {
+ if (errno == EAGAIN || errno == EWOULDBLOCK) {
+ return 0;
+ } else {
+ return luaL_error(L, "watcher: error reading inotify events");
+ }
+ }
+
+ const struct inotify_event *event;
+ for (char *ptr = buf; ptr < buf + len; ptr += sizeof(struct inotify_event) + event->len) {
+ event = (const struct inotify_event *) ptr;
+ if (event->len > 0 && (event->mask & (IN_CREATE | IN_MOVED_TO))) {
+ watchlib_aux_callback(L, w->lua_ref, event->name);
+ }
+ }
+
+ # elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
+
+ struct timespec timeout = { 0, 0 }; /* Non-blocking poll */
+ struct kevent ev;
+ int n = kevent(w->kq, NULL, 0, &ev, 1, &timeout);
+ if (n > 0) {
+ // kqueue signals that directory changed; pass directory path or notification
+ watchlib_aux_callback(L, w->lua_ref, w->path);
+ // re-add event structure if cleared
+ struct kevent readd;
+ EV_SET(
+ &readd,
+ w->fd,
+ EVFILT_VNODE,
+ EV_ADD | EV_ENABLE | EV_CLEAR,
+ NOTE_WRITE | NOTE_EXTEND | NOTE_RENAME | NOTE_DELETE,
+ 0,
+ NULL
+ );
+ kevent(w->kq, &readd, 1, NULL, 0, NULL);
+ }
+
+ # endif
+
+ return 0;
+}
+
+static int watchlib_gc(lua_State *L)
+{
+ watch_data *w = (watch_data *) luaL_checkudata(L, 1, WATCHER_METATABLE_INSTANCE);
+
+ if (! w->path) {
+ return 0;
+ }
+
+ if (w->lua_ref != LUA_NOREF) {
+ luaL_unref(L, LUA_REGISTRYINDEX, w->lua_ref);
+ }
+ if (w->path) {
+ lmt_memory_free(w->path);
+ w->path = NULL;
+ }
+
+ # if defined(_WIN32)
+
+ if (w->hDir != INVALID_HANDLE_VALUE) {
+ CancelIo(w->hDir);
+ CloseHandle(w->hDir);
+ }
+ if (w->overlapped.hEvent) {
+ CloseHandle(w->overlapped.hEvent);
+ }
+
+ # elif defined(__linux__)
+
+ if (w->fd >= 0) {
+ if (w->wd >= 0) {
+ inotify_rm_watch(w->fd, w->wd);
+ }
+ close(w->fd);
+ }
+
+ # elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
+
+ if (w->fd >= 0) {
+ close(w->fd);
+ }
+ if (w->kq >= 0) {
+ close(w->kq);
+ }
+
+ # endif
+
+ w->path = NULL; /* A signal that we're done with it. */
+
+ return 0;
+}
+
+/*tex
+
+ Currently this one is the same as a garbage collection. We let \LUA\ do the userdata cleanup
+ but this way we can make sure that there is no dangling event handler when we're done.
+
+*/
+
+static int watchlib_unregister(lua_State *L)
+{
+ return watchlib_gc(L);
+}
+
+static int watchlib_tostring(lua_State *L)
+{
+ watch_data *w = (watch_data *) luaL_checkudata(L, 1, WATCHER_METATABLE_INSTANCE);
+ if (w) {
+ lua_pushfstring(L, "<watcher %p : %s>", w, w->path ? w->path : "not active");
+ return 1;
+ } else {
+ return 0;
+ }
+}
+
+static const struct luaL_Reg watchlib_function_list[] = {
+ { "register", watchlib_register },
+ { "unregister", watchlib_unregister },
+ { "check", watchlib_check },
+ /* */
+ { "tostring", watchlib_tostring },
+ /* */
+ { "__gc", watchlib_gc },
+ /* */
+ { NULL, NULL }
+};
+
+int luaopen_watcher(lua_State *L)
+{
+ luaL_newmetatable(L, WATCHER_METATABLE_INSTANCE);
+ luaL_setfuncs(L, watchlib_function_list, 0);
+ lua_pushliteral(L, "__index");
+ lua_pushvalue(L, -2);
+ lua_settable(L, -3);
+ lua_pushliteral(L, "__tostring");
+ lua_pushliteral(L, "tostring");
+ lua_gettable(L, -3);
+ lua_settable(L, -3);
+ lua_pushliteral(L, "__name");
+ lua_pushliteral(L, "watcher");
+ lua_settable(L, -3);
+ return 1;
+}
diff --git a/source/luametatex/source/luarest/lmtserverlib.c b/source/luametatex/source/luarest/lmtserverlib.c
new file mode 100644
index 000000000..7bf70eba2
--- /dev/null
+++ b/source/luametatex/source/luarest/lmtserverlib.c
@@ -0,0 +1,1012 @@
+/*
+ See license.txt in the root of this project.
+*/
+
+# include <luametatex.h>
+/*tex
+
+ One of the first decisions we (Taco & Hans) made when we started with \LUATEX\ is to also
+ let it act as a \LUA\ interpreter. That would permits is to steer away from the \RUBY\ and
+ \PERL\ depencies (runners, scripts). In the end we saw other macro packages (etc) also use
+ \LUATEX\ as interpreter. We've come far from packagers and distributers complaints that
+ \quotation {It's bad that \CONTEXT\ uses a script to manage multipeas runs.} indeed.
+
+ However, it makes little sense to have a full blown server in the engine but there are
+ some arguments for a simple one and they come from how we used the engien as server.
+
+ - We have a lot of libraries on board and like to use them. In a self contained ecosystem
+ like \CONTEXT\ we don't want users to depend on external tools. Support for sockets is
+ something that can provided by a library but then one needs to compile it.
+
+ - Applications are simple, for instance we have a help server and that one just serves a
+ single user on a local machine. The response is simple and can be generated fast. Blocking
+ is not really an issue (unless a client does).
+
+ - We have straightforward services behind a proxy where the service handles for instance an
+ interface and orchestrates a product run, but large downloads are delegated to the proxy
+ so they don't block.
+
+ So, we don't need to support various protocols, deal with many client atthe same time, recover
+ from tricky situations. We've run services like these for very long periods of time on the
+ engine in \LUA\ mode without problems.
+
+ So from these experiences we came to the following solution, which for now is an experiment
+ only. It's also something that is not meant to compete with what is out there, just something
+ I need myself and in the perspective of the \CONTEXT\ ecosystem.
+
+ The basics one can finds everywhere in the Internet (or just look in the luasocket sources)
+ and once these are in place one stepwise adds to it. Asking e.g. Gemini for platform specific
+ solutions and http specifics is handy, after all these technologies evolved.
+
+ We can go very simple and let the \LUA\ end construct the whole response but even then we need
+ to catch errors. Some instead we return a table and do some work here.
+
+ Because we want to add features (and actually did in the process) we pass a tabel to the server
+ startup function.
+
+ .status : integer
+ .mime : string
+ .body : string
+ .statistics : boolean (add statistics table to reply)
+ .trace : boolean (enable lua error reporting)
+ .headers : string | table
+ .timeout : integer (client timeout)
+ .report : function (ConTeXt reporter callback)
+ .step : function (called at the end of the loop)
+ .delay : select delay (handy for step)
+
+ A client request triggers a callback that also gets a table:
+
+ .method : string
+ .path : string
+ .body : string
+ .ip : string
+ .headers : table
+
+ The code below started with little but stepwise was extended to suit our needs, which is a
+ simple, robust and performant servlet without adding to much code to the engine and lots of
+ wrapper code in \LUA. It's a compromise.
+
+ There are a few platform dependencies so that's what the Internet is for: figuring out how to
+ deal with those. Maintaining this is not too hard because nowadays one can consult various tools
+ to check and report issues. The main logic and interfaces are just regular \LUA.
+
+ Just for the record: if we don't include (the stripped down) luasocket library we safe some 50K
+ or 1% on the engine binary which is just noise, but we also get a smaller mtxrun.lmt file, as
+ well as a smaller format file (although we delay loading). It anyway removes a dependency (we
+ just can't keep track of how external libraries change over time) and we can make usage a bit
+ cleaner.
+
+*/
+
+# ifdef _WIN32
+
+ # include <winsock2.h>
+ # include <ws2tcpip.h>
+ # include <time.h>
+
+ typedef SOCKET socket_t;
+
+ # define close_socket(s) closesocket(s)
+ # define invalid_socket(s) ((s) == INVALID_SOCKET)
+ # define would_block (WSAGetLastError() == WSAEWOULDBLOCK)
+ # define send_flags 0
+
+ # define strncasecmp _strnicmp
+
+ static inline int set_nonblocking(socket_t fd)
+ {
+ u_long mode = 1;
+ return ioctlsocket(fd, FIONBIO, &mode) == 0;
+ }
+
+# else
+
+ # include <sys/socket.h>
+ # include <netinet/in.h>
+ # include <arpa/inet.h>
+ # include <unistd.h>
+ # include <fcntl.h>
+ # include <errno.h>
+ # include <time.h>
+ # include <strings.h>
+
+ typedef int socket_t;
+
+ # define close_socket(s) close(s)
+ # define invalid_socket(s) ((s) < 0)
+ # define would_block (errno == EAGAIN || errno == EWOULDBLOCK)
+
+ # ifdef MSG_NOSIGNAL
+ # define send_flags MSG_NOSIGNAL
+ # else
+ # define send_flags 0
+ # endif
+
+ static inline int set_nonblocking(socket_t fd)
+ {
+ int flags = fcntl(fd, F_GETFL, 0);
+ return (flags != -1) && (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0);
+ }
+
+# endif
+
+static inline void serverlib_aux_set_no_sigpipe(socket_t fd)
+{
+# ifdef SO_NOSIGPIPE
+ int option = 1;
+ setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &option, sizeof(option));
+# else
+ (void) fd;
+# endif
+}
+
+/*
+
+ We maintain a double linked list of connections (clients) that are in two states: reading or
+ writing. We also decided to add a way to get statistics. Because the server itself is blocking,
+ we don't need a server record and userdata.
+
+*/
+
+# define default_timeout 60
+# define default_delay 1
+
+typedef struct server_statistics {
+ time_t start_time;
+ size_t total_requests;
+ size_t total_errors;
+ size_t bytes_read;
+ size_t bytes_written;
+ size_t active_clients;
+ size_t max_nofclients;
+ size_t timedout_clients;
+ size_t client_timeout;
+} server_statistics;
+
+typedef enum {
+ client_state_reading = 0,
+ client_state_writing = 1,
+} client_states;
+
+typedef struct client {
+ socket_t fd; /* aka |filedescriptor|, the common name for this */
+ char peer_ip[INET_ADDRSTRLEN];
+ char read_buffer[65536]; /* if we even need more we can have some dynamic fallback */
+ size_t read_bytes;
+ const char *write_buffer; /* pointer to Lua string data (no copy needed) */
+ size_t write_length;
+ size_t write_position;
+ int write_reference; /* registry reference to anchor Lua string |write_buffer| */
+ int state;
+ time_t last_time;
+ struct client *prev;
+ struct client *next;
+} client;
+
+/* We have a more extensive list of messages (and mimes) at the \LUA\ end. */
+
+static inline const char *serverlib_aux_status_to_string(int status)
+{
+ switch (status) {
+ case 200: return "OK";
+ case 201: return "Created";
+ case 204: return "No Content";
+ case 400: return "Bad Request";
+ case 401: return "Unauthorized";
+ case 403: return "Forbidden";
+ case 404: return "Not Found";
+ case 413: return "Request Entity Too Large";
+ case 500: return "Internal Error";
+ default: return "OK";
+ }
+}
+
+static int serverlib_aux_get_content_length(
+ const char *buffer,
+ size_t header_len,
+ size_t *content_length
+)
+{
+ const char *ptr = buffer;
+ const char *end = buffer + header_len;
+ int first_line = 1;
+ int found = 0;
+
+ *content_length = 0;
+
+ while (ptr < end) {
+ const char *line_end = strstr(ptr, "\r\n");
+ if (! line_end || line_end > end) {
+ break;
+ }
+ if (! first_line && (size_t) (line_end - ptr) >= 15 &&
+ (ptr[0] == 'C' || ptr[0] == 'c') && strncasecmp(ptr, "content-length:", 15) == 0) {
+ const char *value = ptr + 15;
+ size_t length = 0;
+
+ while (value < line_end && (*value == ' ' || *value == '\t')) {
+ value++;
+ }
+ if (value == line_end || *value < '0' || *value > '9') {
+ return 0;
+ }
+ while (value < line_end && *value >= '0' && *value <= '9') {
+ size_t digit = (size_t) (*value - '0');
+ if (length > (SIZE_MAX - digit) / 10) {
+ return 0;
+ }
+ length = length * 10 + digit;
+ value++;
+ }
+ while (value < line_end && (*value == ' ' || *value == '\t')) {
+ value++;
+ }
+ if (value != line_end || (found && *content_length != length)) {
+ return 0;
+ }
+ *content_length = length;
+ found = 1;
+ }
+ first_line = 0;
+ ptr = line_end + 2;
+ }
+ return 1;
+}
+
+static size_t serverlib_aux_buffer_length(int length, size_t size)
+{
+ if (length <= 0 || size == 0) {
+ return 0;
+ } else if ((size_t) length >= size) {
+ return size - 1;
+ } else {
+ return (size_t) length;
+ }
+}
+
+static void serverlib_aux_report(
+ lua_State *L,
+ int report_ref,
+ const char *fmt,
+ ...
+)
+{
+ if (report_ref == LUA_NOREF || ! fmt) {
+ return;
+ }
+
+ lua_rawgeti(L, LUA_REGISTRYINDEX, report_ref);
+ lua_pushstring(L, fmt);
+ int nargs = 1;
+
+ /* We need to map onto our formatter and deal with the vararg. */
+
+ va_list args;
+ va_start(args, fmt);
+ const char *p = fmt;
+ while (*p) {
+ if (*p == '%') {
+ p++;
+ switch (*p) {
+ case 's':
+ {
+ const char *s = va_arg(args, const char *);
+ lua_pushstring(L, s ? s : "");
+ nargs++;
+ break;
+ }
+ case 'i':
+ /* case 'd': */
+ {
+ int i = va_arg(args, int);
+ lua_pushinteger(L, i);
+ nargs++;
+ break;
+ }
+ case '\0':
+ continue; /*quits the while */
+ default:
+ break;
+ }
+ }
+ p++;
+ }
+ va_end(args);
+
+ if (lua_pcall(L, nargs, 0, 0) != LUA_OK) {
+ /* we just ignore errors */
+ lua_pop(L, 1);
+ }
+}
+
+static void serverlib_aux_client(
+ client **head,
+ socket_t fd,
+ const char *ip,
+ server_statistics *statistics
+)
+{
+ client *c = (client*) lmt_memory_calloc(1, sizeof(client));
+ if (! c) {
+ close_socket(fd);
+ return;
+ }
+ c->fd = fd;
+ c->write_reference = LUA_NOREF;
+ c->state = client_state_reading;
+ if (ip) {
+ strncpy(c->peer_ip, ip, sizeof(c->peer_ip) - 1);
+ }
+ c->last_time = time(NULL);
+ c->next = *head;
+ c->prev = NULL;
+ if (*head) {
+ (*head)->prev = c;
+ }
+ *head = c;
+ if (statistics) {
+ statistics->active_clients++;
+ if (statistics->active_clients > statistics->max_nofclients) {
+ statistics->max_nofclients = statistics->active_clients;
+ }
+ }
+}
+
+static void serverlib_aux_remove_client(
+ lua_State *L,
+ client **head,
+ client *target,
+ server_statistics *statistics
+)
+{
+ if (target) {
+ if (target->prev) {
+ target->prev->next = target->next;
+ } else {
+ *head = target->next;
+ }
+ if (target->next) {
+ target->next->prev = target->prev;
+ }
+ close_socket(target->fd);
+ if (target->write_reference != LUA_NOREF) {
+ luaL_unref(L, LUA_REGISTRYINDEX, target->write_reference);
+ target->write_reference = LUA_NOREF;
+ }
+ lmt_memory_free(target);
+ if (statistics && statistics->active_clients > 0) {
+ statistics->active_clients--;
+ }
+ }
+}
+
+static void serverlib_aux_send_error_response(
+ lua_State *L,
+ client *c,
+ server_statistics *statistics,
+ int status,
+ const char *body,
+ int report_ref
+)
+{
+ statistics->total_errors++;
+ serverlib_aux_report(L, report_ref, "error %i for client %s (%s)", status, c->peer_ip[0] ? c->peer_ip : "client", body ? body : "");
+
+ size_t body_length = body ? strlen(body) : 0;
+
+ luaL_Buffer buffer;
+ luaL_buffinit(L, &buffer);
+
+ char header[128];
+ int header_length = snprintf(header, sizeof(header),
+ "HTTP/1.1 %d %s\r\n"
+ "Content-Type: text/plain\r\n"
+ "Content-Length: %lu\r\n"
+ "Connection: close\r\n\r\n",
+ status, serverlib_aux_status_to_string(status), (unsigned long) body_length
+ );
+ luaL_addlstring(&buffer, header, serverlib_aux_buffer_length(header_length, sizeof(header)));
+
+ if (body_length > 0) {
+ luaL_addlstring(&buffer, body, body_length);
+ }
+
+ luaL_pushresult(&buffer);
+ c->write_buffer = lua_tolstring(L, -1, &c->write_length);
+ c->write_reference = luaL_ref(L, LUA_REGISTRYINDEX); /* also pops */
+ c->state = client_state_writing;
+}
+
+/*tex
+
+ Features like the report and step (with delay) are just there because we need those in existing
+ applications. Some use cases are (private:) hue and evohome servers (wrappers), publishing on
+ demand workflows where we produce sets of (educational) documents from a huge collection of xml
+ files based on user selection (chapters, features), context related services (help, font samples,
+ etc). These various applications determined what we have below. But some more might be added.
+
+ We run on localhost, mayeb on a server in the intranet, and for the outside world simpe servers
+ like below sit nicely behind for instance nginx that then does the https and deals with the
+ redirection of subdomains.
+
+*/
+
+static void serverlib_aux_process_request(
+ lua_State *L,
+ client *c,
+ size_t content_length,
+ int callback_ref,
+ int trace,
+ server_statistics *statistics,
+ int stats,
+ int report_ref
+)
+{
+ char method[16] = { 0 };
+ char path[512] = { 0 };
+
+ statistics->total_requests++;
+
+ /* first we validate the http request line strictly using space delimiters */
+
+ char *line_end = strstr(c->read_buffer, "\r\n");
+ char *sp1 = line_end ? strchr(c->read_buffer, ' ') : NULL;
+ char *sp2 = sp1 ? strchr(sp1 + 1, ' ') : NULL;
+
+ if (! line_end || ! sp1 || ! sp2 || sp1 > line_end || sp2 > line_end) {
+ serverlib_aux_send_error_response(L, c, statistics, 400, "400 Bad Request", report_ref);
+ return;
+ }
+
+ size_t m_len = sp1 - c->read_buffer;
+ size_t p_len = sp2 - (sp1 + 1);
+
+ if (m_len == 0 || m_len >= sizeof(method) || p_len == 0 || p_len >= sizeof(path)) {
+ serverlib_aux_send_error_response(L, c, statistics, 400, "400 Bad Request", report_ref);
+ return;
+ }
+
+ memcpy(method, c->read_buffer, m_len);
+ method[m_len] = '\0';
+ memcpy(path, sp1 + 1, p_len);
+ path[p_len] = '\0';
+
+ /* we're fine and can push the callback function */
+ lua_rawgeti(L, LUA_REGISTRYINDEX, callback_ref);
+
+ /* we take a look at the keys in the table */
+ lua_newtable(L);
+ lua_pushstring(L, method);
+ lua_setfield(L, -2, "method");
+ lua_pushstring(L, path);
+ lua_setfield(L, -2, "path");
+ lua_pushstring(L, c->peer_ip);
+ lua_setfield(L, -2, "ip");
+
+ /* extract request body payload if present */
+ char *header_end = strstr(c->read_buffer, "\r\n\r\n");
+ if (header_end) {
+ const char *body_ptr = header_end + 4;
+ size_t header_len = (header_end - c->read_buffer) + 4;
+ size_t body_len = (c->read_bytes > header_len) ? (c->read_bytes - header_len) : 0;
+ if (body_len > content_length) {
+ body_len = content_length;
+ }
+
+ lua_pushlstring(L, body_ptr, body_len);
+ lua_setfield(L, -2, "body");
+ }
+
+ /*
+ we need headers when we want to handle post requests, we could do this in Lua instead
+ as we did before
+ */
+ if (header_end) {
+ lua_newtable(L);
+ /* skip the request line */
+ char *line_start = strstr(c->read_buffer, "\r\n");
+ if (line_start && line_start < header_end) {
+ /* skip the initial \r\n */
+ line_start += 2;
+ while (line_start < header_end) {
+ char *next_line = strstr(line_start, "\r\n");
+ if (! next_line || next_line > header_end) {
+ break;
+ }
+ char *colon = memchr(line_start, ':', next_line - line_start);
+ if (colon) {
+ /* lowercase key */
+ size_t klen = colon - line_start;
+ char *val_start = colon + 1;
+ char key_buf[256]; /* plenty */
+ char *key = key_buf;
+ if (klen >= sizeof(key_buf)) {
+ key = (char *) lmt_memory_malloc(klen);
+ if (! key) {
+ line_start = next_line + 2;
+ continue;
+ }
+ }
+ for (size_t i = 0; i < klen; i++) {
+ key[i] = (char) tolower((unsigned char) line_start[i]);
+ }
+ lua_pushlstring(L, key, klen);
+ if (key != key_buf) {
+ lmt_memory_free(key);
+ }
+ size_t vlen = next_line - val_start;
+ lua_pushlstring(L, val_start, vlen);
+ lua_settable(L, -3);
+ }
+ line_start = next_line + 2;
+ }
+ }
+ lua_setfield(L, -2, "headers");
+ }
+
+ if (stats) {
+ lua_newtable(L);
+ lua_pushinteger(L, (lua_Integer) (time(NULL) - statistics->start_time));
+ lua_setfield(L, -2, "uptime");
+ lua_pushinteger(L, (lua_Integer) statistics->total_requests);
+ lua_setfield(L, -2, "requests");
+ lua_pushinteger(L, (lua_Integer) statistics->total_errors);
+ lua_setfield(L, -2, "errors");
+ lua_pushinteger(L, (lua_Integer) statistics->bytes_read);
+ lua_setfield(L, -2, "bytesread");
+ lua_pushinteger(L, (lua_Integer) statistics->bytes_written);
+ lua_setfield(L, -2, "byteswritten");
+ lua_pushinteger(L, (lua_Integer) statistics->active_clients);
+ lua_setfield(L, -2, "activeclients");
+ lua_pushinteger(L, (lua_Integer) statistics->max_nofclients);
+ lua_setfield(L, -2, "maxnofclients");
+ lua_pushinteger(L, (lua_Integer) statistics->client_timeout);
+ lua_setfield(L, -2, "clienttimeout");
+ lua_pushinteger(L, (lua_Integer) statistics->timedout_clients);
+ lua_setfield(L, -2, "timedoutclients");
+ lua_setfield(L, -2, "statistics");
+ }
+
+ /* time for some action */
+ if (lua_pcall(L, 1, 1, 0) == LUA_OK) {
+ int status = 200;
+ const char *mime = "text/plain";
+ size_t mime_length = sizeof("text/plain") - 1;
+ const char *body = "";
+ size_t body_length = 0;
+
+ if (lua_istable(L, -1)) {
+ int table_index = lua_gettop(L);
+
+ lua_getfield(L, table_index, "status");
+ if (lua_isinteger(L, -1)) {
+ status = (int) lua_tointeger(L, -1);
+ }
+ lua_pop(L, 1);
+ if (status >= 400) {
+ statistics->total_errors++;
+ serverlib_aux_report(L, report_ref, "handler returned status %i for %s %s", status, method, path);
+ }
+
+ lua_getfield(L, table_index, "mime");
+ if (lua_isstring(L, -1)) {
+ mime = lua_tolstring(L, -1, &mime_length);
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, table_index, "body");
+ if (lua_isstring(L, -1)) {
+ body = lua_tolstring(L, -1, &body_length);
+ }
+ lua_pop(L, 1);
+
+ luaL_Buffer buffer;
+ luaL_buffinit(L, &buffer);
+
+ char status_header[128];
+ int status_length = snprintf(status_header, sizeof(status_header),
+ "HTTP/1.1 %d %s\r\nContent-Type: ",
+ status, serverlib_aux_status_to_string(status)
+ );
+ luaL_addlstring(&buffer, status_header,
+ serverlib_aux_buffer_length(status_length, sizeof(status_header)));
+ luaL_addlstring(&buffer, mime, mime_length);
+
+ char content_header[128];
+ int content_length_header = snprintf(content_header, sizeof(content_header),
+ "\r\nContent-Length: %lu\r\nConnection: close\r\n", (unsigned long) body_length
+ );
+ luaL_addlstring(&buffer, content_header,
+ serverlib_aux_buffer_length(content_length_header, sizeof(content_header)));
+
+ lua_getfield(L, table_index, "headers");
+ if (lua_isstring(L, -1)) {
+ size_t len = 0;
+ const char *str = lua_tolstring(L, -1, &len);
+ if (len > 0) {
+ luaL_addlstring(&buffer, str, len);
+ if (len < 2 || str[len - 2] != '\r' || str[len - 1] != '\n') {
+ luaL_addstring(&buffer, "\r\n");
+ }
+ }
+ lua_pop(L, 1);
+ } else if (lua_istable(L, -1)) {
+ int index = lua_gettop(L);
+ lua_pushnil(L);
+ while (lua_next(L, index) != 0) {
+ if (lua_type(L, -2) == LUA_TSTRING && lua_isstring(L, -1)) {
+ luaL_addstring(&buffer, lua_tostring(L, -2));
+ luaL_addstring(&buffer, ": ");
+ luaL_addstring(&buffer, lua_tostring(L, -1));
+ luaL_addstring(&buffer, "\r\n");
+ } else if (lua_type(L, -2) == LUA_TNUMBER && lua_isstring(L, -1)) {
+ luaL_addstring(&buffer, lua_tostring(L, -1));
+ luaL_addstring(&buffer, "\r\n");
+ }
+ lua_pop(L, 1);
+ }
+ lua_pop(L, 1);
+ } else {
+ lua_pop(L, 1);
+ }
+
+ luaL_addstring(&buffer, "\r\n");
+
+ if (body_length > 0) {
+ luaL_addlstring(&buffer, body, body_length);
+ }
+
+ luaL_pushresult(&buffer);
+ lua_remove(L, table_index);
+ } else {
+ luaL_Buffer buffer;
+ luaL_buffinit(L, &buffer);
+ luaL_addstring(&buffer, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
+ luaL_pushresult(&buffer);
+ lua_remove(L, -2);
+ }
+ /* now the result string is at the top: -1 */
+ c->write_buffer = lua_tolstring(L, -1, &c->write_length);
+ c->write_reference = luaL_ref(L, LUA_REGISTRYINDEX);
+ c->state = client_state_writing;
+ } else {
+ const char *err = trace ? lua_tostring(L, -1) : "Internal Server Error";
+ serverlib_aux_report(L, report_ref, "lua callback error: %s", lua_tostring(L, -1));
+ serverlib_aux_send_error_response(L, c, statistics, 500, err, report_ref);
+ lua_pop(L, 1);
+ }
+}
+
+/*
+ Here we have the event loop. When a request is encountered the \LUA\ callback kicks in.
+*/
+
+static int serverlib_httpserver(lua_State *L)
+{
+ int port = 0;
+ int client_timeout = default_timeout;
+ int trace = 0;
+ int stats = 0;
+ int callback_ref = LUA_NOREF;
+ int report_ref = LUA_NOREF;
+ int step_ref = LUA_NOREF;
+# ifdef _WIN32
+ int wsa_initialized = 0;
+# endif
+ long select_sec = default_delay;
+ long select_usec = 0;
+
+ server_statistics statistics;
+ memset(&statistics, 0, sizeof(server_statistics));
+ statistics.start_time = time(NULL);
+
+ if (lua_istable(L, 1)) {
+
+ lua_getfield(L, 1, "port");
+ if (lua_isinteger(L, -1)) {
+ port = lmt_tointeger(L, -1);
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, 1, "report");
+ if (lua_isfunction(L, -1)) {
+ report_ref = luaL_ref(L, LUA_REGISTRYINDEX);
+ } else {
+ lua_pop(L, 1);
+ }
+
+ lua_getfield(L, 1, "action");
+ if (lua_isfunction(L, -1)) {
+ callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
+ } else {
+ lua_pop(L, 1);
+ serverlib_aux_report(L, report_ref, "valid 'action' function required");
+ goto DONE;
+ }
+
+ lua_getfield(L, 1, "timeout");
+ if (lua_isinteger(L, -1)) {
+ client_timeout = lmt_tointeger(L, -1);
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, 1, "trace");
+ trace = lua_toboolean(L, -1);
+ lua_pop(L, 1);
+
+ lua_getfield(L, 1, "statistics");
+ stats = lua_toboolean(L, -1);
+ lua_pop(L, 1);
+
+ lua_getfield(L, 1, "step");
+ if (lua_isfunction(L, -1)) {
+ step_ref = luaL_ref(L, LUA_REGISTRYINDEX);
+ } else {
+ lua_pop(L, 1);
+ }
+
+ lua_getfield(L, 1, "delay"); /* also accepts 0.5 */
+ if (lua_isnumber(L, -1)) {
+ double d = lua_tonumber(L, -1);
+ if (d > 0.0) {
+ select_sec = (long) d;
+ select_usec = (long) ((d - (double) select_sec) * 1000000.0);
+ }
+ }
+ lua_pop(L, 1);
+
+ } else {
+ /* we don't have the reporter available */
+ return luaL_error(L, "server.httpserver expects a table");
+ }
+
+ statistics.client_timeout = client_timeout;
+
+ if (port <= 0 || port > 65535) {
+ serverlib_aux_report(L, report_ref, "valid 'port' required");
+ goto DONE;
+ }
+
+# ifdef _WIN32
+ WSADATA wsa;
+ if (WSAStartup(MAKEWORD(2, 2), &wsa) == 0) {
+ wsa_initialized = 1;
+ } else {
+ serverlib_aux_report(L, report_ref, "failed to initialize winsock");
+ goto DONE;
+ }
+# endif
+
+ socket_t server_fd = socket(AF_INET, SOCK_STREAM, 0);
+ if (invalid_socket(server_fd)) {
+ serverlib_aux_report(L, report_ref, "failed to create socket");
+ goto DONE;
+ }
+
+# ifndef _WIN32
+ if (server_fd >= FD_SETSIZE) {
+ serverlib_aux_report(L, report_ref, "server socket descriptor too large");
+ close_socket(server_fd);
+ goto DONE;
+ }
+# endif
+
+ int opt = 1;
+ setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, (const char*) &opt, sizeof(opt));
+ if (! set_nonblocking(server_fd)) {
+ serverlib_aux_report(L, report_ref, "failed to configure socket");
+ close_socket(server_fd);
+ goto DONE;
+ }
+
+ struct sockaddr_in addr;
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = INADDR_ANY;
+ addr.sin_port = htons(port);
+
+ if (bind(server_fd, (struct sockaddr*) &addr, sizeof(addr)) < 0 || listen(server_fd, 128) < 0) {
+ serverlib_aux_report(L, report_ref, "failed to bind or listen on port %i", port);
+ close_socket(server_fd);
+ goto DONE;
+ }
+
+# if !defined(_WIN32) && !defined(MSG_NOSIGNAL) && !defined(SO_NOSIGPIPE)
+ signal(SIGPIPE, SIG_IGN);
+# endif
+
+ serverlib_aux_report(L, report_ref, "non-blocking event loop started on http://localhost:%i", port);
+
+ client *clients = NULL;
+
+ while (1) {
+ fd_set read_fds, write_fds;
+ FD_ZERO(&read_fds);
+ FD_ZERO(&write_fds);
+
+ /* always monitor listening socket for new incoming connections */
+ FD_SET(server_fd, &read_fds);
+ socket_t max_fd = server_fd;
+
+ /* register client sockets depending on state */
+ client *current = clients;
+ while (current) {
+ if (current->state == client_state_reading) {
+ FD_SET(current->fd, &read_fds);
+ } else if (current->state == client_state_writing) {
+ FD_SET(current->fd, &write_fds);
+ }
+ if (current->fd > max_fd) {
+ max_fd = current->fd;
+ }
+ current = current->next;
+ }
+
+ /* we can configure the timeout */
+ struct timeval timeout = { select_sec, select_usec };
+ int activity = select((int) max_fd + 1, &read_fds, &write_fds, NULL, &timeout);
+ if (activity < 0) {
+# ifdef _WIN32
+ if (WSAGetLastError() == WSAEINTR) {
+# else
+ if (errno == EINTR) {
+# endif
+ continue;
+ }
+ serverlib_aux_report(L, report_ref, "select failed");
+ break;
+ }
+
+ /* handle a new connection and possibly add it to the linked list */
+ if (FD_ISSET(server_fd, &read_fds)) {
+ struct sockaddr_in client_addr;
+ socklen_t addrlen = sizeof(client_addr);
+ socket_t client_fd = accept(server_fd, (struct sockaddr*) &client_addr, &addrlen);
+ if (! invalid_socket(client_fd)) {
+# ifdef _WIN32
+ int room = statistics.active_clients < (size_t) (FD_SETSIZE - 1);
+# else
+ int room = client_fd < FD_SETSIZE;
+# endif
+ if (room && set_nonblocking(client_fd)) {
+ serverlib_aux_set_no_sigpipe(client_fd);
+ char ip_str[INET_ADDRSTRLEN] = {0};
+ inet_ntop(AF_INET, &client_addr.sin_addr, ip_str, INET_ADDRSTRLEN);
+ serverlib_aux_client(&clients, client_fd, ip_str, &statistics);
+ } else {
+ close_socket(client_fd);
+ }
+ }
+ }
+
+ /* service existing clients in the linked list */
+ current = clients;
+ while (current) {
+ /* we save the next pointer becauuse we can free current */
+ client *next = current->next;
+ if (current->state == client_state_reading && FD_ISSET(current->fd, &read_fds)) {
+ /* read state: accumulate request bytes */
+ int n = recv(
+ current->fd, current->read_buffer + current->read_bytes,
+ sizeof(current->read_buffer) - 1 - current->read_bytes,
+ 0
+ );
+ if (n > 0) {
+ statistics.bytes_read += n;
+ current->last_time = time(NULL); /* update timestamp */
+ current->read_bytes += n;
+ current->read_buffer[current->read_bytes] = '\0';
+
+ /* check if the https header end (\r\n\r\n) is reached */
+ char *header_end = strstr(current->read_buffer, "\r\n\r\n");
+ if (header_end) {
+ size_t header_len = (header_end - current->read_buffer) + 4;
+ size_t content_len = 0;
+ if (! serverlib_aux_get_content_length(current->read_buffer, header_len, &content_len)) {
+ serverlib_aux_send_error_response(L, current, &statistics, 400, "400 Bad Request", report_ref);
+ } else if (content_len >= sizeof(current->read_buffer) - header_len) {
+ serverlib_aux_send_error_response(L, current, &statistics, 413, "413 Request Entity Too Large", report_ref);
+ } else if (current->read_bytes >= header_len + content_len) {
+ serverlib_aux_process_request(L, current, content_len, callback_ref, trace, &statistics, stats, report_ref);
+ }
+ }
+ } else if (n == 0 || (n < 0 && ! would_block)) {
+ /* the client closed the connection or went bad */
+ serverlib_aux_remove_client(L, &clients, current, &statistics);
+ }
+ } else if (current->state == client_state_writing && FD_ISSET(current->fd, &write_fds)) {
+ /* write state: send response chunk by chunk */
+ int sent = send(
+ current->fd,
+ current->write_buffer + current->write_position,
+ (int) (current->write_length - current->write_position),
+ send_flags
+ );
+ if (sent > 0) {
+ statistics.bytes_written += sent;
+ current->write_position += sent;
+ if (current->write_position >= current->write_length) {
+ /* we're finished sending response */
+ serverlib_aux_remove_client(L, &clients, current, &statistics);
+ }
+ } else if (sent < 0 && ! would_block) {
+ serverlib_aux_remove_client(L, &clients, current, &statistics);
+ }
+ }
+ current = next;
+ }
+
+ /* cleanup stale clients */
+ if (client_timeout > 0) {
+ time_t now = time(NULL);
+ current = clients;
+ while (current) {
+ client *next = current->next;
+ if (now - current->last_time > client_timeout) {
+ serverlib_aux_report(L, report_ref, "client %s timed out", current->peer_ip[0] ? current->peer_ip : "client");
+ serverlib_aux_remove_client(L, &clients, current, &statistics);
+ statistics.timedout_clients += 1;
+ }
+ current = next;
+ }
+ }
+
+ /* optionally run a step function */
+ if (step_ref != LUA_NOREF) {
+ lua_rawgeti(L, LUA_REGISTRYINDEX, step_ref);
+ if (lua_pcall(L, 0, 1, 0) == LUA_OK) {
+ if (lua_isnumber(L, -1)) {
+ double d = lua_tonumber(L, -1);
+ if (d >= 0.0) {
+ select_sec = (long) d;
+ select_usec = (long) ((d - (double) select_sec) * 1000000.0);
+ }
+ }
+ } else if (trace) {
+ serverlib_aux_report(L, report_ref, "lua step callback error: %s", lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+ }
+ }
+
+ while (clients) {
+ serverlib_aux_remove_client(L, &clients, clients, &statistics);
+ }
+ close_socket(server_fd);
+
+ DONE:
+ if (callback_ref != LUA_NOREF) {
+ luaL_unref(L, LUA_REGISTRYINDEX, callback_ref);
+ }
+ if (report_ref != LUA_NOREF) {
+ luaL_unref(L, LUA_REGISTRYINDEX, report_ref);
+ }
+ if (step_ref != LUA_NOREF) {
+ luaL_unref(L, LUA_REGISTRYINDEX, step_ref);
+ }
+# ifdef _WIN32
+ if (wsa_initialized) {
+ WSACleanup();
+ }
+# endif
+ return 0;
+}
+
+static int serverlib_supported(lua_State *L)
+{
+ /* todo: some magick check */
+ lua_pushboolean(L, 1);
+ return 1;
+}
+
+static const struct luaL_Reg serverlib_function_list[] = {
+ { "httpserver", serverlib_httpserver },
+ { "supported", serverlib_supported },
+ { NULL, NULL },
+};
+
+int luaopen_server(lua_State *L)
+{
+ luaL_newlib(L, serverlib_function_list);
+ return 1;
+}
diff --git a/source/luametatex/source/luarest/lmtstrlibext.c b/source/luametatex/source/luarest/lmtstrlibext.c
index b29e99465..41f79cd80 100644
--- a/source/luametatex/source/luarest/lmtstrlibext.c
+++ b/source/luametatex/source/luarest/lmtstrlibext.c
@@ -18,90 +18,105 @@
*/
# include "luametatex.h"
+# include <limits.h>
-/*tex Helpers */
+# define max_format_precision (INT_MAX - 350)
+# define max_nesting_depth 1000 /* nested tables, we need to stay within the C stack */
-static inline int strlib_aux_tounicode(const char *str, size_t len, size_t *pos)
+static inline int strlib_aux_parse_decimal(int value, int digit)
{
- const unsigned char *s = (const unsigned char *) str;
- size_t p = *pos;
- if (p < len) {
- unsigned char i = s[p++];
- if (i < 0x80) {
- *pos = p;
- return i;
- } else {
- /*tex We only test redundantly when we have a wrong one. */
- if (i >= 0xF0) {
- if (p + 2 < len) {
- unsigned char j = s[p];
- unsigned char k = s[p + 1];
- unsigned char l = s[p + 2];
- if ((j & 0xC0) == 0x80 && (k & 0xC0) == 0x80 && (l & 0xC0) == 0x80) {
- *pos = p + 3;
- return ((i & 0x07) << 18) | ((j & 0x3F) << 12) | ((k & 0x3F) << 6) | (l & 0x3F);
- }
- }
- } else if (i >= 0xE0) {
- if (p + 1 < len) {
- unsigned char j = s[p];
- unsigned char k = s[p + 1];
- if ((j & 0xC0) == 0x80 && (k & 0xC0) == 0x80) {
- *pos = p + 2;
- return ((i & 0x0F) << 12) | ((j & 0x3F) << 6) | (k & 0x3F);
- }
- }
- } else if (i >= 0xC0) {
- if (p < len) {
- unsigned char j = s[p];
- if ((j & 0xC0) == 0x80) {
- *pos = p + 1;
- return ((i & 0x1F) << 6) | (j & 0x3F);
- }
- }
- }
- *pos = p;
- }
+ if (value > (INT_MAX - digit) / 10) {
+ return INT_MAX;
+ } else {
+ return value * 10 + digit;
}
- /* invalid sequence or incomplete trailing bytes */
- return 0xFFFD;
}
-static inline int strlib_aux_tounichar(const char *str, size_t len, size_t pos)
+static inline int strlib_aux_normalize_precision(lua_Integer precision)
{
- if (pos < len) {
- const unsigned char *s = (const unsigned char *) str;
- unsigned char i = s[pos++];
- if (i < 0x80) {
- return 1;
- } else if (i >= 0xF0) {
- if ((pos + 2) < len) {
- unsigned char j = s[pos];
- unsigned char k = s[pos + 1];
- unsigned char l = s[pos + 2];
- if ((j & 0xC0) == 0x80 && (k & 0xC0) == 0x80 && (l & 0xC0) == 0x80) {
- return 4;
- }
- }
- } else if (i >= 0xE0) {
- if ((pos + 1) < len) {
- unsigned char j = s[pos];
- unsigned char k = s[pos + 1];
- if ((j & 0xC0) == 0x80 && (k & 0xC0) == 0x80) {
- return 3;
- }
+ if (precision <= 0) {
+ return 0;
+ } else if ((lua_Unsigned) precision > (lua_Unsigned) max_format_precision) {
+ return max_format_precision;
+ } else {
+ return (int) precision;
+ }
+}
+
+/*tex
+ Helpers. We do a bit more checking than needed; we know what goes in, but do it anyway.
+*/
+
+static inline int strlib_aux_tounicode(const char *str, size_t len, size_t *pos)
+{
+ const unsigned char *s = (const unsigned char *) str;
+ size_t start = *pos;
+ if (start >= len) {
+ return 0xFFFD;
+ }
+ unsigned char i = s[start];
+ size_t required = 0;
+ size_t total_len = 1;
+ int codepoint = 0;
+ if (i < 0x80) {
+ *pos = start + 1;
+ return i;
+ } else if (i >= 0xC0 && i <= 0xDF) {
+ required = 1;
+ total_len = 2;
+ codepoint = i & 0x1F;
+ } else if (i >= 0xE0 && i <= 0xEF) {
+ required = 2;
+ total_len = 3;
+ codepoint = i & 0x0F;
+ } else if (i >= 0xF0 && i <= 0xF4) {
+ required = 3;
+ total_len = 4;
+ codepoint = i & 0x07;
+ } else {
+ /* invalid lead byte (e.g., 0xF5-0xFF or raw continuation bytes 0x80-0xBF) */
+ *pos = start + 1;
+ return 0xFFFD;
+ }
+ /* check if the string ends prematurely before the sequence completes */
+ if (start + total_len > len) {
+ *pos = start + 1;
+ return 0xFFFD;
+ }
+ /* validate continuation bytes and check for overlong/invalid encodings */
+ if (required == 1) {
+ unsigned char j = s[start + 1];
+ if ((j & 0xC0) == 0x80 && i >= 0xC2) { /* i >= 0xC2 rejects overlong 0xC0, 0xC1 */
+ *pos = start + 2;
+ return codepoint << 6 | (j & 0x3F);
+ }
+ } else if (required == 2) {
+ unsigned char j = s[start + 1];
+ unsigned char k = s[start + 2];
+ if ((j & 0xC0) == 0x80 && (k & 0xC0) == 0x80) {
+ /* reject overlong (E0 0x80-0x9F) and surrogate halves (ED 0xA0-0xBF) */
+ if (!((i == 0xE0 && j < 0xA0) || (i == 0xED && j >= 0xA0))) {
+ int cp = (codepoint << 12) | ((j & 0x3F) << 6) | (k & 0x3F);
+ *pos = start + 3;
+ return cp;
}
- } else if (i >= 0xC0) {
- if (pos < len) {
- unsigned char j = s[pos];
- if ((j & 0xC0) == 0x80) {
- return 2;
- }
+ }
+ } else if (required == 3) {
+ unsigned char j = s[start + 1];
+ unsigned char k = s[start + 2];
+ unsigned char l = s[start + 3];
+ if ((j & 0xC0) == 0x80 && (k & 0xC0) == 0x80 && (l & 0xC0) == 0x80) {
+ /* reject out-of-range (> 0x10FFFF) */
+ if (!((i == 0xF0 && j < 0x90) || (i == 0xF4 && j > 0x8F))) {
+ int cp = (codepoint << 18) | ((j & 0x3F) << 12) | ((k & 0x3F) << 6) | (l & 0x3F);
+ *pos = start + 4;
+ return cp;
}
}
}
- /* invalid sequence or incomplete bytes */
- return 0;
+ /* validation failed: only consume the lead byte so that we don't swallow valid characters */
+ *pos = start + 1;
+ return 0xFFFD;
}
static inline size_t strlib_aux_toline(const char *s, size_t l, size_t p, size_t *b)
@@ -203,6 +218,90 @@ static int strlib_aux_utf_failed(lua_State *L, int new_ind)
return 1;
}
+static int strlib_onlyascii(lua_State *L)
+{
+ size_t len = 0;
+ const char *str = lua_tolstring(L, 1, &len);
+
+ if (str == NULL) {
+ return luaL_error(L, "string expected for ascii check");
+ } else {
+ lua_pushboolean(L, aux_onlyascii(str, len));
+ return 1;
+ }
+}
+
+/*
+ Here is a nice test for gemini (best also feed it a coding style):
+
+ -- can you make me function that strips characters that don't match 0-9, a-z, A-Z, and > 127
+ -- good, but instead of adding chars to the buffer can we check if needed first
+ -- better, now let's add the first slice when we have a hit and go from there
+ -- nice, so how about an outer loop and just add slices
+ -- last, let's make the triple check an inline function
+
+ After that one has a template and can clean it up bit. It saves a little time and one still
+ has to use one's brain. Between the stages one gets compliments about the suggestions. It's
+ a bit of a game.
+
+*/
+
+static inline int is_allowed(unsigned char c)
+{
+ return (c >= '0' && c <= '9') ||
+ (c >= 'A' && c <= 'Z') ||
+ (c >= 'a' && c <= 'z') ||
+ (c > 127);
+}
+
+static int strlib_filter_weird(lua_State *L)
+{
+ size_t len;
+ const char *str = lua_tolstring(L, 1, &len);
+ if (! str) {
+ lua_pushnil(L);
+ return 1;
+ }
+ /* check if the string is already 100% clean */
+ size_t first_bad = len;
+ for (size_t i = 0; i < len; i++) {
+ if (! is_allowed((unsigned char) str[i])) {
+ first_bad = i;
+ break;
+ }
+ }
+ if (first_bad == len) {
+ lua_pushvalue(L, 1);
+ return 1;
+ }
+ /* initialize buffer and add the initial clean prefix */
+ luaL_Buffer b;
+ luaL_buffinit(L, &b);
+ if (first_bad > 0) {
+ luaL_addlstring(&b, str, first_bad);
+ }
+ /* outer loop: jump over bad characters and bulk-copy subsequent clean slices */
+ size_t i = first_bad;
+ while (i < len) {
+ /* skip past consecutive bad characters */
+ while (i < len && ! is_allowed((unsigned char) str[i])) {
+ i++;
+ }
+ if (i >= len) {
+ break;
+ }
+ /* find the end of this clean slice */
+ size_t slice_start = i;
+ while (i < len && is_allowed((unsigned char) str[i])) {
+ i++;
+ }
+ /* bulk-copy the entire clean slice in one shot */
+ luaL_addlstring(&b, str + slice_start, i - slice_start);
+ }
+ luaL_pushresult(&b);
+ return 1;
+}
+
/* kind of complex ... these masks */
// static int strlib_aux_utfcharacters(lua_State *L)
@@ -295,14 +394,6 @@ static int strlib_aux_utf_failed(lua_State *L, int new_ind)
consult the competition as this seems to be a common approach.
*/
-static const unsigned char utf8_lengths[16] = {
- 1, 1, 1, 1, 1, 1, 1, 1, /* 0x0 - 0x7 : ASCII (1 byte) */
- 0, 0, 0, 0, /* 0x8 - 0xB : continuation bytes (invalid lead) */
- 2, 2, /* 0xC - 0xD : 2-byte sequence */
- 3, /* 0xE : 3-byte sequence */
- 4 /* 0xF : 4-byte sequence (or invalid if > 0xF4) */
-};
-
static int strlib_aux_utfcharacters(lua_State *L)
{
size_t ls = 0;
@@ -311,32 +402,15 @@ static int strlib_aux_utfcharacters(lua_State *L)
if (ind >= ls) {
return 0;
} else {
- unsigned char c = (unsigned char) s[ind];
- if (c < 0x80) {
- lua_pushinteger(L, ind + 1);
- lua_replace(L, lua_upvalueindex(2));
- lua_pushlstring(L, s + ind, 1);
- return 1;
- } else {
- size_t len = utf8_lengths[c >> 4];
- if (len == 0 || c > 0xF4) {
- return strlib_aux_utf_failed(L, (int) (ind + 1));
- } else if (ind + len > ls) {
- /*tex The result will not fit. */
- return strlib_aux_utf_failed(L, (int) ls);
- } else {
- for (size_t k = 1; k < len; k++) {
- if (((unsigned char) s[ind + k] & 0xC0) != 0x80) {
- /*tex We have a bad follow byte. */
- return strlib_aux_utf_failed(L, (int) (ind + k));
- }
- }
- lua_pushinteger(L, ind + len);
- lua_replace(L, lua_upvalueindex(2));
- lua_pushlstring(L, s + ind, len);
- return 1;
- }
+ size_t next = ind;
+ int codepoint = strlib_aux_tounicode(s, ls, &next);
+ if (codepoint == 0xFFFD) {
+ return strlib_aux_utf_failed(L, (int) next);
}
+ lua_pushinteger(L, next);
+ lua_replace(L, lua_upvalueindex(2));
+ lua_pushlstring(L, s + ind, next - ind);
+ return 1;
}
}
@@ -351,14 +425,14 @@ static int strlib_utfcharacters(lua_State *L)
static int strlib_aux_utfvalues(lua_State *L)
{
- size_t l = 0;
- const char *s = lua_tolstring(L, lua_upvalueindex(1), &l);
- size_t ind = lmt_tointeger(L, lua_upvalueindex(2));
- if (ind < l) {
- int v = strlib_aux_tounicode(s, l, &ind);
+ size_t len = 0;
+ const char *str = lua_tolstring(L, lua_upvalueindex(1), &len);
+ size_t ind = lmt_tointeger(L, lua_upvalueindex(2));
+ if (ind < len) {
+ int val = strlib_aux_tounicode(str, len, &ind);
lua_pushinteger(L, ind);
lua_replace(L, lua_upvalueindex(2));
- lua_pushinteger(L, v);
+ lua_pushinteger(L, val);
return 1;
} else {
return 0;
@@ -432,18 +506,72 @@ static int strlib_characters(lua_State *L)
return 1;
}
+/*tex
+ These deal with raw bytes (not \UTF).
+*/
+
static int strlib_bytetable(lua_State *L)
{
- size_t l;
- const char *s = luaL_checklstring(L, 1, &l);
- lua_createtable(L, (int) l, 0);
- for (size_t i = 0; i < l; i++) {
- lua_pushinteger(L, (unsigned char)*(s + i));
+ size_t len;
+ const char *str = luaL_checklstring(L, 1, &len);
+ lua_createtable(L, (int) len, 0);
+ for (size_t i = 0; i < len; i++) {
+ lua_pushinteger(L, (unsigned char) *(str + i));
+ lua_rawseti(L, -2, i + 1);
+ }
+ return 1;
+}
+
+static int strlib_chartable(lua_State *L)
+{
+ size_t len;
+ const char *str = luaL_checklstring(L, 1, &len);
+ lua_createtable(L, (int) len, 0);
+ for (size_t i = 0; i < len; i++) {
+ lua_pushlstring(L, str + i, 1);
lua_rawseti(L, -2, i + 1);
}
return 1;
}
+static int strlib_totable(lua_State *L)
+{
+ size_t len;
+ const char *str = luaL_checklstring(L, 1, &len);
+ int byt = lua_toboolean(L, 2);
+ lua_createtable(L, (int) len, 0);
+ for (size_t i = 0; i < len; i++) {
+ if (byt) {
+ lua_pushinteger(L, (unsigned char) *(str + i));
+ } else {
+ lua_pushlstring(L, str + i, 1);
+ }
+ lua_rawseti(L, -2, i + 1);
+ }
+ return 1;
+}
+
+/* */
+
+static int strlib_replacecharacter(lua_State *L)
+{
+ size_t source_len, old_len, new_len;
+ luaL_Buffer b;
+ const char *source_str = luaL_checklstring(L, 1, &source_len);
+ const char *old_str = luaL_checklstring(L, 2, &old_len);
+ const char *new_str = luaL_checklstring(L, 3, &new_len);
+ char *target_str = luaL_buffinitsize(L, &b, source_len);
+ char old = old_str[0];
+ char new = new_str[0];
+ for (size_t i = 0; i < source_len; i++) {
+ target_str[i] = (source_str[i] == old) ? new : source_str[i];
+ }
+ luaL_pushresultsize(&b, source_len);
+ return 1;
+}
+
+/* */
+
static int strlib_utfvaluetable(lua_State *L)
{
size_t n = 1;
@@ -466,14 +594,18 @@ static int strlib_utfcharactertable(lua_State *L)
const char *s = luaL_checklstring(L, 1, &l);
lua_createtable(L, (int) l, 0);
while (p < l) {
- int b = strlib_aux_tounichar(s, l, p);
- if (b) {
- lua_pushlstring(L, s + p, b);
- p += b;
- } else {
+ size_t next = p;
+ int cp = strlib_aux_tounicode(s, l, &next);
+ if (next <= p) {
+ next = p + 1;
+ }
+ /* Emit U+FFFD if decoding failed, unless it's a literal U+FFFD string in the source */
+ if (cp == 0xFFFD && !(next - p == 3 && (unsigned char)s[p] == 0xEF && (unsigned char)s[p+1] == 0xBF && (unsigned char)s[p+2] == 0xBD)) {
lua_pushliteral(L, utf_fffd_string);
- p += 1;
+ } else {
+ lua_pushlstring(L, s + p, next - p);
}
+ p = next;
lua_rawseti(L, -2, n++);
}
return 1;
@@ -520,7 +652,7 @@ static int strlib_linetable(lua_State *L)
static inline void strlib_aux_add_utfchar(luaL_Buffer *b, unsigned u)
{
- if (u <= MAXUNICODE) {
+ if (u <= MAXUNICODE && (u < 0xD800 || u > 0xDFFF)) {
if (0x80 > u) {
luaL_addchar(b, (unsigned char) u);
} else {
@@ -545,36 +677,48 @@ static inline void strlib_aux_add_utfnumber(lua_State *L, luaL_Buffer *b, int in
strlib_aux_add_utfchar(b, (unsigned) lmt_tounsigned(L, index));
}
-static inline void strlib_aux_add_utfstring(lua_State *L, luaL_Buffer *b, int index)
-{
- size_t ls = 0;
- const char *s = lua_tolstring(L, index, &ls);
- luaL_addlstring(b, s, ls);
-}
+/*tex
+ When we loop over a table we push its elements, which is not permitted when a \LUA\ buffer has
+ to grow because then it expects a balanced stack. So we first determine the (maximum) size and
+ then fill a buffer of that size directly. Code points are handled as in the single character
+ case.
+*/
-static inline void strlib_aux_add_utftable(lua_State *L, luaL_Buffer *b, int index)
+static size_t strlib_aux_utf_collect(lua_State *L, int index, char *s, size_t size, int depth)
{
- lua_Unsigned n = lua_rawlen(L, index);
- if (n > 0) {
- for (lua_Unsigned i = 1; i <= n; i++) {
- lua_rawgeti(L, index, i);
- switch (lua_type(L, -1)) {
- case LUA_TNUMBER:
- strlib_aux_add_utfnumber(L, b, -1);
- break;
- case LUA_TTABLE:
- strlib_aux_add_utftable(L, b, -1);
- break;
- case LUA_TSTRING:
- strlib_aux_add_utfstring(L, b, -1);
- break;
- default:
- /* we could just quit */
- break;
+ size_t n = 0;
+ switch (lua_type(L, index)) {
+ case LUA_TNUMBER:
+ if (! s) {
+ n = 4;
+ } else if (size >= 4) {
+ n = (size_t) (aux_uni2string(s, (unsigned) lmt_tounsigned(L, index)) - s);
}
- lua_pop(L, 1);
- }
+ break;
+ case LUA_TSTRING:
+ {
+ size_t l = 0;
+ const char *str = lua_tolstring(L, index, &l);
+ if (! s) {
+ n = l;
+ } else if (l <= size) {
+ memcpy(s, str, l);
+ n = l;
+ }
+ break;
+ }
+ case LUA_TTABLE:
+ if (depth < max_nesting_depth && lua_checkstack(L, 1)) {
+ lua_Unsigned m = lua_rawlen(L, index);
+ for (lua_Unsigned i = 1; i <= m; i++) {
+ lua_rawgeti(L, index, (lua_Integer) i);
+ n += strlib_aux_utf_collect(L, lua_gettop(L), s ? s + n : NULL, s ? size - n : 0, depth + 1);
+ lua_pop(L, 1);
+ }
+ }
+ break;
}
+ return n;
}
static int strlib_utfcharacter(lua_State *L)
@@ -588,15 +732,16 @@ static int strlib_utfcharacter(lua_State *L)
return 1;
} else {
luaL_Buffer b;
- luaL_buffinitsize(L, &b, (size_t) n * 4);
+ size_t size = 0;
+ size_t length = 0;
for (int i = 1; i <= n; i++) {
- switch (lua_type(L, i)) {
- case LUA_TNUMBER: strlib_aux_add_utfnumber(L, &b, i); break;
- case LUA_TTABLE : strlib_aux_add_utftable (L, &b, i); break;
- case LUA_TSTRING: strlib_aux_add_utfstring(L, &b, i); break;
- }
+ size += strlib_aux_utf_collect(L, i, NULL, 0, 0);
}
- luaL_pushresult(&b);
+ char *s = luaL_buffinitsize(L, &b, size);
+ for (int i = 1; i <= n; i++) {
+ length += strlib_aux_utf_collect(L, i, s + length, size - length, 0);
+ }
+ luaL_pushresultsize(&b, length);
return 1;
}
}
@@ -615,6 +760,11 @@ static int strlib_utfvalue(lua_State *L)
size_t p = 0;
int i = 0;
const char *s = luaL_checklstring(L, 1, &l);
+ /* we return each code point, so (as in |utf8.codepoint|) we need room on the stack */
+ if lmt_unlikely(l >= INT_MAX) {
+ return luaL_error(L, "string too long");
+ }
+ luaL_checkstack(L, (int) l, "string too long");
while (p < l) {
lua_pushinteger(L, strlib_aux_tounicode(s, l, &p));
i++;
@@ -622,34 +772,6 @@ static int strlib_utfvalue(lua_State *L)
return i;
}
-/*tex This is a simplified version of utf8.len but without range. */
-
-// static int strlib_utflength(lua_State *L)
-// {
-// size_t ls = 0;
-// size_t ind = 0;
-// size_t n = 0;
-// const char *s = lua_tolstring(L, 1, &ls);
-// while (ind < ls) {
-// unsigned char i = (unsigned char) *(s + ind);
-// if (i < 0x80) {
-// ind += 1;
-// } else if (i >= 0xF0) {
-// ind += 4;
-// } else if (i >= 0xE0) {
-// ind += 3;
-// } else if (i >= 0xC0) {
-// ind += 2;
-// } else {
-// /*tex bad news, stupid recovery */
-// ind += 1;
-// }
-// n++;
-// }
-// lua_pushinteger(L, n);
-// return 1;
-// }
-
/*tex
This one uses the same shift based few \CPU\ cycle length trick as above. It does
a bit more checking so that likely kills the gain.
@@ -662,25 +784,12 @@ static int strlib_utflength(lua_State *L)
size_t ind = 0;
size_t n = 0;
while (ind < ls) {
- unsigned char i = (unsigned char) s[ind];
- if (i < 0x80) {
- ind++;
- n++;
- continue;
- }
- /* O(1) length lookup via high nibble */
- size_t len = utf8_lengths[i >> 4];
- /*
- If we have an invalid lead byte (len == 0, continuation byte 0x80..0xBF, etc.)
- or an overlong lead byte (> 0xF4), we fall back to 1 byte.
- */
- if (len == 0 || i > 0xF4) {
- len = 1;
+ size_t next = ind;
+ strlib_aux_tounicode(s, ls, &next);
+ if (next <= ind) {
+ next = ind + 1;
}
- if (ind + len > ls) {
- len = ls - ind;
- }
- ind += len;
+ ind = next;
n++;
}
lua_pushinteger(L, (lua_Integer) n);
@@ -694,102 +803,184 @@ static int strlib_utflength(lua_State *L)
digits.
*/
-// static int strlib_format_f6(lua_State *L)
-// {
-// double n = luaL_optnumber(L, 1, 0.0);
-// if (n == 0.0) {
-// lua_pushliteral(L, "0");
-// } else if (n == 1.0) {
-// lua_pushliteral(L, "1");
-// // } else if (n == 10.0) {
-// // /* does happen in our use case but not worth it */
-// // lua_pushliteral(L, "10");
-// } else {
-// char s[128];
-// int i;
-// /* this is really needed in order to get integers in pdf */
-// if (fmod(n, 1) == 0 && n >= min_integer && n <= max_integer) {
-// i = snprintf(s, 128, "%i", (int) n);
-// } else {
-// int l;
-// if (lua_type(L, 2) == LUA_TSTRING) {
-// const char *f = lua_tostring(L, 2);
-// i = snprintf(s, 128, f, n);
-// } else {
-// i = snprintf(s, 128, "%0.6f", n) ;
-// }
-// l = i - 1;
-// while (l > 1) {
-// if (s[l - 1] == '.') {
-// break;
-// } else if (s[l] == '0') {
-// // s[l] = '\0'; /* redundant */
-// --i;
-// } else {
-// break;
-// }
-// l--;
-// }
-// }
-// lua_pushlstring(L, s, i);
-// }
-// return 1;
-// }
+# include <inttypes.h>
-# ifndef MIN_INTEGER
- # define MIN_INTEGER -2147483648.0
- # define MAX_INTEGER 2147483647.0
-# endif
+/*tex
+ A user format has to be a single floating point specifier, like |%.3f|, so no literal text,
+ no |*| and no length modifiers: we pass a double and want to get just a number.
+*/
+
+static inline int strlib_aux_valid_f6_format(const char *f)
+{
+ if (*f++ != '%') {
+ return 0;
+ }
+ while (*f && strchr("-+ #0", *f)) {
+ f++;
+ }
+ for (int d = 0; d < 3 && *f >= '0' && *f <= '9'; d++) {
+ f++;
+ }
+ if (*f == '.') {
+ f++;
+ for (int d = 0; d < 3 && *f >= '0' && *f <= '9'; d++) {
+ f++;
+ }
+ }
+ return *f && strchr("fFeEgG", *f) && ! f[1];
+}
static int strlib_format_f6(lua_State *L)
{
double n = luaL_optnumber(L, 1, 0.0);
- /* Fast paths for standard constants */
if (n == 0.0) {
- // if (signbit(n)) {
- // lua_pushliteral(L, "-0");
- // } else {
- lua_pushliteral(L, "0");
- // }
+ lua_pushliteral(L, "0");
return 1;
} else if (n == 1.0) {
lua_pushliteral(L, "1");
return 1;
} else {
- char s[64];
+ char s[512];
int len;
- if (fmod(n, 1.0) == 0.0 && n >= MIN_INTEGER && n <= MAX_INTEGER) {
- len = snprintf(s, sizeof(s), "%ld", (long) n);
+ /* do we have an integer within 53-bit float precision */
+ if (fmod(n, 1.0) == 0.0 && n >= -9007199254740992.0 && n <= 9007199254740992.0) {
+ len = snprintf(s, sizeof(s), "%" PRId64, (int64_t) n);
lua_pushlstring(L, s, (size_t) len);
return 1;
- } else {
- if (lua_type(L, 2) == LUA_TSTRING) {
- const char *f = lua_tostring(L, 2);
- len = snprintf(s, sizeof(s), f, n);
- } else {
- len = snprintf(s, sizeof(s), "%.6f", n);
+ }
+ /* default format */
+ const char *fmt = "%.6f";
+ if (lua_type(L, 2) == LUA_TSTRING) {
+ const char *user_fmt = lua_tostring(L, 2);
+ if (strlib_aux_valid_f6_format(user_fmt)) {
+ fmt = user_fmt;
}
- if (len <= 0 || len >= (int) sizeof(s)) {
- lua_pushliteral(L, "0");
- return 1;
+ }
+ len = snprintf(s, sizeof(s), fmt, n);
+ if (len <= 0 || len >= (int) sizeof(s)) {
+ /* a user format can be too wide but the default always fits */
+ len = snprintf(s, sizeof(s), "%.6f", n);
+ }
+ /* remove trailing zeros after decimal point, respecting exponents if present */
+ char *dot = strchr(s, '.');
+ if (dot) {
+ char *exp_ptr = strpbrk(s, "eE");
+ char *ptr = exp_ptr ? (exp_ptr - 1) : (s + len - 1);
+
+ while (ptr > dot && *ptr == '0') {
+ ptr--;
}
- char *dot = strchr(s, '.');
- if (dot) {
- char *ptr = s + len - 1;
- while (ptr > dot && *ptr == '0') {
- ptr--;
- }
- if (ptr == dot) {
- ptr--;
- }
+ if (ptr == dot) {
+ ptr--;
+ }
+ if (exp_ptr) {
+ size_t mantissa_len = (size_t) (ptr - s + 1);
+ size_t exp_len = strlen(exp_ptr);
+ memmove(s + mantissa_len, exp_ptr, exp_len + 1);
+ len = (int) (mantissa_len + exp_len);
+ } else {
len = (int) (ptr - s + 1);
+ s[len] = '\0';
}
+ }
+ lua_pushlstring(L, s, (size_t) len);
+ return 1;
+ }
+}
+
+static int strlib_format_g6(lua_State *L)
+{
+ double n = luaL_optnumber(L, 1, 0.0);
+ if (n == 0.0) {
+ lua_pushliteral(L, "0");
+ return 1;
+ } else if (n == 1.0) {
+ lua_pushliteral(L, "1");
+ return 1;
+ } else {
+ char s[128];
+ /* Fast path: 53-bit exact integers */
+ if (fmod(n, 1.0) == 0.0 && n >= -9007199254740992.0 && n <= 9007199254740992.0) {
+ int len = snprintf(s, sizeof(s), "%" PRId64, (int64_t) n);
+ lua_pushlstring(L, s, (size_t) len);
+ return 1;
}
+ /* Standard custom double-to-string conversion (handles exponential notation & trimming deterministically) */
+ int len = double_to_string_g(n, s, 6);
lua_pushlstring(L, s, (size_t) len);
return 1;
}
}
+static int strlib_format_fd(lua_State *L)
+{
+ double n = luaL_optnumber(L, 1, 0.0);
+ int m = strlib_aux_normalize_precision(luaL_optinteger(L, 2, 6));
+ if (n == 0.0) {
+ lua_pushliteral(L, "0");
+ return 1;
+ } else if (n == 1.0) {
+ lua_pushliteral(L, "1");
+ return 1;
+ } else {
+ char str[512]; /* Safe capacity for large doubles */
+ int len = double_to_string_f(n, str, m);
+ if (len < 0 || len >= (int) sizeof(str)) {
+ len = (int) sizeof(str) - 1;
+ str[len] = '\0';
+ }
+ lua_pushlstring(L, str, (size_t) len);
+ return 1;
+ }
+}
+
+static inline int strlib_format_fdn(lua_State *L, int m)
+{
+ double n = luaL_optnumber(L, 1, 0.0);
+ if (n == 0.0) {
+ lua_pushliteral(L, "0");
+ return 1;
+ } else if (n == 1.0) {
+ lua_pushliteral(L, "1");
+ return 1;
+ } else {
+ char str[512];
+ int len = double_to_string_f(n, str, m);
+ if (len < 0 || len >= (int) sizeof(str)) {
+ len = (int) sizeof(str) - 1;
+ str[len] = '\0';
+ }
+ lua_pushlstring(L, str, (size_t) len);
+ return 1;
+ }
+}
+
+static int strlib_format_fd3(lua_State *L) { return strlib_format_fdn(L, 3); }
+static int strlib_format_fd6(lua_State *L) { return strlib_format_fdn(L, 6); }
+static int strlib_format_fd9(lua_State *L) { return strlib_format_fdn(L, 9); }
+
+static int strlib_format_gd(lua_State *L)
+{
+ double n = luaL_optnumber(L, 1, 0.0);
+ int m = strlib_aux_normalize_precision(luaL_optinteger(L, 2, 6));
+ if (n == 0.0) {
+ lua_pushliteral(L, "0");
+ return 1;
+ } else if (n == 1.0) {
+ lua_pushliteral(L, "1");
+ return 1;
+ } else {
+ char str[512];
+ int len = double_to_string_g(n, str, m);
+ if (len < 0 || len >= (int) sizeof(str)) {
+ len = (int) sizeof(str) - 1;
+ str[len] = '\0';
+ }
+ lua_pushlstring(L, str, (size_t) len);
+ return 1;
+ }
+}
+
/*tex
The next one is mostly provided as check because doing it in pure \LUA\ is not slower and it's
not a bottleneck anyway. There are some subtle side effects when we don't check for these ranges,
@@ -826,78 +1017,238 @@ static int strlib_format_f6(lua_State *L)
# endif
-// static inline unsigned char strlib_aux_hexdigit(unsigned char n)
-// {
-// return (n < 10 ? '0' : 'A' - 10) + n;
-// }
-//
-// static int strlib_format_tounicode16(lua_State *L)
+static const char hex_upper[] = "0123456789ABCDEF";
+static const char hex_lower[] = "0123456789abcdef";
+
+static inline void write_hex16(char *s, unsigned int val)
+{
+ s[0] = hex_upper[(val >> 12) & 0xF];
+ s[1] = hex_upper[(val >> 8) & 0xF];
+ s[2] = hex_upper[(val >> 4) & 0xF];
+ s[3] = hex_upper[ val & 0xF];
+}
+
+// static int strlib_tounicode16(lua_State *L)
// {
-// lua_Integer u = lua_tointeger(L, 1);
-// if (invalid_unicode(u)) {
-// /* privates are valid but we don't want them */
+// lua_Integer u = lua_tointeger(L, 1);
+// if (u < 0 || u > MAXUNICODE || invalid_unicode(u)) {
// lua_pushliteral(L, "FFFD");
-// } else if (u < 0xD7FF || (u >= 0xDFFF && u <= 0xFFFF)) {
+// } else if (u <= 0xFFFF) {
// /* basic multilingual plane: single 16-bit word */
-// char s[4] ;
-// s[3] = strlib_aux_hexdigit((unsigned char) ((u & 0x000F) >> 0));
-// s[2] = strlib_aux_hexdigit((unsigned char) ((u & 0x00F0) >> 4));
-// s[1] = strlib_aux_hexdigit((unsigned char) ((u & 0x0F00) >> 8));
-// s[0] = strlib_aux_hexdigit((unsigned char) ((u & 0xF000) >> 12));
+// char s[4];
+// write_hex16(s, (unsigned int) u);
// lua_pushlstring(L, s, 4);
// } else {
// /* supplementary planes (U+10000 .. U+10FFFF): UTF-16 surrogate pair */
-// unsigned u1, u2;
-// char s[8] ;
-// u = u - 0x10000; /* negative when invalid range */
-// u1 = (unsigned) (u >> 10) + 0xD800; /* high surrogate */
-// u2 = (unsigned) (u % 0x400) + 0xDC00; /* low surrogate */
-// s[3] = strlib_aux_hexdigit((unsigned char) ((u1 & 0x000F) >> 0));
-// s[2] = strlib_aux_hexdigit((unsigned char) ((u1 & 0x00F0) >> 4));
-// s[1] = strlib_aux_hexdigit((unsigned char) ((u1 & 0x0F00) >> 8));
-// s[0] = strlib_aux_hexdigit((unsigned char) ((u1 & 0xF000) >> 12));
-// s[7] = strlib_aux_hexdigit((unsigned char) ((u2 & 0x000F) >> 0));
-// s[6] = strlib_aux_hexdigit((unsigned char) ((u2 & 0x00F0) >> 4));
-// s[5] = strlib_aux_hexdigit((unsigned char) ((u2 & 0x0F00) >> 8));
-// s[4] = strlib_aux_hexdigit((unsigned char) ((u2 & 0xF000) >> 12));
+// char s[8];
+// unsigned int v = (unsigned int) (u - 0x10000);
+// unsigned int u1 = (v >> 10) + 0xD800; /* high surrogate */
+// unsigned int u2 = (v & 0x3FF) + 0xDC00; /* low surrogate */
+// write_hex16(s, u1);
+// write_hex16(s + 4, u2);
// lua_pushlstring(L, s, 8);
// }
// return 1;
// }
-static const char hex_digits[] = "0123456789ABCDEF";
+/*tex
-static inline void write_hex16(char *s, unsigned int val)
-{
- s[0] = hex_digits[(val >> 12) & 0xF];
- s[1] = hex_digits[(val >> 8) & 0xF];
- s[2] = hex_digits[(val >> 4) & 0xF];
- s[3] = hex_digits[ val & 0xF];
-}
+ When porting the \LUA\ variant we combined three functions in one and handle for instance
+ negative numbers better.
+
+*/
-static int strlib_format_tounicode16(lua_State *L)
+static inline size_t strlib_aux_tounicode16_chars(lua_Integer u, char *s)
{
- lua_Integer u = lua_tointeger(L, 1);
- if (invalid_unicode(u)) {
- lua_pushliteral(L, "FFFD");
+ if (u < 0 || u > MAXUNICODE || invalid_unicode(u)) {
+ memcpy(s, "FFFD", 4);
+ return 4;
} else if (u <= 0xFFFF) {
/* basic multilingual plane: single 16-bit word */
- char s[4];
write_hex16(s, (unsigned int) u);
- lua_pushlstring(L, s, 4);
+ return 4;
} else {
/* supplementary planes (U+10000 .. U+10FFFF): UTF-16 surrogate pair */
- char s[8];
- unsigned int v = (unsigned int) (u - 0x10000);
+ unsigned int v = (unsigned int) (u - 0x10000);
unsigned int u1 = (v >> 10) + 0xD800; /* high surrogate */
unsigned int u2 = (v & 0x3FF) + 0xDC00; /* low surrogate */
write_hex16(s, u1);
write_hex16(s + 4, u2);
- lua_pushlstring(L, s, 8);
+ return 8;
+ }
+}
+
+static inline void strlib_aux_add_tounicode16(luaL_Buffer *b, lua_Integer u)
+{
+ char str[8];
+ size_t len = strlib_aux_tounicode16_chars(u, str);
+ luaL_addlstring(b, str, len);
+}
+
+inline static void strlib_aux_tounicode16_collect(lua_State *L, int index, luaL_Buffer *b, int depth)
+{
+ switch (lua_type(L, index)) {
+ case LUA_TNUMBER:
+ strlib_aux_add_tounicode16(b, lua_tointeger(L, index));
+ break;
+ case LUA_TTABLE:
+ if (depth < max_nesting_depth && lua_checkstack(L, 1)) {
+ lua_Unsigned n = lua_rawlen(L, index);
+ for (lua_Unsigned i = 1; i <= n; i++) {
+ lua_rawgeti(L, index, (lua_Integer) i);
+ strlib_aux_tounicode16_collect(L, lua_gettop(L), b, depth + 1);
+ lua_pop(L, 1);
+ }
+ }
+ break;
+ default:
+ luaL_addlstring(b, "FFFD", 4);
+ break;
+ }
+}
+
+static int strlib_tounicode16(lua_State *L)
+{
+ int n = lua_gettop(L);
+ if (n == 1 && lua_type(L, 1) == LUA_TNUMBER) {
+ char s[8];
+ size_t len = strlib_aux_tounicode16_chars(lua_tointeger(L, 1), s);
+ lua_pushlstring(L, s, len);
+ return 1;
+ } else {
+ luaL_Buffer b;
+ luaL_buffinitsize(L, &b, (size_t) (n > 0 ? n : 1) * 8);
+ for (int i = 1; i <= n; i++) {
+ strlib_aux_tounicode16_collect(L, i, &b, 0);
+ }
+ luaL_pushresult(&b);
+ return 1;
}
- return 1;
}
+/*tex
+ This converts a hex string to characters. Spacing is ignored and invalid characters result in
+ a false result. Empty strings are okay. Originally we assumed \type {XX XX XX} and just skipped
+ single ones but we might as well also handle \type {X X X}. This code is not that critical and
+ was introduced when we wanted flexible bitmap definition in \METAPOST\ and \LUA\ as part of the
+ \type {potrace} experiments.
+
+ Previous (less efficient) implementations can be found in the git history (luametatex and
+ context). Here we use a 256-byte lookup table for hex decoding but of course it comes at a
+ memory price (we use shorts as suggested by gemini):
+
+ - 0 .. 15 : valid hex nibbles
+ - 256 : whitespace (skip)
+ - 257 : invalid character / failure
+
+ It's anyway a nice example of a variant, given the usual reformatting and a bit of
+ cleaning up. We need the table a few times.
+*/
+
+static const unsigned short strlib_hex_table[256] = {
+ /* 0x00 - 0x1F: control characters \t \n \r are valid spacing */
+ 257,257,257,257,257,257,257,257,257,256,256,257,257,256,257,257,
+ 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
+ /* 0x20 - 0x2F: ' ' is valid spacing */
+ 256,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
+ /* 0x30 - 0x39: digits '0'-'9' (0 .. 9) */
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,257,257,257,257,257,257,
+ /* 0x40 - 0x4F: uppercase 'A'-'F' (10 .. 15) */
+ 257, 10, 11, 12, 13, 14, 15,257,257,257,257,257,257,257,257,257,
+ 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
+ /* 0x60 - 0x6F: lowercase 'a'-'f' (10 .. 15) */
+ 257, 10, 11, 12, 13, 14, 15,257,257,257,257,257,257,257,257,257,
+ 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
+ /* 0x80 - 0xFF: high ASCII / non ASCII (all invalid) */
+ 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
+ 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
+ 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
+ 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
+ 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
+ 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
+ 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
+ 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
+};
+
+/*tex
+
+ Contrary to the original \LUA\ variant we return multiple code points but our normal use case
+ is still a single one. Checking is a bit more aggressive (thank you, internet).
+
+*/
+
+static inline int strlib_aux_from_hex_4(const char *s)
+{
+ unsigned short h0 = strlib_hex_table[(unsigned char) s[0]];
+ unsigned short h1 = strlib_hex_table[(unsigned char) s[1]];
+ unsigned short h2 = strlib_hex_table[(unsigned char) s[2]];
+ unsigned short h3 = strlib_hex_table[(unsigned char) s[3]];
+ if (h0 >= 16 || h1 >= 16 || h2 >= 16 || h3 >= 16) {
+ return -1;
+ }
+ return (int) ((h0 << 12) | (h1 << 8) | (h2 << 4) | h3);
+}
+
+static int strlib_fromunicode16(lua_State *L)
+{
+ size_t len = 0;
+ const char *str = luaL_checklstring(L, 1, &len);
+ /* ensure multiple of 4 trick: cutoff */
+ len &= ~(size_t) 3;
+ if (len == 0) {
+ return 0;
+ } else if (len >= INT_MAX) {
+ return luaL_error(L, "string too long");
+ }
+ luaL_checkstack(L, (int) (len / 4), "string too long");
+ size_t i = 0;
+ int count = 0;
+ unsigned int high_surrogate = 0;
+ while (i < len) {
+ int word = strlib_aux_from_hex_4(str + i);
+ i += 4;
+ if (word < 0) {
+ if (high_surrogate) {
+ lua_pushinteger(L, 0xFFFD);
+ count++;
+ high_surrogate = 0;
+ }
+ lua_pushinteger(L, 0xFFFD);
+ count++;
+ continue;
+ }
+ if (high_surrogate) {
+ if (word >= 0xDC00 && word <= 0xDFFF) {
+ unsigned int cp = 0x10000 + (((high_surrogate & 0x3FF) << 10) | (word & 0x3FF));
+ lua_pushinteger(L, (lua_Integer) cp);
+ count++;
+ high_surrogate = 0;
+ continue;
+ } else {
+ lua_pushinteger(L, 0xFFFD);
+ count++;
+ high_surrogate = 0;
+ }
+ }
+ if (word >= 0xD800 && word <= 0xDBFF) {
+ high_surrogate = (unsigned int) word;
+ } else if (word >= 0xDC00 && word <= 0xDFFF) {
+ lua_pushinteger(L, 0xFFFD);
+ count++;
+ } else {
+ lua_pushinteger(L, (lua_Integer) word);
+ count++;
+ }
+ }
+ if (high_surrogate) {
+ lua_pushinteger(L, 0xFFFD);
+ count++;
+ }
+ return count;
+}
+
+/* */
+
static int strlib_format_toutf8(lua_State *L) /* could be integrated into utfcharacter */
{
if (lua_type(L, 1) == LUA_TTABLE) {
@@ -905,15 +1256,16 @@ static int strlib_format_toutf8(lua_State *L) /* could be integrated into utfcha
if (n > 0) {
luaL_Buffer b;
luaL_buffinitsize(L, &b, (n + 1) * 4);
- for (lua_Integer i = 0; i <= n; i++) {
+ for (lua_Integer i = 1; i <= n; i++) {
/* there should be one operation for getting a number from a table */
if (lua_rawgeti(L, 1, i) == LUA_TNUMBER) {
unsigned u = (unsigned) lua_tointeger(L, -1);
if (0x80 > u) {
luaL_addchar(&b, (unsigned char) u);
} else if (invalid_unicode(u)) {
- luaL_addchar(&b, 0xFF);
- luaL_addchar(&b, 0xFD);
+ luaL_addchar(&b, 0xEF);
+ luaL_addchar(&b, 0xBF);
+ luaL_addchar(&b, 0xBD);
} else {
if (0x800 > u)
luaL_addchar(&b, (unsigned char) (0xC0 | (u >> 6)));
@@ -947,12 +1299,12 @@ static int strlib_format_toutf16(lua_State* L) {
int addzero = lua_toboolean(L, 2);
luaL_Buffer b;
luaL_buffinitsize(L, &b, (n + 2) * 4);
- for (lua_Integer i = 0; i <= n; i++) {
+ for (lua_Integer i = 1; i <= n; i++) {
if (lua_rawgeti(L, 1, i) == LUA_TNUMBER) {
unsigned u = (unsigned) lua_tointeger(L, -1);
if (invalid_unicode(u)) {
- luaL_addchar(&b, 0xFF);
luaL_addchar(&b, 0xFD);
+ luaL_addchar(&b, 0xFF);
} else if (u < 0x10000) {
luaL_addchar(&b, (unsigned char) ((u & 0x00FF) ));
luaL_addchar(&b, (unsigned char) ((u & 0xFF00) >> 8));
@@ -987,15 +1339,15 @@ static int strlib_format_toutf32(lua_State *L)
int addzero = lua_toboolean(L, 2);
luaL_Buffer b;
luaL_buffinitsize(L, &b, (n + 2) * 4);
- for (lua_Integer i = 0; i <= n; i++) {
+ for (lua_Integer i = 1; i <= n; i++) {
/* there should be one operation for getting a number from a table */
if (lua_rawgeti(L, 1, i) == LUA_TNUMBER) {
unsigned u = (unsigned) lua_tointeger(L, -1);
if (invalid_unicode(u)) {
+ luaL_addchar(&b, 0xFD);
+ luaL_addchar(&b, 0xFF);
luaL_addchar(&b, 0x00);
luaL_addchar(&b, 0x00);
- luaL_addchar(&b, 0xFF);
- luaL_addchar(&b, 0xFD);
} else {
luaL_addchar(&b, (unsigned char) ((u & 0x000000FF) ));
luaL_addchar(&b, (unsigned char) ((u & 0x0000FF00) >> 8));
@@ -1005,7 +1357,7 @@ static int strlib_format_toutf32(lua_State *L)
}
lua_pop(L, 1);
}
- if (addzero) {
+ if (addzero) {
for (int i = 0; i <= 3; i++) {
luaL_addchar(&b, 0);
}
@@ -1027,51 +1379,6 @@ static int strlib_format_toutf32(lua_State *L)
str, nil, nil : check bom, default to little endian
*/
-// static int strlib_utf16toutf8(lua_State *L)
-// {
-// size_t ls = 0;
-// const char *s = lua_tolstring(L, 1, &ls);
-// if (ls % 2) {
-// --ls;
-// }
-// if (ls) {
-// luaL_Buffer b;
-// int more = 0;
-// int be = 1;
-// size_t i = 0;
-// luaL_buffinitsize(L, &b, ls * 2); /* unlikely to be larger if we have latin */
-// if (lua_type(L, 2) == LUA_TBOOLEAN) {
-// be = lua_toboolean(L, 2);
-// } else if (s[0] == '\xFE' && s[1] == '\xFF') {
-// be = 1;
-// i += 2;
-// } else if (s[0] == '\xFF' && s[1] == '\xFE') {
-// be = 0;
-// i += 2;
-// } else {
-// be = lua_toboolean(L, 3);
-// }
-// while (i < ls) {
-// unsigned char l = (unsigned char) s[i++];
-// unsigned char r = (unsigned char) s[i++];
-// unsigned now = be ? 256 * l + r : l + 256 * r;
-// if (more) {
-// now = (more - 0xD800) * 0x400 + (now - 0xDC00) + 0x10000;
-// more = 0;
-// strlib_aux_add_utfchar(&b, now);
-// } else if (now >= 0xD800 && now <= 0xDBFF) {
-// more = now;
-// } else {
-// strlib_aux_add_utfchar(&b, now);
-// }
-// }
-// luaL_pushresult(&b);
-// } else {
-// lua_pushliteral(L, "");
-// }
-// return 1;
-// }
-
static int strlib_utf16toutf8(lua_State *L)
{
size_t ls = 0;
@@ -1098,10 +1405,9 @@ static int strlib_utf16toutf8(lua_State *L)
luaL_buffinitsize(L, &b, (ls - i) * 3 / 2 + 1);
unsigned int high_surrogate = 0;
while (i < ls) {
- unsigned char c1 = (unsigned char) s[i++];
- unsigned char c2 = (unsigned char) s[i++];
- unsigned int word = be ? ((unsigned int) c1 << 8) | c2
- : ((unsigned int) c2 << 8) | c1;
+ unsigned char c1 = (unsigned char) s[i++];
+ unsigned char c2 = (unsigned char) s[i++];
+ unsigned int word = be ? ((unsigned int) c1 << 8) | c2 : ((unsigned int) c2 << 8) | c1;
if (high_surrogate) {
if (word >= 0xDC00 && word <= 0xDFFF) {
/* valid surrogate pair: decode codepoint */
@@ -1135,27 +1441,214 @@ static int strlib_utf16toutf8(lua_State *L)
return 1;
}
+/* for pdf */
+
+static inline void strlib_aux_topdfsixteen(const char *s, size_t ls, luaL_Buffer *b, int bom, int brackets)
+{
+ if (brackets) {
+ luaL_addchar(b, '<');
+ }
+ if (bom) {
+ luaL_addlstring(b, "FEFF", 4);
+ }
+ size_t p = 0;
+ while (p < ls) {
+ int u = strlib_aux_tounicode(s, ls, &p);
+ if (u < 0 || u > MAXUNICODE || invalid_unicode(u)) {
+ luaL_addlstring(b, "FFFD", 4);
+ } else if (u <= 0xFFFF) {
+ char hex[4];
+ write_hex16(hex, (unsigned int) u);
+ luaL_addlstring(b, hex, 4);
+ } else {
+ char hex[8];
+ unsigned int v = (unsigned int) (u - 0x10000);
+ unsigned int u1 = (v >> 10) + 0xD800;
+ unsigned int u2 = (v & 0x3FF) + 0xDC00;
+ write_hex16(hex, u1);
+ write_hex16(hex + 4, u2);
+ luaL_addlstring(b, hex, 8);
+ }
+ }
+ if (brackets) {
+ luaL_addchar(b, '>');
+ }
+}
+
+static int strlib_topdfsixteen(lua_State *L)
+{
+ size_t len = 0;
+ const char *str = luaL_checklstring(L, 1, &len);
+ int bom = ! lua_toboolean(L, 2);
+ int brackets = ! lua_toboolean(L, 3);
+ luaL_Buffer b;
+ /* each unicode point can be up to 8 hex chars (including surrogate pair) */
+ luaL_buffinitsize(L, &b, (len + 1) * 8 + (bom ? 4 : 0) + (brackets ? 2 : 0));
+ strlib_aux_topdfsixteen(str, len, &b, bom, brackets);
+ luaL_pushresult(&b);
+ return 1;
+}
+
+static int strlib_topdfeight(lua_State *L)
+{
+ size_t len = 0;
+ const char *str = luaL_checklstring(L, 1, &len);
+ int parentheses = ! lua_toboolean(L, 2);
+ luaL_Buffer b;
+ /* in the worst case every char expands or gets prefixed/suffixed */
+ luaL_buffinitsize(L, &b, len * 2 + (parentheses ? 2 : 0));
+ if (parentheses) {
+ luaL_addchar(&b, '(');
+ }
+ for (size_t i = 0; i < len; i++) {
+ unsigned char c = (unsigned char) str[i];
+ switch (c) {
+ case '(':
+ if (parentheses) {
+ luaL_addchar(&b, '\\');
+ luaL_addchar(&b, '(');
+ } else {
+ luaL_addchar(&b, '(');
+ }
+ break;
+ case ')':
+ if (parentheses) {
+ luaL_addchar(&b, '\\');
+ luaL_addchar(&b, ')');
+ } else {
+ luaL_addchar(&b, ')');
+ }
+ break;
+ case '\\':
+ luaL_addchar(&b, '\\');
+ luaL_addchar(&b, '\\');
+ break;
+ case '\n':
+ luaL_addchar(&b, '\\');
+ luaL_addchar(&b, 'n');
+ break;
+ case '\r':
+ luaL_addchar(&b, '\\');
+ luaL_addchar(&b, 'r');
+ break;
+ case '\t':
+ luaL_addchar(&b, '\\');
+ luaL_addchar(&b, 't');
+ break;
+ case '\b':
+ luaL_addchar(&b, '\\');
+ luaL_addchar(&b, 'b');
+ break;
+ case '\f':
+ luaL_addchar(&b, '\\');
+ luaL_addchar(&b, 'f');
+ break;
+ default:
+ luaL_addchar(&b, (char) c);
+ break;
+ }
+ }
+ if (parentheses) {
+ luaL_addchar(&b, ')');
+ }
+ luaL_pushresult(&b);
+ return 1;
+}
+
+static int strlib_topdfstring(lua_State *L)
+{
+ luaL_Buffer b;
+ size_t len = 0;
+ const char *str = luaL_checklstring(L, 1, &len);
+ int utf16 = 0;
+ int utf8 = 0;
+ /* check for characters outside 0x20 .. 0x7F (0x00..0x1F and 0x80..0xFF) */
+ if (lua_toboolean(L, 2)) {
+ /* possibly utf () strings */
+ for (size_t i = 0; i < len; i++) {
+ unsigned char c = (unsigned char) str[i];
+ if (c < 0x20) {
+ utf16 = 1;
+ break;
+ } else if (c > 0x7F) {
+ utf8 = 1;
+ }
+ }
+ } else {
+ /* no utf () strings */
+ for (size_t i = 0; i < len; i++) {
+ unsigned char c = (unsigned char) str[i];
+ if (c < 0x20 || c > 0x7F) {
+ utf16 = 1;
+ break;
+ }
+ }
+ }
+ if (utf16) {
+ /* UTF-16 hex format with FEFF BOM, wrapped in < and > */
+ luaL_buffinitsize(L, &b, (len + 1) * 8 + 4 + 2);
+ strlib_aux_topdfsixteen(str, len, &b, 1, 1);
+ } else {
+ /* 0x20..0x7F ASCII/UTF8: wrap in () and escape (, ), and \ */
+ luaL_buffinitsize(L, &b, len * 2 + (utf8 ? 5 : 2));
+ luaL_addchar(&b, '(');
+ if (utf8) {
+ luaL_addlstring(&b, "\xEF\xBB\xBF", 3);
+ }
+ for (size_t i = 0; i < len; i++) {
+ unsigned char c = (unsigned char) str[i];
+ if (c == '(') {
+ luaL_addchar(&b, '\\');
+ luaL_addchar(&b, '(');
+ } else if (c == ')') {
+ luaL_addchar(&b, '\\');
+ luaL_addchar(&b, ')');
+ } else if (c == '\\') {
+ luaL_addchar(&b, '\\');
+ luaL_addchar(&b, '\\');
+ } else {
+ luaL_addchar(&b, (char) c);
+ }
+ }
+ luaL_addchar(&b, ')');
+ }
+ luaL_pushresult(&b);
+ return 1;
+}
+
static int strlib_pack_rows_columns(lua_State* L)
{
if (lua_type(L, 1) == LUA_TTABLE) {
lua_Integer rows = lua_rawlen(L, 1);
- if (lua_rawgeti(L, 1, 1) == LUA_TTABLE) {
+ if (rows <= 0) {
+ lua_pushliteral(L, "");
+ return 1;
+ } else if (lua_rawgeti(L, 1, 1) == LUA_TTABLE) {
lua_Integer columns = lua_rawlen(L, -1);
+ if (columns <= 0) {
+ lua_pop(L, 1); /* pop row table */
+ lua_pushliteral(L, "");
+ return 1;
+ }
switch (lua_rawgeti(L, -1, 1)) {
case LUA_TNUMBER:
{
- size_t size = rows * columns;
+ if lmt_unlikely((size_t) rows > SIZE_MAX / (size_t) columns) {
+ lua_pop(L, 2); /* row and cell */
+ return luaL_error(L, "table dimensions in string.packrowscolumns are too large");
+ }
+ size_t size = (size_t) rows * (size_t) columns;
unsigned char *result = lmt_memory_malloc(size);
lua_pop(L, 2); /* row and cell */
- if (result) {
+ if lmt_likely(result) {
unsigned char *first = result;
for (lua_Integer r = 1; r <= rows; r++) {
- if (lua_rawgeti(L, -1, r) == LUA_TTABLE) {
+ if (lua_rawgeti(L, 1, r) == LUA_TTABLE) {
for (lua_Integer c = 1; c <= columns; c++) {
if (lua_rawgeti(L, -1, c) == LUA_TNUMBER) {
- lua_Integer v = lua_tointeger(L, -1);
+ lua_Integer v = lua_tointeger(L, -1);
*result++ = v < 0 ? 0 : v > 255 ? 255 : (unsigned char) v;
- } else {
+ } else {
*result++ = 0;
}
lua_pop(L, 1);
@@ -1163,27 +1656,39 @@ static int strlib_pack_rows_columns(lua_State* L)
}
lua_pop(L, 1);
}
- lua_pushlstring(L, (char *) first, result - first);
+ lua_pushlstring(L, (char *) first, (size_t) (result - first));
+ lmt_memory_free(first);
return 1;
+ } else {
+ return luaL_error(L, "not enough memory for string.packrowscolumns");
}
}
case LUA_TTABLE:
{
int mode = (int) lua_rawlen(L, -1);
- size_t size = rows * columns * mode;
+ if (mode <= 0) {
+ lua_pop(L, 2);
+ lua_pushliteral(L, "");
+ return 1;
+ }
+ if lmt_unlikely((size_t) rows > SIZE_MAX / (size_t) columns || ((size_t) rows * (size_t) columns) > SIZE_MAX / (size_t) mode) {
+ lua_pop(L, 2);
+ return luaL_error(L, "table dimensions in string.packrowscolumns are too large");
+ }
+ size_t size = (size_t) rows * (size_t) columns * (size_t) mode;
unsigned char *result = lmt_memory_malloc(size);
lua_pop(L, 2); /* row and cell */
- if (result) {
+ if lmt_likely(result) {
unsigned char *first = result;
for (lua_Integer r = 1; r <= rows; r++) {
- if (lua_rawgeti(L, -1, r) == LUA_TTABLE) {
+ if (lua_rawgeti(L, 1, r) == LUA_TTABLE) {
for (lua_Integer c = 1; c <= columns; c++) {
if (lua_rawgeti(L, -1, c) == LUA_TTABLE) {
for (int i = 1; i <= mode; i++) {
- if (lua_rawgeti(L, -1, i) == LUA_TNUMBER) {
+ if (lua_rawgeti(L, -1, i) == LUA_TNUMBER) {
lua_Integer v = lua_tointeger(L, -1);
*result++ = v < 0 ? 0 : v > 255 ? 255 : (unsigned char) v;
- } else {
+ } else {
*result++ = 0;
}
lua_pop(L, 1);
@@ -1194,10 +1699,16 @@ static int strlib_pack_rows_columns(lua_State* L)
}
lua_pop(L, 1);
}
- lua_pushlstring(L, (char *) first, result - first);
+ lua_pushlstring(L, (char *) first, (size_t) (result - first));
+ lmt_memory_free(first);
return 1;
+ } else {
+ return luaL_error(L, "not enough memory for string.packrowscolumns");
}
}
+ default:
+ lua_pop(L, 1); /* pop element */
+ break;
}
}
}
@@ -1205,162 +1716,6 @@ static int strlib_pack_rows_columns(lua_State* L)
return 1;
}
-/*tex
- This converts a hex string to characters. Spacing is ignored and invalid characters result in
- a false result. Empty strings are okay. Originally we assumed \type {XX XX XX} and just skipped
- single ones but we might as well also handle \type {X X X}. This code is not that critical and
- was introduced when we wanted flexible bitmap definition in \METAPOST\ and \LUA\ as part of the
- \type {potrace} experiments.
-*/
-
-// static int strlib_hextocharacters(lua_State *L)
-// {
-// size_t ls = 0;
-// const char *s = lua_tolstring(L, 1, &ls);
-// if (ls > 0) {
-// luaL_Buffer b;
-// luaL_buffinitsize(L, &b, ls/2);
-// while (1) {
-// unsigned char first = *s++;
-// switch (first) {
-// case ' ': case '\n': case '\r': case '\t':
-// continue;
-// case '\0':
-// goto DONE;
-// default:
-// {
-// unsigned char second = *s++;
-// switch (second) {
-// case ' ': case '\n': case '\r': case '\t':
-// continue;
-// case '\0':
-// goto BAD;
-// default:
-// {
-// unsigned char chr;
-// if (first >= '0' && first <= '9') {
-// chr = 16 * (first - '0');
-// } else if (first >= 'A' && first <= 'F') {
-// chr = 16 * (first - 'A' + 10);
-// } else if (first >= 'a' && first <= 'f') {
-// chr = 16 * (first - 'a' + 10);
-// } else {
-// goto BAD;
-// }
-// if (second >= '0' && second <= '9') {
-// chr += second - '0';
-// } else if (second >= 'A' && second <= 'F') {
-// chr += second - 'A' + 10;
-// } else if (second >= 'a' && second <= 'f') {
-// chr += second - 'a' + 10;
-// } else {
-// goto BAD;
-// }
-// luaL_addchar(&b, chr);
-// break;
-// }
-// }
-// break;
-// }
-// }
-// }
-// DONE:
-// luaL_pushresult(&b);
-// return 1;
-// BAD:
-// lua_pushboolean(L, 0);
-// return 1;
-// } else {
-// lua_pushliteral(L, "");
-// return 1;
-// }
-// }
-
-// static int strlib_hextocharacters(lua_State *L)
-// {
-// size_t ls = 0;
-// const char *s = lua_tolstring(L, 1, &ls);
-// if (ls == 0) {
-// lua_pushliteral(L, "");
-// return 1;
-// } else {
-// const char *end = s + ls;
-// luaL_Buffer b;
-// luaL_buffinitsize(L, &b, ls / 2);
-// while (s < end) {
-// unsigned char first;
-// do {
-// if (s >= end) {
-// goto DONE;
-// } else {
-// first = (unsigned char) *s++;
-// }
-// } while (first == ' ' || first == '\n' || first == '\r' || first == '\t');
-// unsigned char second;
-// do {
-// if (s >= end) {
-// goto BAD;
-// } else {
-// second = (unsigned char) *s++;
-// }
-// } while (second == ' ' || second == '\n' || second == '\r' || second == '\t');
-// unsigned char high, low;
-// if (first >= '0' && first <= '9') high = first - '0';
-// else if (first >= 'A' && first <= 'F') high = first - 'A' + 10;
-// else if (first >= 'a' && first <= 'f') high = first - 'a' + 10;
-// else goto BAD;
-// if (second >= '0' && second <= '9') low = second - '0';
-// else if (second >= 'A' && second <= 'F') low = second - 'A' + 10;
-// else if (second >= 'a' && second <= 'f') low = second - 'a' + 10;
-// else goto BAD;
-// luaL_addchar(&b, (high << 4) | low);
-// }
-// DONE:
-// luaL_pushresult(&b);
-// return 1;
-// BAD:
-// lua_pushboolean(L, 0);
-// return 1;
-// }
-// }
-
-/*
- Here we use a 256-byte lookup table for hex decoding but of course it comes
- at a memory price (as we use shorts as suggested by gemini):
-
- - 0 .. 15 : valid hex nibbles
- - 256 : whitespace (skip)
- - 257 : invalid character / failure
-
- It's anyway a nice example of a variant, given the usual reformatting and a bit of
- cleaning up.
-*/
-
-static const unsigned short strlib_hex_table[256] = {
- /* 0x00 - 0x1F: control characters \t \n \r are valid spacing */
- 257,257,257,257,257,257,257,257,257,256,256,257,257,256,257,257,
- 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
- /* 0x20 - 0x2F: ' ' is valid spacing */
- 256,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
- /* 0x30 - 0x39: digits '0'-'9' (0 .. 9) */
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,257,257,257,257,257,257,
- /* 0x40 - 0x4F: uppercase 'A'-'F' (10 .. 15) */
- 257, 10, 11, 12, 13, 14, 15,257,257,257,257,257,257,257,257,257,
- 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
- /* 0x60 - 0x6F: lowercase 'a'-'f' (10 .. 15) */
- 257, 10, 11, 12, 13, 14, 15,257,257,257,257,257,257,257,257,257,
- 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
- /* 0x80 - 0xFF: high ASCII / non ASCII (all invalid) */
- 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
- 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
- 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
- 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
- 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
- 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
- 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
- 257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,257,
-};
-
static int strlib_hextocharacters(lua_State *L)
{
size_t ls = 0;
@@ -1408,70 +1763,23 @@ static int strlib_hextocharacters(lua_State *L)
static int strlib_octtointeger(lua_State *L)
{
- const char *s = lua_tostring(L, 1);
- // lua_Integer n = 0;
- // int negate = *s == '-';
- // if (negate) {
- // s++;
- // }
- // while (*s && n < 0xFFFFFFFF) { /* large enough */
- // if (*s >= '0' && *s <= '7') {
- // n = n * 8 + *s - '0';
- // } else {
- // break;
- // }
- // s++;
- // }
- // lua_pushinteger(L, negate ? -n : n);
- lua_pushinteger(L, strtoul(s, NULL, 8));
- return 1;
+ const char *s = luaL_checkstring(L, 1);
+ lua_pushinteger(L, (lua_Integer) strtoul(s, NULL, 8));
+ return 1;
}
static int strlib_dectointeger(lua_State *L)
{
- const char *s = lua_tostring(L, 1);
- // lua_Integer n = 0;
- // int negate = *s == '-';
- // if (negate) {
- // s++;
- // }
- // while (*s && n < 0xFFFFFFFF) { /* large enough */
- // if (*s >= '0' && *s <= '9') {
- // n = n * 10 + *s - '0';
- // } else {
- // break;
- // }
- // s++;
- // }
- // lua_pushinteger(L, negate ? -n : n);
- // lua_pushinteger(L, atol(s));
- lua_pushinteger(L, strtoul(s, NULL, 10));
- return 1;
+ const char *s = luaL_checkstring(L, 1);
+ lua_pushinteger(L, (lua_Integer) strtoul(s, NULL, 10));
+ return 1;
}
static int strlib_hextointeger(lua_State *L)
{
- const char *s = lua_tostring(L, 1);
- // lua_Integer n = 0;
- // int negate = *s == '-';
- // if (negate) {
- // s++;
- // }
- // while (*s && n < 0xFFFFFFFF) { /* large enough */
- // if (*s >= '0' && *s <= '9') {
- // n = n * 16 + *s - '0';
- // } else if (*s >= 'A' && *s <= 'F') {
- // n = n * 16 + *s - 'A' + 10;
- // } else if (*s >= 'a' && *s <= 'f') {
- // n = n * 16 + *s - 'a' + 10;
- // } else {
- // break;
- // }
- // s++;
- // }
- // lua_pushinteger(L, negate ? -n : n);
- lua_pushinteger(L, strtoul(s, NULL, 16));
- return 1;
+ const char *s = luaL_checkstring(L, 1);
+ lua_pushinteger(L, (lua_Integer) strtoul(s, NULL, 16));
+ return 1;
}
static int strlib_chrtointeger(lua_State *L)
@@ -1510,12 +1818,12 @@ static int strlib_utftabletostring(lua_State *L)
if (l > n) { l = n; }
if (l >= f) {
luaL_Buffer b;
- luaL_buffinitsize(L, &b, (size_t) (l-f+1) * 4);
+ luaL_buffinitsize(L, &b, (size_t) (l-f+1) * 4);
for (lua_Integer i = f; i <= l; i++) {
if (lua_rawgeti(L, 1, i) == LUA_TNUMBER) {
strlib_aux_add_utfnumber(L, &b, -1);
- lua_pop(L, 1);
}
+ lua_pop(L, 1);
}
luaL_pushresult(&b);
return 1;
@@ -1536,25 +1844,25 @@ static int strlib_splitintolines(lua_State *L)
lua_Integer i = 0;
const char *f = s;
while (*s) {
- if (*s == 13) {
+ if (*s == 13) {
/* cr */
lua_pushlstring(L, f, n);
lua_rawseti(L, -2, ++i);
- f = ++s;
- if (*f == 10) {
- f = ++s;
+ f = ++s;
+ if (*f == 10) {
+ f = ++s;
}
if (! *f) {
- return 1;
+ return 1;
}
n = 0;
- } else if (*s == 10) {
+ } else if (*s == 10) {
/* lf */
lua_pushlstring(L, f, n);
lua_rawseti(L, -2, ++i);
- f = ++s;
+ f = ++s;
if (! *f) {
- return 1;
+ return 1;
}
n = 0;
} else {
@@ -1567,183 +1875,3797 @@ static int strlib_splitintolines(lua_State *L)
lua_rawseti(L, -2, ++i);
}
}
- return 1;
+ return 1;
}
-static const luaL_Reg strlib_function_list[] = {
- { "characters", strlib_characters },
- { "characterpairs", strlib_characterpairs },
- { "bytes", strlib_bytes },
- { "bytepairs", strlib_bytepairs },
- { "bytetable", strlib_bytetable },
- { "linetable", strlib_linetable },
- { "utfvalues", strlib_utfvalues },
- { "utfcharacters", strlib_utfcharacters },
- { "utfcharacter", strlib_utfcharacter },
- { "utfvalue", strlib_utfvalue },
- { "utflength", strlib_utflength },
- { "utfvaluetable", strlib_utfvaluetable },
- { "utfcharactertable", strlib_utfcharactertable },
- { "utftabletostring", strlib_utftabletostring },
- { "f6", strlib_format_f6 },
- { "tounicode16", strlib_format_tounicode16 },
- { "toutf8", strlib_format_toutf8 },
- { "toutf16", strlib_format_toutf16 }, /* untested */
- { "toutf32", strlib_format_toutf32 },
- { "utf16toutf8", strlib_utf16toutf8 },
- { "packrowscolumns", strlib_pack_rows_columns },
- { "hextocharacters", strlib_hextocharacters },
- { "octtointeger", strlib_octtointeger },
- { "dectointeger", strlib_dectointeger },
- { "hextointeger", strlib_hextointeger },
- { "chrtointeger", strlib_chrtointeger },
- { "splitintolines", strlib_splitintolines },
- /* */
- { NULL, NULL },
-};
+/*tex
-/*
- The next (old, moved here) experiment was used to check if using some buffer is more efficient
- than using a table that we concat. It makes no difference. If we ever use this, the initializer
- |luaextend_string_buffer| will be merged into |luaextend_string|. We could gain a little on a
- bit more efficient |luaL_checkudata| as we use elsewhere because in practice (surprise) its
- overhead makes buffers like this {\em 50 percent} slower than the concatinated variant and
- twice as slow when we reuse a temporary table. It's just better to stay at the \LUA\ end.
+ The table serializer in \CONTEXT\ is quite okay but sometimes we have rather large tables,
+ like the character database, fonts and a utility file. So, as a test I played with a C based
+ serializer variant. Some initial statistics were promising:
+
+ loading char-def.lua : 0.11100000000000002
+ table.serialize : size 6127996, time: 0.312
+ string.serialize : size 6127997, time: 0.053
+
+ So indeed handy to have it as alternative. For this approach we revive an older idea of
+ buffers so eventually we might implement it as described at the bottom of this file.
+
+ Because we know the length of constant strings, we can use the more optimal length aware
+ append in most cases. Single characters have their own optimal append. We might add more
+ to this repertoire if we ever add the buffer userdata.
+
+ We start with string buffers. As mentioned this is oldish code revived. To that we added
+ some more, in order to support serializing but after that we also added for instance a
+ format feature because we could share code that way. So it became abit larger effort than
+ initially planned. This kind of code is rather easy in the sense that there are no
+ heuristics or unexpected side effects, contrary to the rest of the engine. This is easy
+ going coding, a distraction from more complex matters, and desired interfaces are known
+ and translations of what we already have in \LUA.
- Replacing the userdata test with a dedicated test gives a speed boost but we're still some
- {\em 10 percent} slower. So, for now we comment this feature.
*/
-# if (0)
+# define lmt_string_buffer_default (1024 * 1024)
+# define default_format_size 4096 /* occasionally 8192 or 16384 */
- /*tex See |lmtinterface.h| for |STRING_BUFFER_METATABLE_INSTANCE|. */
+typedef struct lmt_string_buffer {
+ char *buffer;
+ size_t length;
+ size_t size;
+ size_t step;
+ lua_State *L; /* the (current) state, errors have to be raised there (think coroutines) */
+} lmt_string_buffer;
- typedef struct lmt_string_buffer {
- char *buffer;
- size_t length;
- size_t size;
- size_t step;
- } lmt_string_buffer;
+inline static void lmt_buffer_allocate(lua_State *L, lmt_string_buffer *b)
+{
+ b->size = lmt_string_buffer_default;
+ b->length = 0;
+ b->buffer = (char *) lmt_memory_malloc(b->size);
+ b->step = 0; /* maybe, as other memory management in lmtx */
+ b->L = L;
+}
- static lmt_string_buffer *strlib_buffer_instance(lua_State *L)
- {
- lmt_string_buffer *b = (lmt_string_buffer *) lua_touserdata(L, 1);
- if (b && lua_getmetatable(L, 1)) {
- lua_get_metatablelua(string_buffer_instance);
- if (! lua_rawequal(L, -1, -2)) {
- b = NULL;
- } else if (! b->buffer) {
- b = NULL;
+inline static void lmt_buffer_dispose(lmt_string_buffer *b)
+{
+ lmt_memory_free(b->buffer);
+}
+
+inline static int lmt_buffer_has_room(lmt_string_buffer *b, size_t needed)
+{
+ if (b->size == 0) {
+ b->size = default_format_size;
+ b->length = 0;
+ b->buffer = (char *) lmt_memory_malloc(b->size);
+ b->step = 0;
+ }
+ if lmt_unlikely(needed > SIZE_MAX - b->length) {
+ luaL_error(b->L, "not enough memory for buffer");
+ return 0;
+ }
+ size_t required = b->length + needed;
+ if (required >= b->size) {
+ size_t new_size = b->size;
+ if (b->step) {
+ while (required >= new_size) {
+ if lmt_unlikely(new_size > SIZE_MAX - b->step) {
+ luaL_error(b->L, "not enough memory for buffer");
+ return 0;
+ }
+ new_size += b->step;
+ }
+ } else {
+ while (required >= new_size) {
+ if lmt_unlikely(new_size > (SIZE_MAX / 2)) {
+ /* prevent arithmetic overflow wrap-around */
+ luaL_error(b->L, "not enough memory for buffer");
+ return 0;
+ }
+ new_size *= 2;
}
- lua_pop(L, 2);
- return b;
}
- return NULL;
+ char *new_buffer = (char *) lmt_memory_realloc(b->buffer, new_size);
+ if lmt_unlikely(! new_buffer) {
+ luaL_error(b->L, "not enough memory for buffer");
+ return 0;
+ }
+ b->buffer = new_buffer;
+ b->size = new_size;
}
+ return 1;
+}
- static int strlib_buffer_gc(lua_State *L)
- {
- lmt_string_buffer *b = strlib_buffer_instance(L);
- if (b) {
- lmt_memory_free(b->buffer);
+inline static void lmt_buffer_add_lstring(lmt_string_buffer *b, const char *str, size_t len)
+{
+ if (lmt_buffer_has_room(b, len)) {
+ memcpy(b->buffer + b->length, str, len);
+ b->length += len;
+ }
+}
+
+inline static void lmt_buffer_add_string(lmt_string_buffer *b, const char *str)
+{
+ lmt_buffer_add_lstring(b, str, strlen(str));
+}
+
+inline static void lmt_buffer_add_char(lmt_string_buffer *b, char chr)
+{
+ if (lmt_buffer_has_room(b, 1)) {
+ b->buffer[b->length] = chr;
+ b->length += 1;
+ }
+}
+
+inline static void lmt_buffer_add_char_ok(lmt_string_buffer *b, char chr)
+{
+ b->buffer[b->length] = chr;
+ b->length += 1;
+}
+
+inline static void lmt_buffer_add_spaces(lmt_string_buffer *b, int n)
+{
+ if (n > 0 && lmt_buffer_has_room(b, n)) {
+ memset(b->buffer + b->length, ' ', n);
+ b->length += n;
+ }
+}
+
+static inline void strlib_aux_add_z(lmt_string_buffer *b, lua_Number val, lua_Integer precision)
+{
+ int req_precision = strlib_aux_normalize_precision(precision);
+ size_t req_room = (size_t) req_precision + 350;
+ if (lmt_buffer_has_room(b, req_room)) {
+ int len = double_to_string_z(val, b->buffer + b->length, b->size - b->length, req_precision);
+ if (len >= 0) {
+ b->length += (size_t) len;
}
+ }
+}
+
+/*tex
+
+ The next (old, moved here) experiment was used to check if using some buffer is more efficient
+ than using a table that we concat. It makes no difference. The experiment added the helpers to
+ the string library but now that we have the sequencer lib we can best add it there. We could
+ gain a little on a bit more efficient |luaL_checkudata| as we use elsewhere because in practice
+ (surprise) its overhead makes buffers like this {\em 50 percent} slower than the concatinated
+ variant and twice as slow when we reuse a temporary table. It's just better to stay at the
+ \LUA\ end. Replacing the userdata test with a dedicated test gives a speed boost but we're
+ still some {\em 10 percent} slower. So, as the overhead in the engine is little we just enable
+ it, if only for experiments.The archive has the previous code, where it hooks into the string
+ library (that we extend anyway).
+
+ Because I knew that there was room for improvement I chat a bit with gemini and we got to
+ a real low level speedup.
+
+ Baseline C API 0.381s 1.0× Full C API stack validation + lua_tolstring
+ Direct Pointer Check 0.095s 4.0× ttisfulluserdata + getudatamem (bypassed C API stack)
+ Direct Buffer Formatting 0.063s 6.0× serialize_integer (bypassed Lua string creation)
+ Lua table.concat 0.032s 11.9× Inlined VM bytecode instructions (TSETI)
+
+ Using this feature only makes sense when we have massive amounts and don't want to create
+ intermediate tables. So a 50% performance loss is acceptable. After that I added a addformat
+ variant (okay, asked gemini and then refactored that in what we had as serializers) and after
+ playing around abit we got a 400% percent gain over using |string.format|:
+
+ \starttyping
+ local add = sequencer.addtobuffer
+ local addformat = sequencer.addformattobuffer
+ local format = string.format
+
+ local n = 500000
+
+ local c = os.clock()
+ local b = sequencer.newbuffer(1024*1024)
+ for i=1,n do
+ add(b,"foo")
+ add(b,i)
+ addformat(b,"%.10f",1.2345678900) -- extra test
+ add(b,"\n")
+ end
+ print(sequencer.getbuffersize(b),os.clock()-c)
+
+ local c = os.clock()
+ local b = { }
+ for i=1,n do
+ b[#b+1] = "foo"
+ b[#b+1] = i
+ b[#b+1] = format("%.10f",1.2345678900) -- extra test
+ b[#b+1] = "\n"
+ end
+ b = table.concat(b)
+ print(#,os.clock()-c)
+ \stoptyping
+
+ The buffered size is smaller because we strip redundant zero's. So, after all an interesting
+ experiment.
+
+*/
+
+static const void *G_BUFFER_METATABLE_PTR = NULL;
+
+static inline lmt_string_buffer *strlib_buffer_instance(lua_State *L)
+{
+ lmt_string_buffer *b = (lmt_string_buffer *) lua_touserdata(L, 1);
+ if (b && lua_getmetatable(L, 1)) {
+ if (lua_topointer(L, -1) != G_BUFFER_METATABLE_PTR || ! b->buffer) {
+ b = NULL;
+ } else {
+ b->L = L; /* the buffer can be used in another coroutine than where it was made */
+ }
+ lua_pop(L, 1);
+ return b;
+ }
+ return NULL;
+}
+
+static int strlib_buffer_gc(lua_State *L)
+{
+ lmt_string_buffer *b = strlib_buffer_instance(L);
+ if (b) {
+ lmt_memory_free(b->buffer);
+ b->buffer = NULL;
+ }
+ return 0;
+}
+
+static int strlib_buffer_tostring(lua_State *L)
+{
+ lmt_string_buffer *b = strlib_buffer_instance(L);
+ if (b) {
+ lua_pushfstring(L, "<buffer %p>", b);
+ return 1;
+ } else {
return 0;
}
+}
- static int strlib_buffer_new(lua_State *L)
- {
- size_t size = lmt_optsizet(L, 1, LUAL_BUFFERSIZE);
- size_t step = lmt_optsizet(L, 2, size);
- lmt_string_buffer *b = (lmt_string_buffer *) lua_newuserdatauv(L, sizeof(lmt_string_buffer), 0);
- b->buffer = lmt_memory_malloc(size);
- b->size = size;
- b->step = step;
- b->length = 0;
- lua_get_metatablelua(string_buffer_instance);
- lua_setmetatable(L, -2);
+# define minimum_step 1024
+
+static int strlib_buffer_new(lua_State *L)
+{
+ size_t size = lmt_optsizet(L, 1, LUAL_BUFFERSIZE);
+ if (size < minimum_step) {
+ size = minimum_step; /* Ensure size is never zero or unreasonably small */
+ }
+ size_t step = lmt_optsizet(L, 2, size);
+ lmt_string_buffer *b = (lmt_string_buffer *) lua_newuserdatauv(L, sizeof(lmt_string_buffer), 0);
+ /* lmt_buffer_allocate(b); */
+ b->size = size;
+ b->length = 0;
+ b->buffer = (char *) lmt_memory_malloc(b->size);
+ b->step = (step < minimum_step) ? minimum_step : ((step > size) ? size : step); /* let's be reasonable*/
+ b->L = L;
+ lua_get_metatablelua(string_buffer_instance);
+ lua_setmetatable(L, -2);
+ return 1;
+}
+
+static int strlib_buffer_get_data(lua_State *L)
+{
+ lmt_string_buffer *b = strlib_buffer_instance(L);
+ if (b) {
+ lua_pushlstring(L, b->buffer, b->length);
+ lua_pushinteger(L, (lua_Integer) b->length);
+ return 2;
+ } else {
+ lua_pushnil(L);
return 1;
}
+}
+
+static int strlib_buffer_get_size(lua_State *L)
+{
+ lmt_string_buffer *b = strlib_buffer_instance(L);
+ lua_pushinteger(L, b ? b->length : 0);
+ return 1;
+}
+
+static const luaL_Reg sequencerlib_metatable_list[] =
+{
+ // { "__newindex", strlib_buffer_setvalue },
+ { "__tostring", strlib_buffer_tostring },
+ { "__gc", strlib_buffer_gc },
+ { NULL, NULL },
+};
+
+/*tex
+
+ Right after we started with \MKIV\ we needed serialization of (often large) tables. Of
+ course we used \LUA. That code could either construct a table with strings (to be concat)
+ or write to file. That handle overhead was later avoided by a variant. We also wanted
+ some number values to be hex as it's easier with \UNICODE\ but in the end the overhead
+ made that a seldom used option. We also kept track of circular references but again, that
+ was never useful at this level so we dealt with that differently. We also moved on to
+ using formatters, because those are faster than \LUA's formatter.
+
+ Move some to \CCODE\ was already on the agenda and prototyped in a helperlib that is
+ not part of the regular distribution. We now include an update to this.
+
+*/
+
+/*
+ This is a typical case where one can prompt an llm framework: can you make me a lookup table
+ for this. Most languages need something like this when they serialize, so here is what Gemini
+ cooked up (not that much faster but neat anyway). It actually did it wrong but I wanted |\xNN|
+ anyway that got fixed. This replaces a loop with per-character escape checking, pretty much
+ what we do at the \LUA\ end. The |> 127| slots are unchanged because \LUA\ is byte agnostic.
+*/
+
+typedef struct {
+ char bytes[4];
+ uint8_t len;
+} char_esc_t;
+
+#define ESC1(c) { { (char) (c), 0, 0, 0 }, 1 }
+#define ESC2(a, b) { { a, b, 0, 0 }, 2 }
+#define ESC3(a, b, c) { { a, b, c, 0 }, 3 }
+#define ESC4(a, b, c, d) { { a, b, c, d }, 4 }
+
+static const char_esc_t ESCAPE_LUT[256] = {
+ /* 0x00 - 0x07 */ ESC4('\\','x','0','0'), ESC4('\\','x','0','1'), ESC4('\\','x','0','2'), ESC4('\\','x','0','3'), ESC4('\\','x','0','4'), ESC4('\\','x','0','5'), ESC4('\\','x','0','6'), ESC4('\\','x','0','7'),
+ /* 0x08 - 0x0F */ ESC4('\\','x','0','8'), ESC2('\\','t'), ESC2('\\','n'), ESC4('\\','x','0','B'), ESC4('\\','x','0','C'), ESC2('\\','r'), ESC4('\\','x','0','E'), ESC4('\\','x','0','F'),
+ /* 0x10 - 0x17 */ ESC4('\\','x','1','0'), ESC4('\\','x','1','1'), ESC4('\\','x','1','2'), ESC4('\\','x','1','3'), ESC4('\\','x','1','4'), ESC4('\\','x','1','5'), ESC4('\\','x','1','6'), ESC4('\\','x','1','7'),
+ /* 0x18 - 0x1F */ ESC4('\\','x','1','8'), ESC4('\\','x','1','9'), ESC4('\\','x','1','A'), ESC4('\\','x','1','B'), ESC4('\\','x','1','C'), ESC4('\\','x','1','D'), ESC4('\\','x','1','E'), ESC4('\\','x','1','F'),
+ /* 0x20 - 0x27 */ ESC1(' '), ESC1('!'), ESC2('\\','"'), ESC1('#'), ESC1('$'), ESC1('%'), ESC1('&'), ESC1('\''),
+ /* 0x28 - 0x2F */ ESC1('('), ESC1(')'), ESC1('*'), ESC1('+'), ESC1(','), ESC1('-'), ESC1('.'), ESC1('/'),
+ /* 0x30 - 0x37 */ ESC1('0'), ESC1('1'), ESC1('2'), ESC1('3'), ESC1('4'), ESC1('5'), ESC1('6'), ESC1('7'),
+ /* 0x38 - 0x3F */ ESC1('8'), ESC1('9'), ESC1(':'), ESC1(';'), ESC1('<'), ESC1('='), ESC1('>'), ESC1('?'),
+ /* 0x40 - 0x47 */ ESC1('@'), ESC1('A'), ESC1('B'), ESC1('C'), ESC1('D'), ESC1('E'), ESC1('F'), ESC1('G'),
+ /* 0x48 - 0x4F */ ESC1('H'), ESC1('I'), ESC1('J'), ESC1('K'), ESC1('L'), ESC1('M'), ESC1('N'), ESC1('O'),
+ /* 0x50 - 0x57 */ ESC1('P'), ESC1('Q'), ESC1('R'), ESC1('S'), ESC1('T'), ESC1('U'), ESC1('V'), ESC1('W'),
+ /* 0x58 - 0x5F */ ESC1('X'), ESC1('Y'), ESC1('Z'), ESC1('['), ESC2('\\','\\'), ESC1(']'), ESC1('^'), ESC1('_'),
+ /* 0x60 - 0x67 */ ESC1('`'), ESC1('a'), ESC1('b'), ESC1('c'), ESC1('d'), ESC1('e'), ESC1('f'), ESC1('g'),
+ /* 0x68 - 0x6F */ ESC1('h'), ESC1('i'), ESC1('j'), ESC1('k'), ESC1('l'), ESC1('m'), ESC1('n'), ESC1('o'),
+ /* 0x70 - 0x77 */ ESC1('p'), ESC1('q'), ESC1('r'), ESC1('s'), ESC1('t'), ESC1('u'), ESC1('v'), ESC1('w'),
+ /* 0x78 - 0x7F */ ESC1('x'), ESC1('y'), ESC1('z'), ESC1('{'), ESC1('|'), ESC1('}'), ESC1('~'), ESC4('\\','x','7','F'),
+ /* 0x80 - 0xFF */ // High bytes (128-255) map to single bytes (UTF-8 compatible)
+ ESC1(128), ESC1(129), ESC1(130), ESC1(131), ESC1(132), ESC1(133), ESC1(134), ESC1(135), ESC1(136), ESC1(137), ESC1(138), ESC1(139), ESC1(140), ESC1(141), ESC1(142), ESC1(143),
+ ESC1(144), ESC1(145), ESC1(146), ESC1(147), ESC1(148), ESC1(149), ESC1(150), ESC1(151), ESC1(152), ESC1(153), ESC1(154), ESC1(155), ESC1(156), ESC1(157), ESC1(158), ESC1(159),
+ ESC1(160), ESC1(161), ESC1(162), ESC1(163), ESC1(164), ESC1(165), ESC1(166), ESC1(167), ESC1(168), ESC1(169), ESC1(170), ESC1(171), ESC1(172), ESC1(173), ESC1(174), ESC1(175),
+ ESC1(176), ESC1(177), ESC1(178), ESC1(179), ESC1(180), ESC1(181), ESC1(182), ESC1(183), ESC1(184), ESC1(185), ESC1(186), ESC1(187), ESC1(188), ESC1(189), ESC1(190), ESC1(191),
+ ESC1(192), ESC1(193), ESC1(194), ESC1(195), ESC1(196), ESC1(197), ESC1(198), ESC1(199), ESC1(200), ESC1(201), ESC1(202), ESC1(203), ESC1(204), ESC1(205), ESC1(206), ESC1(207),
+ ESC1(208), ESC1(209), ESC1(210), ESC1(211), ESC1(212), ESC1(213), ESC1(214), ESC1(215), ESC1(216), ESC1(217), ESC1(218), ESC1(219), ESC1(220), ESC1(221), ESC1(222), ESC1(223),
+ ESC1(224), ESC1(225), ESC1(226), ESC1(227), ESC1(228), ESC1(229), ESC1(230), ESC1(231), ESC1(232), ESC1(233), ESC1(234), ESC1(235), ESC1(236), ESC1(237), ESC1(238), ESC1(239),
+ ESC1(240), ESC1(241), ESC1(242), ESC1(243), ESC1(244), ESC1(245), ESC1(246), ESC1(247), ESC1(248), ESC1(249), ESC1(250), ESC1(251), ESC1(252), ESC1(253), ESC1(254), ESC1(255)
+};
+
+#undef ESC1
+#undef ESC2
+#undef ESC3
+#undef ESC4
+
+static void serialize_string_escaped(lmt_string_buffer *b, const char *s, size_t len)
+{
+ if lmt_unlikely(len > (SIZE_MAX - 2) / 4) {
+ luaL_error(b->L, "not enough memory for buffer");
+ return;
+ }
+ if (lmt_buffer_has_room(b, len * 4 + 2)) {
+ b->buffer[b->length++] = '"';
+ for (size_t i = 0; i < len; i++) {
+ unsigned char c = (unsigned char)s[i];
+ char_esc_t esc = ESCAPE_LUT[c];
+ memcpy(b->buffer + b->length, esc.bytes, esc.len);
+ b->length += esc.len;
+ }
+ b->buffer[b->length++] = '"';
+ }
+}
- static int strlib_buffer_add(lua_State *L)
+/*tex
+
+ We can use this:
+
+ \starttyping
+ static void serialize_string(lmt_string_buffer *b, const char *s, size_t len)
{
- lmt_string_buffer *b = strlib_buffer_instance(L);
- if (b) {
- switch (lua_type(L, 2)) {
+ if (lmt_buffer_has_room(b, (len * 2) + 2)) {
+ b->buffer[b->length++] = '"';
+ for (size_t i = 0; i < len; i++) {
+ char c = s[i];
+ if (c == '"' || c == '\\' ) {
+ b->buffer[b->length++] = '\\';
+ }
+ b->buffer[b->length++] = c;
+ }
+ b->buffer[b->length++] = '"';
+ }
+ }
+ \stoptyping
+
+ Instead we use an editor safe variant instead. It adds e.g. 3K to a dejavu stream table of
+ nearly 500K so that's ok. After all we use the bytecode compiler version which is smaller
+ anyway.
+
+*/
+
+static void serialize_string(lmt_string_buffer *b, const char *s, size_t len)
+{
+ if lmt_unlikely(len > (SIZE_MAX - 2) / 2) {
+ luaL_error(b->L, "not enough memory for buffer");
+ return;
+ }
+ if (lmt_buffer_has_room(b, (len * 2) + 2)) {
+ b->buffer[b->length++] = '"';
+ for (size_t i = 0; i < len; i++) {
+ char c = s[i];
+ switch (c) {
+ /* we keep nul, e.g. scite just shows that well */
+ case '"':
+ case '\\':
+ b->buffer[b->length++] = '\\';
+ b->buffer[b->length++] = c;
+ break;
+ case '\f':
+ b->buffer[b->length++] = '\\';
+ b->buffer[b->length++] = 'f';
+ break;
+ case '\n':
+ b->buffer[b->length++] = '\\';
+ b->buffer[b->length++] = 'n';
+ break;
+ case '\r':
+ b->buffer[b->length++] = '\\';
+ b->buffer[b->length++] = 'r';
+ break;
+ case '\t':
+ b->buffer[b->length++] = '\\';
+ b->buffer[b->length++] = 't';
+ break;
+ case '\v':
+ b->buffer[b->length++] = '\\';
+ b->buffer[b->length++] = 'v';
+ break;
+ default:
+ b->buffer[b->length++] = c;
+ break;
+ }
+ }
+ b->buffer[b->length++] = '"';
+ }
+}
+
+static void serialize_double(lmt_string_buffer *b, double val)
+{
+ if (lmt_buffer_has_room(b, 350)) {
+ if (val >= -9223372036854775808.0 && val < 9223372036854775808.0) {
+ int64_t i = (int64_t) val;
+ if ((double) i == val && ! (i == 0 && signbit(val))) {
+ b->length += snprintf(b->buffer + b->length, 350, "%" PRId64, i);
+ return;
+ }
+ }
+ b->length += snprintf(b->buffer + b->length, 350, "%a", val);
+ }
+}
+
+static void serialize_integer(lmt_string_buffer *b, lua_Integer val)
+{
+ if (lmt_buffer_has_room(b, 32)) {
+ b->length += snprintf(b->buffer + b->length, 32, "%" LUA_INTEGER_FRMLEN "d", val);
+ }
+}
+
+static int strlib_buffer_add(lua_State *L)
+{
+ lmt_string_buffer *b = strlib_buffer_instance(L);
+ if (b) {
+ int top = lua_gettop(L);
+ for (int i = 2; i <= top; i++) {
+ switch (lua_type(L, i)) {
case LUA_TSTRING:
- case LUA_TNUMBER:
{
size_t l;
- const char *s = lua_tolstring(L, 2, &l);
- size_t length = b->length + l;
- if (length >= b->size) {
- while (length >= b->size) {
- b->size += b->step;
+ const char *s = lua_tolstring(L, i, &l);
+ lmt_buffer_add_lstring(b, s, l);
+ break;
+ }
+ case LUA_TNUMBER:
+ {
+ if (lua_isinteger(L, i)) {
+ /* Write integer directly into b->buffer (zero Lua string creation) */
+ serialize_integer(b, lua_tointeger(L, i));
+ } else {
+ if (lmt_buffer_has_room(b, 350)) {
+ b->length += double_to_string_f(lua_tonumber(L, i), b->buffer + b->length, 17);
}
- b->buffer = lmt_memory_realloc(b->buffer, b->size);
}
- memcpy(&b->buffer[b->length], s, l);
- b->length = length;
+ break;
}
+ case LUA_TBOOLEAN:
+ {
+ if (lua_toboolean(L, i)) {
+ lmt_buffer_add_lstring(b, "true", 4);
+ } else {
+ lmt_buffer_add_lstring(b, "false", 5);
+ }
+ break;
+ }
+ default:
break;
+ }
+ }
+ }
+ return 0;
+}
+
+/*tex
+
+ With a bit of gemini help I stepwise added a formatter. Intermediate and final checks
+ stepwise made the buffering faster. A kind of fun excercize as long as one stays in
+ control and does specific suggestions and corrects when needed. Kind of a game and this
+ is straightforward code.
+
+ \startty ping
+ local n = 500000
+
+ local format = string.format
+ local f = string.formatters["%i %N %N %N %N %N %N cm"]
+ local sqformat = sequencer.format
+ local s
+
+ local c = os.clock()
+ for i=1,n do
+ s = format("%i %f %f %f %f %f %f cm",i,1.999,2.999,3.999,4.999,5.999,6.999)
+ end
+ print("format ",os.clock()-c,s)
+
+ local c = os.clock()
+ for i=1,n do
+ s = f(i,1.999,2.999,3.999,4.999,5.999,6.999)
+ end
+ print("formatter",os.clock()-c,s)
+
+ local c = os.clock()
+ for i=1,n do
+ local b = newbuffer(64)
+ addformat(b,"%i %f %f %f %f %f %f cm",i,1.999,2.999,3.999,4.999,5.999,6.999)
+ s = getbuffer(b)
+ end
+ print("buffer ",os.clock()-c,s)
+
+ local c = os.clock()
+ for i=1,n do
+ s = sqformat("%i %N %N %N %N %N %N cm",i,1.999,2.999,3.999,4.999,5.999,6.999)
+ end
+ print("sqformat",os.clock()-c,s)
+ \stoptyping
+
+ \starttabulate[|l|r|r|r|]
+ \HL
+ \NC \bf Method
+ \NC \bf 6 Floats (\type{%N})
+ \NC \bf 1 Int + 6 Floats (\type{%i %N...})
+ \NC \bf Delta (Overhead of \type{%i}) \NR
+ \HL
+ \NC \type{string.format} \NC 1.036s \NC 1.097s \NC +0.061s (+5.8\%) \NR
+ \NC \type{formatter} \NC 0.334s \NC \bf 0.460s \NC \bf +0.126s (+37.7\% penalty) \NR
+ \NC \type{buffer} (per-loop allocation) \NC 1.080s \NC 1.128s \NC +0.048s (+4.4\%) \NR
+ \NC \type{sqformat} \NC 0.336s \NC \bf 0.354s \NC \bf +0.018s (+5.3\% penalty) \NR
+ \HL
+ \stoptabulate
+
+ Key Takeaways
+
+ \startitemize
+ \startitem
+ formatter (ConTeXt Lua Generator): Performs best when format strings are static and
+ consist purely of fast primitive conversions, but takes a performance hit as format
+ complexity and argument count grow due to Lua string concatenation chain overhead.
+ \stopitem
+ \startitem
+ sequencer.format (sqformat): Handles complex, multi-type format strings (integers,
+ floats, hex, strings, booleans) with virtually linear performance scaling.
+ \stopitem
+ \startitem
+ sequencer.addformattobuffer (Persistent Buffer): Remaining in C memory across
+ multiple steps without returning an intermediate string to Lua remains the fastest
+ path for bulk output (PDF/SVG streams, file writing, macro expansion).
+ \stopitem
+ \stopitemize
+
+*/
+
+static void strlib_aux_sequenced(
+ lua_State *L,
+ int index,
+ lmt_string_buffer *buffer,
+ int sep_is_true,
+ const char *sep_str,
+ size_t sep_len,
+ int simple,
+ int seen,
+ int depth
+);
+
+static inline void strlib_aux_array_sequenced(
+ lua_State *L,
+ int tbl_idx,
+ lmt_string_buffer *b,
+ const char *sep_str,
+ size_t sep_len
+)
+{
+ lua_Unsigned n = lua_rawlen(L, tbl_idx);
+ for (lua_Unsigned k = 1; k <= n; k++) {
+ if (k > 1 && sep_len > 0) {
+ lmt_buffer_add_lstring(b, sep_str, sep_len);
+ }
+ lua_rawgeti(L, tbl_idx, (lua_Integer) k);
+
+ switch (lua_type(L, -1)) {
+ case LUA_TNUMBER:
+ if (lua_isinteger(L, -1)) {
+ serialize_integer(b, lua_tointeger(L, -1));
+ } else {
+ if (lmt_buffer_has_room(b, 350)) {
+ b->length += double_to_string_f(lua_tonumber(L, -1), b->buffer + b->length, 17);
+ }
+ }
+ break;
+ case LUA_TSTRING:
+ {
+ size_t len;
+ const char *str = lua_tolstring(L, -1, &len);
+ lmt_buffer_add_lstring(b, str, len);
+ }
+ break;
+ case LUA_TBOOLEAN:
+ if (lua_toboolean(L, -1)) {
+ lmt_buffer_add_lstring(b, "true", 4);
+ } else {
+ lmt_buffer_add_lstring(b, "false", 5);
+ }
+ break;
+ default:
+ break;
+ }
+ lua_pop(L, 1);
+ }
+}
+
+static inline void strlib_aux_format_padded_number(
+ lmt_string_buffer *b,
+ const char *prefix,
+ size_t prefix_len,
+ const char *temp_digits,
+ int digit_count,
+ int width,
+ int precision,
+ int has_precision,
+ int pad_zero,
+ int left_align
+)
+{
+ /* left alignment takes precedence and disables zero-padding, as does a precision (printf) */
+ if (left_align || has_precision) {
+ pad_zero = 0;
+ }
+ /* when we pad with zeros the sign is part of the width */
+ int min_digits = has_precision ? precision : (pad_zero ? width - (int) prefix_len : 1);
+ if (min_digits <= 0) {
+ min_digits = 1;
+ }
+ int num_len = (digit_count < min_digits) ? min_digits : digit_count;
+ int sign_len = (int) prefix_len;
+ int total_content_len = num_len + sign_len;
+ int padding = (width > total_content_len) ? width - total_content_len : 0;
+ int total_len = total_content_len + padding;
+ if (lmt_buffer_has_room(b, (size_t) total_len)) {
+ /* right alignment spaces (if not zero-padding and not left-aligned) */
+ if (padding > 0 && !left_align && !pad_zero) {
+ for (int z = 0; z < padding; z++) {
+ b->buffer[b->length++] = ' ';
+ }
+ }
+ /* write sign or prefix (e.g., "-", "+", "0x", "U+") */
+ if (prefix_len > 0 && prefix != NULL) {
+ memcpy(b->buffer + b->length, prefix, prefix_len);
+ b->length += prefix_len;
+ }
+ /* zero padding between prefix and digits */
+ if (pad_zero && padding > 0) {
+ for (int z = 0; z < padding; z++) {
+ b->buffer[b->length++] = '0';
+ }
+ }
+ /* leading zero padding for precision / min_digits */
+ for (int z = 0; z < num_len - digit_count; z++) {
+ b->buffer[b->length++] = '0';
+ }
+ /* append digits in correct forward order */
+ int len = digit_count;
+ while (len > 0) {
+ b->buffer[b->length++] = temp_digits[--len];
+ }
+ /* left alignment spaces */
+ if (padding > 0 && left_align) {
+ for (int z = 0; z < padding; z++) {
+ b->buffer[b->length++] = ' ';
+ }
+ }
+ }
+}
+
+static inline void strlib_aux_format_padded_string(
+ lmt_string_buffer *b,
+ const char *temp,
+ int len,
+ int width,
+ int left_align
+)
+{
+ int padding = (width > len) ? width - len : 0;
+ if (padding <= 0) {
+ lmt_buffer_add_lstring(b, temp, (size_t) len);
+ } else {
+ if (left_align) {
+ lmt_buffer_add_lstring(b, temp, (size_t) len);
+ lmt_buffer_add_spaces(b, padding);
+ } else {
+ lmt_buffer_add_spaces(b, padding);
+ lmt_buffer_add_lstring(b, temp, (size_t) len);
+ }
+ }
+}
+
+/*tex
+ Floats are formatted directly into the buffer, for which there is room for the width, and
+ then we pad in place. Zeros go after the sign but are not used for infinity and nan.
+*/
+
+static inline void strlib_aux_format_padded_float(
+ lmt_string_buffer *b,
+ int len,
+ int width,
+ int pad_zero,
+ int left_align
+)
+{
+ int padding = width - len;
+ if (padding > 0) {
+ char *s = b->buffer + b->length;
+ if (left_align) {
+ memset(s + len, ' ', (size_t) padding);
+ } else {
+ int sign = s[0] == '-';
+ if (pad_zero && s[sign] >= '0' && s[sign] <= '9') {
+ memmove(s + sign + padding, s + sign, (size_t) (len - sign));
+ memset(s + sign, '0', (size_t) padding);
+ } else {
+ memmove(s + padding, s, (size_t) len);
+ memset(s, ' ', (size_t) padding);
+ }
+ }
+ len = width;
+ }
+ b->length += (size_t) len;
+}
+
+/* %S and^%s are a bit diferent but ok */
+
+static const char *const C_X00_table[33] = {
+ "[null]", "[soh]", "[stx]", "[etx]", "[eot]", "[enq]", "[ack]", "[bel]",
+ "[bs]", "[ht]", "[lf]", "[vt]", "[ff]", "[cr]", "[so]", "[si]",
+ "[dle]", "[dc1]", "[dc2]", "[dc3]", "[dc4]", "[nak]", "[syn]", "[etb]",
+ "[can]", "[em]", "[sub]", "[esc]", "[fs]", "[gs]", "[rs]", "[us]",
+ "[space]" /* 0x20 */
+};
+
+static inline void strlib_aux_format_sS(
+ lua_State *L,
+ lmt_string_buffer *b,
+ int *arg_idx,
+ char spec,
+ int width,
+ int left_align,
+ int has_precision,
+ int precision
+)
+{
+ size_t len = 0;
+ const char *str = NULL;
+ int pop = 0;
+ if (spec == 'S') {
+ str = luaL_tolstring(L, (*arg_idx)++, &len);
+ pop = 1;
+ } else {
+ switch(lua_type(L, *arg_idx)) {
+ case LUA_TSTRING:
+ str = lua_tolstring(L, (*arg_idx)++, &len);
+ break;
+ case LUA_TNUMBER:
+ str = luaL_tolstring(L, (*arg_idx)++, &len);
+ pop = 1;
+ break;
+ default:
+ (*arg_idx)++;
+ break;
+ }
+ }
+ if (str) {
+ if (has_precision && (size_t) precision < len) {
+ len = (size_t) precision;
+ }
+ if (width == 0) {
+ lmt_buffer_add_lstring(b, str, len);
+ } else {
+ int padding = width - (int) len;
+ if (padding > 0) {
+ if (! left_align) {
+ lmt_buffer_add_spaces (b, padding);
+ lmt_buffer_add_lstring(b, str, len);
+ } else {
+ lmt_buffer_add_lstring(b, str, len);
+ lmt_buffer_add_spaces (b, padding);
+ }
+ } else {
+ lmt_buffer_add_lstring(b, str, len);
+ }
+ }
+ }
+ if (pop) {
+ lua_pop(L, 1);
+ }
+}
+
+static inline void strlib_aux_format_qQ(
+ lua_State *L,
+ lmt_string_buffer *b,
+ int *arg_idx,
+ char spec
+)
+{
+ if (spec == 'q') {
+ switch (lua_type(L, *arg_idx)) {
+ case LUA_TBOOLEAN:
+ if (lua_toboolean(L, (*arg_idx)++)) {
+ lmt_buffer_add_lstring(b, "true", 4);
+ } else {
+ lmt_buffer_add_lstring(b, "false", 5);
+ }
+ break;
+ case LUA_TNUMBER:
+ if (lua_isinteger(L, *arg_idx)) {
+ serialize_integer(b, lua_tointeger(L, (*arg_idx)++));
+ } else {
+ serialize_double(b, lua_tonumber(L, (*arg_idx)++));
+ }
+ break;
+ case LUA_TNIL:
+ lmt_buffer_add_lstring(b, "nil", 3);
+ (*arg_idx)++;
+ break;
+ default:
+ {
+ size_t len = 0;
+ const char *str = lua_tolstring(L, (*arg_idx)++, &len);
+ if (str) {
+ serialize_string(b, str, len);
+ } else {
+ lmt_buffer_add_lstring(b, "\"\"", 2);
+ }
+ }
+ break;
+ }
+ } else {
+ /* %Q (fast lpeg-style serialize_string) */
+ size_t len = 0;
+ const char *str = luaL_tolstring(L, (*arg_idx)++, &len);
+ if (str) {
+ serialize_string(b, str, len);
+ } else {
+ lmt_buffer_add_lstring(b, "\"\"", 2);
+ }
+ lua_pop(L, 1);
+ }
+}
+static inline void strlib_aux_format_aA(
+ lua_State *L,
+ lmt_string_buffer *b,
+ int *arg_idx,
+ char spec,
+ const char *sep_str,
+ size_t sep_len
+)
+{
+ char quote = (spec == 'a') ? '\'' : '"';
+ switch (lua_type(L, *arg_idx)) {
+ case LUA_TNIL:
+ goto EMPTY;
+ case LUA_TNUMBER:
+ {
+ if (lua_isinteger(L, *arg_idx)) {
+ serialize_integer(b, lua_tointeger(L, *arg_idx));
+ } else if (lmt_buffer_has_room(b, 350)) {
+ b->length += double_to_string_f(lua_tonumber(L, *arg_idx), b->buffer + b->length, 17);
+ }
+ (*arg_idx)++;
+ }
+ return;
+ case LUA_TBOOLEAN:
+ lmt_buffer_add_char(b, quote);
+ if (lua_toboolean(L, (*arg_idx)++)) {
+ lmt_buffer_add_lstring(b, "true", 4);
+ } else {
+ lmt_buffer_add_lstring(b, "false", 5);
+ }
+ lmt_buffer_add_char(b, quote);
+ return;
+ case LUA_TTABLE:
+ {
+ lmt_buffer_add_char(b, quote);
+ const char *use_sep = (sep_str != NULL) ? sep_str : ",";
+ size_t use_len = (sep_str != NULL) ? sep_len : 1;
+ int tbl_idx = (*arg_idx)++;
+ // lua_newtable(L);
+ // int seen = lua_gettop(L);
+ strlib_aux_sequenced(L, tbl_idx, b, 0, use_sep, use_len, 0, 0, 1); /* no seen */
+ // lua_remove(L, seen);
+ lmt_buffer_add_char(b, quote);
+ }
+ return;
+ default:
+ {
+ size_t len = 0;
+ const char *str = lua_tolstring(L, (*arg_idx)++, &len);
+ lmt_buffer_add_char(b, quote);
+ if (str && len > 0) {
+ lmt_buffer_add_lstring(b, str, len);
+ }
+ lmt_buffer_add_char(b, quote);
+ }
+ return;
+ }
+ EMPTY:
+ lmt_buffer_add_char(b, quote);
+ lmt_buffer_add_char(b, quote);
+ (*arg_idx)++;
+}
+
+static inline void strlib_aux_format_C(
+ lua_State *L,
+ lmt_string_buffer *b,
+ int *arg_idx
+)
+{
+ switch (lua_type(L, *arg_idx)) {
+ case LUA_TNUMBER:
+ {
+ lua_Unsigned code = (lua_Unsigned) lua_tointeger(L, (*arg_idx)++);
+ if (code <= 0x20) {
+ lmt_buffer_add_string(b, C_X00_table[code]);
+ } else {
+ if (lmt_buffer_has_room(b, 64)) {
+ int len = aux_uni2strlen((unsigned) code, b->buffer + b->length);
+ b->length += len;
+ b->length += snprintf(b->buffer + b->length, 64, " (U+%05X)", (unsigned) code);
+ }
+ }
+ }
+ break;
+ case LUA_TSTRING:
+ {
+ size_t len = 0;
+ const char *str = lua_tolstring(L, (*arg_idx)++, &len);
+ if (str && len > 0) {
+ size_t pos = 0;
+ int code = strlib_aux_tounicode(str, len, &pos);
+ if (code >= 0 && code <= 0x20) {
+ lmt_buffer_add_string(b, C_X00_table[code]);
+ } else if (code > 0x20 && code <= 0x10FFFF) {
+ if (lmt_buffer_has_room(b, len + 64)) {
+ lmt_buffer_add_lstring(b, str, len);
+ b->length += snprintf( b->buffer + b->length, 64, " (U+%05X)", (unsigned) code);
+ }
+ } else {
+ lmt_buffer_add_lstring(b, str, len);
+ lmt_buffer_add_lstring(b, " (U+FFFD)", 9);
+ }
+ }
+ }
+ break;
+ default:
+ (*arg_idx)++;
+ break;
+ }
+}
+
+static inline void strlib_aux_format_F(
+ lua_State *L,
+ lmt_string_buffer *b,
+ int *arg_idx,
+ int has_precision,
+ int precision,
+ int width,
+ int pad_zero,
+ int left_align
+)
+{
+ if (lua_type(L, *arg_idx) == LUA_TNUMBER) {
+ lua_Number val = lua_tonumber(L, (*arg_idx)++);
+ int prc = has_precision ? precision : 9;
+ if (lmt_buffer_has_room(b, (size_t) prc + (size_t) width + 350)) {
+ char *s = b->buffer + b->length;
+ size_t room = b->size - b->length;
+ int len = 0;
+ if (! has_precision && val > -0.0000000005 && val < 0.0000000005) {
+ s[0] = '0';
+ len = 1;
+ } else if (fmod(val, 1.0) == 0.0 && val >= -9007199254740992.0 && val <= 9007199254740992.0) {
+ len = double_to_string_z(val, s, room, 0);
+ } else {
+ len = double_to_string_z(val, s, room, prc);
+ }
+ if (len > 0) {
+ strlib_aux_format_padded_float(b, len, width, pad_zero, left_align);
+ }
+ }
+ } else {
+ (*arg_idx)++;
+ }
+}
+
+static inline void strlib_aux_format_eEgG(
+ lua_State *L,
+ lmt_string_buffer *b,
+ int *arg_idx,
+ char spec,
+ int width,
+ int pad_zero,
+ int left_align,
+ int space_flag,
+ int has_precision,
+ int precision
+)
+{
+ switch (lua_type(L, *arg_idx)) {
+ case LUA_TNUMBER:
+ {
+ lua_Number val = lua_tonumber(L, (*arg_idx)++);
+ int req_prc = has_precision ? precision : 6;
+ size_t req_room = (width > 0 ? (size_t)width : 0) + (size_t)req_prc + 64;
+ if (lmt_buffer_has_room(b, req_room)) {
+ size_t available = b->size - b->length;
+ char fmt_str[32];
+ snprintf(fmt_str, sizeof(fmt_str), "%%%s%s%s%s.*%c",
+ space_flag ? " " : "",
+ left_align ? "-" : "",
+ pad_zero ? "0" : "",
+ width > 0 ? "*" : "",
+ spec
+ );
+ int written;
+ if (width > 0) {
+ written = snprintf(b->buffer + b->length, available, fmt_str, width, req_prc, val);
+ } else {
+ written = snprintf(b->buffer + b->length, available, fmt_str, req_prc, val);
+ }
+ if (written > 0) {
+ size_t add_len = (size_t)written < available ? (size_t)written : available - 1;
+ b->length += add_len;
+ }
+ }
+ }
+ break;
+ default:
+ (*arg_idx)++;
+ break;
+ }
+}
+
+static inline void strlib_aux_format_jJ(
+ lua_State *L,
+ lmt_string_buffer *b,
+ int *arg_idx,
+ char spec,
+ int has_precision,
+ int precision
+)
+{
+ double val = 0.0;
+ int is_num = 0;
+ switch (lua_type(L, *arg_idx)) {
+ case LUA_TNUMBER:
+ {
+ val = lua_tonumber(L, (*arg_idx)++);
+ is_num = 1;
+ }
+ break;
+ case LUA_TSTRING:
+ {
+ /* also string-to-number casting (tonumber(n)) */
+ const char *s = lua_tostring(L, *arg_idx);
+ char *endptr;
+ val = strtod(s, &endptr);
+ if (endptr != s && *endptr == '\0') {
+ is_num = 1;
+ }
+ (*arg_idx)++;
+ }
+ break;
+ default:
+ (*arg_idx)++;
+ break;
+ }
+ if (is_num) {
+ int req_precision = strlib_aux_normalize_precision(has_precision ? precision : 6);
+ size_t req_room = (size_t) req_precision + 350;
+ if (lmt_buffer_has_room(b, req_room)) {
+ int len = double_to_string_j(
+ val,
+ b->buffer + b->length,
+ b->size - b->length, /* Pass true available buffer capacity */
+ (spec == 'j') ? 'e' : 'E',
+ req_precision
+ );
+ if (len >= 0) {
+ b->length += (size_t) len;
+ }
+ }
+ } else {
+ /* fallback to tostring(n) if not a valid number */
+ size_t len = 0;
+ const char *str = luaL_tolstring(L, *arg_idx - 1, &len);
+ if (str) {
+ lmt_buffer_add_lstring(b, str, len);
+ lua_pop(L, 1);
+ }
+ }
+}
+
+/*
+ This |%k| one is handy when we want to align (as in tables) so we have an explicit before/after
+ decimal digit width specifiers.
+
+ string.sqformatters["%7.2f"](12.34) --> " 12.34"
+ string.sqformatters["%4.2k"](12.34) --> " 12.34"
+
+ %f requiring manual total width calculation: 4 digits before + 1 dot + 2 digits after = 7 total
+ %k with explicit before and after widths: %4.2k where before=4, after=2
+*/
+
+static inline void strlib_aux_format_left_right(
+ lua_State *L,
+ lmt_string_buffer *b,
+ int *arg_idx,
+ char spec,
+ int width,
+ int left_align
+)
+{
+ size_t len = 0;
+ const char *str = NULL;
+ int pop = 0;
+ switch (lua_type(L, *arg_idx)) {
+ case LUA_TSTRING:
+ str = lua_tolstring(L, (*arg_idx)++, &len);
+ break;
+ case LUA_TNUMBER:
+ str = luaL_tolstring(L, (*arg_idx)++, &len);
+ pop = 1;
+ break;
+ default:
+ /* ignore non-string types */
+ (*arg_idx)++;
+ break;
+ }
+ if (str && len > 0) {
+ /* if width == 0 (e.g. %< or %> without width), handle string directly */
+ if (width == 0) {
+ lmt_buffer_add_lstring(b, str, len);
+ } else {
+ /* count UTF-8 character length (codepoints) using existing helper */
+ size_t utflen = 0;
+ size_t ind = 0;
+ while (ind < len) {
+ size_t next = ind;
+ strlib_aux_tounicode(str, len, &next);
+ if (next <= ind) {
+ next = ind + 1;
+ }
+ ind = next;
+ utflen++;
+ }
+ int target_width = width;
+ int is_right_aligned = (spec == '>');
+ /* if flag '-' was supplied (%-10> or %-10<), invert effective alignment direction */
+ if (left_align) {
+ is_right_aligned = ! is_right_aligned;
+ }
+ int padding = target_width - (int) utflen;
+ if (padding > 0) {
+ if (is_right_aligned) {
+ /* spaces before string */
+ lmt_buffer_add_spaces (b, padding);
+ lmt_buffer_add_lstring(b, str, len);
+ } else {
+ /* spaces after string */
+ lmt_buffer_add_lstring(b, str, len);
+ lmt_buffer_add_spaces (b, padding);
+ }
+ } else {
+ lmt_buffer_add_lstring(b, str, len);
+ }
+ }
+ }
+ if (pop) {
+ lua_pop(L, 1);
+ }
+}
+
+/* plug-in support, watch out, function hook in differently from formatters */
+
+static inline void strlib_aux_format_extension(
+ lua_State *L,
+ lmt_string_buffer *b,
+ int *arg_idx,
+ int top,
+ const char *ext_name,
+ size_t ext_len,
+ int f_width,
+ int has_width
+)
+{
+ /* upvalue 2 is the local extensions table */
+ int ext_tbl = lua_upvalueindex(2);
+ if (lua_istable(L, ext_tbl)) {
+ lua_pushlstring(L, ext_name, ext_len);
+ lua_gettable(L, ext_tbl);
+ } else {
+ lua_pushnil(L);
+ }
+ if (lua_type(L, -1) == LUA_TFUNCTION) {
+ /* not really width but we pass the shared name */
+ int f = has_width ? f_width : 1;
+ if (f > 0 && *arg_idx <= top) {
+ /* push arguments onto the stack for the callback to pick up */
+ int args_to_pass = (f > (top - *arg_idx + 1)) ? (top - *arg_idx + 1) : f;
+ luaL_checkstack(L, args_to_pass, "too many arguments for format extension");
+ for (int i = 0; i < args_to_pass; i++) {
+ lua_pushvalue(L, (*arg_idx)++);
+ }
+ if (lua_pcall(L, args_to_pass, 1, 0) == LUA_OK) {
+ size_t len = 0;
+ const char *str = lua_tolstring(L, -1, &len);
+ if (str && len > 0) {
+ lmt_buffer_add_lstring(b, str, len);
+ }
+ lua_pop(L, 1); /* return value */
+ } else {
+ lua_error(L);
+ }
+ } else {
+ lua_pop(L, 1); /* function */
+ (*arg_idx)++;
+ }
+ return;
+ } else {
+ /* extension object or nil */
+ lua_pop(L, 1);
+ }
+}
+
+/* %t, %T, %{...}t, %{...}T, %<sep...>t, %<sep...>T (a non table argument is skipped) */
+
+static inline void strlib_aux_format_tT(
+ lua_State *L,
+ lmt_string_buffer *b,
+ int *arg_idx,
+ char spec,
+ const char *sep_str,
+ size_t sep_len
+)
+{
+ int tbl_idx = (*arg_idx)++;
+ if (lua_istable(L, tbl_idx)) {
+ if (spec == 'T') {
+ /* capital %T: key=value pairs (hashed/sorted) */
+ lua_newtable(L);
+ int seen = lua_gettop(L);
+ strlib_aux_sequenced(L, tbl_idx, b, 0, sep_str ? sep_str : " | ", sep_str ? sep_len : 3, 0, seen, 1);
+ lua_remove(L, seen);
+ } else {
+ /* lowercase %t: array values (1..n) */
+ strlib_aux_array_sequenced(L, tbl_idx, b, sep_str, sep_len);
+ }
+ }
+}
+
+/*tex
+
+ This format helper started out simple with a few keys but as it was relative efficient, I
+ stepwise added the various emthods from |string.formatters| which was kind of easy given that
+ we could use gemini to generate the snippets by feeding the \LUA\ code plus a bit of
+ explanation. It took some iterations, testing, fixing, cleanup etc but it was easy to test
+ compatibility. We already had helpers in |auxserialize| that we could use (and a few variants
+ were added).
+
+ Scanning what comes before a key is kind of messy especially because we need to intercept for
+ instance table specific formatters but by adding stepwise we kept it kind of clean im the end.
+
+ Once all was more or less in place there were various places the code could be made a bit more
+ efficient (avoid scanning etc). A typical case of \quotation {think a bit about improvements}
+ during a long walk. The 0..9 trick for instance permits fast paths for frequently used formats
+ and some more will be added (ones we often use in \CONTEXT). I might spot more locations cq.\
+ shortcuts. Using the C formatter over the \LUA\ brought processing the manual down from 16 to
+ just over 15 seconds and the test suite from 455 to 415 seconds (2018 laptop running Wwindows
+ 11). This is mainly because the backend uses lots of formatting and when \METAPOST\ graphics
+ are converted to \PDF\ we also format a lot. The memory footprint is often a bit smaller too.
+
+*/
+
+ /* todo: don't throw errors, just ignore, we quit anyway so ... */
+
+static void strlib_aux_addformat(
+ lua_State *L,
+ lmt_string_buffer *b,
+ const char *fmt,
+ size_t fmt_len,
+ int top,
+ int arg_idx
+)
+{
+ size_t i = 0;
+ size_t start = 0;
+ int base_idx = arg_idx;
+
+ while (i < fmt_len) {
+ if (fmt[i] == '%') {
+ /* flush preceding chunk of literal text */
+ int d = i - start;
+ if (d == 1) {
+ lmt_buffer_add_char(b, (int) fmt[start]);
+ } else if (d > 0) {
+ lmt_buffer_add_lstring(b, fmt + start, d);
+ }
+ /* an incomplete specifier at the end is flushed as it is */
+ start = i;
+ /* skip '%' and check */
+ i++;
+ if (i >= fmt_len) {
+ break;
+ }
+ unsigned char spec = fmt[i];
+ int width = 0;
+ int pad_zero = 0;
+ int left_align = 0;
+ int space_flag = 0;
+ int precision = 17;
+ int has_precision = 0;
+ // const char *sep_str = NULL;
+ // size_t sep_len = 0;
+ /*
+ If the character immediately following '%' is directly in our list of valid single-character format specifiers,
+ we bypass all flag, width, precision, table, and extension parsing.
+ */
+ switch (spec) {
+ case 0x01: // soh %.1N
+ case 0x02: // stx %.2N
+ case 0x03: // etx %.3N
+ case 0x04: // eot %.4N
+ case 0x05: // enq %.5N
+ case 0x06: // ack %.6N
+ case 0x07: // bel %.7N
+ case 0x08: // bs %.8N
+ case 0x09: // ht %.9N
+ {
+ /* stripped float (ConTeXt formatters drop-in: strips redundant zeros) */
+ lua_Number val = lua_tonumber(L, arg_idx++);
+ if (lmt_buffer_has_room(b, 350)) {
+ b->length += double_to_string_f(val, b->buffer + b->length, spec);
+ }
+ }
+ start = ++i;
+ continue;
+ // case 0x0A: // lf
+ // break;
+ case 0x0B: // vt %02i
+ case 0x0C: // ff %03i
+ // case 0x0D: // cr
+ // break;
+ case 0x0E: // so %04i
+ case 0x0F: // si %05i
+ {
+ int w = (spec == 0x0B) ? 2 : (spec == 0x0C) ? 3 : (spec == 0x0E) ? 4 : 5;
+ lua_Integer val = lua_tointeger(L, arg_idx++);
+ size_t req_room = (size_t) w + 32;
+ if (lmt_buffer_has_room(b, req_room)) {
+ char fmt_str[32];
+ snprintf(fmt_str, sizeof(fmt_str), "%%0%d" LUA_INTEGER_FRMLEN "d", w);
+ b->length += (size_t) snprintf(b->buffer + b->length, req_room, fmt_str, val);
+ }
+ }
+ start = ++i;
+ continue;
+ case 0x10: // dle %02X
+ case 0x11: // dc1 %03X
+ case 0x12: // dc2 %04X
+ case 0x13: // dc3 %05X
+ case 0x14: // dc4 %06X
+ case 0x15: // nak %07X
+ case 0x16: // syn %08X
+ {
+ int w = spec - 0x0E;
+ lua_Unsigned val = (lua_Unsigned) lua_tointeger(L, arg_idx++);
+ int min_digits = w;
+ char temp[32];
+ int len = 0;
+ do {
+ temp[len++] = hex_upper[val & 0x0F];
+ val >>= 4;
+ } while (val > 0);
+ int total_len = (len < min_digits) ? min_digits : len;
+ if (lmt_buffer_has_room(b, total_len)) {
+ for (int z = 0; z < total_len - len; z++) {
+ b->buffer[b->length++] = '0';
+ }
+ while (len > 0) {
+ b->buffer[b->length++] = temp[--len];
+ }
+ }
+ }
+ start = ++i;
+ continue;
+ case 0x17: // etb (%.6N,%.6N)
+ {
+ lua_Number v1 = lua_tonumber(L, arg_idx++); if (arg_idx > top) { break; }
+ lua_Number v2 = lua_tonumber(L, arg_idx++);
+ if (lmt_buffer_has_room(b, 350 + 350 + 3)) {
+ lmt_buffer_add_char_ok(b,'(');
+ b->length += double_to_string_f(v1, b->buffer + b->length, 6);
+ lmt_buffer_add_char_ok(b,',');
+ b->length += double_to_string_f(v2, b->buffer + b->length, 6);
+ lmt_buffer_add_char_ok(b,')');
+ }
+ }
+ start = ++i;
+ continue;
+ case 0x18: // can (%.6N,%.6N,%.6N)
+ case 0x1A: // sub (%.3N,%.3N,%.3N)
+ {
+ lua_Number v1 = lua_tonumber(L, arg_idx++); if (arg_idx > top) { break; }
+ lua_Number v2 = lua_tonumber(L, arg_idx++); if (arg_idx > top) { break; }
+ lua_Number v3 = lua_tonumber(L, arg_idx++);
+ if (lmt_buffer_has_room(b, 350 * 3 + 4)) {
+ int precision = spec == 0x18 ? 6 : 3;
+ lmt_buffer_add_char_ok(b,'(');
+ b->length += double_to_string_f(v1, b->buffer + b->length, precision);
+ lmt_buffer_add_char_ok(b,',');
+ b->length += double_to_string_f(v2, b->buffer + b->length, precision);
+ lmt_buffer_add_char_ok(b,',');
+ b->length += double_to_string_f(v3, b->buffer + b->length, precision);
+ lmt_buffer_add_char_ok(b,')');
+ }
+ }
+ start = ++i;
+ continue;
+ case 0x19: // em (%.3N)
+ {
+ lua_Number v1 = lua_tonumber(L, arg_idx++);
+ if (lmt_buffer_has_room(b, 350 + 2)) {
+ lmt_buffer_add_char_ok(b,'(');
+ b->length += double_to_string_f(v1, b->buffer + b->length, 3);
+ lmt_buffer_add_char_ok(b,')');
+ }
+ }
+ start = ++i;
+ continue;
+ case 0x1B: // esc (%.3N,%.3N,%.3N,%.3N)
+ {
+ lua_Number v1 = lua_tonumber(L, arg_idx++); if (arg_idx > top) { break; }
+ lua_Number v2 = lua_tonumber(L, arg_idx++); if (arg_idx > top) { break; }
+ lua_Number v3 = lua_tonumber(L, arg_idx++); if (arg_idx > top) { break; }
+ lua_Number v4 = lua_tonumber(L, arg_idx++);
+ if (lmt_buffer_has_room(b, 350 * 4 + 5)) {
+ lmt_buffer_add_char_ok(b,'(');
+ b->length += double_to_string_f(v1, b->buffer + b->length, 3);
+ lmt_buffer_add_char_ok(b,',');
+ b->length += double_to_string_f(v2, b->buffer + b->length, 3);
+ lmt_buffer_add_char_ok(b,',');
+ b->length += double_to_string_f(v3, b->buffer + b->length, 3);
+ lmt_buffer_add_char_ok(b,',');
+ b->length += double_to_string_f(v4, b->buffer + b->length, 3);
+ lmt_buffer_add_char_ok(b,')');
+ }
+ }
+ start = ++i;
+ continue;
+ // case 0x1C: // fs %-15s
+ // case 0x1D: // gs %--t
+ // case 0x1E: // rs %s
+ // case 0x1F: // us %...
+ case 'a': case 'A':
+ strlib_aux_format_aA(L, b, &arg_idx, spec, NULL, 0);
+ start = ++i;
+ continue;
+ case 't': case 'T':
+ strlib_aux_format_tT(L, b, &arg_idx, spec, NULL, 0);
+ start = ++i;
+ continue;
+ case '{':
+ {
+ /* braces are only used for a table separator: %{...}t or %{...}T */
+ size_t close = i + 1;
+ while (close < fmt_len && fmt[close] != '}') {
+ close++;
+ }
+ if (close + 1 < fmt_len) {
+ switch (fmt[close + 1]) {
+ case 't': case 'T':
+ strlib_aux_format_tT(L, b, &arg_idx, fmt[close + 1], fmt + i + 1, close - i - 1);
+ start = i = close + 2;
+ continue;
+ case 'a': case 'A':
+ strlib_aux_format_aA(L, b, &arg_idx, fmt[close + 1], fmt + i + 1, close - i - 1);
+ start = i = close + 2;
+ continue;
+ default:
+ break;
+ }
+ }
+ }
+ break;
+ case 'b': case 'B':
+ case 'c': case 'C':
+ // case 'd': case 'D': /* 'D' not used */
+ case 'd':
+ case 'e': case 'E':
+ case 'f': case 'F':
+ case 'g': case 'G':
+ case 'h': case 'H':
+ case 'i': case 'I':
+ case 'j': case 'J':
+ case 'k': case 'K':
+ case 'l': case 'L':
+ // case 'm': case 'M': /* 'M' not used */
+ case 'm':
+ case 'n': case 'N':
+ // case 'o': case 'O': /* 'O' not used */
+ case 'o':
+ case 'p': case 'P':
+ case 'q': case 'Q':
+ case 'r': case 'R':
+ case 's': case 'S':
+ // case 't': case 'T': /* see above */
+ case 'u': case 'U':
+ case 'v': case 'V':
+ // case 'w': case 'W': /* see below */
+ case 'W':
+ case 'x': case 'X':
+ // case 'z': case 'Z': /* see below */
+ case 'Z':
+ case '<': case '>':
+ i++;
+ goto SWITCH;
default:
break;
}
+ /*
+ Fast check for %!extension_name! or %1!extension_name! We must check this before
+ table checks so that extension names ending in 't' (like !tex!) are not
+ incorrectly captured as table formatters. Only consume digits if a '!' is actually
+ present ahead, preventing standard flags/widths (like %09i) from being swallowed
+ prematurely.
+ */
+ {
+ size_t scan = i;
+ int has_extension = 0;
+ while (scan < fmt_len && fmt[scan] >= '0' && fmt[scan] <= '9') {
+ scan++;
+ }
+ if (scan < fmt_len && fmt[scan] == '!') {
+ has_extension = 1;
+ }
+
+ if (has_extension) {
+ int pre_val = 0;
+ int has_pre = 0;
+ while (i < fmt_len && fmt[i] >= '0' && fmt[i] <= '9') {
+ pre_val = strlib_aux_parse_decimal(pre_val, fmt[i] - '0');
+ has_pre = 1;
+ i++;
+ }
+ if (i < fmt_len && fmt[i] == '!') {
+ size_t ext_start = i + 1;
+ i++;
+ while (i < fmt_len && fmt[i] != '!') {
+ i++;
+ }
+ if (i < fmt_len && fmt[i] == '!') {
+ const char *ext_name = fmt + ext_start;
+ size_t ext_len = i - ext_start;
+ i++; /* skip ending '!' */
+ strlib_aux_format_extension(L, b, &arg_idx, top, ext_name, ext_len, pre_val, has_pre);
+ start = i;
+ continue;
+ }
+ }
+ }
+ }
+
+ /* check for %<sep...>t, %<sep...>T, %<sep...>a, %<sep...>A (plain and braced tables are handled above) */
+
+ if (i < fmt_len) {
+
+ size_t scan = i;
+
+ while (scan < fmt_len) {
+ unsigned char c = fmt[scan];
+ if (
+ (c >= 'a' && c <= 'z') ||
+ (c >= 'A' && c <= 'Z') ||
+ (c >= '0' && c <= '9') ||
+ c == '%' || c == '{'
+ ) {
+ break;
+ }
+ scan++;
+ }
+
+ /* */
+
+ if (scan < fmt_len) {
+ char target_c = fmt[scan];
+ if (target_c == 't' || target_c == 'T') {
+ strlib_aux_format_tT(L, b, &arg_idx, target_c, fmt + i, scan - i);
+ start = i = scan + 1; /* Skip separator string and 't'/'T' */
+ continue;
+ } else if (target_c == 'a' || target_c == 'A') {
+ // sep_str = fmt + i;
+ // sep_len = scan - i;
+ // i = scan; /* Skip separator string, leave 'a'/'A' for switch */
+ strlib_aux_format_aA(L, b, &arg_idx, target_c, fmt + i, scan - i);
+ start = i = scan + 1; /* Skip separator string and 'a'/'A' */
+ continue;
+ }
+ }
+ }
+ /* single-pass flag scanning */
+ while (i < fmt_len) {
+ char c = fmt[i];
+ if (c == '-') {
+ left_align = 1;
+ i++;
+ } else if (c == '0') {
+ pad_zero = 1;
+ i++;
+ } else if (c == ' ' || c == '\xA0') {
+ space_flag = 1;
+ i++;
+ } else {
+ break;
+ }
+ }
+ /* width parsing loop */
+ if (width == 0) {
+ while (i < fmt_len) {
+ char c = fmt[i];
+ if (c >= '0' && c <= '9') {
+ width = strlib_aux_parse_decimal(width, c - '0');
+ i++;
+ } else {
+ break;
+ }
+ }
+ }
+ /* precision parsing loop */
+ if (i < fmt_len && fmt[i] == '.') {
+ i++;
+ precision = 0;
+ has_precision = 1;
+ while (i < fmt_len) {
+ char c = fmt[i];
+ if (c >= '0' && c <= '9') {
+ precision = strlib_aux_parse_decimal(precision, c - '0');
+ i++;
+ } else {
+ break;
+ }
+ }
+ }
+ /* sanity check */
+ if (i >= fmt_len) {
+ break;
+ }
+ precision = strlib_aux_normalize_precision(precision);
+ spec = fmt[i++];
+
+ SWITCH:
+
+ switch (spec) {
+ /* exceptions: specifiers that do not consume an argument */
+ case '%':
+ lmt_buffer_add_char(b, '%');
+ break;
+ case 'z':
+ arg_idx += (width > 0) ? width : 1;
+ break;
+ case 'Z':
+ if (width > 0 && width <= 100) {
+ size_t len;
+ const char *str = lua_tolstring(L, base_idx + width - 1, &len);
+ if (len > 0 && str) {
+ lmt_buffer_add_lstring(b, str, len);
+ }
+ }
+ break;
+ default:
+ if (arg_idx <= top) {
+ switch (spec) {
+ /* integer with zero-padding support */
+ case 'I':
+ case 'i':
+ case 'd':
+ {
+ lua_Integer val = lua_tointeger(L, arg_idx++);
+ int is_plus = (spec == 'I' && val >= 0);
+ int is_space = (space_flag && !is_plus && val >= 0);
+ int is_neg = (val < 0);
+ lua_Unsigned uval = is_neg ? (lua_Unsigned) (-(val + 1)) + 1 : (lua_Unsigned) val;
+ char temp[32];
+ int len = 0;
+ do {
+ temp[len++] = '0' + (char) (uval % 10);
+ uval /= 10;
+ } while (uval > 0);
+ const char *prefix = NULL;
+ size_t prefix_len = 0;
+ char sign_char[1];
+ if (is_neg) {
+ sign_char[0] = '-'; prefix = sign_char; prefix_len = 1;
+ } else if (is_plus) {
+ sign_char[0] = '+'; prefix = sign_char; prefix_len = 1;
+ } else if (is_space) {
+ sign_char[0] = ' '; prefix = sign_char; prefix_len = 1;
+ }
+ if (spec == 'I' && prefix) {
+ /* as in the \LUA\ formatter the sign is not part of the width */
+ lmt_buffer_add_char(b, sign_char[0]);
+ prefix_len = 0;
+ }
+ strlib_aux_format_padded_number(b, prefix, prefix_len, temp, len, width, precision, has_precision, pad_zero, left_align);
+ }
+ break;
+ /* float (in " m.n") the m is the total and a space is used for minus alignment */
+ case 'f':
+ {
+ lua_Number val = lua_tonumber(L, arg_idx++);
+ int prc = has_precision ? precision : 6;
+ int has_space = (space_flag && val >= 0.0);
+ size_t space_len = has_space ? 1 : 0;
+ if (lmt_buffer_has_room(b, (size_t) prc + (size_t) width + space_len + 350)) {
+ char *s = b->buffer + b->length;
+ if (has_space) {
+ s[0] = ' ';
+ }
+ int len = double_to_string_z(val, s + space_len, b->size - b->length - space_len, prc);
+ if (len > 0) {
+ len += (int) space_len;
+ strlib_aux_format_padded_float(b, len, width, pad_zero, left_align);
+ }
+ }
+ }
+ break;
+ /* checked float: near-zero clamping & exact integer conversion */
+ case 'F':
+ strlib_aux_format_F(L, b, &arg_idx, has_precision, precision, width, pad_zero, left_align);
+ break;
+ /* stripped float without redundant zeros */
+ case 'n':
+ case 'N':
+ {
+ char temp[350];
+ lua_Number val = lua_tonumber(L, arg_idx++);
+ int len = double_to_string_f(val, temp, has_precision ? precision : 9);
+ if (len > 0) {
+ strlib_aux_format_padded_string(b, temp, len, width, left_align);
+ }
+ }
+ break;
+ /* exponential & shortest float (%e, %E, %g, %G) */
+ case 'e':
+ case 'E':
+ case 'g':
+ case 'G':
+ strlib_aux_format_eEgG(L, b, &arg_idx, spec, width, pad_zero, left_align, space_flag, has_precision, precision);
+ break;
+ /* sparse exponential float (%j / %J) */
+ case 'j':
+ case 'J':
+ strlib_aux_format_jJ(L, b, &arg_idx, spec, has_precision, precision);
+ break;
+ /* tex|postscript points */
+ case 'p':
+ {
+ lua_Number val = lua_tonumber(L, arg_idx++) / 65536.0;
+ if (lmt_buffer_has_room(b, 350)) {
+ b->length += double_to_string_f(val, b->buffer + b->length, 5);
+ lmt_buffer_add_lstring(b,"pt", 2);
+ }
+ }
+ break;
+ case 'P':
+ {
+ lua_Number val = lua_tonumber(L, arg_idx++) / 65536.0;
+ strlib_aux_add_z(b, val, 5);
+ }
+ break;
+ case 'b':
+ {
+ lua_Number val = (lua_tonumber(L, arg_idx++) * (7200.0 / 7227.0)) / 65536.0;
+ if (lmt_buffer_has_room(b, 350)) {
+ b->length += double_to_string_f(val, b->buffer + b->length, 5);
+ lmt_buffer_add_lstring(b,"bp", 2);
+ }
+ break;
+ }
+ case 'B':
+ {
+ lua_Number val = (lua_tonumber(L, arg_idx++) * (7200.0 / 7227.0)) / 65536.0;
+ strlib_aux_add_z(b, val, 5);
+ }
+ break;
+ /* rounded float (%r) using custom auxserialize routine */
+ case 'r':
+ {
+ lua_Number val = lua_tonumber(L, arg_idx++);
+ if (lmt_buffer_has_room(b, 350)) {
+ b->length += double_to_string_r(val, b->buffer + b->length);
+ }
+ }
+ break;
+ /* formatted float with before/after widths (%k) */
+ case 'k':
+ {
+ if (lua_type(L, arg_idx) == LUA_TNUMBER) {
+ lua_Number val = lua_tonumber(L, arg_idx++);
+ int digits_before = width;
+ int digits_after = has_precision ? precision : 0;
+ int total_width = digits_before;
+ if (digits_after > INT_MAX - total_width) {
+ total_width = INT_MAX;
+ } else {
+ total_width += digits_after;
+ if (digits_after > 0 && total_width < INT_MAX) {
+ total_width++;
+ }
+ }
+ size_t req_room = (size_t) total_width + 350;
+ if (lmt_buffer_has_room(b, req_room)) {
+ char fmt_str[32];
+ snprintf(fmt_str, sizeof(fmt_str), "%%%d.%df", total_width, digits_after);
+ b->length += (size_t) snprintf(b->buffer + b->length, req_room, fmt_str, val);
+ }
+ } else {
+ arg_idx++; /* skip non-number argument */
+ }
+ }
+ break;
+ /* prefixed hexadecimal variants (U+, u+, 0x) */
+ case 'U':
+ case 'u':
+ case 'H':
+ case 'h':
+ {
+ if (! width) {
+ pad_zero = 1;
+ width = 5;
+ }
+ char temp[32];
+ const char *prefix = (spec == 'U') ? "U+" : (spec == 'u') ? "u+" : "0x";
+ spec = (spec == 'U' || spec == 'H') ? 'X' : 'x';
+ lua_Unsigned val = (lua_Unsigned) lua_tointeger(L, arg_idx++);
+ int len = 0;
+ const char *digits = (spec == 'X') ? hex_upper : hex_lower;
+ do {
+ temp[len++] = digits[val & 0x0F];
+ val >>= 4;
+ } while (val > 0);
+ /* as in the \LUA\ formatter the prefix is not part of the width */
+ lmt_buffer_add_lstring(b, prefix, 2);
+ strlib_aux_format_padded_number(b, NULL, 0, temp, len, width, precision, has_precision, pad_zero, left_align);
+ }
+ break;
+ /* standard hexadecimal (%x, %X) */
+ case 'x':
+ case 'X':
+ {
+ char temp[32];
+ lua_Unsigned val = (lua_Unsigned) lua_tointeger(L, arg_idx++);
+ int len = 0;
+ const char *digits = (spec == 'X') ? hex_upper : hex_lower;
+ do {
+ temp[len++] = digits[val & 0x0F];
+ val >>= 4;
+ } while (val > 0);
+
+ strlib_aux_format_padded_number(b, NULL, 0, temp, len, width, precision, has_precision, pad_zero, left_align);
+ }
+ break;
+ /* string formatting: %s (selective/direct) & %S (forced tostring) */
+ case 's':
+ case 'S':
+ strlib_aux_format_sS(L, b, &arg_idx, spec, width, left_align, has_precision, precision);
+ break;
+ /* quoted string formatting: %q (nil-safe standard Lua %q) & %Q (fast LPeg-style serialize_string) */
+ case 'q':
+ case 'Q':
+ strlib_aux_format_qQ(L, b, &arg_idx, spec);
+ break;
+ /* boolean (logic) */
+ case 'l':
+ case 'L':
+ {
+ int val = lua_toboolean(L, arg_idx++);
+ if (val) {
+ lmt_buffer_add_lstring(b, spec == 'l' ? "true" : "TRUE", 4);
+ } else {
+ lmt_buffer_add_lstring(b, spec == 'l' ? "false" : "FALSE", 5);
+ }
+ }
+ break;
+ /* utf8 character */
+ case 'c':
+ {
+ char buffer[8];
+ lua_Unsigned val = (lua_Unsigned) lua_tointeger(L, arg_idx++);
+ int len = aux_uni2strlen((unsigned) val, buffer);
+ if (len) {
+ lmt_buffer_add_lstring(b, buffer, len);
+ }
+ }
+ break;
+ /* traced unicode character (%C) */
+ case 'C':
+ strlib_aux_format_C(L, b, &arg_idx);
+ break;
+ /* octal */
+ case 'o':
+ {
+ char temp[32];
+ lua_Unsigned val = (lua_Unsigned) lua_tointeger(L, arg_idx++);
+ int len = 0;
+ do {
+ temp[len++] = '0' + (val & 0x07);
+ val >>= 3;
+ } while (val > 0);
+
+ strlib_aux_format_padded_number(b, NULL, 0, temp, len, width, precision, has_precision, pad_zero, left_align);
+ }
+ break;
+ /* spaces/width padding helper (ConTeXt formatters compatibility) */
+ case 'w':
+ case 'W':
+ {
+ int count = width;
+ /* if no explicit width in specifier (e.g. %w instead of %12w), take from argument stack */
+ if (count <= 0) {
+ count = (int) lua_tointeger(L, arg_idx++);
+ }
+ if (count > 0) {
+ lmt_buffer_add_spaces(b, count);
+ }
+ }
+ break;
+ /* money with period or commas and optional thousand separators */
+ case 'm':
+ case 'M':
+ {
+ lua_Number val = lua_tonumber(L, arg_idx++);
+ char decimal_sep = (spec == 'm') ? '.' : ',';
+ const char *thousand_sep;
+ size_t thousand_sep_len;
+ if (space_flag) {
+ /* if space flag was present (% m), use space as thousand separator */
+ thousand_sep = " ";
+ thousand_sep_len = 1;
+ } else {
+ /* default: %m -> ',', %M -> '.' */
+ thousand_sep = (spec == 'm') ? "," : ".";
+ thousand_sep_len = 1;
+ }
+ /* we can have 309 digits plus separators */
+ if (lmt_buffer_has_room(b, 512)) {
+ b->length += double_to_string_m(val, b->buffer + b->length, thousand_sep, thousand_sep_len, decimal_sep);
+ }
+ }
+ break;
+ /* grouped integer (%v / %V) */
+ case 'v':
+ case 'V':
+ {
+ const char *thousand_sep;
+ size_t thousand_sep_len;
+ if (space_flag) {
+ thousand_sep = " ";
+ thousand_sep_len = 1;
+ } else {
+ thousand_sep = (spec == 'v') ? "," : ".";
+ thousand_sep_len = 1;
+ }
+ lua_Integer val = lua_tointeger(L, arg_idx++);
+ if (lmt_buffer_has_room(b, 350)) {
+ b->length += integer_to_string_v(val, b->buffer + b->length, thousand_sep, thousand_sep_len);
+ }
+ }
+ break;
+ /* UTF-8 character-aware padding (%< and %>) */
+ case '<':
+ case '>':
+ strlib_aux_format_left_right(L, b, &arg_idx, spec, width, left_align);
+ break;
+ default:
+ lmt_buffer_add_char(b, '%');
+ lmt_buffer_add_char(b, spec);
+ break;
+ }
+ } else {
+ arg_idx++;
+ }
+ break;
+ }
+ start = i;
+ } else {
+ i++;
+ }
+ }
+ /* flush remaining literal tail */
+ int d = i - start;
+ if (d == 1) {
+ lmt_buffer_add_char(b, (int) fmt[start]);
+ } else if (d > 0) {
+ lmt_buffer_add_lstring(b, fmt + start, d);
+ }
+}
+
+/*
+ 1 : buffer userdata
+ 2 : format string
+ 3+ : arguments
+*/
+
+static int strlib_buffer_addformat(lua_State *L)
+{
+ lmt_string_buffer *b = strlib_buffer_instance(L);
+ if (b) {
+ size_t len;
+ const char *fmt = luaL_checklstring(L, 2, &len);
+ int top = lua_gettop(L);
+ strlib_aux_addformat(L, b, fmt, len, top, 3);
+ }
+ return 0;
+}
+
+/*
+ 1 : format string
+ 2+ : arguments
+*/
+
+# define buffer_stack_size 8 /* this should be enough, but we need to keep an eye on it */
+
+/*
+ We use a bitmap to track which slots [0..7] are in use (a pool), but we can also use a 'depth'
+ counter.
+
+ An error (in a |__tostring| metamethod, an extension, a memory issue) bypasses the release of
+ a slot. Because a nested call always runs at a deeper \CCODE\ call level (we never yield while
+ formatting), a slot that was taken at the same or a deeper level than the current one can no
+ longer be in use, so then we can just take it over.
+*/
+
+typedef struct lmt_buffer_stack {
+ lmt_string_buffer buffers[buffer_stack_size];
+ unsigned int levels[buffer_stack_size];
+ unsigned int active_mask;
+} lmt_buffer_stack;
+
+static inline int lmt_buffer_stack_get(lua_State *L, lmt_buffer_stack *bs, lmt_string_buffer **out_b)
+{
+ unsigned int level = getCcalls(L);
+ /* locate the first available (or abandoned) zero-indexed slot */
+ for (int i = 0; i < buffer_stack_size; i++) {
+ if (! ((bs->active_mask >> i) & 1) || bs->levels[i] >= level) {
+ bs->active_mask |= (1U << i);
+ bs->levels[i] = level;
+ lmt_string_buffer *b = &bs->buffers[i];
+ if (! b->buffer) {
+ b->size = default_format_size;
+ b->length = 0;
+ b->buffer = (char *) lmt_memory_malloc(b->size);
+ b->step = 0;
+ } else if (b->size < default_format_size) {
+ /* we need to guarantee that b->size is never zero or too small on reuse */
+ b->size = default_format_size;
+ b->buffer = (char *) lmt_memory_realloc(b->buffer, b->size);
+ }
+ b->length = 0;
+ b->L = L;
+ *out_b = b;
+ return i; /* Returns zero-based index 0, 1, 2... */
+ }
+ }
+ /* when all stack slots are exhausted we just allocate */
+ lmt_string_buffer *b = (lmt_string_buffer *) lmt_memory_malloc(sizeof(lmt_string_buffer));
+ b->size = default_format_size;
+ b->length = 0;
+ b->buffer = (char *) lmt_memory_malloc(b->size);
+ b->step = 0;
+ b->L = L;
+ *out_b = b;
+ return -1; /* -1 indicates dynamic fallback */
+}
+
+static inline void lmt_buffer_stack_release(lmt_buffer_stack *bs, int stack_idx, lmt_string_buffer *b)
+{
+ if (stack_idx >= 0 && stack_idx < buffer_stack_size) {
+ /* Clear the bit for this zero-indexed slot */
+ bs->active_mask &= ~(1U << stack_idx);
+ } else {
+ /* Clean up dynamic fallback allocation */
+ if (b->buffer) {
+ lmt_memory_free(b->buffer);
+ }
+ lmt_memory_free(b);
+ }
+}
+
+static int strlib_format_buffer_gc(lua_State *L)
+{
+ lmt_buffer_stack *bs = (lmt_buffer_stack *) lua_touserdata(L, 1);
+ if (bs) {
+ for (int i = 0; i < buffer_stack_size; i++) {
+ if (bs->buffers[i].buffer) {
+ lmt_memory_free(bs->buffers[i].buffer);
+ bs->buffers[i].buffer = NULL;
+ }
+ }
+ }
+ return 0;
+}
+
+static int strlib_format(lua_State *L)
+{
+ /* upfront validation (safe to throw errors) */
+ size_t len;
+ const char *fmt = luaL_checklstring(L, 1, &len);
+ int top = lua_gettop(L);
+ /* acquire buffer from stack */
+ lmt_buffer_stack *bs = (lmt_buffer_stack *) lua_touserdata(L, lua_upvalueindex(3));
+ lmt_string_buffer *b = NULL;
+ int stack_idx = lmt_buffer_stack_get(L, bs, &b);
+ /* pure formatting (fmt and top are pre-passed) */
+ strlib_aux_addformat(L, b, fmt, len, top, 2);
+ lua_pushlstring(L, b->buffer, b->length);
+ /* cleanup/reset buffer if it grew too large */
+ if (b->length > default_format_size && stack_idx >= 0) {
+ lmt_memory_free(b->buffer);
+ b->buffer = (char *) lmt_memory_malloc(default_format_size);
+ b->size = default_format_size;
+ b->length = 0;
+ }
+ /* when an error bypasses this, the slot is taken over later (see above) */
+ lmt_buffer_stack_release(bs, stack_idx, b);
+ return 1;
+}
+
+/*tex
+
+ When we checked this file with Luna (on Mikaels machine) it suggested checking for cycles,
+ something we explicitly had removed when going from \LUA\ to \CCODE. Anyway, it's now an
+ option, with basically zero overhead when not enabled. In \CONTEXT\ we never have these cycles
+ but in our inspector we enable the check.
+
+ We also checked with Claude and it fixed some edge cases, especially stack safeguards, although
+ it's is unlikely that we nest too deep or crash on memory (it actually ran quite some tests
+ comparing the old and new methods, unsupported features, real applications in \CONTEXT, so it
+ compafed \PDF\ files that we generate, etc. It also did ASANmemorty checks with a special
+ build.
+
+
+*/
+
+static inline int strlib_aux_serialize_enter(lua_State *L, int index, int seen, int depth);
+static inline void strlib_aux_serialize_leave(lua_State *L, int index, int seen);
+
+static void strlib_aux_tostring(lua_State *L, lmt_string_buffer *b, int index, int seen, int depth)
+{
+ index = lua_absindex(L, index);
+ switch (lua_type(L, index)) {
+ case LUA_TSTRING:
+ {
+ size_t len;
+ const char *str = lua_tolstring(L, index, &len);
+ lmt_buffer_add_lstring(b, str, len);
+ break;
+ }
+ case LUA_TNUMBER:
+ if (lua_isinteger(L, index)) {
+ serialize_integer(b, lua_tointeger(L, index));
+ } else if (lmt_buffer_has_room(b, 350)) {
+ b->length += double_to_string_f(lua_tonumber(L, index), b->buffer + b->length, 17);
+ }
+ break;
+ case LUA_TBOOLEAN:
+ if (lua_toboolean(L, index)) {
+ lmt_buffer_add_lstring(b, "true", 4);
+ } else {
+ lmt_buffer_add_lstring(b, "false", 5);
+ }
+ break;
+ case LUA_TTABLE:
+ {
+ if (! strlib_aux_serialize_enter(L, index, seen, depth)) {
+ lmt_buffer_add_lstring(b, "nil", 3);
+ break;
+ }
+ /* todo: sorted hash */
+ lua_Unsigned n = lua_rawlen(L, index);
+ if (n > 0) {
+ for (lua_Unsigned i = 1; i <= n; i++) {
+ lua_rawgeti(L, index, (lua_Integer) i);
+ strlib_aux_tostring(L, b, lua_gettop(L), seen, depth + 1);
+ lua_pop(L, 1);
+ }
+ }
+ strlib_aux_serialize_leave(L, index, seen);
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+static int strlib_tostring(lua_State *L)
+{
+ lmt_buffer_stack *bs = (lmt_buffer_stack *) lua_touserdata(L, lua_upvalueindex(3));
+ lmt_string_buffer *b = NULL;
+ int stack_idx = lmt_buffer_stack_get(L, bs, &b);
+ int top = lua_gettop(L);
+# if 0
+ int seen = 0;
+ lua_newtable(L);
+ seen = lua_gettop(L);
+ for (int i = 1; i <= top; i++) {
+ strlib_aux_tostring(L, b, i, seen, 1);
+ }
+ lua_remove(L, seen);
+# else
+ for (int i = 1; i <= top; i++) {
+ strlib_aux_tostring(L, b, i, 0, 1);
+ }
+# endif
+ lua_pushlstring(L, b->buffer, b->length);
+ if (b->length > default_format_size && stack_idx >= 0) {
+ lmt_memory_free(b->buffer);
+ b->buffer = (char *) lmt_memory_malloc(default_format_size);
+ b->size = default_format_size;
+ b->length = 0;
+ }
+ lmt_buffer_stack_release(bs, stack_idx, b);
+ return 1;
+}
+
+/*
+ An easy one, no escaping etc.:
+
+ 1 : buffer
+ 2 : string
+ 3 : [offset (1-based)]
+ 4 : [length]
+*/
+
+static int strlib_buffer_addbytes(lua_State *L)
+{
+ lmt_string_buffer *b = strlib_buffer_instance(L);
+ if (b) {
+ size_t len;
+ const char *str = lua_tolstring(L, 2, &len);
+ if (str) {
+ lua_Integer start = luaL_optinteger(L, 3, 1);
+ if (start > 0) {
+ lua_Unsigned offset_value = (lua_Unsigned) (start - 1);
+ if (offset_value < (lua_Unsigned) len) {
+ size_t offset = (size_t) offset_value;
+ lua_Integer length;
+ if (lua_isnoneornil(L, 4)) {
+ length = (lua_Integer) (len - offset);
+ } else {
+ length = luaL_checkinteger(L, 4);
+ }
+ if (length > 0) {
+ size_t available = len - offset;
+ size_t count = (lua_Unsigned) length > (lua_Unsigned) available
+ ? available
+ : (size_t) length;
+ lmt_buffer_add_lstring(b, str + offset, count);
+ }
+ }
+ }
+ }
+ }
+ return 0;
+}
+
+/*
+ A bit like lua pack but simple (we have plenty helpers elsewhere):
+
+ 1 : buffer
+ 2 : format character ('b', 'w', 'l', 'q' or 'W', 'L', 'Q' for Big Endian)
+ 3 : integer
+*/
+
+static int strlib_buffer_addpacking(lua_State *L)
+{
+ lmt_string_buffer *b = strlib_buffer_instance(L);
+ if (b) {
+ const char *fmt = lua_tostring(L, 2);
+ if (!fmt) return 0;
+
+ lua_Integer val = lua_tointeger(L, 3);
+
+ switch (fmt[0]) {
+ case 'b': /* 8-bit uint */
+ case 'B':
+ if (lmt_buffer_has_room(b, 1)) {
+ b->buffer[b->length++] = (char) (val & 0xFF);
+ }
+ break;
+ case 'w': /* 16-bit Little Endian */
+ if (lmt_buffer_has_room(b, 2)) {
+ b->buffer[b->length++] = (char) (val & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 8) & 0xFF);
+ }
+ break;
+ case 'W': /* 16-bit Big Endian */
+ if (lmt_buffer_has_room(b, 2)) {
+ b->buffer[b->length++] = (char) ((val >> 8) & 0xFF);
+ b->buffer[b->length++] = (char) (val & 0xFF);
+ }
+ break;
+ case 'l': /* 32-bit Little Endian */
+ if (lmt_buffer_has_room(b, 4)) {
+ b->buffer[b->length++] = (char) (val & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 8) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 16) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 24) & 0xFF);
+ }
+ break;
+ case 'L': /* 32-bit Big Endian */
+ if (lmt_buffer_has_room(b, 4)) {
+ b->buffer[b->length++] = (char) ((val >> 24) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 16) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 8) & 0xFF);
+ b->buffer[b->length++] = (char) (val & 0xFF);
+ }
+ break;
+ case 'q': /* 64-bit Little Endian */
+ if (lmt_buffer_has_room(b, 8)) {
+ b->buffer[b->length++] = (char) (val & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 8) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 16) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 24) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 32) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 40) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 48) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 56) & 0xFF);
+ }
+ break;
+ case 'Q': /* 64-bit Big Endian */
+ if (lmt_buffer_has_room(b, 8)) {
+ b->buffer[b->length++] = (char) ((val >> 56) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 48) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 40) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 32) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 24) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 16) & 0xFF);
+ b->buffer[b->length++] = (char) ((val >> 8) & 0xFF);
+ b->buffer[b->length++] = (char) (val & 0xFF);
+ }
+ break;
+ default:
+ break;
}
- return 0;
}
+ return 0;
+}
+
+/*tex
+ We now come to the table serializers. We need to retain the same sorting as the original \LUA\
+ variant. This evolved a bit.
+*/
+
+# define lmt_key_default 64
- static int strlib_buffer_get_data(lua_State *L)
+/*tex
+
+ We don't need (have) long strings, so a 32 bit integer is okay for the length. The sort type
+ also dictates the order. It's hard to measure gain but on various large tables we're about
+ 5 times as as efficient as the original \LUA\ variant that we had around for about two
+ decades. I might (as experiment bring back hex indexes but then we also need control over
+ specific fields so plenty of extra overhead).
+
+ There is quite a bit of repetition in the code below but so is in the \LUA\ originals. When
+ implementing this kind of code one has to test compatibility and I think we're fine. The
+ integer check when we have a double is actually better so we acoid hex floats when possible.
+
+ For sure this will evolve a bit more. I also need to check this with the key sorters elsewhere
+ as they were the starting point but became a bit redundant now. But one step at a time (after
+ all we've been fine for quite a while now.)
+
+ Capitalized like LUA_T....:
+*/
+
+typedef enum lmt_sort_type {
+ LMT_TYPE_NIL = 0, // serialized tables normally have sane keys
+ LMT_TYPE_FALSE, // 0 integer
+ LMT_TYPE_TRUE, // 1 integer
+ LMT_TYPE_INTEGER, // NN
+ LMT_TYPE_DOUBLE, // NN.MM after NN
+ LMT_TYPE_STRING,
+ /* not used as key in a serialize */
+ LMT_TYPE_TABLE,
+ LMT_TYPE_FUNCTION,
+ LMT_TYPE_USERDATA,
+} lmt_sort_type;
+
+typedef struct lmt_serialize_sort_data {
+ uint32_t type; /* 4 bytes */
+ uint32_t string_length; /* 4 bytes */
+ union { /* 8 bytes */
+ lua_Integer integer_value;
+ double double_value;
+ const char *string_value;
+ };
+} lmt_serialize_sort_data;
+
+static int lmt_serialize_compare(const void *a, const void *b)
+{
+ const lmt_serialize_sort_data *ka = (const lmt_serialize_sort_data *) a;
+ const lmt_serialize_sort_data *kb = (const lmt_serialize_sort_data *) b;
+ /* Both elements have the exact same type tag. */
+ if (ka->type == kb->type) {
+ switch (ka->type) {
+ case LMT_TYPE_INTEGER:
+ return (ka->integer_value > kb->integer_value)
+ - (ka->integer_value < kb->integer_value);
+ case LMT_TYPE_DOUBLE:
+ return (ka->double_value > kb->double_value)
+ - (ka->double_value < kb->double_value);
+ case LMT_TYPE_STRING: {
+ uint32_t min_len = ka->string_length < kb->string_length
+ ? ka->string_length : kb->string_length;
+ int cmp = memcmp(ka->string_value, kb->string_value, min_len);
+ if (cmp != 0) {
+ return cmp;
+ } else {
+ return (ka->string_length > kb->string_length)
+ - (ka->string_length < kb->string_length);
+ }
+ }
+ default:
+ /* NIL, FALSE, and TRUE are identical to themselves. */
+ return 0;
+ }
+ }
+ /* Mixed number comparison (e.g. INT vs FLOAT: 1 < 1.5 < 2). */
+ if ((ka->type == LMT_TYPE_INTEGER || ka->type == LMT_TYPE_DOUBLE) &&
+ (kb->type == LMT_TYPE_INTEGER || kb->type == LMT_TYPE_DOUBLE))
{
- lmt_string_buffer *b = strlib_buffer_instance(L);
- if (b) {
- lua_pushlstring(L, b->buffer, b->length);
- lua_pushinteger(L, (int) b->length);
- return 2;
+ double da = (ka->type == LMT_TYPE_INTEGER) ? (double) ka->integer_value : ka->double_value;
+ double db = (kb->type == LMT_TYPE_INTEGER) ? (double) kb->integer_value : kb->double_value;
+ return (da > db) - (da < db);
+ }
+ /* Different primary types (ordered by enum: NIL < FALSE < TRUE < INT/FLOAT < STRING) */
+ return (ka->type < kb->type) ? -1 : 1;
+}
+
+/*tex
+ Each nested table keeps some values on the stack so we make sure that there is room. We also
+ quit when the nesting gets too deep, which happens when we have a cycle that is not checked,
+ because otherwise we can run out of \CCODE\ stack. Such a table is treated like a seen one.
+*/
+
+static inline int strlib_aux_serialize_enter(lua_State *L, int index, int seen, int depth)
+{
+ if (depth > max_nesting_depth || ! lua_checkstack(L, LUA_MINSTACK)) {
+ return 0;
+ }
+ if (seen == 0) {
+ return 1; /* Bypass cycle tracking completely */
+ }
+ lua_pushvalue(L, index);
+ lua_rawget(L, seen);
+ int active = lua_toboolean(L, -1);
+ lua_pop(L, 1);
+ if (active) {
+ return 0;
+ }
+ lua_pushvalue(L, index);
+ lua_pushboolean(L, 1);
+ lua_rawset(L, seen);
+ return 1;
+}
+
+static inline void strlib_aux_serialize_leave(lua_State *L, int index, int seen)
+{
+ if (seen == 0) {
+ return; /* Nothing to clean up */
+ }
+ lua_pushvalue(L, index);
+ lua_pushnil(L);
+ lua_rawset(L, seen);
+}
+
+static void strlib_aux_serialize(lua_State *L, int index, lmt_string_buffer *b, int depth, int escaped, int seen)
+{
+ index = lua_absindex(L, index);
+ if (! strlib_aux_serialize_enter(L, index, seen, depth)) {
+ lmt_buffer_add_lstring(b, "nil", 3);
+ return;
+ }
+
+ int maxkeys = lmt_key_default;
+ int nofkeys = 0;
+
+ lmt_serialize_sort_data *keys = (lmt_serialize_sort_data *) lmt_memory_malloc(maxkeys * sizeof(lmt_serialize_sort_data));
+
+ /* First we collect keys. */
+
+ lua_pushnil(L);
+ while (lua_next(L, index) != 0) {
+ if (nofkeys >= maxkeys) {
+ maxkeys *= 2;
+ keys = (lmt_serialize_sort_data *) lmt_memory_realloc(keys, maxkeys * sizeof(lmt_serialize_sort_data));
+ }
+
+ lmt_serialize_sort_data *sk = &keys[nofkeys];
+
+ switch (lua_type(L, -2)) {
+ case LUA_TNUMBER:
+ if (lua_isinteger(L, -2)) {
+ sk->type = LMT_TYPE_INTEGER;
+ sk->integer_value = lua_tointeger(L, -2);
+ } else {
+ sk->type = LMT_TYPE_DOUBLE;
+ sk->double_value = lua_tonumber(L, -2);
+ }
+ nofkeys++;
+ break;
+ case LUA_TBOOLEAN:
+ sk->type = lua_toboolean(L, -2) ? LMT_TYPE_TRUE : LMT_TYPE_FALSE;
+ nofkeys++;
+ break;
+ case LUA_TSTRING: {
+ size_t len;
+ sk->type = LMT_TYPE_STRING;
+ sk->string_value = lua_tolstring(L, -2, &len);
+ sk->string_length = (uint32_t) len;
+ nofkeys++;
+ break;
+ }
+ default:
+ /* Ignore unsupported key types (tables, functions, userdata) */
+ break;
+ }
+ lua_pop(L, 1);
+ }
+
+ /*tex We quit when we have an empty table or one with weird keys. */
+
+ if (nofkeys == 0) {
+ lmt_buffer_add_lstring(b, "{}", 2);
+ lmt_memory_free(keys);
+ strlib_aux_serialize_leave(L, index, seen);
+ return;
+ }
+
+ /*tex We sort as we do in the \LUA\ original. */
+
+ qsort(keys, nofkeys, sizeof(lmt_serialize_sort_data), lmt_serialize_compare);
+
+ /*tex We want simple array-only tables as one-liners. */
+
+ int is_sequence = 1;
+ for (int i = 0; i < nofkeys; i++) {
+ lmt_serialize_sort_data *sk = &keys[i];
+
+ if (sk->type != LMT_TYPE_INTEGER || sk->integer_value != (i + 1)) {
+ is_sequence = 0;
+ break;
+ }
+ lua_pushinteger(L, sk->integer_value);
+ lua_gettable(L, index);
+ if (lua_istable(L, -1)) {
+ is_sequence = 0;
+ }
+ lua_pop(L, 1);
+ if (! is_sequence) {
+ break;
+ }
+ }
+
+ /* Now we can start serializing the (sub)table. */
+
+ lmt_buffer_add_lstring(b, is_sequence ? "{ " : "{\n", 2);
+
+ /* We're serialize the entries. */
+
+ lua_Integer expected_index = 1;
+
+ for (int i = 0; i < nofkeys; i++) {
+ lmt_serialize_sort_data *sk = &keys[i];
+ /* We push the key back onto the stack. */
+ switch (sk->type) {
+ case LMT_TYPE_INTEGER : lua_pushinteger(L, sk->integer_value); break;
+ case LMT_TYPE_DOUBLE : lua_pushnumber (L, sk->double_value); break;
+ case LMT_TYPE_FALSE : lua_pushboolean(L, 0); break;
+ case LMT_TYPE_TRUE : lua_pushboolean(L, 1); break;
+ case LMT_TYPE_STRING : lua_pushlstring(L, sk->string_value, sk->string_length); break;
+ default : lua_pushnil (L); break;
+ }
+
+ lua_pushvalue(L, -1);
+ lua_gettable(L, index);
+
+ int v_index = lua_gettop(L);
+
+ /* Serialize the key but only when we have no sequence. */
+
+ if (! is_sequence) {
+ lmt_buffer_add_spaces(b, depth);
+ int is_sequence_key = 0;
+ switch (sk->type) {
+ case LMT_TYPE_INTEGER:
+ if (sk->integer_value == expected_index) {
+ is_sequence_key = 1;
+ expected_index++;
+ }
+ if (! is_sequence_key) {
+ lmt_buffer_add_char(b, '[');
+ serialize_integer(b, sk->integer_value);
+ lmt_buffer_add_lstring(b, "]=", 2);
+ }
+ break;
+ case LMT_TYPE_DOUBLE:
+ lmt_buffer_add_char(b, '[');
+ serialize_double(b, sk->double_value);
+ lmt_buffer_add_lstring(b, "]=", 2);
+ break;
+ case LMT_TYPE_STRING:
+ lmt_buffer_add_char(b, '[');
+ if lmt_unlikely(escaped) {
+ serialize_string_escaped(b, sk->string_value, sk->string_length);
+ } else {
+ serialize_string(b, sk->string_value, sk->string_length);
+ }
+ lmt_buffer_add_lstring(b, "]=", 2);
+ break;
+ case LMT_TYPE_FALSE:
+ lmt_buffer_add_lstring(b, "[false]=", 8);
+ break;
+ case LMT_TYPE_TRUE:
+ lmt_buffer_add_lstring(b, "[true]=", 7);
+ break;
+ default:
+ break;
+ }
+ }
+
+ /* Serialize the value. */
+
+ switch (lua_type(L, v_index)) {
+ case LUA_TNUMBER:
+ if (lua_isinteger(L, v_index)) {
+ serialize_integer(b, lua_tointeger(L, v_index));
+ } else {
+ serialize_double(b, lua_tonumber(L, v_index));
+ }
+ break;
+ case LUA_TSTRING: {
+ size_t len;
+ const char *v_str = lua_tolstring(L, v_index, &len);
+ serialize_string(b, v_str, len);
+ break;
+ }
+ case LUA_TBOOLEAN:
+ if (lua_toboolean(L, v_index)) {
+ lmt_buffer_add_lstring(b, "true", 4);
+ } else {
+ lmt_buffer_add_lstring(b, "false", 5);
+ }
+ break;
+ case LUA_TTABLE:
+ strlib_aux_serialize(L, v_index, b, depth + 1, escaped, seen);
+ break;
+ default:
+ lmt_buffer_add_lstring(b, "nil", 3);
+ break;
+ }
+
+ /* Add comma's and newlines. */
+
+ if (! is_sequence) {
+ lmt_buffer_add_lstring(b, ",\n", 2);
+ } else if (i < nofkeys - 1) {
+ lmt_buffer_add_lstring(b, ", ", 2);
+ }
+
+ lua_pop(L, 2);
+ }
+
+ /* We can end the table and of course we need to handle spaces. */
+
+ if (is_sequence) {
+ lmt_buffer_add_lstring(b, " }", 2);
+ } else {
+ if (depth > 1) {
+ lmt_buffer_add_spaces(b, depth - 1);
+ }
+ lmt_buffer_add_char(b, '}');
+ }
+
+ lmt_memory_free(keys);
+ strlib_aux_serialize_leave(L, index, seen);
+}
+
+/*
+ 1 : table
+ 2 : string : <string> =
+ "return" : return
+ number : [<number>] =
+ boolean : return
+ default : t =
+ 3 : boolean : in strings characters < 0x20 get [name] (escaped)
+ 4 : boolean : check cycles
+*/
+
+static int strlib_serialize(lua_State *L)
+{
+ lmt_string_buffer buffer;
+ lmt_buffer_allocate(L, &buffer);
+ switch (lua_type(L, 2)) {
+ case LUA_TSTRING:
+ {
+ const char *name = lua_tostring(L, 2);
+ if (strcmp(name, "return") == 0) {
+ lmt_buffer_add_lstring(&buffer, "return ", 7);
+ } else {
+ lmt_buffer_add_string(&buffer, name);
+ lmt_buffer_add_char(&buffer, '=');
+ }
+ }
+ break;
+ case LUA_TNUMBER:
+ {
+ size_t len;
+ const char *num_str = lua_tolstring(L, 2, &len);
+ lmt_buffer_add_char(&buffer, '[');
+ lmt_buffer_add_lstring(&buffer, num_str, len);
+ lmt_buffer_add_lstring(&buffer, "]=", 2);
+ }
+ break;
+ case LUA_TBOOLEAN:
+ if (lua_toboolean(L, 2)) {
+ lmt_buffer_add_lstring(&buffer, "return ", 7);
+ break;
+ }
+ FALLTHROUGH
+ default:
+ lmt_buffer_add_lstring(&buffer, "t=", 2);
+ break;
+ }
+ if (! lua_istable(L, 1)) {
+ lmt_buffer_add_lstring(&buffer, "{}", 2);
+ } else {
+ int seen = 0;
+ int check = lua_toboolean(L, 4);
+ if (check) {
+ lua_newtable(L);
+ seen = lua_gettop(L);
+ }
+ strlib_aux_serialize(L, 1, &buffer, 1, lua_type(L, 3) == LUA_TBOOLEAN ? lua_toboolean(L, 3) : 0, seen);
+ if (check) {
+ lua_remove(L, seen);
+ }
+ }
+ lua_pushlstring(L, buffer.buffer, buffer.length);
+ lmt_buffer_dispose(&buffer);
+ return 1;
+}
+
+static void serialize_value(lua_State *L, int index, lmt_string_buffer *b)
+{
+ switch (lua_type(L, index)) {
+ case LUA_TNUMBER:
+ if (lua_isinteger(L, index)) {
+ serialize_integer(b, lua_tointeger(L, index));
+ } else {
+ serialize_double(b, lua_tonumber(L, index));
+ }
+ break;
+ case LUA_TSTRING: {
+ size_t len;
+ const char *s = lua_tolstring(L, index, &len);
+ serialize_string(b, s, len);
+ break;
+ }
+ case LUA_TBOOLEAN:
+ if (lua_toboolean(L, index)) {
+ lmt_buffer_add_lstring(b, "true", 4);
+ } else {
+ lmt_buffer_add_lstring(b, "false", 5);
+ }
+ break;
+ default:
+ lmt_buffer_add_lstring(b, "nil", 3);
+ break;
+ }
+}
+
+static void strlib_aux_fastserialize(lua_State *L, int index, lmt_string_buffer *b, int outer, int seen, int depth)
+{
+ index = lua_absindex(L, index);
+ if (! strlib_aux_serialize_enter(L, index, seen, depth)) {
+ lmt_buffer_add_lstring(b, outer ? "nil" : "nil,", outer ? 3 : 4);
+ return;
+ }
+
+ lmt_buffer_add_char(b, '{');
+
+ lua_Unsigned n = lua_rawlen(L, index);
+
+ /* Handle index 0 independently of n > 0 */
+ lua_rawgeti(L, index, 0);
+ if (! lua_isnil(L, -1)) {
+ lmt_buffer_add_lstring(b, "[0]=", 4);
+ if (lua_istable(L, -1)) {
+ strlib_aux_fastserialize(L, lua_gettop(L), b, 0, seen, depth + 1);
} else {
- lua_pushnil(L);
- return 1;
+ serialize_value(L, -1, b);
+ lmt_buffer_add_char(b, ',');
}
}
+ lua_pop(L, 1);
- static int strlib_buffer_get_size(lua_State *L)
- {
- lmt_string_buffer *b = strlib_buffer_instance(L);
- lua_pushinteger(L, b ? b->length : 0);
+ if (n > 0) {
+ /* The array part, if present, comes first. */
+ for (lua_Unsigned i = 1; i <= n; i++) {
+ lua_rawgeti(L, index, (lua_Integer)i);
+ lmt_buffer_add_char(b, '[');
+ serialize_integer(b, (lua_Integer)i);
+ lmt_buffer_add_lstring(b, "]=", 2);
+ if (lua_istable(L, -1)) {
+ strlib_aux_fastserialize(L, lua_gettop(L), b, 0, seen, depth + 1);
+ } else {
+ serialize_value(L, -1, b);
+ lmt_buffer_add_char(b, ',');
+ }
+ lua_pop(L, 1);
+ }
+ }
+
+ /* The hash part comes next; skip only exact integer sequence keys already handled. */
+ lua_pushnil(L);
+ while (lua_next(L, index) != 0) {
+ int process = 1;
+ if (lua_type(L, -2) == LUA_TNUMBER) {
+ if (lua_isinteger(L, -2)) {
+ lua_Integer k = lua_tointeger(L, -2);
+ if (k == 0 || (k >= 1 && (lua_Unsigned) k <= n)) {
+ process = 0;
+ }
+ } else {
+ lua_Number k = lua_tonumber(L, -2);
+ if (fmod(k, 1.0) == 0.0 && (k == 0.0 || (k >= 1.0 && k <= (lua_Number) n))) {
+ process = 0;
+ }
+ }
+ }
+ if (process) {
+ lmt_buffer_add_char(b, '[');
+ serialize_value(L, -2, b);
+ lmt_buffer_add_lstring(b, "]=", 2);
+ if (lua_istable(L, -1)) {
+ strlib_aux_fastserialize(L, lua_gettop(L), b, 0, seen, depth + 1);
+ } else {
+ serialize_value(L, -1, b);
+ lmt_buffer_add_char(b, ',');
+ }
+ }
+ /* pop value, retain key for next iteration */
+ lua_pop(L, 1);
+ }
+
+ strlib_aux_serialize_leave(L, index, seen);
+
+ if (outer) {
+ lmt_buffer_add_char(b, '}');
+ } else {
+ lmt_buffer_add_lstring(b, "},", 2);
+ }
+}
+
+/*
+ 1 : table
+ 2 : string : prefix (default "return")
+ 3 : boolean : check cycles
+*/
+
+static int strlib_fastserialize(lua_State *L)
+{
+ lmt_string_buffer buffer;
+ lmt_buffer_allocate(L, &buffer);
+
+ if (lua_type(L, 2) == LUA_TSTRING) {
+ size_t len;
+ const char *prefix = lua_tolstring(L, 2, &len);
+ lmt_buffer_add_lstring(&buffer, prefix, len);
+ } else {
+ lmt_buffer_add_lstring(&buffer, "return", 6);
+ }
+
+ if (lua_istable(L, 1)) {
+ int seen = 0;
+ int check = lua_toboolean(L, 3);
+ if (check) {
+ lua_newtable(L);
+ seen = lua_gettop(L);
+ }
+ strlib_aux_fastserialize(L, 1, &buffer, 1, seen, 1);
+ if (check) {
+ lua_remove(L, seen);
+ }
+ } else {
+ lmt_buffer_add_lstring(&buffer, "{}", 2);
+ }
+
+ lua_pushlstring(L, buffer.buffer, buffer.length);
+ lmt_buffer_dispose(&buffer);
+
+ return 1;
+}
+
+/*tex
+
+ Once we had the above in place, and given the buffer infrastructure, the next bunch
+ was easy: auto converted and cleaned up cq. optimized afterwards.
+
+*/
+
+/*
+ This is a helper structure for zero-copy entry sorting. We just point to the start
+ of a substring. Sorting is needed for consistency and has no real meaning. (So we
+ can cast numbers, see below.) We use a buffer and not many small allocated strings,
+ but we do need something we can swap:
+*/
+
+typedef struct tabstr_entry {
+ const char *str;
+ uint32_t len;
+} tabstr_entry;
+
+typedef struct tabstr_item {
+ uint32_t offset;
+ uint32_t len;
+} tabstr_item;
+
+static int tabstr_entry_compare(const void *a, const void *b)
+{
+ const tabstr_entry *ea = (const tabstr_entry *) a;
+ const tabstr_entry *eb = (const tabstr_entry *) b;
+ uint32_t minlen = ea->len < eb->len ? ea->len : eb->len;
+ int cmp = memcmp(ea->str, eb->str, minlen);
+ if (cmp != 0) {
+ return cmp;
+ } else {
+ return (ea->len > eb->len) - (ea->len < eb->len);
+ }
+}
+
+/* Helper to append key/value strings safely without mutating Lua keys during lua_next */
+
+/* This one is simple (100%). */
+
+static inline void tabstr_add_value_string(lua_State *L, int idx, lmt_string_buffer *b)
+{
+ size_t len;
+ /*
+ luaL_tolstring pushes the string representation onto the top of stack
+ without mutating the value at 'idx' (critical for lua_next key safety).
+ */
+ const char *s = luaL_tolstring(L, idx, &len);
+ lmt_buffer_add_lstring(b, s, len);
+ lua_pop(L, 1);
+}
+
+/*
+ But this one is faster (50%) and it is one of these things you realize when pondering
+ a bottleneck during a walk: hex is always more efficient than decimal. And then it is
+ a small step to just cast bytes (35%). We sort using memcmp so we're zero byte okay.
+*/
+
+static inline void tabstr_add_value_string_raw(lua_State *L, int idx, lmt_string_buffer *b)
+{
+ switch (lua_type(L, idx)) {
+ // case LUA_TNUMBER:
+ // {
+ // char hexbuf[64];
+ // if (lua_isinteger(L, idx)) {
+ // lua_Integer n = lua_tointeger(L, idx);
+ // int len = snprintf(hexbuf, sizeof(hexbuf), "I%llx", (unsigned long long)n);
+ // lmt_buffer_add_lstring(b, hexbuf, len);
+ // } else {
+ // lua_Number n = lua_tonumber(L, idx);
+ // int len = snprintf(hexbuf, sizeof(hexbuf), "F%a", n);
+ // lmt_buffer_add_lstring(b, hexbuf, len);
+ // }
+ // break;
+ // }
+ case LUA_TNUMBER:
+ {
+ /* this is alignment safe as we're on the stack */
+ if (lua_isinteger(L, idx)) {
+ lua_Integer n = lua_tointeger(L, idx);
+ lmt_buffer_add_char(b, 'I');
+ lmt_buffer_add_lstring(b, (const char *) &n, sizeof(n));
+ } else {
+ lua_Number n = lua_tonumber(L, idx);
+ /* we normalize -0.0 but it's unlikely to happen */
+ if (n == 0.0) {
+ n = 0.0;
+ }
+ /* NaN and INF don't occur here */
+ lmt_buffer_add_char(b, 'F');
+ lmt_buffer_add_lstring(b, (const char *) &n, sizeof(n));
+ }
+ break;
+ }
+ case LUA_TBOOLEAN:
+ {
+ lmt_buffer_add_lstring(b, lua_toboolean(L, idx) ? "B1" : "B0", 2);
+ break;
+ }
+ case LUA_TNIL:
+ {
+ lmt_buffer_add_char(b, 'N');
+ break;
+ }
+ default:
+ {
+ lmt_buffer_add_char(b, 'S');
+ size_t len;
+ const char *str = luaL_tolstring(L, idx, &len);
+ lmt_buffer_add_lstring(b, str, len);
+ lua_pop(L, 1);
+ break;
+ }
+ }
+}
+
+/* tabstr_normal */
+
+static void strlib_aux_tabstr_normal(lua_State *L, int index, lmt_string_buffer *out, int seen, int depth)
+{
+ index = lua_absindex(L, index);
+ if (! strlib_aux_serialize_enter(L, index, seen, depth)) {
+ return;
+ }
+ int maxentries = 16;
+ int nofentries = 0;
+ tabstr_item *entries = (tabstr_item *) lmt_memory_malloc(maxentries * sizeof(tabstr_item));
+ lmt_string_buffer text_buf;
+ lmt_buffer_allocate(L, &text_buf);
+ lua_pushnil(L);
+ while (lua_next(L, index) != 0) {
+ if (nofentries >= maxentries) {
+ maxentries *= 2;
+ entries = (tabstr_item *) lmt_memory_realloc(entries, maxentries * sizeof(tabstr_item));
+ }
+ size_t start_off = text_buf.length;
+ /* key: */
+ tabstr_add_value_string_raw(L, -2, &text_buf);
+ /* */
+ // /* value:
+ // - table : k .. ">" .. tabstr_normal(v)
+ // - true : k .. "+"
+ // - truthy : k .. "=" .. v
+ // - falsy : k .. "-"
+ // - string : k
+ // */
+ // if (lua_istable(L, -1)) {
+ // lmt_buffer_add_char(&text_buf, '>');
+ // strlib_aux_tabstr_normal(L, lua_gettop(L), &text_buf, seen, depth + 1);
+ // } else if (lua_isboolean(L, -1) && lua_toboolean(L, -1)) {
+ // lmt_buffer_add_char(&text_buf, '+');
+ // } else if (lua_toboolean(L, -1)) { /* truthy (non-boolean, non-nil, non-table) */
+ // lmt_buffer_add_char(&text_buf, '=');
+ // tabstr_add_value_string(L, -1, &text_buf);
+ // } else { /* falsy (false or nil) */
+ // lmt_buffer_add_char(&text_buf, '-');
+ // }
+ /* */
+ if (lua_istable(L, -1)) {
+ lmt_buffer_add_lstring(&text_buf, "={", 2);
+ strlib_aux_tabstr_normal(L, lua_gettop(L), &text_buf, seen, depth + 1);
+ lmt_buffer_add_char(&text_buf, '}');
+ } else {
+ lmt_buffer_add_char(&text_buf, '=');
+ tabstr_add_value_string_raw(L, -1, &text_buf);
+ }
+ /* */
+ entries[nofentries].offset = (uint32_t) start_off;
+ entries[nofentries].len = (uint32_t) (text_buf.length - start_off);
+ nofentries++;
+ lua_pop(L, 1);
+ }
+ if (nofentries == 1) {
+ lmt_buffer_add_lstring(out, text_buf.buffer + entries[0].offset, entries[0].len);
+ } else if (nofentries > 1) {
+ tabstr_entry *sort_list = (tabstr_entry *) lmt_memory_malloc(nofentries * sizeof(tabstr_entry));
+ for (int i = 0; i < nofentries; i++) {
+ sort_list[i].str = text_buf.buffer + entries[i].offset;
+ sort_list[i].len = entries[i].len;
+ }
+ qsort(sort_list, nofentries, sizeof(tabstr_entry), tabstr_entry_compare);
+ for (int i = 0; i < nofentries; i++) {
+ if (i > 0) {
+ lmt_buffer_add_char(out, ',');
+ }
+ lmt_buffer_add_lstring(out, sort_list[i].str, sort_list[i].len);
+ }
+ lmt_memory_free(sort_list);
+ }
+ lmt_memory_free(entries);
+ lmt_buffer_dispose(&text_buf);
+ strlib_aux_serialize_leave(L, index, seen);
+}
+
+static int strlib_tabstr_normal(lua_State *L)
+{
+ if (! lua_istable(L, 1)) {
+ lua_pushliteral(L, "");
return 1;
}
+ int check = lua_toboolean(L, 2);
+ int seen = 0;
+ lmt_string_buffer buffer;
+ lmt_buffer_allocate(L, &buffer);
+ if (check) {
+ lua_newtable(L);
+ seen = lua_gettop(L);
+ }
+ strlib_aux_tabstr_normal(L, 1, &buffer, seen, 1);
+ if (check) {
+ lua_remove(L, seen);
+ }
+ lua_pushlstring(L, buffer.buffer, buffer.length);
+ lmt_buffer_dispose(&buffer);
+ return 1;
+}
- static const luaL_Reg strlib_function_list_buffer[] = {
- { "newbuffer", strlib_buffer_new },
- { "addtobuffer", strlib_buffer_add },
- { "getbufferdata", strlib_buffer_get_data },
- { "getbuffersize", strlib_buffer_get_size },
- { NULL, NULL },
- };
+/* tabstr_flat */
- static int luaextend_string_buffer(lua_State *L)
- {
- lua_getglobal(L, "string");
- for (const luaL_Reg *lib = strlib_function_list_buffer; lib->name; lib++) {
- lua_pushcfunction(L, lib->func);
- lua_setfield(L, -2, lib->name);
+static int strlib_tabstr_flat(lua_State *L)
+{
+ if (! lua_istable(L, 1)) {
+ lua_pushliteral(L, "");
+ return 1;
+ }
+ int maxentries = 16;
+ int nofentries = 0;
+ tabstr_item *entries = (tabstr_item *) lmt_memory_malloc(maxentries * sizeof(tabstr_item));
+ lmt_string_buffer text_buf;
+ lmt_buffer_allocate(L, &text_buf);
+ lua_pushnil(L);
+ while (lua_next(L, 1) != 0) {
+ if (nofentries >= maxentries) {
+ maxentries *= 2;
+ entries = (tabstr_item *) lmt_memory_realloc(entries, maxentries * sizeof(tabstr_item));
}
+ size_t start_off = text_buf.length;
+ tabstr_add_value_string_raw(L, -2, &text_buf);
+ lmt_buffer_add_char(&text_buf, '=');
+ tabstr_add_value_string_raw(L, -1, &text_buf);
+ entries[nofentries].offset = (uint32_t) start_off;
+ entries[nofentries].len = (uint32_t) (text_buf.length - start_off);
+ nofentries++;
lua_pop(L, 1);
- luaL_newmetatable(L, STRING_BUFFER_METATABLE_INSTANCE);
- lua_pushcfunction(L, strlib_buffer_gc);
- lua_setfield(L, -2, "__gc");
+ }
+ lmt_string_buffer out;
+ lmt_buffer_allocate(L, &out);
+ if (nofentries == 1) {
+ lmt_buffer_add_lstring(&out, text_buf.buffer + entries[0].offset, entries[0].len);
+ } else if (nofentries > 1) {
+ tabstr_entry *sort_list = (tabstr_entry *) lmt_memory_malloc(nofentries * sizeof(tabstr_entry));
+ for (int i = 0; i < nofentries; i++) {
+ sort_list[i].str = text_buf.buffer + entries[i].offset;
+ sort_list[i].len = entries[i].len;
+ }
+ qsort(sort_list, nofentries, sizeof(tabstr_entry), tabstr_entry_compare);
+ for (int i = 0; i < nofentries; i++) {
+ if (i > 0) {
+ lmt_buffer_add_char(&out, ',');
+ }
+ lmt_buffer_add_lstring(&out, sort_list[i].str, sort_list[i].len);
+ }
+ lmt_memory_free(sort_list);
+ }
+ lua_pushlstring(L, out.buffer, out.length);
+ lmt_memory_free(entries);
+ lmt_buffer_dispose(&text_buf);
+ lmt_buffer_dispose(&out);
+ return 1;
+}
+
+/* tabstr_mixed (array indexed 1..n, no sorting) */
+
+static int strlib_tabstr_mixed(lua_State *L)
+{
+ if (! lua_istable(L, 1)) {
+ lua_pushliteral(L, "");
+ return 1;
+ }
+ lua_Unsigned n = lua_rawlen(L, 1);
+ if (n == 0) {
+ lua_pushliteral(L, "");
+ return 1;
+ }
+ lmt_string_buffer b;
+ lmt_buffer_allocate(L, &b);
+ for (lua_Unsigned i = 1; i <= n; i++) {
+ if (i > 1) {
+ lmt_buffer_add_char(&b, ',');
+ }
+ lua_rawgeti(L, 1, (lua_Integer) i);
+ // if (lua_isboolean(L, -1)) {
+ // if (lua_toboolean(L, -1)) {
+ // lmt_buffer_add_lstring(&b, "++", 2);
+ // } else {
+ // lmt_buffer_add_lstring(&b, "--", 2);
+ // }
+ // } else {
+ tabstr_add_value_string_raw(L, -1, &b);
+ // }
lua_pop(L, 1);
+ }
+ lua_pushlstring(L, b.buffer, b.length);
+ lmt_buffer_dispose(&b);
+ return 1;
+}
+
+/* tabstr_boolean */
+
+static int strlib_tabstr_boolean(lua_State *L)
+{
+ if (! lua_istable(L, 1)) {
+ lua_pushliteral(L, "");
return 1;
}
+ int maxentries = 16;
+ int nofentries = 0;
+ tabstr_item *entries = (tabstr_item *) lmt_memory_malloc(maxentries * sizeof(tabstr_item));
+ lmt_string_buffer text_buf;
+ lmt_buffer_allocate(L, &text_buf);
+ lua_pushnil(L);
+ while (lua_next(L, 1) != 0) {
+ if (nofentries >= maxentries) {
+ maxentries *= 2;
+ entries = (tabstr_item *) lmt_memory_realloc(entries, maxentries * sizeof(tabstr_item));
+ }
+ size_t start_off = text_buf.length;
+ tabstr_add_value_string_raw(L, -2, &text_buf);
+ lmt_buffer_add_char(&text_buf, lua_toboolean(L, -1) ? '+' : '-');
+ entries[nofentries].offset = (uint32_t) start_off;
+ entries[nofentries].len = (uint32_t) (text_buf.length - start_off);
+ nofentries++;
+ lua_pop(L, 1);
+ }
+ lmt_string_buffer out;
+ lmt_buffer_allocate(L, &out);
+ if (nofentries == 1) {
+ lmt_buffer_add_lstring(&out, text_buf.buffer + entries[0].offset, entries[0].len);
+ } else if (nofentries > 1) {
+ tabstr_entry *sort_list = (tabstr_entry *) lmt_memory_malloc(nofentries * sizeof(tabstr_entry));
+ for (int i = 0; i < nofentries; i++) {
+ sort_list[i].str = text_buf.buffer + entries[i].offset;
+ sort_list[i].len = entries[i].len;
+ }
+ qsort(sort_list, nofentries, sizeof(tabstr_entry), tabstr_entry_compare);
+ for (int i = 0; i < nofentries; i++) {
+ if (i > 0) {
+ lmt_buffer_add_char(&out, ',');
+ }
+ lmt_buffer_add_lstring(&out, sort_list[i].str, sort_list[i].len);
+ }
+ lmt_memory_free(sort_list);
+ }
+ lua_pushlstring(L, out.buffer, out.length);
+ lmt_memory_free(entries);
+ lmt_buffer_dispose(&text_buf);
+ lmt_buffer_dispose(&out);
+ return 1;
+}
-# else
+/*
+ From this it made sense to also provide a native loop over a sorted hash, another
+ oldie we use a lot. We're constent in the sorting.
+*/
- static int luaextend_string_buffer(lua_State *L)
- {
- (void) L;
+static int strlib_aux_sorted_next(lua_State *L)
+{
+ lua_Integer idx = lua_tointeger(L, lua_upvalueindex(3));
+ lua_Unsigned len = lua_rawlen(L, lua_upvalueindex(2));
+ if ((lua_Unsigned) idx > len) {
+ /* iteration complete */
return 0;
}
+ /* advance iterator index upvalue */
+ lua_pushinteger(L, idx + 1);
+ lua_replace(L, lua_upvalueindex(3));
+ /* push key from sorted keys array (upvalue 2) */
+ lua_rawgeti(L, lua_upvalueindex(2), idx);
+ /* push value from target table (upvalue 1) */
+ lua_pushvalue(L, -1);
+ lua_gettable(L, lua_upvalueindex(1));
+ /* key, value */
+ return 2;
+}
-# endif
+static int strlib_sortedhash(lua_State *L)
+{
+ luaL_checktype(L, 1, LUA_TTABLE);
+ int index = lua_absindex(L, 1);
+ int maxkeys = lmt_key_default;
+ int nofkeys = 0;
+ lmt_serialize_sort_data *keys = (lmt_serialize_sort_data *) lmt_memory_malloc(maxkeys * sizeof(lmt_serialize_sort_data));
+ /* collect all sortable keys */
+ lua_pushnil(L);
+ while (lua_next(L, index) != 0) {
+ if (nofkeys >= maxkeys) {
+ maxkeys *= 2;
+ keys = (lmt_serialize_sort_data *) lmt_memory_realloc(keys, maxkeys * sizeof(lmt_serialize_sort_data));
+ }
+ lmt_serialize_sort_data *sk = &keys[nofkeys];
+ switch (lua_type(L, -2)) {
+ case LUA_TNUMBER:
+ if (lua_isinteger(L, -2)) {
+ sk->type = LMT_TYPE_INTEGER;
+ sk->integer_value = lua_tointeger(L, -2);
+ } else {
+ sk->type = LMT_TYPE_DOUBLE;
+ sk->double_value = lua_tonumber(L, -2);
+ }
+ nofkeys++;
+ break;
+ case LUA_TBOOLEAN:
+ sk->type = lua_toboolean(L, -2) ? LMT_TYPE_TRUE : LMT_TYPE_FALSE;
+ nofkeys++;
+ break;
+ case LUA_TSTRING: {
+ size_t len;
+ sk->type = LMT_TYPE_STRING;
+ sk->string_value = lua_tolstring(L, -2, &len);
+ sk->string_length = (uint32_t) len;
+ nofkeys++;
+ break;
+ }
+ default:
+ break;
+ }
+ lua_pop(L, 1);
+ }
+ /* sort these keys using the already existing comparator */
+ if (nofkeys > 1) {
+ qsort(keys, nofkeys, sizeof(lmt_serialize_sort_data), lmt_serialize_compare);
+ }
+ /* sonstruct an array of sorted keys */
+ lua_createtable(L, nofkeys, 0);
+ int keys_table_idx = lua_gettop(L);
+ for (int i = 0; i < nofkeys; i++) {
+ lmt_serialize_sort_data *sk = &keys[i];
+ switch (sk->type) {
+ case LMT_TYPE_INTEGER:
+ lua_pushinteger(L, sk->integer_value);
+ break;
+ case LMT_TYPE_DOUBLE:
+ lua_pushnumber(L, sk->double_value);
+ break;
+ case LMT_TYPE_FALSE:
+ lua_pushboolean(L, 0);
+ break;
+ case LMT_TYPE_TRUE:
+ lua_pushboolean(L, 1);
+ break;
+ case LMT_TYPE_STRING:
+ lua_pushlstring(L, sk->string_value, sk->string_length);
+ break;
+ default:
+ lua_pushnil(L);
+ break;
+ }
+ lua_rawseti(L, keys_table_idx, i + 1);
+ }
+ lmt_memory_free(keys);
+ /* return a C closure with upvalues (the modern approach):
+
+ 1: target table
+ 2: sorted keys array table
+ 3: first index counter
+
+ */
+ lua_pushvalue(L, 1);
+ lua_pushvalue(L, keys_table_idx);
+ lua_pushinteger(L, 1);
+ /* and off we go */
+ lua_pushcclosure(L, strlib_aux_sorted_next, 3);
+ return 1;
+}
+
+/*tex
+
+ These are (for instance) part of a hash, not that critical in terms of performance but it fits
+ the repertoire.
+
+*/
+
+static void strlib_aux_sequenced(
+ lua_State *L,
+ int index,
+ lmt_string_buffer *buffer,
+ int sep_is_true,
+ const char *sep_str,
+ size_t sep_len,
+ int simple,
+ int seen,
+ int depth
+)
+{
+ index = lua_absindex(L, index);
+ if (! strlib_aux_serialize_enter(L, index, seen, depth)) {
+ return;
+ }
+ if (sep_is_true) {
+ lmt_buffer_add_lstring(buffer, "{ ", 2);
+ }
+ lua_Unsigned n = lua_rawlen(L, index);
+ if (n > 0) {
+ /* array part */
+ for (lua_Unsigned i = 1; i <= n; i++) {
+ if (i > 1) {
+ if (sep_is_true) {
+ lmt_buffer_add_lstring(buffer, ", ", 2);
+ } else {
+ lmt_buffer_add_lstring(buffer, sep_str, sep_len);
+ }
+ }
+ lua_rawgeti(L, index, (lua_Integer)i);
+ if (lua_istable(L, -1)) {
+ lmt_buffer_add_char(buffer, '{');
+ strlib_aux_sequenced(L, lua_gettop(L), buffer, sep_is_true, sep_str, sep_len, simple, seen, depth + 1);
+ lmt_buffer_add_char(buffer, '}');
+ } else {
+ tabstr_add_value_string(L, -1, buffer);
+ }
+ lua_pop(L, 1);
+ }
+ } else {
+ /* hashed part (sorted keys) */
+ int maxkeys = lmt_key_default;
+ int nofkeys = 0;
+ lmt_serialize_sort_data *keys = (lmt_serialize_sort_data *) lmt_memory_malloc(maxkeys * sizeof(lmt_serialize_sort_data));
+ lua_pushnil(L);
+ while (lua_next(L, index) != 0) {
+ if (nofkeys >= maxkeys) {
+ maxkeys *= 2;
+ keys = (lmt_serialize_sort_data *) lmt_memory_realloc(keys, maxkeys * sizeof(lmt_serialize_sort_data));
+ }
+ lmt_serialize_sort_data *sk = &keys[nofkeys];
+ switch (lua_type(L, -2)) {
+ case LUA_TNUMBER:
+ if (lua_isinteger(L, -2)) {
+ sk->type = LMT_TYPE_INTEGER;
+ sk->integer_value = lua_tointeger(L, -2);
+ } else {
+ sk->type = LMT_TYPE_DOUBLE;
+ sk->double_value = lua_tonumber(L, -2);
+ }
+ nofkeys++;
+ break;
+ case LUA_TBOOLEAN:
+ sk->type = lua_toboolean(L, -2) ? LMT_TYPE_TRUE : LMT_TYPE_FALSE;
+ nofkeys++;
+ break;
+ case LUA_TSTRING:
+ {
+ size_t len;
+ sk->type = LMT_TYPE_STRING;
+ sk->string_value = lua_tolstring(L, -2, &len);
+ sk->string_length = (uint32_t) len;
+ nofkeys++;
+ }
+ break;
+ default:
+ break;
+ }
+ lua_pop(L, 1);
+ }
+ if (nofkeys > 1) {
+ qsort(keys, nofkeys, sizeof(lmt_serialize_sort_data), lmt_serialize_compare);
+ }
+ int entries_added = 0;
+ for (int i = 0; i < nofkeys; i++) {
+ lmt_serialize_sort_data *sk = &keys[i];
+ /* key */
+ switch (sk->type) {
+ case LMT_TYPE_INTEGER: lua_pushinteger(L, sk->integer_value); break;
+ case LMT_TYPE_DOUBLE : lua_pushnumber (L, sk->double_value); break;
+ case LMT_TYPE_FALSE : lua_pushboolean(L, 0); break;
+ case LMT_TYPE_TRUE : lua_pushboolean(L, 1); break;
+ case LMT_TYPE_STRING : lua_pushlstring(L, sk->string_value, sk->string_length); break;
+ default: lua_pushnil (L); break;
+ }
+ /* value */
+ lua_pushvalue(L, -1);
+ lua_gettable(L, index);
+ int v_type = lua_type(L, -1);
+ int process = 0;
+ int is_true = 0;
+ if (simple) {
+ if (v_type == LUA_TBOOLEAN && lua_toboolean(L, -1)) {
+ process = 1;
+ is_true = 1;
+ } else if (v_type != LUA_TNIL && !(v_type == LUA_TBOOLEAN && ! lua_toboolean(L, -1))) {
+ if (v_type == LUA_TSTRING) {
+ size_t len;
+ lua_tolstring(L, -1, &len);
+ if (len > 0) {
+ process = 1;
+ }
+ } else {
+ process = 1;
+ }
+ }
+ } else {
+ process = 1;
+ }
+ if (process) {
+ if (entries_added > 0) {
+ if (sep_is_true) {
+ lmt_buffer_add_lstring(buffer, ", ", 2);
+ } else {
+ lmt_buffer_add_lstring(buffer, sep_str, sep_len);
+ }
+ }
+ tabstr_add_value_string(L, -2, buffer); /* key */
+ if (! is_true) {
+ lmt_buffer_add_char(buffer, '=');
+ if (v_type == LUA_TTABLE) {
+ lmt_buffer_add_char(buffer, '{');
+ strlib_aux_sequenced(L, lua_gettop(L), buffer, sep_is_true, sep_str, sep_len, simple, seen, depth + 1);
+ lmt_buffer_add_char(buffer, '}');
+ } else {
+ tabstr_add_value_string(L, -1, buffer);
+ }
+ }
+ entries_added++;
+ }
+ lua_pop(L, 2); /* pop key and value */
+ }
+ lmt_memory_free(keys);
+ }
+ if (sep_is_true) {
+ lmt_buffer_add_lstring(buffer, " }", 2);
+ }
+ strlib_aux_serialize_leave(L, index, seen);
+}
+
+static int strlib_sequenced(lua_State *L)
+{
+ if (lua_isnoneornil(L, 1) || (lua_isboolean(L, 1) && ! lua_toboolean(L, 1))) {
+ lua_pushliteral(L, "");
+ return 1;
+ }
+ if (! lua_istable(L, 1)) {
+ size_t len;
+ const char *s = luaL_tolstring(L, 1, &len);
+ lua_pushlstring(L, s, len);
+ return 1;
+ }
+ /* parse 'sep' parameter */
+ int sep_is_true = 0;
+ const char *sep_str = " | ";
+ size_t sep_len = 3;
+ if (lua_isboolean(L, 2)) {
+ if (lua_toboolean(L, 2)) {
+ sep_is_true = 1;
+ }
+ } else if (lua_type(L, 2) == LUA_TSTRING) {
+ sep_str = lua_tolstring(L, 2, &sep_len);
+ }
+ /* parse 'simple' parameter */
+ int simple = lua_toboolean(L, 3);
+ int check = lua_toboolean(L, 4);
+ int seen = 0;
+ lmt_string_buffer buffer;
+ lmt_buffer_allocate(L, &buffer);
+ if (check) {
+ lua_newtable(L);
+ seen = lua_gettop(L);
+ }
+ strlib_aux_sequenced(L, 1, &buffer, sep_is_true, sep_str, sep_len, simple, seen, 1);
+ if (check) {
+ lua_remove(L, seen);
+ }
+ lua_pushlstring(L, buffer.buffer, buffer.length);
+ lmt_buffer_dispose(&buffer);
+ return 1;
+}
+
+/*tex
+
+ We define these function in the |strlib| namespace but eventually register them in their own
+ library |sequencer|. They could have gone into |table| but they are rather specific and target
+ our usage, although serialize is kind of generic.
+
+*/
+
+static const luaL_Reg sequencerlib_function_list[] = {
+ /* tables */
+ { "serialize", strlib_serialize },
+ { "fastserialize", strlib_fastserialize },
+ { "tabstr_normal", strlib_tabstr_normal },
+ { "tabstr_flat", strlib_tabstr_flat },
+ { "tabstr_mixed", strlib_tabstr_mixed },
+ { "tabstr_boolean", strlib_tabstr_boolean },
+ { "sortedhash", strlib_sortedhash },
+ { "sequenced", strlib_sequenced },
+ /* strings */
+ { "format", strlib_format },
+ { "tostring", strlib_tostring },
+ /* buffers */
+ { "newbuffer", strlib_buffer_new },
+ { "addtobuffer", strlib_buffer_add },
+ { "addformattobuffer", strlib_buffer_addformat },
+ { "addbytestobuffer", strlib_buffer_addbytes },
+ { "addpackingtobuffer", strlib_buffer_addpacking },
+ { "getbufferdata", strlib_buffer_get_data },
+ { "getbuffersize", strlib_buffer_get_size },
+ /* */
+ { NULL, NULL },
+};
+
+/* this would also work when set:
+
+ static const void *G_BUFFER_METATABLE_PTR = NULL;
+
+ ...
+ luaL_getmetatable(L, STRING_BUFFER_METATABLE_INSTANCE);
+ G_BUFFER_METATABLE_PTR = lua_topointer(L, -1);
+ lua_pop(L, 1);
+ ...
+
+ lmt_string_buffer *strlib_buffer_instance(lua_State *L)
+ {
+ lmt_string_buffer *b = (lmt_string_buffer *) lua_touserdata(L, 1);
+ if (b && lua_getmetatable(L, 1)) {
+ if (lua_topointer(L, -1) != G_BUFFER_METATABLE_PTR) {
+ b = NULL;
+ }
+ lua_pop(L, 1);
+ return b;
+ }
+ return NULL;
+ }
+
+*/
+
+int luaopen_sequencer(lua_State *L)
+{
+ luaL_newmetatable(L, STRING_BUFFER_METATABLE_INSTANCE);
+
+ /* Cache metatable pointer for high-performance validation */
+ G_BUFFER_METATABLE_PTR = lua_topointer(L, -1);
+
+ luaL_setfuncs(L, sequencerlib_metatable_list, 0);
+
+ lua_pushvalue(L, -1);
+ lua_setfield(L, -2, "__index");
+
+ /* create extensions table (upvalue 2) */
+
+ lua_newtable(L); /* stack: [metatable, extensions] */
+
+ /* create format/tostring buffer stack (upvalue 3) */
+ lmt_buffer_stack *bs = (lmt_buffer_stack *) lua_newuserdatauv(L, sizeof(lmt_buffer_stack), 0);
+ bs->active_mask = 0;
+ for (int i = 0; i < buffer_stack_size; i++) {
+ bs->buffers[i].buffer = NULL;
+ bs->buffers[i].size = 0;
+ bs->buffers[i].length = 0;
+ bs->buffers[i].step = 0;
+ }
+
+ lua_newtable(L);
+ lua_pushcfunction(L, strlib_format_buffer_gc);
+ lua_setfield(L, -2, "__gc");
+ lua_setmetatable(L, -2); /* stack: [metatable, extensions, buffer_ud] */
+
+ /* create the main 'sequencer' library table */
+ lua_newtable(L); /* stack: [metatable, extensions, buffer_ud, library] */
+
+ lua_pushvalue(L, -3); /* extensions */
+ lua_setfield(L, -2, "extensions");
+
+ /* bind C functions using 3 upvalues */
+ lua_pushvalue(L, -4); /* upvalue 1: metatable */
+ lua_pushvalue(L, -4); /* upvalue 2: extensions table */
+ lua_pushvalue(L, -4); /* upvalue 3: buffer userdata */
+ luaL_setfuncs(L, sequencerlib_function_list, 3); /* register with 3 upvalues */
+
+ /* clean up the stack */
+ lua_remove(L, -2); /* remove buffer_ud */
+ lua_remove(L, -2); /* remove extensions */
+ lua_remove(L, -2); /* remove metatable */
+
+ return 1; /* return library table */
+}
+
+/*tex
+
+ The next list of functions registers in the |string| namespace. Maybe in retrospect we should
+ have created a new namespace but it was already decided when we started with \LUATEX, so we
+ stick to it.
+
+*/
+
+static const luaL_Reg strlib_function_list[] = {
+ { "characters", strlib_characters },
+ { "characterpairs", strlib_characterpairs },
+ { "bytes", strlib_bytes },
+ { "bytepairs", strlib_bytepairs },
+ { "bytetable", strlib_bytetable },
+ { "chartable", strlib_chartable },
+ { "totable", strlib_totable },
+ { "linetable", strlib_linetable },
+ { "utfvalues", strlib_utfvalues },
+ { "utfcharacters", strlib_utfcharacters },
+ { "utfcharacter", strlib_utfcharacter },
+ { "utfvalue", strlib_utfvalue },
+ { "utflength", strlib_utflength },
+ { "utfvaluetable", strlib_utfvaluetable },
+ { "utfcharactertable", strlib_utfcharactertable },
+ { "utftabletostring", strlib_utftabletostring },
+ { "onlyascii", strlib_onlyascii },
+ { "filterweird", strlib_filter_weird },
+ { "f6", strlib_format_f6 },
+ { "g6", strlib_format_g6 },
+ { "fd", strlib_format_fd },
+ { "fd3", strlib_format_fd3 }, /* no argument needed */
+ { "fd6", strlib_format_fd6 }, /* idem */
+ { "fd9", strlib_format_fd9 }, /* idem */
+ { "gd", strlib_format_gd }, /* seldom needed but cheap to provide */
+ { "tounicode16", strlib_tounicode16 },
+ { "fromunicode16", strlib_fromunicode16 },
+ { "toutf8", strlib_format_toutf8 },
+ { "toutf16", strlib_format_toutf16 }, /* this is kind of untested */
+ { "toutf32", strlib_format_toutf32 },
+ { "utf16toutf8", strlib_utf16toutf8 },
+ { "packrowscolumns", strlib_pack_rows_columns },
+ { "hextocharacters", strlib_hextocharacters },
+ { "octtointeger", strlib_octtointeger },
+ { "dectointeger", strlib_dectointeger },
+ { "hextointeger", strlib_hextointeger },
+ { "chrtointeger", strlib_chrtointeger },
+ { "splitintolines", strlib_splitintolines },
+ { "replacecharacter", strlib_replacecharacter },
+ /* handy for pdf strings */
+ { "topdfsixteen", strlib_topdfsixteen },
+ { "topdfeight", strlib_topdfeight },
+ { "topdfstring", strlib_topdfstring },
+ /* */
+ { NULL, NULL },
+};
int luaextend_string(lua_State * L)
{
@@ -1753,45 +5675,42 @@ int luaextend_string(lua_State * L)
lua_setfield(L, -2, lib->name);
}
lua_pop(L, 1);
- luaextend_string_buffer(L);
return 1;
}
/*
LUAMOD_API int luaopen_strlib(lua_State *L) {
- // 1. Create the library table (or use luaL_newlib for other functions)
+ // create the library table (or use luaL_newlib for other functions)
lua_newtable(L);
- // 2. Push the upvalues onto the stack BEFORE creating the closure
+ // push the upvalues onto the stack BEFORE creating the closure
lua_pushliteral(L, "0"); // Upvalue index 1
lua_pushliteral(L, "1"); // Upvalue index 2
- // 3. Create the closure with 2 upvalues
+ // create the closure with 2 upvalues
// (This pops the 2 strings off the stack and attaches them to the function)
lua_pushcclosure(L, strlib_format_f6, 2);
- // 4. Set the function in your library table ( equivalent to: lib["f6"] = strlib_format_f6 )
+ // set the function in the library table
lua_setfield(L, -2, "f6");
- return 1; // Return the library table
+ return 1; // the library table
}
static int strlib_format_f6(lua_State *L)
{
double n = luaL_optnumber(L, 1, 0.0);
-
if (n == 0.0) {
- // Upvalue 1: "0"
+ // upvalue 1: "0"
lua_pushvalue(L, lua_upvalueindex(1));
return 1;
} else if (n == 1.0) {
- // Upvalue 2: "1"
+ // upvalue 2: "1"
lua_pushvalue(L, lua_upvalueindex(2));
return 1;
}
-
// ...
}
-*/ \ No newline at end of file
+*/
diff --git a/source/luametatex/source/luarest/lmttimerlib.c b/source/luametatex/source/luarest/lmttimerlib.c
index c96e1ecc2..9a3c82398 100644
--- a/source/luametatex/source/luarest/lmttimerlib.c
+++ b/source/luametatex/source/luarest/lmttimerlib.c
@@ -194,7 +194,7 @@ typedef struct timer {
static inline timer * timerlib_aux_valid(lua_State *L, int i)
{
- timer * t = lua_touserdata(L, i);
+ timer *t = lua_touserdata(L, i);
if (t && lua_getmetatable(L, i)) {
lua_get_metatablelua(timer_instance);
if (! lua_rawequal(L, -1, -2)) {
diff --git a/source/luametatex/source/luarest/lmtxmathlib.c b/source/luametatex/source/luarest/lmtxmathlib.c
index bcd7051c6..b708bd65b 100644
--- a/source/luametatex/source/luarest/lmtxmathlib.c
+++ b/source/luametatex/source/luarest/lmtxmathlib.c
@@ -73,14 +73,15 @@ static int xmathlib_cbrt(lua_State *L)
{
lua_pushnumber(L, (lua_Number) cbrt(luaL_checknumber(L, 1)));
return 1;
-}
-
-static int xmathlib_ceil(lua_State *L)
-{
- lua_pushnumber(L, (lua_Number) ceil(luaL_checknumber(L, 1)));
return 1;
}
+// static int xmathlib_ceil(lua_State *L)
+// {
+// lua_pushnumber(L, (lua_Number) ceil(luaL_checknumber(L, 1)));
+// return 1;
+// }
+
static int xmathlib_copysign (lua_State *L)
{
lua_pushnumber(L, (lua_Number) copysign(luaL_checknumber(L, 1), luaL_checknumber(L, 2)));
@@ -147,16 +148,17 @@ static int xmathlib_fdim(lua_State *L)
return 1;
}
-static int xmathlib_floor(lua_State *L)
-{
- lua_pushnumber(L, (lua_Number) floor(luaL_checknumber(L, 1)));
- return 1;
-}
+// static int xmathlib_floor(lua_State *L)
+// {
+// lua_pushnumber(L, (lua_Number) floor(luaL_checknumber(L, 1)));
+// return 1;
+// }
static int xmathlib_fma(lua_State *L)
{
lua_pushnumber(L, (lua_Number) fma(luaL_checknumber(L, 1), luaL_checknumber(L, 2), luaL_checknumber(L, 3)));
return 1;
+ return 1;
}
static int xmathlib_fmax(lua_State *L)
@@ -194,7 +196,7 @@ static int xmathlib_frexp(lua_State *L)
lua_pushinteger(L, e);
return 2;
}
-static int xmathlib_fremquo(lua_State *L)
+static int xmathlib_remquo(lua_State *L)
{
int e;
lua_pushnumber(L, (lua_Number) remquo(luaL_checknumber(L, 1),luaL_checknumber(L, 2), &e));
@@ -483,6 +485,179 @@ static int xmathlib_dotproduct(lua_State *L)
return 1;
}
+# define xmathlib_pipi (2 * xmathlib_pi / 360)
+
+static int xmathlib_sind(lua_State *L)
+{
+ lua_pushnumber(L, (lua_Number) sin(luaL_checknumber(L, 1) * xmathlib_pipi));
+ return 1;
+}
+
+static int xmathlib_cosd(lua_State *L)
+{
+ lua_pushnumber(L, (lua_Number) cos(luaL_checknumber(L, 1) * xmathlib_pipi));
+ return 1;
+}
+
+static int xmathlib_tand(lua_State *L)
+{
+ lua_pushnumber(L, (lua_Number) tan(luaL_checknumber(L, 1) * xmathlib_pipi));
+ return 1;
+}
+
+static int xmathlib_div(lua_State *L)
+{
+ /* Lua 5.3+ : if both arguments are integers, return an integer result */
+ if (lua_isinteger(L, 1) && lua_isinteger(L, 2)) {
+ lua_Integer n = lua_tointeger(L, 1);
+ lua_Integer m = lua_tointeger(L, 2);
+ if (m == 0) {
+ return luaL_error(L, "attempt to divide by zero");
+ } else {
+ /* C division truncates towards zero; Lua floor division rounds towards -inf */
+ lua_Integer q = n / m;
+ lua_Integer r = n % m;
+ if ((r != 0) && ((n ^ m) < 0)) {
+ q--;
+ }
+ lua_pushinteger(L, q);
+ }
+ } else {
+ /* floats / mixed types */
+ lua_Number n = luaL_checknumber(L, 1);
+ lua_Number m = luaL_checknumber(L, 2);
+ lua_pushnumber(L, (lua_Number) floor(n / m));
+ }
+ return 1;
+}
+
+static int xmathlib_mod(lua_State *L)
+{
+ /* Lua 5.3+ : if both arguments are integers, return an integer result */
+ if (lua_isinteger(L, 1) && lua_isinteger(L, 2)) {
+ lua_Integer n = lua_tointeger(L, 1);
+ lua_Integer m = lua_tointeger(L, 2);
+ if (m == 0) {
+ return luaL_error(L, "attempt to perform 'modulo' by zero");
+ } else {
+ /* Lua integer modulo behavior */
+ lua_Integer r = n % m;
+ if ((r != 0) && ((n ^ m) < 0)) {
+ r += m;
+ }
+ lua_pushinteger(L, r);
+ }
+ } else {
+ /* floats / mixed types */
+ lua_Number n = luaL_checknumber(L, 1);
+ lua_Number m = luaL_checknumber(L, 2);
+ lua_pushnumber(L, (lua_Number) (n - m * floor(n / m)));
+ }
+ return 1;
+}
+
+static int xmathlib_odd(lua_State *L)
+{
+ long long n = luaL_checkinteger(L, 1);
+ lua_pushboolean(L, (n % 2 != 0));
+ return 1;
+}
+
+static int xmathlib_even(lua_State *L)
+{
+ long long n = luaL_checkinteger(L, 1);
+ lua_pushboolean(L, (n % 2 == 0));
+ return 1;
+}
+
+/* -1, 0, or 1 */
+
+static int xmathlib_sign(lua_State *L)
+{
+ lua_Number n = luaL_checknumber(L, 1);
+ lua_pushinteger(L, n > 0 ? 1 : (n < 0 ? -1 : 0));
+ return 1;
+}
+
+static int xmathlib_clamp(lua_State *L)
+{
+ /* If all arguments are integers, return an integer result */
+ if (lua_isinteger(L, 1) && lua_isinteger(L, 2) && lua_isinteger(L, 3)) {
+ lua_Integer n = lua_tointeger(L, 1);
+ lua_Integer min = lua_tointeger(L, 2);
+ lua_Integer max = lua_tointeger(L, 3);
+ lua_pushinteger(L, n < min ? min : (n > max ? max : n));
+ } else {
+ /* floats or mixed types */
+ lua_Number n = luaL_checknumber(L, 1);
+ lua_Number min = luaL_checknumber(L, 2);
+ lua_Number max = luaL_checknumber(L, 3);
+ lua_pushnumber(L, n < min ? min : (n > max ? max : n));
+ }
+ return 1;
+}
+
+/* linear interpolation */
+
+static int xmathlib_lerp(lua_State *L)
+{
+ lua_Number a = luaL_checknumber(L, 1);
+ lua_Number b = luaL_checknumber(L, 2);
+ lua_Number c = luaL_checknumber(L, 3);
+ lua_pushnumber(L, a + (b - a) * c);
+ return 1;
+}
+
+/* round to specified decimal places */
+
+static int xmathlib_rounded(lua_State *L)
+{
+ lua_Number n = luaL_checknumber(L, 1);
+ int decimals = lmt_optinteger(L, 2, 0);
+ lua_Number multiplier = pow(10.0, decimals);
+ lua_pushnumber(L, floor(n * multiplier + 0.5) / multiplier);
+ return 1;
+}
+
+static int xmathlib_floor(lua_State *L)
+{
+ /* if it's already a native integer, the floor is itself */
+ if (lua_isinteger(L, 1)) {
+ lua_settop(L, 1);
+ return 1;
+ } else {
+ lua_Number n = luaL_checknumber(L, 1);
+ lua_Number f = floor(n);
+ /* if the result fits in a Lua integer, return an integer type */
+ if (f >= (lua_Number) LUA_MININTEGER && f <= (lua_Number) LUA_MAXINTEGER) {
+ lua_pushinteger(L, (lua_Integer) f);
+ } else {
+ /* NaN, Inf, or out-of-range values */
+ lua_pushnumber(L, f);
+ }
+ return 1;
+ }
+}
+
+static int xmathlib_ceil(lua_State *L)
+{
+ if (lua_isinteger(L, 1)) {
+ lua_settop(L, 1);
+ return 1;
+ } else {
+ lua_Number n = luaL_checknumber(L, 1);
+ lua_Number c = ceil(n);
+ /* if the result fits in a Lua integer, return an integer type */
+ if (c >= (lua_Number) LUA_MININTEGER && c <= (lua_Number) LUA_MAXINTEGER) {
+ lua_pushinteger(L, (lua_Integer) c);
+ } else {
+ /* NaN, Inf, or out-of-range values */
+ lua_pushnumber(L, c);
+ }
+ }
+ return 1;
+}
+
static const luaL_Reg xmathlib_function_list[] =
{
{ "acos", xmathlib_acos },
@@ -494,15 +669,20 @@ static const luaL_Reg xmathlib_function_list[] =
{ "atanh", xmathlib_atanh },
{ "cbrt", xmathlib_cbrt },
{ "ceil", xmathlib_ceil },
+ { "ceiling", xmathlib_ceil },
+ { "clamp", xmathlib_clamp },
{ "copysign", xmathlib_copysign },
{ "cos", xmathlib_cos },
+ { "cosd", xmathlib_cosd },
{ "cosh", xmathlib_cosh },
{ "deg", xmathlib_deg },
+ { "div", xmathlib_div },
{ "erf", xmathlib_erf },
{ "erfc", xmathlib_erfc },
{ "exp", xmathlib_exp },
{ "exp2", xmathlib_exp2 },
{ "expm1", xmathlib_expm1 },
+ { "even", xmathlib_even },
{ "fabs", xmathlib_fabs },
{ "fdim", xmathlib_fdim },
{ "floor", xmathlib_floor },
@@ -521,25 +701,32 @@ static const luaL_Reg xmathlib_function_list[] =
{ "j1", xmathlib_j1 },
{ "jn", xmathlib_jn },
{ "ldexp", xmathlib_ldexp },
+ { "lerp", xmathlib_lerp },
{ "lgamma", xmathlib_lgamma },
{ "log", xmathlib_log },
{ "log10", xmathlib_log10 },
{ "log1p", xmathlib_log1p },
{ "log2", xmathlib_log2 },
{ "logb", xmathlib_logb },
+ { "mod", xmathlib_mod },
{ "modf", xmathlib_modf },
{ "nearbyint", xmathlib_nearbyint },
{ "nextafter", xmathlib_nextafter },
+ { "odd", xmathlib_odd },
{ "pow", xmathlib_pow },
{ "rad", xmathlib_rad },
{ "remainder", xmathlib_remainder },
- { "remquo", xmathlib_fremquo },
+ { "remquo", xmathlib_remquo },
{ "round", xmathlib_round },
+ { "rounded", xmathlib_rounded },
{ "scalbn", xmathlib_scalbn },
+ { "sign", xmathlib_sign },
{ "sin", xmathlib_sin },
+ { "sind", xmathlib_sind },
{ "sinh", xmathlib_sinh },
{ "sqrt", xmathlib_sqrt },
{ "tan", xmathlib_tan },
+ { "tand", xmathlib_tand },
{ "tanh", xmathlib_tanh },
{ "tgamma", xmathlib_tgamma },
{ "trunc", xmathlib_trunc },
diff --git a/source/luametatex/source/luarest/lmtxzlib.c b/source/luametatex/source/luarest/lmtxzlib.c
new file mode 100644
index 000000000..9f8b81afd
--- /dev/null
+++ b/source/luametatex/source/luarest/lmtxzlib.c
@@ -0,0 +1,278 @@
+/*
+ See license.txt in the root of this project.
+*/
+
+# include "luametatex.h"
+
+/*tex
+ Because we already have |tar| support in \CONTEXT\ (just \LUA), I decided to also get
+ a simple |xz| compressor in the engine because thsi file format is popular in the \TEX\
+ ecosystem. A bit of research learned that \quote {xz embedded} was the best candidate.
+
+ We could have an |auxxzembedded.h| file but we need to adapt the |xz_config.h| file
+ anyway: |XZ_DEC_CONCATENATED| as well as |XZ_USE_CRC64|.
+
+*/
+
+# include "../libraries/xzembedded/xz_config.h"
+
+/*tex
+
+ We initialize the decoder with dynamic allocation mode and a max dictionary size limit
+ (64 MB) to protect against malicious headers.
+
+ This wrapper is simular to for instance miniz but with less options. Here We only
+ decompress. We need |xz_dec_catrun| and not |xz_dec_run| as well as 64 bit checksum
+ support. We could go for larger chunks but it looks fast enough.
+
+*/
+
+/*tex
+
+ This one calculates the exact byte size of an XZ stream from an in-memory buffer. A \CCODE\
+ template was provided by gemini. First a helper to read a 32-bit little-endian integer
+ safely from arbitrary memory. We also need a Variable-Length Integer (VLI) decoder that
+ reads a variable-length integer from the buffer and advances the pointer/length.
+
+*/
+
+
+static inline uint32_t read_le32(const uint8_t *buf)
+{
+ return ((uint32_t) buf[0] ) |
+ ((uint32_t) buf[1] << 8) |
+ ((uint32_t) buf[2] << 16) |
+ ((uint32_t) buf[3] << 24);
+}
+
+static int read_vli(const uint8_t **buf, size_t *left, uint64_t *val)
+{
+ *val = 0;
+ int shift = 0;
+ while (*left > 0) {
+ uint8_t b = **buf;
+ (*buf)++;
+ (*left)--;
+ *val |= (uint64_t) (b & 0x7F) << shift;
+ if (! (b & 0x80)) {
+ return 0; /* success */
+ }
+ shift += 7;
+ if (shift >= 64) {
+ return -1; /* overflow */
+ }
+ }
+ return -1; /* unexpected end of buffer */
+}
+
+static int64_t xzlib_aux_targetsize(const char *data, size_t len)
+{
+ if (! data) {
+ /* bad stream */
+ return -1;
+ }
+
+ if (len < 12) {
+ /* too short to contain a valid XZ stream header and footer */
+ return -1;
+ }
+
+ const uint8_t *bytes = (const uint8_t *) data;
+
+ // check stream header magic at the beginning (6 bytes) */
+
+ if (bytes[0] != 0xFD || bytes[1] != '7' || bytes[2] != 'z' ||
+ bytes[3] != 'X' || bytes[4] != 'Z' || bytes[5] != 0x00) {
+ /* invalid XZ header */
+ return -2;
+ }
+
+ /* verify stream footer magic at the last 2 bytes ('Y' = 0x59, 'Z' = 0x5A) */
+
+ if (bytes[len - 2] != 0x59 || bytes[len - 1] != 0x5A) {
+ /* invalid XZ footer */
+ return -2;
+ }
+
+ /* extract backward size (4 bytes, located 8 to 5 bytes from the end) */
+
+ uint32_t backward_size_val = read_le32(&bytes[len - 8]);
+
+ /* the actual index size formula is |real_backward_size = (stored_backward_size + 1) * 4| */
+
+ uint64_t index_size = ((uint64_t) backward_size_val + 1) * 4;
+
+ /* compute structural offsets, the index field starts right before the 12-byte stream footer */
+
+ int64_t index_start = (int64_t) len - 12 - (int64_t) index_size;
+
+ if (index_start < 12) {
+ /* corrupted backward size or invalid layout */
+ return -3;
+ }
+
+ /* index structure starts at bytes[index_start] */
+
+ const uint8_t *ptr = &bytes[index_start];
+ size_t left = index_size;
+
+ // index indicator (must be 0x00) */
+
+ if (left == 0 || *ptr != 0x00) {
+ return -4;
+ }
+ ptr++;
+ left--;
+
+ /* number of (VLI) records */
+
+ uint64_t num_records = 0;
+ if (read_vli(&ptr, &left, &num_records) != 0) {
+ return -5;
+ }
+
+ uint64_t total_uncompressed_size = 0;
+
+ /* loop through each block record in the index */
+
+ for (uint64_t i = 0; i < num_records; i++) {
+ uint64_t comp_size = 0;
+ uint64_t uncomp_size = 0;
+ if (read_vli(&ptr, &left, &comp_size) != 0) {
+ return -6;
+ }
+ if (read_vli(&ptr, &left, &uncomp_size) != 0) {
+ return -7;
+ }
+ total_uncompressed_size += uncomp_size;
+ }
+
+ /* index CRC32 validation can happen here if needed */
+
+ return total_uncompressed_size;
+}
+
+static int xzlib_decompresssize(lua_State *L)
+{
+ size_t len = 0;
+ const char *str = lua_tolstring(L, 1, &len);
+ if (str) {
+ lua_Integer size = (lua_Integer) xzlib_aux_targetsize(str, len);
+ if (size > 0) {
+ lua_pushinteger(L, size);
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/*tex
+ Because we have the whole data stream loaded we can calculate the target length and use a fast
+ code path. So, we extended the decompressor but kept the previous chunk variant as fallback.
+
+ \starttabulate
+ \NC date \NC 2026-10-27 \NC \NR
+ \NC file \NC cont-tfm.tar.xz \NC \NR
+ \NC compressed \NC 227,915,180 \NC \NR
+ \NC uncompressed \NC 367,853,056 \NC \NR
+ \NC compression ratio \NC 1.61 \NC \NR
+ \NC chunked \NC 12.3 sec \NC \NR
+ \NC single allocation \NC 11.8 sec \NC \NR
+ \NC laptop \NC (2018) Xeon E3-1505M v6, Windows 11 \NC \NR
+ \stoptabulate
+
+ Although we only gain about 4\percent\ we get less memory fragmentation and no spikes in memory
+ usage (stable baseline).
+
+*/
+
+static int xzlib_decompress(lua_State *L)
+{
+ size_t size = 0;
+ const char *data = luaL_checklstring(L, 1, &size);
+ lua_Integer max = luaL_optinteger(L, 2, 0);
+ int success = 0;
+ int64_t targetsize = xzlib_aux_targetsize(data, size);
+
+ if (max > 0 && targetsize > max) {
+ // tex_formatted_warning("xz decompress", "target size: %i, max size: %i, overflow", targetsize, max);
+ goto DONE;
+ }
+
+ struct xz_dec *decoder = xz_dec_init(XZ_DYNALLOC, 1 << 26);
+
+ if (! decoder) {
+ goto DONE;
+ }
+
+ luaL_Buffer buffer;
+
+ struct xz_buf b;
+ b.in = (const uint8_t *) data;
+ b.in_pos = 0;
+ b.in_size = size;
+
+ if (targetsize > 0) {
+ char *out_ptr = luaL_buffinitsize(L, &buffer, (size_t) targetsize);
+
+ b.out = (uint8_t *) out_ptr;
+ b.out_pos = 0;
+ b.out_size = (size_t) targetsize;
+
+ enum xz_ret ret = xz_dec_catrun(decoder, &b, 1);
+
+ if (ret == XZ_STREAM_END && b.out_pos == (size_t) targetsize) {
+ success = 1;
+ luaL_pushresultsize(&buffer, b.out_pos);
+ }
+ }
+
+ if (! success) {
+ luaL_buffinit(L, &buffer);
+ size_t chunksize = 16 * 1024;
+ while (1) {
+ uint8_t *out = (uint8_t *) luaL_prepbuffsize(&buffer, chunksize);
+
+ b.out = out;
+ b.out_pos = 0;
+ b.out_size = chunksize;
+
+ enum xz_ret ret = xz_dec_catrun(decoder, &b, 1);
+
+ if (b.out_pos > 0) {
+ luaL_addsize(&buffer, b.out_pos);
+ }
+ if (ret == XZ_STREAM_END) {
+ success = 1;
+ luaL_pushresult(&buffer);
+ break;
+ } else if (ret != XZ_OK) {
+ success = 0;
+ break;
+ }
+ }
+ }
+
+ xz_dec_end(decoder);
+
+ DONE:
+ if (! success) {
+ lua_pushnil(L);
+ }
+ return 1;
+}
+
+static struct luaL_Reg xzlib_function_list[] = {
+ { "decompress", xzlib_decompress },
+ { "decompresssize", xzlib_decompresssize },
+ { NULL, NULL },
+};
+
+int luaopen_xz(lua_State *L)
+{
+ xz_crc32_init();
+ xz_crc64_init();
+ lua_newtable(L);
+ luaL_setfuncs(L, xzlib_function_list, 0);
+ return 1;
+} \ No newline at end of file
diff --git a/source/luametatex/source/luarest/lmtziplib.c b/source/luametatex/source/luarest/lmtziplib.c
index a1350d25c..1c39fbff3 100644
--- a/source/luametatex/source/luarest/lmtziplib.c
+++ b/source/luametatex/source/luarest/lmtziplib.c
@@ -198,7 +198,8 @@ static struct luaL_Reg ziplib_function_list[] = {
{ NULL, NULL },
};
-int luaopen_xzip(lua_State *L) {
+int luaopen_xzip(lua_State *L)
+{
lua_newtable(L);
luaL_setfuncs(L, ziplib_function_list, 0);
return 1;
diff --git a/source/luametatex/source/mp/mp.c b/source/luametatex/source/mp/mp.c
index 27f45b5e0..99ea9655f 100644
--- a/source/luametatex/source/mp/mp.c
+++ b/source/luametatex/source/mp/mp.c
@@ -15339,25 +15339,25 @@ static int mp_check_outer_validity(MP mp)
{
if (mp->scanner_status == mp_normal_state) {
return 1;
- } else if (mp->scanner_status == mp_tex_flushing_state) {
- /*tex
- Check if the file has ended while flushing \tex\ material and set the result value for
- |check_outer_validity|.
- */
- if (cur_sym != NULL) {
- return 1;
- } else {
- char msg[256];
- snprintf(msg, 256, "TeX mode didn't end; all text was ignored after line %d", (int) mp->warning_line);
- set_cur_sym(mp->frozen_etex);
- mp_ins_error(
- mp,
- msg,
- "The file ended while I was looking for the 'etex' to finish this TeX material.\n"
- "I've inserted 'etex' now."
- );
- return 0;
- }
+ // } else if (mp->scanner_status == mp_tex_flushing_state) {
+ // /*tex
+ // Check if the file has ended while flushing \tex\ material and set the result value for
+ // |check_outer_validity|.
+ // */
+ // if (cur_sym != NULL) {
+ // return 1;
+ // } else {
+ // char msg[256];
+ // snprintf(msg, 256, "TeX mode didn't end; all text was ignored after line %d", (int) mp->warning_line);
+ // set_cur_sym(mp->frozen_etex);
+ // mp_ins_error(
+ // mp,
+ // msg,
+ // "The file ended while I was looking for the 'etex' to finish this TeX material.\n"
+ // "I've inserted 'etex' now."
+ // );
+ // return 0;
+ // }
} else {
/*tex back up an outer symbolic token so that it can be reread */
// if (cur_sym != NULL) {
@@ -15541,10 +15541,10 @@ static void mp_get_next(MP mp)
case mp_space_class:
goto SWITCH;
case mp_percent_class:
- if (mp->scanner_status == mp_tex_flushing_state && mp_input_location < mp_input_limit) {
- /*tex |btex .. etex|: */
- goto SWITCH;
- }
+ // if (mp->scanner_status == mp_tex_flushing_state && mp_input_location < mp_input_limit) {
+ // /*tex |btex .. etex|: */
+ // goto SWITCH;
+ // }
/*tex
Move to next line of file, or |goto restart| if there is no
next line.
@@ -15555,9 +15555,10 @@ static void mp_get_next(MP mp)
goto SWITCH;
}
case mp_string_class:
- if (mp->scanner_status == mp_tex_flushing_state) {
- goto SWITCH;
- } else {
+ // if (mp->scanner_status == mp_tex_flushing_state) {
+ // goto SWITCH;
+ // } else {
+ {
/* We also accept ASCII BTX ... ETX here. */
unsigned char cend = c == '"' ? '"' : c == '\'' ? '\'' : 3 ;
if (c == '\'') {
@@ -15604,7 +15605,7 @@ static void mp_get_next(MP mp)
++mp_input_location;
set_cur_cmd(mp_string_command);
return;
- }
+ }
case mp_comma_class:
case mp_semicolon_class:
case mp_left_parenthesis_class:
@@ -15612,9 +15613,9 @@ static void mp_get_next(MP mp)
k = mp_input_location - 1;
goto FOUND;
case mp_invalid_class:
- if (mp->scanner_status == mp_tex_flushing_state) {
- goto SWITCH;
- } else {
+ // if (mp->scanner_status == mp_tex_flushing_state) {
+ // goto SWITCH;
+ // } else {
/*tex
Decry the invalid character and |goto restart|. We go to |restart| instead of
to |SWITCH|, because we might enter |token_state| after the error has been
@@ -15627,7 +15628,7 @@ static void mp_get_next(MP mp)
"that it ever happened."
);
goto RESTART;
- }
+ // }
default:
/*tex letters, etc. */
break;
diff --git a/source/luametatex/source/mp/mp.h b/source/luametatex/source/mp/mp.h
index 6b40a1351..7fa295644 100644
--- a/source/luametatex/source/mp/mp.h
+++ b/source/luametatex/source/mp/mp.h
@@ -840,7 +840,7 @@ typedef enum mp_class_codes {
mp_period_class = 1, /* the class number of |.| */
mp_space_class = 2, /* the class number of spaces and nonstandard characters */
mp_percent_class = 3, /* the class number of `\.\%' */
- mp_string_class = 4, /* the class number of |"| */
+ mp_string_class = 4, /* the class number of |"|, |'| and |\x02| */
mp_comma_class = 5, /* the , */
mp_semicolon_class = 6, /* the ; */
mp_left_parenthesis_class = 7, /* the class number of |(| */
@@ -872,7 +872,7 @@ typedef enum mp_scanner_states {
mp_var_defining_state, /* |scanner_status| when a |vardef| is being scanned */
mp_op_defining_state, /* |scanner_status| when a macro |def| is being scanned */
mp_loop_defining_state, /* |scanner_status| when a |for| loop is being scanned */
- mp_tex_flushing_state,
+ // mp_tex_flushing_state, /* we have a different |btex ... etex| scanner */
} mp_scanner_states;
typedef enum mp_verbatim_codes {
diff --git a/source/luametatex/source/mp/mpmathdecimal.c b/source/luametatex/source/mp/mpmathdecimal.c
index 8e9b51fb1..2000227f1 100644
--- a/source/luametatex/source/mp/mpmathdecimal.c
+++ b/source/luametatex/source/mp/mpmathdecimal.c
@@ -738,7 +738,8 @@ static void mp_decimal_aux_wrapup_numeric_token(MP mp, const unsigned char *star
mp_memory_free(buf);
if (mp_decimal_data.set.status == 0) {
set_cur_mod(&result);
- } else if (mp->scanner_status != mp_tex_flushing_state) {
+ // } else if (mp->scanner_status != mp_tex_flushing_state) {
+ } else {
if (too_large(mp_decimal_data.set.status)) {
mp_decnumber_check(mp, &result, &mp_decimal_data.set);
set_cur_mod(&result);
@@ -749,7 +750,8 @@ static void mp_decimal_aux_wrapup_numeric_token(MP mp, const unsigned char *star
);
} else if (too_precise(mp_decimal_data.set.status)) {
set_cur_mod(&result);
- if (decNumberIsPositive((decNumber *) internal_value(mp_warning_check_internal).data.num) && (mp->scanner_status != mp_tex_flushing_state)) {
+ // if (decNumberIsPositive((decNumber *) internal_value(mp_warning_check_internal).data.num) && (mp->scanner_status != mp_tex_flushing_state)) {
+ if (decNumberIsPositive((decNumber *) internal_value(mp_warning_check_internal).data.num)) {
char msg[256];
snprintf (msg, 256, "Number is too precise (numberprecision = %d)", mp_decimal_data.set.digits);
mp_error(
diff --git a/source/luametatex/source/mp/mpmathdouble.c b/source/luametatex/source/mp/mpmathdouble.c
index c6b9e8e72..64bce543b 100644
--- a/source/luametatex/source/mp/mpmathdouble.c
+++ b/source/luametatex/source/mp/mpmathdouble.c
@@ -456,7 +456,8 @@ static void mp_wrapup_numeric_token(MP mp, unsigned char *start, unsigned char *
if (errno == 0) {
set_cur_mod(result);
if (result >= warning_limit) {
- if (internal_value(mp_warning_check_internal).data.dval > 0 && (mp->scanner_status != mp_tex_flushing_state)) {
+ // if (internal_value(mp_warning_check_internal).data.dval > 0 && (mp->scanner_status != mp_tex_flushing_state)) {
+ if (internal_value(mp_warning_check_internal).data.dval > 0) {
char msg[256];
snprintf(msg, 256, "Number is too large (%g)", result);
mp_error(
@@ -467,7 +468,8 @@ static void mp_wrapup_numeric_token(MP mp, unsigned char *start, unsigned char *
);
}
}
- } else if (mp->scanner_status != mp_tex_flushing_state) {
+ // } else if (mp->scanner_status != mp_tex_flushing_state) {
+ } else {
mp_error(
mp,
"Enormous number has been reduced.",
@@ -680,7 +682,7 @@ static void mp_double_pyth_add(MP mp, mp_number *ret, const mp_number *a_orig, c
double a = fabs(a_orig->data.dval);
double b = fabs(b_orig->data.dval);
errno = 0;
- ret->data.dval = hypot(a, b);
+ ret->data.dval = lmt_hypot(a, b);
if (errno) {
mp->arithmic_error = mp_error_code(mp, 3);
ret->data.dval = EL_GORDO;
diff --git a/source/luametatex/source/mp/mpmathexperiment.c b/source/luametatex/source/mp/mpmathexperiment.c
index 9fa498295..cc92d60be 100644
--- a/source/luametatex/source/mp/mpmathexperiment.c
+++ b/source/luametatex/source/mp/mpmathexperiment.c
@@ -626,7 +626,8 @@ static void mp_wrapup_numeric_token(MP mp, unsigned char *start, unsigned char *
interval i = to_constant(result);
set_cur_mod(i);
if (result >= mp_interval_warning_limit) {
- if (q_mid(to_internum(internal_value(mp_warning_check_internal).data.num)) > 0 && (mp->scanner_status != mp_tex_flushing_state)) {
+ // if (q_mid(to_internum(internal_value(mp_warning_check_internal).data.num)) > 0 && (mp->scanner_status != mp_tex_flushing_state)) {
+ if (q_mid(to_internum(internal_value(mp_warning_check_internal).data.num)) > 0) {
char msg[256];
snprintf(msg, 256, "Number is too large (%g)", result);
mp_error(
@@ -637,7 +638,8 @@ static void mp_wrapup_numeric_token(MP mp, unsigned char *start, unsigned char *
);
}
}
- } else if (mp->scanner_status != mp_tex_flushing_state) {
+ // } else if (mp->scanner_status != mp_tex_flushing_state) {
+ } else {
mp_error(
mp,
"Enormous number has been reduced.",
diff --git a/source/luametatex/source/mp/mpmathposit.c b/source/luametatex/source/mp/mpmathposit.c
index a19f4aa89..62e3fe988 100644
--- a/source/luametatex/source/mp/mpmathposit.c
+++ b/source/luametatex/source/mp/mpmathposit.c
@@ -454,7 +454,8 @@ static void mp_posit_aux_wrapup_numeric_token(MP mp, unsigned char *start, unsig
if (errno == 0) {
set_cur_mod(double_to_posit(result));
if (result >= mp_warning_limit) {
- if (posit_gt(internal_value(mp_warning_check_internal).data.pval, mp_posit_data.zero) && (mp->scanner_status != mp_tex_flushing_state)) {
+ // if (posit_gt(internal_value(mp_warning_check_internal).data.pval, mp_posit_data.zero) && (mp->scanner_status != mp_tex_flushing_state)) {
+ if (posit_gt(internal_value(mp_warning_check_internal).data.pval, mp_posit_data.zero)) {
char msg[256];
snprintf(msg, 256, "Number is too large (%g)", result);
mp_error(
@@ -465,7 +466,8 @@ static void mp_posit_aux_wrapup_numeric_token(MP mp, unsigned char *start, unsig
);
}
}
- } else if (mp->scanner_status != mp_tex_flushing_state) {
+ // } else if (mp->scanner_status != mp_tex_flushing_state) {
+ } else {
mp_error(
mp,
"Enormous number has been reduced.",
diff --git a/source/luametatex/source/mp/mpmathscaled.c b/source/luametatex/source/mp/mpmathscaled.c
index 4bb7c9462..f9d7ec9db 100644
--- a/source/luametatex/source/mp/mpmathscaled.c
+++ b/source/luametatex/source/mp/mpmathscaled.c
@@ -724,7 +724,8 @@ static void mp_scaled_wrapup_numeric_token(MP mp, mp_scaled_t n, mp_scaled_t f)
mp_scaled_t mod = (n * unity + f);
set_cur_mod((int) mod);
if (mod >= fraction_one) {
- if (internal_value(mp_warning_check_internal).data.val > 0 && (mp->scanner_status != mp_tex_flushing_state)) {
+ // if (internal_value(mp_warning_check_internal).data.val > 0 && (mp->scanner_status != mp_tex_flushing_state)) {
+ if (internal_value(mp_warning_check_internal).data.val > 0) {
char msg[256];
snprintf(msg, 256, "Number is too large (%s)", mp_string_scaled(mp, mod));
mp_error(
@@ -735,7 +736,8 @@ static void mp_scaled_wrapup_numeric_token(MP mp, mp_scaled_t n, mp_scaled_t f)
);
}
}
- } else if (mp->scanner_status != mp_tex_flushing_state) {
+ // } else if (mp->scanner_status != mp_tex_flushing_state) {
+ } else {
mp_error(
mp,
"Enormous number has been reduced",
diff --git a/source/luametatex/source/mp/readme.txt b/source/luametatex/source/mp/readme.txt
index 21ef031dc..b65c55a21 100644
--- a/source/luametatex/source/mp/readme.txt
+++ b/source/luametatex/source/mp/readme.txt
@@ -1,44 +1,44 @@
-Remark
-
-When a CWEB (W) file is adapted we need to convert to C. This is normally done with the
-tangle program but as we want to be independent of other tools (which themselves can result
-in a chain of dependencies) we use a Lua script which happens to be run with LuaMetaTeX.
-
-Of course there is a chicken egg issue here because we need the engine as Lua interpreter
-but at some point we started with C files so now we only need to update.
-
-The script is located in the "tools" path alongside the "source" path and it is run in its
-own directory (which for me means: hit the run key when the document is open). As we always
-ship the C files, there is no need for a user to run the script.
-
-The script does a reasonable good job on the conversion and tries to generate good looking
-C code denying the argument that "it is only a machine that looks at it". We also had to
-catch some compiler issues. As LuaMetaTeX evolved some new functionality has been added and
-the W files have been cleanup quite a bit.
-
-Per begin March 2024 we no longer start from the W files but use C files that have the
-documentation embedded. For a while we keep the old W files around. An patch to the convert
-script tried to keep the documentation close to the code but some had to be manually moved
-to the right spot. This is partly due to the fact that we want it in the C file and not
-the H file. One reason for this change is that it is easier to add (upcoming) new features
-to the MetaPost engine. Due to changes over the years and the fact that the original code
-is used in the MP program we no longer have backporting on the agenda.
-
-In the current C files the documentation looks suboptimal but it will stepwise be cleaned up
-a bit without loosing the original. There is no intention to process the documentation but
-we keep using a mixture of Plain (the original) and ConTeXt (more structure). Although the C
-code was already optimimized and reshuffled we start from a reasonable clean code base. The
-idea is to gradually improve it and maybe even split of the now monolithic |mp.c| file into
-smaller files, although it is not that important.
-
-For a while we will keep the W files around because they are also a timestamp but eventually
-they will be archived. After all, they are still in the GIT repository. By keeping them we
-can backtrack the documentation but as they are frozen you should not use them!
-
-There can be fixes in the c files that are not backported to the w files! Per version 211.3
-we no longer distribute the W sources and we moved the files one level up. The lua tool file
-that we used for conversion has been removed. It serv4ed us well for five years and is still
-in the history. We keep the comments above.
-
-Hans Hagen
+Remark
+
+When a CWEB (W) file is adapted we need to convert to C. This is normally done with the
+tangle program but as we want to be independent of other tools (which themselves can result
+in a chain of dependencies) we use a Lua script which happens to be run with LuaMetaTeX.
+
+Of course there is a chicken egg issue here because we need the engine as Lua interpreter
+but at some point we started with C files so now we only need to update.
+
+The script is located in the "tools" path alongside the "source" path and it is run in its
+own directory (which for me means: hit the run key when the document is open). As we always
+ship the C files, there is no need for a user to run the script.
+
+The script does a reasonable good job on the conversion and tries to generate good looking
+C code denying the argument that "it is only a machine that looks at it". We also had to
+catch some compiler issues. As LuaMetaTeX evolved some new functionality has been added and
+the W files have been cleanup quite a bit.
+
+Per begin March 2024 we no longer start from the W files but use C files that have the
+documentation embedded. For a while we keep the old W files around. An patch to the convert
+script tried to keep the documentation close to the code but some had to be manually moved
+to the right spot. This is partly due to the fact that we want it in the C file and not
+the H file. One reason for this change is that it is easier to add (upcoming) new features
+to the MetaPost engine. Due to changes over the years and the fact that the original code
+is used in the MP program we no longer have backporting on the agenda.
+
+In the current C files the documentation looks suboptimal but it will stepwise be cleaned up
+a bit without loosing the original. There is no intention to process the documentation but
+we keep using a mixture of Plain (the original) and ConTeXt (more structure). Although the C
+code was already optimimized and reshuffled we start from a reasonable clean code base. The
+idea is to gradually improve it and maybe even split of the now monolithic |mp.c| file into
+smaller files, although it is not that important.
+
+For a while we will keep the W files around because they are also a timestamp but eventually
+they will be archived. After all, they are still in the GIT repository. By keeping them we
+can backtrack the documentation but as they are frozen you should not use them!
+
+There can be fixes in the c files that are not backported to the w files! Per version 211.3
+we no longer distribute the W sources and we moved the files one level up. The lua tool file
+that we used for conversion has been removed. It serv4ed us well for five years and is still
+in the history. We keep the comments above.
+
+Hans Hagen
2018-2024+ \ No newline at end of file
diff --git a/source/luametatex/source/tex/texalign.c b/source/luametatex/source/tex/texalign.c
index 8c25569e4..527c0819f 100644
--- a/source/luametatex/source/tex/texalign.c
+++ b/source/luametatex/source/tex/texalign.c
@@ -231,6 +231,7 @@ typedef enum align_options {
align_option_split = 0x1000,
align_option_use_glue = 0x2000,
align_option_add_penalties = 0x4000,
+ align_option_combine_size = 0x8000,
} align_options;
/* Do we still need these .. we have a dedicated stack. */
@@ -271,7 +272,7 @@ typedef struct alignment_row_state {
scaled yoffset;
scaled xmove;
scaled ymove;
- halfword shift;
+ scaled shift;
halfword source;
halfword target;
halfword anchor;
@@ -306,7 +307,7 @@ typedef struct alignment_state_info {
halfword column_number;
halfword last_row_number;
halfword last_column_number;
- halfword tabskip_amount;
+ scaled tabskip_amount;
/* */
alignment_row_state row_state;
} alignment_state_info ;
@@ -457,17 +458,17 @@ halfword tex_alignment_get_options(void)
static void tex_aux_wipe_row_state(void)
{
- lmt_alignment_state.row_state.attrlist = null;
+ lmt_alignment_state.row_state.attrlist = null;
lmt_alignment_state.row_state.orientation = 0;
- lmt_alignment_state.row_state.xoffset = 0;
- lmt_alignment_state.row_state.yoffset = 0;
- lmt_alignment_state.row_state.xmove = 0;
- lmt_alignment_state.row_state.ymove = 0;
- lmt_alignment_state.row_state.shift = 0;
- lmt_alignment_state.row_state.source = 0;
- lmt_alignment_state.row_state.target = 0;
- lmt_alignment_state.row_state.anchor = 0;
- lmt_alignment_state.row_state_set = 0;
+ lmt_alignment_state.row_state.xoffset = 0;
+ lmt_alignment_state.row_state.yoffset = 0;
+ lmt_alignment_state.row_state.xmove = 0;
+ lmt_alignment_state.row_state.ymove = 0;
+ lmt_alignment_state.row_state.shift = 0;
+ lmt_alignment_state.row_state.source = 0;
+ lmt_alignment_state.row_state.target = 0;
+ lmt_alignment_state.row_state.anchor = 0;
+ lmt_alignment_state.row_state_set = 0;
}
/*tex The current preamble list: */
@@ -492,14 +493,14 @@ static void tex_aux_finish_align (void);
static inline void tex_aux_change_list_type(halfword n, quarterword type)
{
- node_type(n) = type;
- box_w_offset(n) = 0; /* box_glue_stretch align_record_span_ptr */
- box_h_offset(n) = 0; /* box_glue_shrink align_record_extra_info */
- box_d_offset(n) = 0; /* box_span_count */
- box_x_offset(n) = 0; /* align_record_u_part */
- box_y_offset(n) = 0; /* align_record_v_part */
- /* box_geometry(n) = 0; */ /* box_size */
- box_orientation(n) = 0; /* box_size */
+ node_type (n) = type;
+ box_w_offset (n) = 0; /* box_glue_stretch align_record_span_ptr */
+ box_h_offset (n) = 0; /* box_glue_shrink align_record_extra_info */
+ box_d_offset (n) = 0; /* box_span_count */
+ box_x_offset (n) = 0; /* align_record_u_part */
+ box_y_offset (n) = 0; /* align_record_v_part */
+ /* box_geometry (n) = 0; */ /* box_size */
+ box_orientation(n) = 0; /* box_size */
}
/*tex
@@ -771,14 +772,25 @@ static void tex_aux_scan_align_spec(quarterword c)
}
break;
case 'c':
- /* We permits multiple callbacks so we |or| them. */
- if (tex_scan_mandate_keyword("callback", 1)) {
- options |= align_option_callback;
- if (tex_scan_character("s", 0, 0, 0)) {
- callback |= tex_scan_integer(0, NULL, NULL);
- } else {
- callback = tex_scan_integer(0, NULL, NULL);
- }
+ switch (tex_scan_character("ao", 0, 0, 0)) {
+ case 'a':
+ if (tex_scan_mandate_keyword("callback", 2)) {
+ options |= align_option_callback;
+ if (tex_scan_character("s", 0, 0, 0)) {
+ callback |= tex_scan_integer(0, NULL, NULL);
+ } else {
+ callback = tex_scan_integer(0, NULL, NULL);
+ }
+ }
+ break;
+ case 'o':
+ if (tex_scan_mandate_keyword("combine", 2)) {
+ options |= align_option_combine_size;
+ }
+ break;
+ default:
+ tex_aux_show_keyword_error("callback|combine");
+ goto DONE;
}
break;
case 'd':
@@ -951,9 +963,7 @@ static void tex_aux_align_peek(void);
static void tex_aux_trace_no_align(const char *s)
{
if (tracing_alignments_par > 0) {
- tex_begin_diagnostic();
- tex_print_format("%l[alignment: %s noalign, level %i]", s, lmt_alignment_state.no_align_level);
- tex_end_diagnostic();
+ tex_print_format("%<%l[alignment: %s noalign, level %i]%>", s, lmt_alignment_state.no_align_level);
}
}
@@ -1702,6 +1712,17 @@ static int tex_aux_finish_column(void)
if (state) {
size = box_size(lmt_alignment_state.cur_align);
packing = packing_exactly;
+
+if (lmt_alignment_state.options & align_option_combine_size) {
+ if (lmt_alignment_state.cur_span != lmt_alignment_state.cur_align) {
+ halfword ptr = lmt_alignment_state.cur_span;
+ do {
+ ptr = node_next(node_next(ptr));
+ size += box_size(ptr);
+ } while (ptr != lmt_alignment_state.cur_align);
+ }
+}
+
}
if (cur_list.mode == restricted_hmode) {
lmt_packaging_state.post_adjust_tail = lmt_alignment_state.cur_post_adjust_tail;
@@ -2129,7 +2150,7 @@ static void tex_aux_prune_align_two(void)
*/
typedef struct alignment_split_state {
- halfword glueamount;
+ scaled glueamount;
int glueused;
halfword penalty;
halfword padding;
@@ -2398,7 +2419,7 @@ static void tex_aux_split_align(void)
int maxlines = tex_aux_get_maxlines(&state, rowptr);
if (maxlines > 1) {
halfword curptr = rowptr;
- halfword amount = 0;
+ scaled amount = 0;
halfword prvptr = node_prev(rowptr);
if (prvptr && node_type(prvptr) == glue_node) {
switch (node_subtype(prvptr)) {
@@ -2485,7 +2506,7 @@ static void tex_aux_finish_align(void)
halfword reverse = lmt_alignment_state.options & align_option_reverse;
halfword callback = lmt_alignment_state.options & align_option_callback;
halfword discard = normalize_line_mode_option(discard_zero_tab_skips_mode) || (lmt_alignment_state.options & align_option_discard);
- halfword amount = 0;
+ scaled amount = 0;
halfword mode = 0;
/*tex The |align_group| was for individual entries: */
if (cur_group != align_group) {
@@ -2582,7 +2603,7 @@ static void tex_aux_finish_align(void)
|r|, according as |link(r) = n| or |link(r) > n| or |link(r) < n|.
*/
- halfword t = box_width(q) + glue_amount(node_next(q));
+ scaled t = box_width(q) + glue_amount(node_next(q));
halfword n = 1;
halfword r = align_record_span_ptr(q);
halfword s = end_span;
diff --git a/source/luametatex/source/tex/texarithmetic.c b/source/luametatex/source/tex/texarithmetic.c
index a4130018b..8e347798b 100644
--- a/source/luametatex/source/tex/texarithmetic.c
+++ b/source/luametatex/source/tex/texarithmetic.c
@@ -222,17 +222,45 @@ static inline scaled tex_aux_checked_scaledround(double value, scaled lo, scaled
}
}
-scaled tex_round_xn_over_d(scaled x, int n, unsigned int d)
-{
- if (d == 0) {
- lmt_scanner_state.arithmetic_error = 1;
- return 0;
- } else if (x == 0 || (n >= 0 && (unsigned int) n == d && x >= min_dimension && x <= max_dimension)) {
- return x;
- } else {
- return tex_aux_checked_scaledround((1.0 / d) * n * x, min_dimension, max_dimension);
+# if lmt_float_math
+
+ scaled tex_round_xn_over_d(scaled x, int n, unsigned int d)
+ {
+ if (d == 0) {
+ lmt_scanner_state.arithmetic_error = 1;
+ return 0;
+ } else if (x == 0 || (n >= 0 && (unsigned int) n == d && x >= min_dimension && x <= max_dimension)) {
+ return x;
+ } else {
+ return tex_aux_checked_scaledround((1.0 / d) * n * x, min_dimension, max_dimension);
+ }
}
-}
+
+# else
+
+ scaled tex_round_xn_over_d(scaled x, int n, unsigned int d)
+ {
+ if (d == 0) {
+ lmt_scanner_state.arithmetic_error = 1;
+ return 0;
+ }
+ if (x == 0 || (n >= 0 && (unsigned int) n == d && x >= min_dimension && x <= max_dimension)) {
+ return x;
+ }
+ /* 64-bit widening allows exact integer multiplication without overflow */
+ long long prod = (long long) x * (long long) n;
+ long long half = (long long) d / 2;
+ /* Symmetric rounding matching TeX's exact rounding convention */
+ long long q = (prod >= 0) ? (prod + half) / (long long) d
+ : (prod - half) / (long long) d;
+ if (q < (long long) min_dimension || q > (long long) max_dimension) {
+ lmt_scanner_state.arithmetic_error = 1;
+ return 0;
+ }
+ return (scaled) q;
+ }
+
+# endif
/*tex
@@ -280,3 +308,25 @@ scaled tex_nx_plus_y_posit(halfword p, scaled x, scaled y)
}
}
}
+
+scaled tex_divide_scaled_factor(scaled sd, scaled md)
+{
+ if (md == 0) {
+ lmt_scanner_state.arithmetic_error = 1;
+ return 0;
+ }
+ if (sd == 0) {
+ return 0;
+ }
+ /* Multiply by 1000 in 64-bit space to prevent overflow */
+ long long num = (long long) sd * 1000LL;
+ long long half = (long long) md / 2LL;
+ /* Symmetric round-to-nearest integer division */
+ long long res = (num >= 0) ? (num + half) / (long long) md
+ : (num - half) / (long long) md;
+ if (res < (long long) min_integer || res > (long long) max_integer) {
+ lmt_scanner_state.arithmetic_error = 1;
+ return 0;
+ }
+ return (scaled) res;
+}
diff --git a/source/luametatex/source/tex/texarithmetic.h b/source/luametatex/source/tex/texarithmetic.h
index b1d2d1cc3..aff679859 100644
--- a/source/luametatex/source/tex/texarithmetic.h
+++ b/source/luametatex/source/tex/texarithmetic.h
@@ -13,21 +13,22 @@
*/
-extern scaled tex_multiply_and_add (int n, scaled x, scaled y, scaled max_answer);
-extern scaled tex_nx_plus_y (int n, scaled x, scaled y);
-extern scaled tex_multiply_integers (int n, scaled x);
-extern scaled tex_x_over_n_r (scaled x, int n, int *remainder); /* used once */
-extern scaled tex_x_over_n (scaled x, int n); /* used a few times, maybe use scaledround instead to prevent wrap around */
-extern scaled tex_x_over_n_unity (scaled x); /* not used */
-extern scaled tex_x_over_n_factor (scaled x); /* rarely used */
-extern scaled tex_xn_over_d_r (scaled x, int n, int d, int *remainder); /* seldom kicks in */
-/* scaled tex_xn_over_d (scaled x, int n, int d); */ /* inlined */
-/* scaled tex_xn_over_d_unity (scaled x, int n); */ /* inlined */
-/* scaled tex_xn_over_d_factor (scaled x, int n); */ /* inlined */
-/* scaled tex_divide_scaled (scaled s, scaled m, int dd); */ /* inlined */
-extern scaled tex_divide_scaled_n (double s, double m, double d);
-extern scaled tex_ext_xn_over_d (scaled x, scaled n, scaled d);
-extern scaled tex_round_xn_over_d (scaled x, int n, unsigned int d);
+extern scaled tex_multiply_and_add (int n, scaled x, scaled y, scaled max_answer);
+extern scaled tex_nx_plus_y (int n, scaled x, scaled y);
+extern scaled tex_multiply_integers (int n, scaled x);
+extern scaled tex_x_over_n_r (scaled x, int n, int *remainder); /* used once */
+extern scaled tex_x_over_n (scaled x, int n); /* used a few times, maybe use scaledround instead to prevent wrap around */
+extern scaled tex_x_over_n_unity (scaled x); /* not used */
+extern scaled tex_x_over_n_factor (scaled x); /* rarely used */
+extern scaled tex_xn_over_d_r (scaled x, int n, int d, int *remainder); /* seldom kicks in */
+/* scaled tex_xn_over_d (scaled x, int n, int d); */ /* inlined */
+/* scaled tex_xn_over_d_unity (scaled x, int n); */ /* inlined */
+/* scaled tex_xn_over_d_factor (scaled x, int n); */ /* inlined */
+/* scaled tex_divide_scaled (scaled s, scaled m, int dd); */ /* inlined */
+extern scaled tex_divide_scaled_n (double s, double m, double d);
+extern scaled tex_ext_xn_over_d (scaled x, scaled n, scaled d);
+extern scaled tex_round_xn_over_d (scaled x, int n, unsigned int d);
+extern scaled tex_divide_scaled_factor(scaled sd, scaled md);
static inline scaled tex_round_decimals_digits(const unsigned char *digits, unsigned k)
{
@@ -85,4 +86,15 @@ static inline scaled tex_xn_over_d_factor(scaled x, int n)
}
}
+/* Pure 64-bit integer: exact rounding, zero overflow, no floats */
+
+static inline scaled tex_xn_over_1000(scaled x, scaled n)
+{
+ if (! x || ! n) {
+ return 0;
+ }
+ long long prod = (long long) x * (long long) n;
+ return (scaled) ((prod >= 0) ? (prod + 500LL) / 1000LL
+ : (prod - 500LL) / 1000LL);
+}
# endif
diff --git a/source/luametatex/source/tex/texbalance.c b/source/luametatex/source/tex/texbalance.c
index 87b152f7c..05261d76e 100644
--- a/source/luametatex/source/tex/texbalance.c
+++ b/source/luametatex/source/tex/texbalance.c
@@ -423,7 +423,7 @@ static inline halfword tex_normalized_tight_badness(halfword b, halfword fitness
static void tex_aux_set_quality(halfword active, halfword passive, scaled shrt, scaled glue, scaled height, halfword badness)
{
halfword quality = 0;
- halfword deficiency = 0;
+ scaled deficiency = 0;
active_short(active) = shrt;
active_glue(active) = glue;
active_page_height(active) = height;
@@ -447,7 +447,7 @@ static void tex_aux_set_quality(halfword active, halfword passive, scaled shrt,
active_deficiency(active) = deficiency;
}
-static void tex_check_skips_shortfall(const balance_properties *properties, halfword breakpoint, halfword first, halfword current, halfword page_topskip, halfword page_bottomskip, halfword *shortfall, halfword *stretch, halfword *shrink, halfword options)
+static void tex_check_skips_shortfall(const balance_properties *properties, halfword breakpoint, halfword first, halfword current, halfword page_topskip, halfword page_bottomskip, scaled *shortfall, scaled *stretch, scaled *shrink, halfword options)
{
halfword left = active_break_node(breakpoint) ? passive_cur_break(active_break_node(breakpoint)) : first; /* nasty */
scaled top = 0;
@@ -529,9 +529,7 @@ static void tex_check_skips_shortfall(const balance_properties *properties, half
*shortfall -= e;
}
if ((top || bottom) && properties->tracing_balancing > 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[balance: correction, top %p, bottom %p]", top, bottom);
- tex_end_diagnostic();
+ tex_print_format("%<%l[balance: correction, top %p, bottom %p]%>", top, bottom);
}
if (lmt_balance_state.inserts_found) {
*shortfall -= tex_insert_distances(left, current ? node_next(current) : null, stretch, shrink);
@@ -834,15 +832,13 @@ static scaled tex_aux_try_balance(
artificial_demerits = 0;
shortfall = page_height - current_active_height[total_advance_amount];
if (properties->tracing_balancing > 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[balance: check, page %i, height %p, total %p, extra %p, shortfall %p]",
+ tex_print_format("%<%l[balance: check, page %i, height %p, total %p, extra %p, shortfall %p]%>",
page,
page_height,
lmt_balance_state.active_height[total_advance_amount],
extra,
shortfall
);
- tex_end_diagnostic();
}
shortfall -= extra;
tex_check_skips_shortfall(properties, current, first_p, cur_p, page_topskip, page_bottomskip, &shortfall, &stretch, &shrink, options);
@@ -1109,11 +1105,11 @@ static int tex_aux_set_sub_pass_parameters(
halfword first,
int details,
halfword features,
- halfword overfull,
- halfword underfull,
+ scaled overfull,
+ scaled underfull,
halfword verdict,
halfword classified,
- halfword threshold,
+ scaled threshold,
halfword demerits,
halfword classes
) {
@@ -1147,7 +1143,7 @@ static int tex_aux_set_sub_pass_parameters(
}
/* */
if (okay & passes_emergencystretch_okay) {
- halfword v = tex_get_balance_passes_emergencystretch(passes, subpass);
+ scaled v = tex_get_balance_passes_emergencystretch(passes, subpass);
if (v) {
properties->emergency_stretch = v;
properties->original_stretch = v; /* ! */
@@ -1167,7 +1163,7 @@ static int tex_aux_set_sub_pass_parameters(
lmt_balance_state.background[total_stretch_amount] += properties->emergency_stretch;
/* */
if (okay & passes_emergencyshrink_okay) {
- halfword v = tex_get_balance_passes_emergencyshrink(passes, subpass);
+ scaled v = tex_get_balance_passes_emergencyshrink(passes, subpass);
if (v) {
properties->emergency_shrink = v;
properties->original_shrink = v; /* ! */
@@ -1245,11 +1241,9 @@ static int tex_aux_set_sub_pass_parameters(
static void tex_aux_skip_message(halfword passes, int subpass, int nofsubpasses, const char *str)
{
- tex_begin_diagnostic();
- tex_print_format("%l[balance: id %i, subpass %i of %i, skip %s]\n",
+ tex_print_format("%<%l[balance: id %i, subpass %i of %i, skip %s]\n%>",
passes_identifier(passes), subpass, nofsubpasses, str
);
- tex_end_diagnostic();
}
static inline int tex_aux_next_subpass(const balance_properties *properties, halfword passes, int subpass, int nofsubpasses, int tracing)
@@ -1297,11 +1291,9 @@ static inline int tex_aux_check_sub_pass(balance_properties *properties, scaled
int result = tex_check_balance_quality(shortfall, &overfull, &underfull, &verdict, &classified);
if (result) {
if (tracing && result > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[balance: id %i, subpass %i of %i, overfull %p, verdict %i, special case, entering subpasses]\n",
+ tex_print_format("%<%l[balance: id %i, subpass %i of %i, overfull %p, verdict %i, special case, entering subpasses]\n%>",
passes_identifier(passes), subpass, nofsubpasses, overfull, verdict
);
- tex_end_diagnostic();
}
while (subpass < nofsubpasses) {
subpass = tex_aux_next_subpass(properties, passes, subpass, nofsubpasses, tracing);
@@ -1381,8 +1373,7 @@ static inline int tex_aux_check_sub_pass(balance_properties *properties, scaled
static void tex_aux_trace_list(halfword current, int line, const char *action)
{
- tex_begin_diagnostic();
- tex_print_format("%l[balance: list, slot %i, line %i, height %p, depth %p, total %p, %s]",
+ tex_print_format("%<%l[balance: list, slot %i, line %i, height %p, depth %p, total %p, %s]%>",
lmt_balance_state.current_slot_number,
line,
box_height(current),
@@ -1390,13 +1381,11 @@ static void tex_aux_trace_list(halfword current, int line, const char *action)
lmt_balance_state.active_height[total_advance_amount],
action
);
- tex_end_diagnostic();
}
static void tex_aux_trace_rule(halfword current, int line, const char *action)
{
- tex_begin_diagnostic();
- tex_print_format("%l[balance: list, slot %i, line %i, height %p, depth %p, total %p, %s]",
+ tex_print_format("%<%l[balance: list, slot %i, line %i, height %p, depth %p, total %p, %s]%>",
lmt_balance_state.current_slot_number,
line,
rule_height(current),
@@ -1404,43 +1393,36 @@ static void tex_aux_trace_rule(halfword current, int line, const char *action)
lmt_balance_state.active_height[total_advance_amount],
action
);
- tex_end_diagnostic();
}
static void tex_aux_trace_glue(halfword current, const char *action)
{
- tex_begin_diagnostic();
- tex_print_format("%l[balance: glue, slot %i, amount %p, total %p, %s]",
+ tex_print_format("%<%l[balance: glue, slot %i, amount %p, total %p, %s]%>",
lmt_balance_state.current_slot_number,
glue_amount(current),
lmt_balance_state.active_height[total_advance_amount],
action
);
- tex_end_diagnostic();
}
static void tex_aux_trace_kern(halfword current, const char *action)
{
- tex_begin_diagnostic();
- tex_print_format("%l[balance: kern, slot %i, amount %p, total %p, %s]",
+ tex_print_format("%<%l[balance: kern, slot %i, amount %p, total %p, %s]%>",
lmt_balance_state.current_slot_number,
kern_amount(current),
lmt_balance_state.active_height[total_advance_amount],
action
);
- tex_end_diagnostic();
}
static void tex_aux_trace_penalty(halfword current, const char *action)
{
- tex_begin_diagnostic();
- tex_print_format("%l[balance: penalty, slot %i, amount %i, total %p, %s]",
+ tex_print_format("%<%l[balance: penalty, slot %i, amount %i, total %p, %s]%>",
lmt_balance_state.current_slot_number,
node_type(current) == penalty_node ? penalty_amount(current) : glue_penalty(current),
lmt_balance_state.active_height[total_advance_amount],
action
);
- tex_end_diagnostic();
}
// halfword tex_get_balance_currentheight(void)
@@ -1878,9 +1860,7 @@ void tex_balance(balance_properties *properties, halfword head)
lmt_balance_state.threshold = properties->pretolerance; /* or tolerance */
if (properties->tracing_balancing > 0 || properties->tracing_passes > 0) {
if (specification_presets(passes)) {
- tex_begin_diagnostic();
- tex_print_format("%l[balance: specification presets]");
- tex_end_diagnostic();
+ tex_print_format("%<%l[balance: specification presets]%>");
}
}
if (specification_presets(passes)) {
@@ -2099,9 +2079,9 @@ static void tex_aux_pre_balance(const balance_properties *properties, int callba
static void tex_vbalanced_process_insert(halfword insert, double factor)
{
- halfword height = tex_insert_height(insert);
- halfword stretch = insert_stretch(insert);
- halfword shrink = insert_shrink(insert);
+ scaled height = tex_insert_height(insert);
+ scaled stretch = insert_stretch(insert);
+ scaled shrink = insert_shrink(insert);
if (height > 0 && (stretch || shrink)) {
scaled amount = 0;
halfword callback = insert_callback(insert);
@@ -2113,7 +2093,7 @@ static void tex_vbalanced_process_insert(halfword insert, double factor)
amount = scaledround(factor * shrink);
}
if (callback) {
- /*tex Beware: is we have a split insert we callback each. */
+ /*tex Beware: if we have a split insert we callback each. */
halfword result = lmt_uinsert_callback(callback, insert_index(insert), insert_belongs_to(insert), packed, height, amount);
if (result) {
packed = result;
@@ -2986,7 +2966,7 @@ void tex_vbalanced_deinsert(
/* todo: multiplier, so a better set height */
if (last && node_subtype(head) == baseline_skip_glue) {
if (forcedepth) {
- halfword depth = insert_line_depth(last);
+ scaled depth = insert_line_depth(last);
if (depth > 0) {
halfword list = insert_list(last);
switch (node_type(list)) {
diff --git a/source/luametatex/source/tex/texbuildpage.c b/source/luametatex/source/tex/texbuildpage.c
index 5bc5cb32e..8b70c07b4 100644
--- a/source/luametatex/source/tex/texbuildpage.c
+++ b/source/luametatex/source/tex/texbuildpage.c
@@ -257,16 +257,14 @@ static void tex_aux_freeze_page_specs(int s)
page_total += glue_amount(additional_page_skip_par);
update_tex_additional_page_skip(null);
}
- if (tracing_pages_par > 0) {
- tex_begin_diagnostic();
+ if lmt_unlikely(tracing_pages_par > 0) {
tex_print_format(
- "%l[page: frozen state, goal %p, maxdepth %p, contribution %s, insertheights %p]",
+ "%<%l[page: frozen state, goal %p, maxdepth %p, contribution %s, insertheights %p]%>",
page_goal,
lmt_page_builder_state.max_depth,
lmt_interface.page_contribute_values[s].name,
lmt_page_builder_state.insert_heights
);
- tex_end_diagnostic();
}
}
@@ -279,13 +277,11 @@ static void update_page_goal(const char *where, halfword index, scaled total, sc
lmt_page_builder_state.insert_heights = max_dimension;
}
}
- if (tracing_inserts_par > 0) {
- tex_begin_diagnostic();
+ if lmt_unlikely(tracing_inserts_par > 0) {
tex_print_format(
- "%l[page: insert %s, index %i, total %p, insertheights %p, vsize %p, delta %p, goal %p]",
+ "%<%l[page: insert %s, index %i, total %p, insertheights %p, vsize %p, delta %p, goal %p]%>",
where, index, total, lmt_page_builder_state.insert_heights, page_vsize, delta, page_goal
);
- tex_end_diagnostic();
}
}
@@ -329,7 +325,7 @@ static void tex_aux_start_new_page(void)
static halfword tex_aux_delete_box_content(int n, const char *what, int where)
{
- if (tracing_pages_par > 0) {
+ if lmt_unlikely(tracing_pages_par > 0) {
tex_begin_diagnostic();
tex_print_format("%l[page: deleting %s box, case %i]", what, where);
tex_show_box(n);
@@ -375,24 +371,20 @@ static int tex_aux_valid_insert_content(halfword content)
static void tex_aux_display_page_break_cost(int context, halfword badness, halfword penalty, halfword cost, int moveon, int fireup)
{
- tex_begin_diagnostic();
- tex_print_format("%l[page: break at %s, total %P, goal %p, badness %B, penalty %i, cost %B%s, moveon %s, fireup %s]",
+ tex_print_format("%<%l[page: break at %s, total %P, goal %p, badness %B, penalty %i, cost %B%s, moveon %s, fireup %s]%>",
lmt_interface.page_context_values[context].name,
page_total, page_stretch, page_fistretch, page_filstretch, page_fillstretch, page_filllstretch, page_shrink,
page_goal, badness, penalty, cost, cost < lmt_page_builder_state.least_cost ? "#" : "",
moveon ? "yes" : "no", fireup ? "yes" : "no"
);
- tex_end_diagnostic();
}
static void tex_aux_display_insertion_split_cost(halfword index, scaled height, scaled best, halfword penalty)
{
/*tex Display the insertion split cost. */
- tex_begin_diagnostic();
- tex_print_format("%l[page: split insert %i: height %p, best htdp %p, penalty %i]",
+ tex_print_format("%<%l[page: split insert %i: height %p, best htdp %p, penalty %i]%>",
index, height, best, penalty
);
- tex_end_diagnostic();
}
static halfword tex_aux_page_badness(scaled goal)
@@ -425,7 +417,7 @@ static inline halfword tex_aux_page_costs(halfword badness, halfword penalty)
}
}
-static halfword tex_aux_insert_topskip(halfword height, int contribution)
+static halfword tex_aux_insert_topskip(scaled height, int contribution)
{
if (lmt_page_builder_state.contents != contribute_nothing) {
lmt_page_builder_state.contents = contribution;
@@ -540,11 +532,9 @@ static void tex_aux_append_insert(halfword current)
"made finite."
);
}
- if (tracing_inserts_par > 0) {
+ if lmt_unlikely(tracing_inserts_par > 0) {
// %P : total, stretch, fistretch, filstretch, fillstretch, filllstretch, shrink
- tex_begin_diagnostic();
- tex_print_format("%l[inserts: index %i, first %i, top %i, distance %p]", index, first, top, glue_amount(distance));
- tex_end_diagnostic();
+ tex_print_format("%<%l[inserts: index %i, first %i, top %i, distance %p]%>", index, first, top, glue_amount(distance));
}
}
tex_flush_node(distance);
@@ -566,7 +556,8 @@ static void tex_aux_append_insert(halfword current)
/*tex This much room is needed. */
/* needed = needed * multiplier / scaling_factor; */ /* can overflow */
/* needed = scaledround(needed * multiplier / scaling_factor_double); */
- needed = tex_x_over_n_factor(needed) * multiplier;
+ /* needed = tex_x_over_n_factor(needed) * multiplier; */
+ needed = tex_xn_over_1000(needed, multiplier);
}
/*tex Somehow with multiple notes we overflow. */
if ((needed <= 0 || needed <= delta) && (insert_total_height(current) + box_height(location) <= limit)) {
@@ -620,10 +611,8 @@ static void tex_aux_append_insert(halfword current)
*/
if (tex_aux_catch_insert_overflow()) {
if (height < 0) {
- if (tracing_inserts_par > 0) {
- tex_begin_diagnostic();
- tex_print_format("%l[page: insert overflow, index %i, prepend dummy, case %i]", index, 1);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_inserts_par > 0) {
+ tex_print_format("%<%l[page: insert overflow, index %i, prepend dummy, case %i]%>", index, 1);
}
tex_insert_prepend_dummy(current);
height = 0;
@@ -639,10 +628,8 @@ static void tex_aux_append_insert(halfword current)
*/
if (tex_aux_catch_insert_overflow()) {
if (best_height_plus_depth > height) {
- if (tracing_inserts_par > 0) {
- tex_begin_diagnostic();
- tex_print_format("%l[page: insert overflow, index %i, prepend dummy, case %i]", index, 2);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_inserts_par > 0) {
+ tex_print_format("%<%l[page: insert overflow, index %i, prepend dummy, case %i]%>", index, 2);
}
tex_insert_prepend_dummy(current);
height = 0;
@@ -652,13 +639,14 @@ static void tex_aux_append_insert(halfword current)
/* */
box_height(location) += best_height_plus_depth;
penalty = breaknode ? (node_type(breaknode) == penalty_node ? penalty_amount(breaknode) : 0) : eject_penalty;
- if (tracing_pages_par > 0) {
+ if lmt_unlikely(tracing_pages_par > 0) {
tex_aux_display_insertion_split_cost(index, height, best_height_plus_depth, penalty);
}
if (multiplier != scaling_factor) {
// best_height_plus_depth = tex_x_over_n_factor(best_height_plus_depth) * multiplier;
// best_height_plus_depth = scaledround(best_height_plus_depth * multiplier / scaling_factor_double)
- best_height_plus_depth = best_height_plus_depth * multiplier / scaling_factor;
+ // best_height_plus_depth = best_height_plus_depth * multiplier / scaling_factor; */
+ best_height_plus_depth = tex_xn_over_1000(best_height_plus_depth, multiplier);
}
/*tex No need to update when no room or ignore. */
update_page_goal("split", index, best_height_plus_depth, best_height_plus_depth);
@@ -681,17 +669,13 @@ static inline int tex_aux_get_penalty_option(halfword current)
case penalty_node:
if (penalty_amount(current) >= infinite_penalty) {
if (tex_has_penalty_option(current, penalty_option_widowed)) {
- if (tracing_pages_par > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[page: widowed]");
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_pages_par > 1) {
+ tex_print_format("%<%l[page: widowed]%>");
}
return penalty_option_widowed;
} else if (tex_has_penalty_option(current, penalty_option_clubbed)) {
- if (tracing_pages_par > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[page: clubbed]");
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_pages_par > 1) {
+ tex_print_format("%<%l[page: clubbed]%>");
}
return penalty_option_clubbed;
}
@@ -791,10 +775,8 @@ static int tex_aux_topskip_restart(halfword current, int where, scaled height, s
tex_attach_attribute_list_copy(gluenode, current);
tex_couple_nodes(gluenode, current);
tex_couple_nodes(contribute_head, gluenode);
- if (tracing > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[page: initialize, topskip at %s]", where == contribute_box ? "box" : "rule");
- tex_end_diagnostic();
+ if lmt_unlikely(tracing > 1) {
+ tex_print_format("%<%l[page: initialize, topskip at %s]%>", where == contribute_box ? "box" : "rule");
}
}
return 1;
@@ -820,7 +802,7 @@ static int tex_aux_migrating_restart(halfword current, int tracing)
halfword head = box_post_migrated(current);
if (head) {
halfword tail = tex_tail_of_node_list(head);
- if (tracing > 1 || tracing_adjusts_par > 1) {
+ if lmt_unlikely(tracing > 1 || tracing_adjusts_par > 1) {
tex_begin_diagnostic();
tex_print_format("%l[adjust: post, mvl]");
tex_print_node_list(head, "post", show_box_depth_par, show_box_breadth_par);
@@ -839,7 +821,7 @@ static int tex_aux_migrating_restart(halfword current, int tracing)
halfword head = box_pre_migrated(current);
if (head) {
halfword tail = tex_tail_of_node_list(head);
- if (tracing > 1 || tracing_adjusts_par > 1) {
+ if lmt_unlikely(tracing > 1 || tracing_adjusts_par > 1) {
tex_begin_diagnostic();
tex_print_format("%l[adjust: pre, mvl]");
tex_print_node_list(head, "pre", show_box_depth_par, show_box_breadth_par);
@@ -926,25 +908,21 @@ static void tex_aux_reconsider_goal(halfword current, halfword *badness, halfwor
if (page_total <= (page_goal + page_extra_goal_par)) {
halfword extrabadness = tex_aux_page_badness(page_goal + page_extra_goal_par);
halfword extracosts = tex_aux_page_costs(extrabadness, *penalty);
- if (tracing > 0) {
- tex_begin_diagnostic();
+ if lmt_unlikely(tracing > 0) {
tex_print_format(
- "%l[page: extra check, total %P, goal %p, extragoal %p, badness %B, costs %i, extrabadness %B, extracosts %i]",
+ "%<%l[page: extra check, total %P, goal %p, extragoal %p, badness %B, costs %i, extrabadness %B, extracosts %i]%>",
page_total, page_stretch, page_fistretch, page_filstretch, page_fillstretch, page_filllstretch, page_shrink,
page_goal, page_extra_goal_par,
*badness, *costs, extrabadness, extracosts
);
- tex_end_diagnostic();
}
/* we need to append etc. so an extra loop cycle */
*badness = extrabadness;
*costs = extracosts;
/* */
lmt_page_builder_state.last_extra_used = 1;
- if (tracing > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[page: widowed]");
- tex_end_diagnostic();
+ if lmt_unlikely(tracing > 1) {
+ tex_print_format("%<%l[page: widowed]%>");
}
}
break;
@@ -953,10 +931,8 @@ static void tex_aux_reconsider_goal(halfword current, halfword *badness, halfwor
/* we force a flush and no extra loop cycle */
*penalty = eject_penalty;
/* */
- if (tracing > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[page: clubbed]");
- tex_end_diagnostic();
+ if lmt_unlikely(tracing > 1) {
+ tex_print_format("%<%l[page: clubbed]%>");
}
}
break;
@@ -1178,10 +1154,8 @@ static void tex_process_mvl(halfword context, halfword boundary)
prepare for output, and either fire up the users output routine and |return| or
ship out the page and |goto done|.
*/
- if (tracing > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[page: compute: %N, %d, penalty %i]", current, current, penalty);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing > 1) {
+ tex_print_format("%<%l[page: compute: %N, %d, penalty %i]%>", current, current, penalty);
}
if (penalty < infinite_penalty) {
/*tex
@@ -1191,15 +1165,13 @@ static void tex_process_mvl(halfword context, halfword boundary)
halfword badness = tex_aux_page_badness(page_goal);
halfword costs = tex_aux_page_costs(badness, penalty);
lmt_page_builder_state.last_extra_used = 0;
- if (tracing > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[page: calculate, %N, %d, total %P, goal %p, badness %B, costs %i]",
+ if lmt_unlikely(tracing > 1) {
+ tex_print_format("%<%l[page: calculate, %N, %d, total %P, goal %p, badness %B, costs %i]%>",
current, current,
page_total, page_stretch, page_fistretch, page_filstretch, page_fillstretch, page_filllstretch, page_shrink,
page_goal,
badness, costs
);
- tex_end_diagnostic();
}
tex_aux_reconsider_goal(current, &badness, &costs, &penalty, tracing);
{
@@ -1209,7 +1181,7 @@ static void tex_process_mvl(halfword context, halfword boundary)
tex_aux_check_show_build_node(callback_id, current, badness, costs, penalty, &moveon, &fireup);
}
- if (tracing > 0) {
+ if lmt_unlikely(tracing > 0) {
tex_aux_display_page_break_cost(context, badness, penalty, costs, moveon, fireup);
}
if (moveon) {
@@ -1229,10 +1201,8 @@ static void tex_process_mvl(halfword context, halfword boundary)
}
}
if (fireup) {
- if (tracing > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[page: fireup: %N, %d]", current, current);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing > 1) {
+ tex_print_format("%<%l[page: fireup: %N, %d]%>", current, current);
}
if (callback_id > 0) {
tex_aux_fireup_show_build_node(callback_id, current);
@@ -1261,10 +1231,8 @@ static void tex_process_mvl(halfword context, halfword boundary)
Go here to record glue in the |active_height| table. Update the current page
measurements with respect to the glue or kern specified by node~|p|.
*/
- if (tracing > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[page: update, %N, %d]", current, current);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing > 1) {
+ tex_print_format("%<%l[page: update, %N, %d]%>", current, current);
}
switch(node_type(current)) {
case kern_node:
@@ -1295,20 +1263,16 @@ static void tex_process_mvl(halfword context, halfword boundary)
Go here to link a node into the current page. Make sure that |page_max_depth| is
not exceeded.
*/
- if (tracing > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[page: contribute, %N, %d]", current, current);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing > 1) {
+ tex_print_format("%<%l[page: contribute, %N, %d]%>", current, current);
}
if (page_depth > lmt_page_builder_state.max_depth) {
page_total += page_depth - lmt_page_builder_state.max_depth;
page_depth = lmt_page_builder_state.max_depth;
}
APPEND:
- if (tracing > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[page: append, %N, %d]", current, current);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing > 1) {
+ tex_print_format("%<%l[page: append, %N, %d]%>", current, current);
}
/*tex Link node |p| into the current page and |goto done|. We assume a positive depth. */
tex_couple_nodes(lmt_page_builder_state.tail, current);
@@ -1317,10 +1281,8 @@ static void tex_process_mvl(halfword context, halfword boundary)
node_next(current) = null;
continue; // or: break;
DISCARD:
- if (tracing > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[page: discard, %N, %d]", current, current);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing > 1) {
+ tex_print_format("%<%l[page: discard, %N, %d]%>", current, current);
}
/*tex Recycle node |p|. */
tex_try_couple_nodes(contribute_head, node_next(current));
@@ -1524,9 +1486,7 @@ static void tex_aux_show_loners(void)
if (tex_has_penalty_option(lmt_page_builder_state.best_break, penalty_option_club )) { state[1] = 'C'; }
if (tex_has_penalty_option(lmt_page_builder_state.best_break, penalty_option_broken )) { state[2] = 'B'; }
if (tex_has_penalty_option(lmt_page_builder_state.best_break, penalty_option_shaping)) { state[3] = 'S'; }
- tex_begin_diagnostic();
- tex_print_format("%l[page: loner: %s penalty %i]", state, penalty);
- tex_end_diagnostic();
+ tex_print_format("%<%l[page: loner: %s penalty %i]%>", state, penalty);
}
}
}
@@ -1703,7 +1663,7 @@ static halfword tex_aux_assemble_output_box(void)
static void tex_aux_pack_output_box(void)
{
halfword save_vbadness = vbadness_par;
- halfword save_vfuzz = vfuzz_par;
+ scaled save_vfuzz = vfuzz_par;
vbadness_par = infinite_bad;
vfuzz_par = max_dimension;
tex_show_marks();
@@ -1736,7 +1696,7 @@ static void tex_aux_update_output_penalty()
{
if (node_type(lmt_page_builder_state.best_break) == penalty_node) {
update_tex_output_penalty(penalty_amount(lmt_page_builder_state.best_break));
- if (tracing_loners_par) {
+ if lmt_unlikely(tracing_loners_par) {
tex_aux_show_loners();
}
penalty_amount(lmt_page_builder_state.best_break) = infinite_penalty;
@@ -1816,7 +1776,7 @@ void tex_resume_after_output(void)
box_register(output_box_par) = tex_aux_delete_box_content(box_register(output_box_par), "output", 1);
}
if (lmt_insert_state.storing == insert_storage_delay && tex_insert_stored()) {
- if (tracing_inserts_par > 0) {
+ if lmt_unlikely(tracing_inserts_par > 0) {
tex_print_format(lmt_insert_state.head ? "%l<delaying inserts>" : "%l<no inserts to delay>");
if (lmt_insert_state.head && tracing_inserts_par > 1) {
tex_show_node_list(lmt_insert_state.head, max_integer, max_integer);
@@ -1853,7 +1813,7 @@ void tex_resume_after_output(void)
}
h = n;
}
- if (tracing_inserts_par > 0) {
+ if lmt_unlikely(tracing_inserts_par > 0) {
tex_print_format(lmt_insert_state.head ? "%l<storing inserts>" : "%l<no inserts to store>");
if (lmt_insert_state.head && tracing_inserts_par > 1) {
tex_show_node_list(lmt_insert_state.head, max_integer, max_integer);
diff --git a/source/luametatex/source/tex/texcommands.c b/source/luametatex/source/tex/texcommands.c
index f950bb437..0e9e45c3a 100644
--- a/source/luametatex/source/tex/texcommands.c
+++ b/source/luametatex/source/tex/texcommands.c
@@ -69,8 +69,7 @@ const unsigned char some_item_classification[] = {
[luametatex_major_version_code] = classification_no_arguments,
[luametatex_minor_version_code] = classification_no_arguments,
[luametatex_release_code] = classification_no_arguments,
- [luatex_version_code] = classification_no_arguments,
- [luatex_revision_code] = classification_no_arguments,
+ [luametatex_version_code] = classification_no_arguments,
[current_group_level_code] = classification_no_arguments,
[current_group_type_code] = classification_no_arguments,
[current_stack_size_code] = classification_no_arguments,
@@ -228,7 +227,7 @@ const unsigned char some_convert_classification[] = {
[font_specification_code] = classification_integer,
[job_name_code] = classification_no_arguments,
[format_name_code] = classification_no_arguments,
- [luatex_banner_code] = classification_no_arguments,
+ [luametatex_banner_code] = classification_no_arguments,
[font_identifier_code] = classification_integer,
};
@@ -1011,8 +1010,7 @@ void tex_initialize_commands(void)
tex_primitive(luametatex_command, no_legacy, "luametatexmajorversion", some_item_cmd, luametatex_major_version_code, 0);
tex_primitive(luametatex_command, no_legacy, "luametatexminorversion", some_item_cmd, luametatex_minor_version_code, 0);
tex_primitive(luametatex_command, no_legacy, "luametatexrelease", some_item_cmd, luametatex_release_code, 0);
- tex_primitive(luatex_command, no_legacy, "luatexrevision", some_item_cmd, luatex_revision_code, 0);
- tex_primitive(luatex_command, no_legacy, "luatexversion", some_item_cmd, luatex_version_code, 0);
+ tex_primitive(luametatex_command, no_legacy, "luametatexversion", some_item_cmd, luametatex_version_code, 0);
/* tex_primitive(luametatex_command, no_legacy, "luavaluefunction", some_item_cmd, lua_value_function_code, 0); */
tex_primitive(luametatex_command, no_legacy, "mathatomglue", some_item_cmd, math_atom_glue_code, 0);
tex_primitive(luametatex_command, no_legacy, "mathmainstyle", some_item_cmd, math_main_style_code, 0);
@@ -1079,7 +1077,7 @@ void tex_initialize_commands(void)
tex_primitive(luatex_command, no_legacy, "luabytecode", convert_cmd, lua_bytecode_code, 0);
tex_primitive(luatex_command, no_legacy, "luaescapestring", convert_cmd, lua_escape_string_code, 0);
tex_primitive(luatex_command, no_legacy, "luafunction", convert_cmd, lua_function_code, 0);
- tex_primitive(luatex_command, no_legacy, "luatexbanner", convert_cmd, luatex_banner_code, 0);
+ tex_primitive(luametatex_command, no_legacy, "luametatexbanner", convert_cmd, luametatex_banner_code, 0);
/* tex_primitive(luametatex_command, no_legacy, "luatokenstring", convert_cmd, lua_token_string_code, 0); */
tex_primitive(tex_command, no_legacy, "meaning", convert_cmd, meaning_code, 0);
tex_primitive(luametatex_command, no_legacy, "meaningasis", convert_cmd, meaning_asis_code, 0); /* for manuals and articles */
diff --git a/source/luametatex/source/tex/texcommands.h b/source/luametatex/source/tex/texcommands.h
index 160ff7282..3cd0ff53a 100644
--- a/source/luametatex/source/tex/texcommands.h
+++ b/source/luametatex/source/tex/texcommands.h
@@ -542,7 +542,7 @@ typedef enum convert_codes {
font_specification_code, /*tex command code for |\fontspecification| */
job_name_code, /*tex command code for |\jobname| */
format_name_code, /*tex command code for |\AlephVersion| */
- luatex_banner_code, /*tex command code for |\luatexbanner| */
+ luametatex_banner_code, /*tex command code for |\luametatexbanner| */
font_identifier_code, /*tex command code for |tex.fontidentifier| (virtual) */
} convert_codes;
@@ -592,8 +592,7 @@ typedef enum some_item_codes {
luametatex_major_version_code, /*tex |\luametatexversion| */
luametatex_minor_version_code, /*tex |\luametatexrevision| */
luametatex_release_code, /*tex |\luametatexrelease| */
- luatex_version_code, /*tex |\luatexversion| (old) */
- luatex_revision_code, /*tex |\luatexrevision| (old) */
+ luametatex_version_code, /*tex |\luametatexversion| */
current_group_level_code, /*tex |\currentgrouplevel| */
current_group_type_code, /*tex |\currentgrouptype| */
current_stack_size_code, /*tex |\currentstacksize| */
diff --git a/source/luametatex/source/tex/texconditional.c b/source/luametatex/source/tex/texconditional.c
index 6d5017efa..6db3294a8 100644
--- a/source/luametatex/source/tex/texconditional.c
+++ b/source/luametatex/source/tex/texconditional.c
@@ -174,9 +174,7 @@ static int tex_aux_pass_text_x(int tracing_ifs, int tracing_commands)
if (level == 0) {
int unless = cur_chr == or_unless_code;
if (tracing_commands > 1) {
- tex_begin_diagnostic();
- tex_print_format(unless ? "%l{orunless}" : "%l{orelse}");
- tex_end_diagnostic();
+ tex_print_format(unless ? "%<%l{orunless}%>" : "%<%l{orelse}%>");
} else if (tracing_ifs) {
tex_show_cmd_chr(cur_cmd, cur_chr);
}
@@ -243,10 +241,8 @@ static void tex_aux_if_warning(void)
lmt_input_state.in_stack[index].if_ptr = node_next(lmt_condition_state.cond_ptr);
--index;
}
- if (warning) {
- tex_begin_diagnostic();
- tex_print_format("%l[conditional: end of %C%L of a different file]", if_test_cmd, lmt_condition_state.state.cur_if, lmt_condition_state.state.if_line);
- tex_end_diagnostic();
+ if lmt_unlikely(warning) {
+ tex_print_format("%<%l[conditional: end of %C%L of a different file]%>", if_test_cmd, lmt_condition_state.state.cur_if, lmt_condition_state.state.if_line);
if (tracing_nesting_par > 1) {
tex_show_context();
}
@@ -280,10 +276,8 @@ static void tex_aux_if_warning(void)
lmt_input_state.in_stack[index].if_ptr = lmt_condition_state.cond_ptr - 1;
--index;
}
- if (warning) {
- tex_begin_diagnostic();
- tex_print_format("%l[conditional: end of %C%L of a different file]", if_test_cmd, lmt_condition_state.state.cur_if, lmt_condition_state.state.if_line);
- tex_end_diagnostic();
+ if lmt_unlikely(warning) {
+ tex_print_format("%<%l[conditional: end of %C%L of a different file]%>", if_test_cmd, lmt_condition_state.state.cur_if, lmt_condition_state.state.if_line);
if (tracing_nesting_par > 1) {
tex_show_context();
}
@@ -360,7 +354,7 @@ static void tex_aux_push_condition_stack(int code, int unless)
{
if (! lmt_condition_state.stack || lmt_condition_state.cond_ptr >= lmt_condition_state.stack_size - 1) {
int stack_size = lmt_condition_state.stack_size + lmt_condition_state.stack_step;
- if (lmt_condition_state.cond_ptr + 1 > lmt_condition_state.stack_max) {
+ if lmt_unlikely(lmt_condition_state.cond_ptr + 1 > lmt_condition_state.stack_max) {
tex_overflow_error("conditionals", lmt_condition_state.stack_max);
return;
}
@@ -369,7 +363,7 @@ static void tex_aux_push_condition_stack(int code, int unless)
}
{
condition_state *stack = lmt_memory_realloc(lmt_condition_state.stack, stack_size * sizeof(condition_state));
- if (! stack) {
+ if lmt_unlikely(! stack) {
tex_overflow_error("conditionals", stack_size);
return;
}
@@ -389,7 +383,7 @@ static void tex_aux_push_condition_stack(int code, int unless)
static void tex_aux_pop_condition_stack(void)
{
- if (lmt_condition_state.cond_ptr <= 0) {
+ if lmt_unlikely(lmt_condition_state.cond_ptr <= 0) {
tex_handle_error(normal_error_type,
"Extra %C%h",
if_test_cmd, cur_chr,
@@ -551,10 +545,7 @@ static void tex_aux_show_if_state(halfword code, halfword case_value)
if (code >= first_if_case_code && code <= last_if_case_code) {
name = if_state_names[code];
}
- tex_begin_diagnostic();
- tex_print_levels();
- tex_print_format("{%s %i}", name ? name : "userdefined", case_value);
- tex_end_diagnostic();
+ tex_print_format("%<%l{%s %i}%>", name ? name : "userdefined", case_value);
}
/*tex Why do we skip over relax? */
@@ -595,9 +586,8 @@ static inline halfword tex_aux_grab_toks(int expand, int expandlist, int *head)
p = eq_value(lmt_scanner_state.last_cs_name);
}
break;
- } else {
- /* fall through */
}
+ FALLTHROUGH
case call_cmd:
case protected_call_cmd:
case semi_protected_call_cmd:
@@ -876,7 +866,7 @@ void tex_conditional_if(halfword code, int unless)
int tracing_ifs = tracing_ifs_par > 0;
int tracing_commands = tracing_commands_par;
int tracing_both = tracing_ifs && (tracing_commands <= 1);
- if (tracing_both) {
+ if lmt_unlikely(tracing_both) {
tex_show_cmd_chr(cur_cmd, cur_chr);
}
tex_aux_push_condition_stack(code, unless);
@@ -1641,9 +1631,7 @@ void tex_conditional_if(halfword code, int unless)
/*tex This could be a helper as we do this a few more times. */
halfword online = tracing_online_par;
tracing_online_par = 1;
- tex_begin_diagnostic();
- tex_print_format("%lignoring \\unless in %C test", if_test_cmd, code);
- tex_end_diagnostic();
+ tex_print_format("%<%lignoring \\unless in %C test%>", if_test_cmd, code);
tracing_online_par = online;
}
CASEWITHUNLESS:
@@ -1686,11 +1674,9 @@ void tex_conditional_if(halfword code, int unless)
if (unless) {
result = ! result;
}
- if (tracing_commands > 1) {
+ if lmt_unlikely(tracing_commands > 1) {
/*tex Display the value of |b|. */
- tex_begin_diagnostic();
- tex_print_format(result ? "%l{true}" : "%l{false}");
- tex_end_diagnostic();
+ tex_print_format(result ? "%<%l{true}%>" : "%<%l{false}%>");
}
if (result) {
tex_aux_change_if_limit(else_code, save_cond_ptr);
@@ -1754,7 +1740,7 @@ void tex_conditional_fi_or_else(void)
if (tracing_ifs && tracing_commands_par <= 1) {
tex_show_cmd_chr(if_test_cmd, cur_chr);
}
- if (! lmt_condition_state.cond_ptr) {
+ if lmt_unlikely(! lmt_condition_state.cond_ptr) {
tex_handle_error(normal_error_type,
"Extra %C%h",
if_test_cmd, cur_chr,
@@ -2082,7 +2068,7 @@ void tex_initialize_conditionals(void)
if (! lmt_condition_state.stack) {
int stack_size = lmt_condition_state.stack_step;
condition_state *stack = lmt_memory_malloc(stack_size * sizeof(condition_state));
- if (stack) {
+ if lmt_likely(stack) {
lmt_condition_state.stack = stack;
lmt_condition_state.stack_size = stack_size;
} else {
diff --git a/source/luametatex/source/tex/texdiscretionaries.c b/source/luametatex/source/tex/texdiscretionaries.c
index 55f238976..ebee6b90e 100644
--- a/source/luametatex/source/tex/texdiscretionaries.c
+++ b/source/luametatex/source/tex/texdiscretionaries.c
@@ -416,9 +416,8 @@ void tex_finish_discretionary(void)
glue_shrink_order(next) = 0;
}
break;
- } else {
- // fall through
}
+ FALLTHROUGH
default:
if lmt_likely(hyphenation_permitted(hyphenation_mode_par, permit_all_hyphenation_mode)) {
break;
diff --git a/source/luametatex/source/tex/texdumpdata.c b/source/luametatex/source/tex/texdumpdata.c
index 3234e0dbb..5d5312d09 100644
--- a/source/luametatex/source/tex/texdumpdata.c
+++ b/source/luametatex/source/tex/texdumpdata.c
@@ -8,7 +8,7 @@ dump_state_info lmt_dump_state = {
.statistics = { 0 },
};
-const static char *dump_statistic_names[] = {
+static const char *dump_statistic_names[] = {
[dump_stat_fingerprint] = "fingerprint",
[dump_stat_engine] = "engine",
[dump_stat_preamble] = "preamble",
diff --git a/source/luametatex/source/tex/texdumpdata.h b/source/luametatex/source/tex/texdumpdata.h
index 9eaf35870..46ced79d1 100644
--- a/source/luametatex/source/tex/texdumpdata.h
+++ b/source/luametatex/source/tex/texdumpdata.h
@@ -55,7 +55,7 @@
*/
-# define luametatex_format_fingerprint 736
+# define luametatex_format_fingerprint 737
typedef enum dump_statistics {
dump_stat_fingerprint,
diff --git a/source/luametatex/source/tex/texequivalents.c b/source/luametatex/source/tex/texequivalents.c
index 12774bbbf..8a3b4b14c 100644
--- a/source/luametatex/source/tex/texequivalents.c
+++ b/source/luametatex/source/tex/texequivalents.c
@@ -533,9 +533,7 @@ void tex_save_halfword_on_stack(quarterword t, halfword v) /* todo: also value_2
static void tex_aux_group_trace(int g)
{
- tex_begin_diagnostic();
- tex_print_format(g ? "%l{leaving %G}" : "%l{entering %G}", g);
- tex_end_diagnostic();
+ tex_print_format(g ? "%<%l{leaving %G}%>" : "%<%l{entering %G}%>", g);
}
/*tex
@@ -587,7 +585,7 @@ static void tex_aux_group_warning(void)
stack in order to determine the type of the current input file.
*/
- if (tracing_nesting_par > 0) {
+ if lmt_unlikely(tracing_nesting_par > 0) {
while ((lmt_input_state.input_stack[lmt_input_state.base_ptr].state == token_list_state) || (lmt_input_state.input_stack[lmt_input_state.base_ptr].index > index)) {
--lmt_input_state.base_ptr;
}
@@ -600,10 +598,8 @@ static void tex_aux_group_warning(void)
--index;
}
if (warning) {
- tex_begin_diagnostic();
- tex_print_format("%l[warning: end of %G of a different file]", 1);
- tex_end_diagnostic();
- if (tracing_nesting_par > 1) {
+ tex_print_format("%<%l[warning: end of %G of a different file]%>", 1);
+ if lmt_unlikely(tracing_nesting_par > 1) {
tex_show_context();
}
if (lmt_error_state.history == spotless) {
@@ -655,7 +651,7 @@ void tex_new_save_level(quarterword group)
}
cur_boundary = lmt_save_state.save_stack_data.ptr;
cur_group = group;
- if (tracing_groups_par > 0) {
+ if lmt_unlikely(tracing_groups_par > 0) {
tex_aux_group_trace(0);
}
++cur_level;
@@ -1432,11 +1428,11 @@ void tex_eq_define(halfword p, singleword cmd, halfword chr)
{
bool trace = tracing_assigns_par > 0;
if (tex_aux_equal_eq(p, cmd, 0, chr)) {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "reassigning");
}
} else {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "changing");
}
if (eq_level(p) == cur_level) {
@@ -1448,7 +1444,7 @@ void tex_eq_define(halfword p, singleword cmd, halfword chr)
set_eq_type(p, cmd);
set_eq_flag(p, 0);
set_eq_value(p, chr);
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "into");
}
}
@@ -1466,11 +1462,11 @@ void tex_eq_word_define(halfword p, int w) /* not used */
{
bool trace = tracing_assigns_par > 0;
if (eq_value(p) == w) {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "reassigning");
}
} else {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "changing");
}
if (eq_level(p) != cur_level) {
@@ -1478,7 +1474,7 @@ void tex_eq_word_define(halfword p, int w) /* not used */
set_eq_level(p, cur_level);
}
eq_value(p) = w;
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "into");
}
}
@@ -1495,7 +1491,7 @@ void tex_eq_word_define(halfword p, int w) /* not used */
void tex_geq_define(halfword p, singleword cmd, halfword chr) /* not used */
{
bool trace = tracing_assigns_par > 0;
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "globally changing");
}
tex_aux_eq_destroy(&lmt_hash_state.eqtb[p]);
@@ -1503,7 +1499,7 @@ void tex_geq_define(halfword p, singleword cmd, halfword chr) /* not used */
set_eq_type(p, cmd);
set_eq_flag(p, 0);
set_eq_value(p, chr);
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "into");
}
}
@@ -1511,12 +1507,12 @@ void tex_geq_define(halfword p, singleword cmd, halfword chr) /* not used */
void tex_geq_word_define(halfword p, int w) /* not used */
{
bool trace = tracing_assigns_par > 0;
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "globally changing");
}
eq_value(p) = w;
set_eq_level(p, level_one);
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "into");
}
}
@@ -1547,7 +1543,7 @@ void tex_define(int g, halfword p, singleword t, halfword e) /* int g -> singlew
singleword f = make_eq_flag_bits(g);
if (is_global(g)) {
/* what if already global */
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "globally changing");
}
// if (tex_aux_equal_eq(p, t, f, e) && (eq_level(p) == level_one)) {
@@ -1557,12 +1553,12 @@ void tex_define(int g, halfword p, singleword t, halfword e) /* int g -> singlew
tex_aux_set_eq_data(p, t, e, f, level_one);
} else if (! is_constrained(g) && tex_aux_equal_eq(p, t, f, e)) {
/* hm, we tweak the ref ! */
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "reassigning");
return;
}
} else {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "changing");
}
if (eq_level(p) == cur_level) {
@@ -1574,7 +1570,7 @@ void tex_define(int g, halfword p, singleword t, halfword e) /* int g -> singlew
}
tex_aux_set_eq_data(p, t, e, f, cur_level);
}
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "into");
}
}
@@ -1602,7 +1598,7 @@ void tex_define_mutated(int g, halfword p, singleword t, halfword e) /* int g ->
singleword f = make_eq_flag_bits(is_permanent(csflags) ? csflags : g);
if (is_global(g)) {
/* what if already global */
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "globally changing");
}
// if (tex_aux_equal_eq(p, t, f, e) && (eq_level(p) == level_one)) {
@@ -1622,12 +1618,12 @@ void tex_define_mutated(int g, halfword p, singleword t, halfword e) /* int g ->
# endif
} else if (! is_constrained(g) && tex_aux_equal_eq(p, t, f, e)) {
/* hm, we tweak the ref ! */
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "reassigning");
return;
}
} else {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "changing");
}
if (eq_level(p) == cur_level) {
@@ -1649,7 +1645,7 @@ void tex_define_mutated(int g, halfword p, singleword t, halfword e) /* int g ->
tex_aux_set_eq_data(p, t, e, f, cur_level);
# endif
}
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "into");
}
}
@@ -1662,7 +1658,7 @@ void tex_define_mutated(int g, halfword p, singleword t, halfword e) /* int g ->
void tex_define_again(int g, halfword p, singleword t, halfword e) /* int g -> singleword g */
{
- if (tracing_assigns_par > 0) {
+ if lmt_unlikely(tracing_assigns_par > 0) {
singleword f = make_eq_flag_bits(g);
if (is_global(g)) {
/* what if already global */
@@ -1710,7 +1706,7 @@ void tex_define_inherit(int g, halfword p, singleword f, singleword t, halfword
bool trace = tracing_assigns_par > 0;
if (is_global(g)) {
/* what if already global */
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "globally changing");
}
// if (equal_eq(p, t, f, e) && (eq_level(p) == level_one)) {
@@ -1719,12 +1715,12 @@ void tex_define_inherit(int g, halfword p, singleword f, singleword t, halfword
tex_aux_eq_destroy(&lmt_hash_state.eqtb[p]);
tex_aux_set_eq_data(p, t, e, f, level_one);
} else if (! is_constrained(g) && tex_aux_equal_eq(p, t, f, e)) {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "reassigning");
return;
}
} else {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, is_retained(g) ? "retained changing" : "changing");
}
if (eq_level(p) == cur_level) {
@@ -1736,7 +1732,7 @@ void tex_define_inherit(int g, halfword p, singleword f, singleword t, halfword
}
tex_aux_set_eq_data(p, t, e, f, cur_level);
}
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "into");
}
}
@@ -1750,13 +1746,13 @@ static void tex_aux_just_define(int g, halfword p, halfword e)
{
bool trace = tracing_assigns_par > 0;
if (is_global(g)) {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "globally changing");
}
tex_aux_eq_destroy(&lmt_hash_state.eqtb[p]);
set_eq_level(p, level_one);
} else {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "changing");
}
if (eq_level(p) == cur_level) {
@@ -1767,7 +1763,7 @@ static void tex_aux_just_define(int g, halfword p, halfword e)
set_eq_level(p, cur_level);
}
set_eq_value(p, e);
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "into");
}
}
@@ -1881,13 +1877,13 @@ void tex_forced_define(int g, halfword p, singleword f, singleword t, halfword e
{
bool trace = tracing_assigns_par > 0;
if (is_global(g)) {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "globally changing");
}
tex_aux_eq_destroy(&lmt_hash_state.eqtb[p]);
set_eq_level(p, level_one);
} else {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "changing");
}
if (eq_level(p) == cur_level) {
@@ -1900,7 +1896,7 @@ void tex_forced_define(int g, halfword p, singleword f, singleword t, halfword e
set_eq_type(p, t);
set_eq_flag(p, f);
set_eq_value(p, e);
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "into");
}
}
@@ -1913,23 +1909,23 @@ void tex_word_define(int g, halfword p, halfword w)
{
bool trace = tracing_assigns_par > 0;
if (is_global(g)) {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "globally changing");
}
eq_value(p) = w;
set_eq_level(p, level_one);
} else if (! is_constrained(g) && eq_value(p) == w) {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "reassigning");
}
} else if (is_retained(g)) {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "retained changing");
}
set_eq_level(p, cur_level);
eq_value(p) = w;
} else {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "changing");
}
if (eq_level(p) != cur_level) {
@@ -1938,7 +1934,7 @@ void tex_word_define(int g, halfword p, halfword w)
}
eq_value(p) = w;
}
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "into");
}
if (is_immutable(g)) {
@@ -1954,23 +1950,23 @@ void tex_forced_word_define(int g, halfword p, singleword f, halfword w)
if (tex_mutation_permitted(p)) {
bool trace = tracing_assigns_par > 0;
if (is_global(g)) {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "globally changing");
}
eq_value(p) = w;
set_eq_level(p, level_one);
} else if (eq_value(p) == w) {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "reassigning");
return;
}
} else if (is_retained(g)) {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "retained changing");
}
eq_value(p) = w;
} else {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "changing");
}
if (eq_level(p) != cur_level) {
@@ -1979,7 +1975,7 @@ void tex_forced_word_define(int g, halfword p, singleword f, halfword w)
}
eq_value(p) = w;
}
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "into");
}
eq_flag(p) = f;
@@ -2044,7 +2040,7 @@ void tex_unsave(void)
*/
tex_begin_inserted_list(tex_get_available_token(token_val(end_local_cmd, 0)));
tex_begin_token_list(end_of_group_par, end_of_group_text);
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
tex_local_control_message("entering token scanner via endgroup");
}
tex_local_control(1);
@@ -2083,23 +2079,23 @@ void tex_unsave(void)
if (p < internal_integer_base || p >= internal_specification_base) {
if (eq_level(p) == level_one) {
tex_aux_eq_destroy(&(save_word(lmt_save_state.save_stack_data.ptr)));
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "retaining");
}
} else {
tex_aux_eq_destroy(&lmt_hash_state.eqtb[p]);
lmt_hash_state.eqtb[p] = save_word(lmt_save_state.save_stack_data.ptr);
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "restoring");
}
}
} else if (eq_level(p) == level_one) {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "retaining");
}
} else {
lmt_hash_state.eqtb[p] = save_word(lmt_save_state.save_stack_data.ptr);
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "restoring");
}
}
@@ -2140,7 +2136,7 @@ void tex_unsave(void)
{
halfword p = save_value(lmt_save_state.save_stack_data.ptr);
if (eq_level(p) == level_one) {
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "retaining");
}
} else {
@@ -2148,7 +2144,7 @@ void tex_unsave(void)
tex_aux_eq_destroy(&lmt_hash_state.eqtb[p]);
}
lmt_hash_state.eqtb[p] = lmt_hash_state.eqtb[undefined_control_sequence];
- if (trace) {
+ if lmt_unlikely(trace) {
tex_aux_diagnostic_trace(p, "restoring");
}
}
@@ -2161,7 +2157,7 @@ void tex_unsave(void)
}
}
DONE:
- if (tracing_groups_par > 0) {
+ if lmt_unlikely(tracing_groups_par > 0) {
tex_aux_group_trace(1);
}
if (lmt_input_state.in_stack[lmt_input_state.in_stack_data.ptr].group == cur_boundary) {
@@ -2257,7 +2253,7 @@ void tex_show_cmd_chr(halfword cmd, halfword chr)
if (cmd == if_test_cmd && tracing_ifs_par > 0) {
// halfword p;
int n, l;
- if (tracing_commands_par >= 4) {
+ if lmt_unlikely(tracing_commands_par >= 4) {
tex_print_str_len(": ", 2);
} else {
tex_print_char(' ');
@@ -2282,7 +2278,7 @@ void tex_show_cmd_chr(halfword cmd, halfword chr)
// p = node_next(p);
// }
if (l) {
- if (tracing_commands_par >= 4) {
+ if lmt_unlikely(tracing_commands_par >= 4) {
tex_print_format("(level %i, line %i, nesting %i)", n, l, lmt_condition_state.level);
} else {
// tex_print_format("(level %i) entered on line %i", n, l);
@@ -2366,7 +2362,7 @@ void tex_aux_show_eqtb(halfword n)
case register_glue_reference_cmd:
tex_print_format("%eskip%i", register_glue_number(n));
SKIP:
- if (tracing_nodes_par > 2) {
+ if lmt_unlikely(tracing_nodes_par > 2) {
tex_print_format("=<%i>%Q", eq_value(n), eq_value(n), pt_unit);
} else {
tex_print_format("=%Q", eq_value(n), pt_unit);
@@ -2378,7 +2374,7 @@ void tex_aux_show_eqtb(halfword n)
case register_muglue_reference_cmd:
tex_print_format("%emuskip%i", register_muglue_number(n));
MUSKIP:
- if (tracing_nodes_par > 2) {
+ if lmt_unlikely(tracing_nodes_par > 2) {
tex_print_format("=<%i>%Q", eq_value(n), eq_value(n), mu_unit);
} else {
tex_print_format("=%Q", eq_value(n), mu_unit);
diff --git a/source/luametatex/source/tex/texequivalents.h b/source/luametatex/source/tex/texequivalents.h
index 234009422..058be013c 100644
--- a/source/luametatex/source/tex/texequivalents.h
+++ b/source/luametatex/source/tex/texequivalents.h
@@ -792,8 +792,8 @@ typedef enum int_codes {
number_integer_pars,
} int_codes;
-# define first_integer_code pre_tolerance_code
-# define last_integer_code line_snapping_dp_factor_code
+# define first_integer_code tracing_online_code
+# define last_integer_code tracing_raggedness_code
typedef enum dimension_codes {
/* normal ones */
@@ -837,6 +837,9 @@ typedef enum dimension_codes {
number_dimension_pars,
} dimension_codes;
+# define first_tracing_code
+# define last_tracing_code
+
# define first_dimension_code par_indent_code
# define last_dimension_code line_snapping_tolerance_code
diff --git a/source/luametatex/source/tex/texexpand.c b/source/luametatex/source/tex/texexpand.c
index 5a468dcfa..239f00f3d 100644
--- a/source/luametatex/source/tex/texexpand.c
+++ b/source/luametatex/source/tex/texexpand.c
@@ -144,7 +144,7 @@ void tex_expand_current_token(void)
if (cur_cmd < first_call_cmd) {
/*tex Expand a non-macro. */
halfword code = cur_chr;
- if (tracing_commands_par > 1) {
+ if lmt_unlikely(tracing_commands_par > 1) {
tex_show_cmd_chr(cur_cmd, cur_chr);
}
switch (cur_cmd) {
@@ -883,9 +883,8 @@ static int tex_aux_collect_cs_tokens(halfword *p, int *n, int *count)
*p = tex_store_new_token(*p, token_val(cur_cmd, cur_chr));
}
break;
- } else {
- /* fall through */
}
+ FALLTHROUGH
default:
if (cur_cmd > max_command_cmd && cur_cmd < first_call_cmd) {
tex_expand_current_token();
@@ -1320,7 +1319,7 @@ static inline void tex_aux_macro_gobble_upto(halfword gobbletoken, bool gobblemo
static void tex_aux_macro_call(halfword cs, halfword cmd, halfword chr)
{
bool tracing = tracing_macros_par > 0;
- if (tracing) {
+ if lmt_unlikely(tracing) {
/*tex
Setting |\tracingmacros| to 2 means that elsewhere marks etc are shown so in fact a bit
more detail. However, as we turn that on anyway, using a value of 3 is not that weird
@@ -1572,7 +1571,7 @@ case dimension_match_token:
if (last) {
tex_back_input(cur_tok);
}
- halfword v = tex_scan_dimension(0, 0, 0, 0, NULL, NULL);
+ scaled v = tex_scan_dimension(0, 0, 0, 0, NULL, NULL);
halfword p ;
if (node_token_overflow(v)) {
p = tex_store_new_token(null, token_val(dimension_reference_cmd, node_token_msb(v)));
@@ -1898,7 +1897,7 @@ case integer_match_token:
}
}
++nofscanned;
- if (tracing) {
+ if lmt_unlikely(tracing) {
tex_begin_diagnostic();
tex_print_format("%l%c%c<-", match_visualizer, '0' + nofscanned + (nofscanned > 9 ? gap_match_count : 0));
tex_show_token_list(pstack[nofscanned - 1], 0, 0);
@@ -1980,7 +1979,7 @@ case integer_match_token:
}
}
nofscanned++;
- if (tracing) {
+ if lmt_unlikely(tracing) {
tex_begin_diagnostic();
tex_print_format("%l%c%i--", match_visualizer, nofscanned);
tex_end_diagnostic();
diff --git a/source/luametatex/source/tex/texfont.c b/source/luametatex/source/tex/texfont.c
index 3b6e6387a..e8ff9f417 100644
--- a/source/luametatex/source/tex/texfont.c
+++ b/source/luametatex/source/tex/texfont.c
@@ -84,37 +84,93 @@ static inline int tex_aux_apply_base_ligaturing(halfword n)
/* */
-static inline scaled tex_aux_font_x_scaled(scaled v)
-{
- return v ? scaledround(0.000001 * (glyph_scale_par ? glyph_scale_par : 1000) * (glyph_x_scale_par ? glyph_x_scale_par : 1000) * v) : 0;
-}
+# if lmt_float_math
-static inline scaled tex_aux_font_y_scaled(scaled v)
-{
- return v ? scaledround(0.000001 * (glyph_scale_par ? glyph_scale_par : 1000) * (glyph_y_scale_par ? glyph_y_scale_par : 1000) * v) : 0;
-}
+ static inline scaled tex_aux_font_x_scaled(scaled v)
+ {
+ if (! v) return 0;
+ double s = glyph_scale_par ? glyph_scale_par : 1000.0;
+ double x = glyph_x_scale_par ? glyph_x_scale_par : 1000.0;
+ return scaledround(0.000001 * s * x * (double) v);
+ }
-static inline scaled tex_aux_glyph_x_scaled(halfword g, scaled v)
-{
- return v ? scaledround(0.000001 * (glyph_scale(g) ? glyph_scale(g) : 1000) * (glyph_x_scale(g) ? glyph_x_scale(g) : 1000) * v) : 0;
-}
+ static inline scaled tex_aux_font_y_scaled(scaled v)
+ {
+ if (! v) return 0;
+ double s = glyph_scale_par ? glyph_scale_par : 1000.0;
+ double y = glyph_y_scale_par ? glyph_y_scale_par : 1000.0;
+ return scaledround(0.000001 * s * y * (double) v);
+ }
-static inline scaled tex_aux_glyph_y_scaled(halfword g, scaled v)
-{
- return v ? scaledround(0.000001 * (glyph_scale(g) ? glyph_scale(g) : 1000) * (glyph_y_scale(g) ? glyph_y_scale(g) : 1000) * v) : 0;
-}
+ static inline scaled tex_aux_glyph_x_scaled(halfword g, scaled v)
+ {
+ if (! v) return 0;
+ double gs = glyph_scale(g);
+ double gx = glyph_x_scale(g);
+ double s = gs ? gs : 1000.0;
+ double x = gx ? gx : 1000.0;
+ return scaledround(0.000001 * s * x * (double) v);
+ }
-static inline scaled tex_aux_glyph_lr_scaled(halfword l, halfword r, scaled v)
-{
- return v
- ? scaledround (
- (
- 0.0000005 * (glyph_scale(l) ? glyph_scale(l) : 1000) * (glyph_x_scale(l) ? glyph_x_scale(l) : 1000)
- + 0.0000005 * (glyph_scale(r) ? glyph_scale(r) : 1000) * (glyph_x_scale(r) ? glyph_x_scale(r) : 1000)
- ) * v
- )
- : 0;
-}
+ static inline scaled tex_aux_glyph_y_scaled(halfword g, scaled v)
+ {
+ if (! v) return 0;
+ double gs = glyph_scale(g);
+ double gy = glyph_y_scale(g);
+ double s = gs ? gs : 1000.0;
+ double y = gy ? gy : 1000.0;
+ return scaledround(0.000001 * s * y * (double) v);
+ }
+
+ static inline scaled tex_aux_glyph_lr_scaled(halfword l, halfword r, scaled v)
+ {
+ if (! v) return 0;
+ double ls = glyph_scale(l); double lx = glyph_x_scale(l);
+ double rs = glyph_scale(r); double rx = glyph_x_scale(r);
+ double sl = (ls ? ls : 1000.0) * (lx ? lx : 1000.0);
+ double sr = (rs ? rs : 1000.0) * (rx ? rx : 1000.0);
+ return scaledround(0.0000005 * (sl + sr) * (double) v);
+ }
+
+# else
+
+ static inline scaled tex_aux_font_x_scaled(scaled v)
+ {
+ return tex_aux_scale_1e6(v, glyph_scale_par, glyph_x_scale_par);
+ }
+
+ static inline scaled tex_aux_font_y_scaled(scaled v)
+ {
+ return tex_aux_scale_1e6(v, glyph_scale_par, glyph_y_scale_par);
+ }
+
+ static inline scaled tex_aux_glyph_x_scaled(halfword g, scaled v)
+ {
+ return tex_aux_scale_1e6(v, glyph_scale(g), glyph_x_scale(g));
+ }
+
+ static inline scaled tex_aux_glyph_y_scaled(halfword g, scaled v)
+ {
+ return tex_aux_scale_1e6(v, glyph_scale(g), glyph_y_scale(g));
+ }
+
+ static inline scaled tex_aux_glyph_lr_scaled(halfword l, halfword r, scaled v)
+ {
+ if (! v) return 0;
+ long long ls = glyph_scale(l); long long lx = glyph_x_scale(l);
+ long long rs = glyph_scale(r); long long rx = glyph_x_scale(r);
+ long long sl = ls ? ls : 1000LL;
+ long long xl = lx ? lx : 1000LL;
+ long long sr = rs ? rs : 1000LL;
+ long long xr = rx ? rx : 1000LL;
+
+ if (sl == 1000LL && xl == 1000LL && sr == 1000LL && xr == 1000LL) {
+ return v; /* Fast path */
+ }
+ return (scaled) tex_aux_round_sum_products(v, sl, xl, sr, xr, 2000000LL);
+ }
+
+# endif
font_state_info lmt_font_state = {
.fonts = NULL,
@@ -912,12 +968,12 @@ void tex_create_null_font(void)
tex_set_font_original(id, "nullfont");
}
-int inline tex_is_valid_font(halfword f)
+inline int tex_is_valid_font(halfword f)
{
return (f >= 0 && f <= lmt_font_state.font_data.ptr && lmt_font_state.fonts[f]);
}
-int inline tex_checked_font(halfword f)
+inline int tex_checked_font(halfword f)
{
return (f >= 0 && f <= lmt_font_state.font_data.ptr && lmt_font_state.fonts[f]) ? f : null_font;
}
@@ -1067,7 +1123,7 @@ int tex_valid_font_parameter(halfword f, halfword code)
return 1;
}
-halfword tex_get_font_parameter(halfword f, halfword code) /* todo: math */
+scaled tex_get_font_parameter(halfword f, halfword code) /* todo: math */
{
if (tex_valid_font_parameter(f, code)) {
return font_parameter(f, code);
@@ -1102,7 +1158,7 @@ scaled tex_get_scaled_extra_space (halfword f) { return tex_aux_font_x_scaled(
scaled tex_font_x_scaled (scaled v) { return tex_aux_font_x_scaled(v); }
scaled tex_font_y_scaled (scaled v) { return tex_aux_font_y_scaled(v); }
-halfword tex_get_scaled_parameter(halfword f, halfword code) /* todo: math */
+scaled tex_get_scaled_parameter(halfword f, halfword code) /* todo: math */
{
if (tex_valid_font_parameter(f, code)) {
switch (code) {
@@ -1943,9 +1999,10 @@ void tex_missing_character(halfword n, halfword f, halfword c, halfword where)
if (tracing_lost_chars_par > 1) {
tracing_online_par = 1;
}
- tex_begin_diagnostic();
- tex_print_format("%l[font: missing character, character %c (%U), font '%s', location %i]", c, c, tex_is_valid_font(f) ? font_name(f) : "<invalid>", where);
- tex_end_diagnostic();
+ tex_print_format(
+ "%<%l[font: missing character, character %c (%U), font '%s', location %i]%>",
+ c, c, tex_is_valid_font(f) ? font_name(f) : "<invalid>", where
+ );
tracing_online_par = old_setting;
}
}
@@ -2396,40 +2453,55 @@ void tex_set_font_original(halfword f, const char *s)
set_font_original(f, s ? lmt_memory_strdup(s) : NULL);
}
-scaled tex_get_math_font_scale(halfword f, halfword size)
+static inline scaled tex_aux_get_size_scale_param(halfword size)
{
- scaled scale;
switch (size) {
- case 2: scale = (lmt_font_state.fonts[f]->mathscales[2] ? lmt_font_state.fonts[f]->mathscales[2] : scaling_factor) * glyph_scriptscript_scale_par; break;
- case 1: scale = (lmt_font_state.fonts[f]->mathscales[1] ? lmt_font_state.fonts[f]->mathscales[1] : scaling_factor) * glyph_script_scale_par; break;
- default: scale = (lmt_font_state.fonts[f]->mathscales[0] ? lmt_font_state.fonts[f]->mathscales[0] : scaling_factor) * glyph_text_scale_par; break;
+ case 2: return glyph_scriptscript_scale_par;
+ case 1: return glyph_script_scale_par;
+ default: return glyph_text_scale_par;
}
- scale = scaledround(0.001 * (double) scale);
- return scale ? scale : scaling_factor;
+}
+
+# if lmt_float_math
+
+ static inline scaled tex_aux_get_math_font_scale_generic(halfword f, halfword size, const scaled *scales_array)
+ {
+ (void) f;
+ int idx = (size == 1 || size == 2) ? size : 0;
+ scaled font_scale = scales_array[idx] ? scales_array[idx] : scaling_factor;
+ scaled global_scale = tex_aux_get_size_scale_param(size);
+ scaled scale = scaledround(0.001 * (double) font_scale * (double) global_scale);
+ return scale ? scale : scaling_factor;
+ }
+
+# else
+
+ static inline scaled tex_aux_get_math_font_scale_generic(halfword f, halfword size, const scaled *scales_array)
+ {
+ (void) f;
+ int idx = (size == 1 || size == 2) ? size : 0;
+ scaled font_scale = scales_array[idx] ? scales_array[idx] : scaling_factor;
+ scaled global_scale = tex_aux_get_size_scale_param(size);
+
+ scaled scale = tex_aux_scale_1000(font_scale, global_scale);
+ return scale ? scale : scaling_factor;
+ }
+
+# endif
+
+scaled tex_get_math_font_scale(halfword f, halfword size)
+{
+ return tex_aux_get_math_font_scale_generic(f, size, lmt_font_state.fonts[f]->mathscales);
}
scaled tex_get_math_font_x_scale(halfword f, halfword size)
{
- scaled scale;
- switch (size) {
- case 2: scale = (lmt_font_state.fonts[f]->mathxscales[2] ? lmt_font_state.fonts[f]->mathxscales[2] : scaling_factor) * glyph_scriptscript_scale_par; break;
- case 1: scale = (lmt_font_state.fonts[f]->mathxscales[1] ? lmt_font_state.fonts[f]->mathxscales[1] : scaling_factor) * glyph_script_scale_par; break;
- default: scale = (lmt_font_state.fonts[f]->mathxscales[0] ? lmt_font_state.fonts[f]->mathxscales[0] : scaling_factor) * glyph_text_scale_par; break;
- }
- scale = scaledround(0.001 * (double) scale);
- return scale ? scale : scaling_factor;
+ return tex_aux_get_math_font_scale_generic(f, size, lmt_font_state.fonts[f]->mathxscales);
}
scaled tex_get_math_font_y_scale(halfword f, halfword size)
{
- scaled scale;
- switch (size) {
- case 2: scale = (lmt_font_state.fonts[f]->mathyscales[2] ? lmt_font_state.fonts[f]->mathyscales[2] : scaling_factor) * glyph_scriptscript_scale_par; break;
- case 1: scale = (lmt_font_state.fonts[f]->mathyscales[1] ? lmt_font_state.fonts[f]->mathyscales[1] : scaling_factor) * glyph_script_scale_par; break;
- default: scale = (lmt_font_state.fonts[f]->mathyscales[0] ? lmt_font_state.fonts[f]->mathyscales[0] : scaling_factor) * glyph_text_scale_par; break;
- }
- scale = scaledround(0.001 * (double) scale);
- return scale ? scale : scaling_factor;
+ return tex_aux_get_math_font_scale_generic(f, size, lmt_font_state.fonts[f]->mathyscales);
}
scaled tex_get_math_font_weight(halfword f, halfword size)
diff --git a/source/luametatex/source/tex/texinserts.c b/source/luametatex/source/tex/texinserts.c
index 19e05e6bc..5f7fc2c04 100644
--- a/source/luametatex/source/tex/texinserts.c
+++ b/source/luametatex/source/tex/texinserts.c
@@ -180,7 +180,7 @@ halfword tex_get_insert_penalty(halfword i)
}
}
-halfword tex_get_insert_maxdepth(halfword i)
+scaled tex_get_insert_maxdepth(halfword i)
{
if (tex_valid_insert_id(i)) {
return lmt_insert_state.mode == index_insert_mode ? split_max_depth_par : lmt_insert_state.inserts[i].maxdepth;
@@ -190,7 +190,7 @@ halfword tex_get_insert_maxdepth(halfword i)
}
-halfword tex_get_insert_distance(halfword i)
+scaled tex_get_insert_distance(halfword i)
{
if (tex_valid_insert_id(i)) {
return lmt_insert_state.mode == index_insert_mode ? insert_distance(i) : lmt_insert_state.inserts[i].distance;
@@ -309,7 +309,7 @@ void tex_set_insert_penalty(halfword i, halfword v)
}
}
-void tex_set_insert_maxdepth(halfword i, halfword v)
+void tex_set_insert_maxdepth(halfword i, scaled v)
{
if (tex_valid_insert_id(i) && lmt_insert_state.mode == class_insert_mode) {
lmt_insert_state.inserts[i].options = set_insert_option(lmt_insert_state.inserts[i].options, insert_option_maxdepth);
@@ -317,7 +317,7 @@ void tex_set_insert_maxdepth(halfword i, halfword v)
}
}
-void tex_set_insert_distance(halfword i, halfword v)
+void tex_set_insert_distance(halfword i, scaled v)
{
if (tex_valid_insert_id(i)) {
int d = null;
@@ -477,7 +477,7 @@ halfword lmt_set_insert_distance(halfword i, halfword head)
}
}
-halfword tex_get_insert_progress(halfword i)
+scaled tex_get_insert_progress(halfword i)
{
if (tex_valid_insert_id(i)) {
halfword p = page_insert_head;
@@ -695,7 +695,7 @@ void tex_finish_insert_group(void)
halfword data = saved_insert_data;
halfword callback = saved_insert_callback;
halfword insert = tex_new_node(insert_node, 0);
- halfword maxdepth = tex_get_insert_maxdepth(index);
+ scaled maxdepth = tex_get_insert_maxdepth(index);
halfword floating = tex_get_insert_penalty(index);
if (tex_get_insert_storage(index)) {
tex_insert_store(index, insert);
@@ -832,11 +832,12 @@ scaled tex_insert_height(halfword node)
/*tex A redundant check but we do it anyway. */
if (node && node_type(node) == insert_node) {
halfword multiplier = tex_get_insert_multiplier(insert_index(node));
- halfword needed = insert_total_height(node);
+ scaled needed = insert_total_height(node);
if (multiplier > 0 && needed > 0) {
// return tex_x_over_n_factor(needed) * multiplier;
// return scaledround(needed * multiplier / scaling_factor_double)
- return needed * multiplier / scaling_factor;
+ // return needed * multiplier / scaling_factor;
+ return tex_xn_over_1000(needed, multiplier);
}
}
return 0;
diff --git a/source/luametatex/source/tex/texinserts.h b/source/luametatex/source/tex/texinserts.h
index 5e5dba116..13cacca86 100644
--- a/source/luametatex/source/tex/texinserts.h
+++ b/source/luametatex/source/tex/texinserts.h
@@ -78,8 +78,8 @@ extern insert_state_info lmt_insert_state;
extern scaled tex_get_insert_limit (halfword i);
extern halfword tex_get_insert_multiplier (halfword i);
extern halfword tex_get_insert_penalty (halfword i);
-extern halfword tex_get_insert_distance (halfword i);
-extern halfword tex_get_insert_maxdepth (halfword i);
+extern scaled tex_get_insert_distance (halfword i);
+extern scaled tex_get_insert_maxdepth (halfword i);
extern scaled tex_get_insert_height (halfword i);
extern scaled tex_get_insert_depth (halfword i);
extern scaled tex_get_insert_width (halfword i);
@@ -94,8 +94,8 @@ extern halfword tex_get_insert_direction (halfword i);
extern void tex_set_insert_limit (halfword i, scaled v);
extern void tex_set_insert_multiplier (halfword i, halfword v);
extern void tex_set_insert_penalty (halfword i, halfword v);
-extern void tex_set_insert_distance (halfword i, halfword v);
-extern void tex_set_insert_maxdepth (halfword i, halfword v);
+extern void tex_set_insert_distance (halfword i, scaled v);
+extern void tex_set_insert_maxdepth (halfword i, scaled v);
extern void tex_set_insert_height (halfword i, scaled v);
extern void tex_set_insert_depth (halfword i, scaled v);
extern void tex_set_insert_width (halfword i, scaled v);
@@ -125,7 +125,7 @@ extern void tex_undump_insert_data (dumpstream f);
extern halfword lmt_get_insert_distance (halfword i, int first, int top, int dis); /* callback */
extern halfword lmt_set_insert_distance (halfword i, halfword head); /* callback */
-extern halfword tex_get_insert_progress (halfword i);
+extern scaled tex_get_insert_progress (halfword i);
extern void tex_insert_store (halfword i, halfword n);
extern void tex_insert_restore (halfword n);
diff --git a/source/luametatex/source/tex/texlanguage.c b/source/luametatex/source/tex/texlanguage.c
index 71ad99aa9..33d8647b9 100644
--- a/source/luametatex/source/tex/texlanguage.c
+++ b/source/luametatex/source/tex/texlanguage.c
@@ -1359,9 +1359,10 @@ static int tex_aux_hnj_hyphen_hyphenate(
/* we can also check the original */
-static int tex_aux_still_okay(halfword f, halfword l, halfword r, int n, const char *utf8original) {
+static int tex_aux_still_okay(halfword f, halfword l, halfword r, int n, const char *utf8original, size_t utf8length) {
if (_valid_node_(f) && _valid_node_(l) && node_next(l) == r) {
int i = 0;
+ const char *utf8end = utf8original + utf8length;
while (f) {
++i;
if (node_type(f) != glyph_node) {
@@ -1369,7 +1370,7 @@ static int tex_aux_still_okay(halfword f, halfword l, halfword r, int n, const c
return 0;
} else {
int cl;
- halfword c = (halfword) aux_str2uni_len((const unsigned char *) utf8original, &cl);
+ halfword c = (halfword) aux_str2uni_len((const unsigned char *) utf8original, (size_t) (utf8end - utf8original), &cl);
utf8original += cl;
if (! (c && c == glyph_character(f))) {
tex_normal_warning("language", "the hyphenated word contains different characters, skipping");
@@ -1638,9 +1639,7 @@ void tex_hyphenate_list(halfword head, halfword tail)
r = tex_aux_compound_word_break(r, get_glyph_language(g), explicit_hyphen);
if (trace > 1) {
*utf8ori = 0;
- tex_begin_diagnostic();
- tex_print_format("%l[language: compound word break after %s]", utf8original);
- tex_end_diagnostic();
+ tex_print_format("%<%l[language: compound word break after %s]%>", utf8original);
}
if (hyphenation_permitted(glyph_hyphenate(g), compound_hyphenation_mode)) {
explicit_hyphen = 0;
@@ -1699,7 +1698,7 @@ void tex_hyphenate_list(halfword head, halfword tail)
lmt_memory_free(replacement);
replacement = NULL;
} else if (replacement) {
- if (tex_aux_still_okay(start, word_end, r, word_length, utf8original)) {
+ if (tex_aux_still_okay(start, word_end, r, word_length, utf8original, (size_t) (utf8ori - utf8original))) {
goto EXCEPTIONS2;
} else {
goto PICKUP;
@@ -1724,13 +1723,13 @@ void tex_hyphenate_list(halfword head, halfword tail)
}
goto PICKUP;
case 2:
- if (tex_aux_still_okay(start, word_end, r, word_length, utf8original)) {
+ if (tex_aux_still_okay(start, word_end, r, word_length, utf8original, (size_t) (utf8ori - utf8original))) {
goto EXCEPTIONS1;
} else {
goto PICKUP;
}
case 3:
- if (tex_aux_still_okay(start, word_end, r, word_length, utf8original)) {
+ if (tex_aux_still_okay(start, word_end, r, word_length, utf8original, (size_t) (utf8ori - utf8original))) {
goto PATTERNS;
} else {
goto PICKUP;
@@ -1882,4 +1881,4 @@ halfword tex_glyph_to_discretionary(halfword glyph, quarterword code, int keepke
tex_try_couple_nodes(prev, disc);
tex_try_couple_nodes(disc, next);
return disc;
-} \ No newline at end of file
+}
diff --git a/source/luametatex/source/tex/texlinebreak.c b/source/luametatex/source/tex/texlinebreak.c
index ac2d6cc0a..fbc02c36c 100644
--- a/source/luametatex/source/tex/texlinebreak.c
+++ b/source/luametatex/source/tex/texlinebreak.c
@@ -230,7 +230,7 @@ linebreak_state_info lmt_linebreak_state = {
.global_threshold = 0,
.line_break_dir = 0,
.checked_expansion = -1,
- .passes = { { 0, 0, 0, 0, 0, 0, 0, 0 } },
+ .passes = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
.n_of_left_twins = 0,
.n_of_right_twins = 0,
.n_of_double_twins = 0,
@@ -287,7 +287,7 @@ void tex_line_break_prepare(
{
/* too much testing of next .. it needs checking anyway */
if (node_type(par) == par_node) { /* maybe check for h|v subtype */
- if (tracing_linebreak_lists) {
+ if lmt_unlikely(tracing_linebreak_lists) {
tex_begin_diagnostic();
tex_print_format("%l[linebreak: prepare, before]");
tex_show_box(par);
@@ -338,7 +338,7 @@ void tex_line_break_prepare(
}
}
}
- if (tracing_linebreak_lists) {
+ if lmt_unlikely(tracing_linebreak_lists) {
tex_begin_diagnostic();
tex_print_format("%l[linebreak: prepare, after]");
tex_show_box(par);
@@ -1028,13 +1028,11 @@ static int tex_aux_analyze_raggedness(const line_break_properties *properties, i
q = passive_prev_break(q);
}
lmt_linebreak_state.raggedness = max - min;
- if (properties->tracing_raggedness > 0) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: subpass %i, raggedness, min %i, max %i, effective %i, overfull %i, lines %i, %s]\n",
- subpass, min, max, lmt_linebreak_state.raggedness, overfull, lines,
- overfull ? "overfull, quit" : "underfull, check"
+ if lmt_unlikely(properties->tracing_raggedness > 0) {
+ tex_print_format("%<%l[linebreak: subpass %i, raggedness, min %i, max %i, effective %i, overfull %i, lines %i, %s]\n%>",
+ subpass, min, max, lmt_linebreak_state.raggedness, overfull, lines,
+ overfull ? "overfull, quit" : "underfull, check"
);
- tex_end_diagnostic();
}
return overfull ? 1 : 0;
} else {
@@ -1883,7 +1881,7 @@ halfword tex_default_fitness_classes(void) {
return n;
}
-static void tex_check_protrusion_shortfall(halfword breakpoint, halfword first, halfword current, halfword *shortfall)
+static void tex_check_protrusion_shortfall(halfword breakpoint, halfword first, halfword current, scaled *shortfall)
{
// if (line_break_dir == dir_righttoleft) {
// /*tex Not now, we need to keep more track. */
@@ -1931,7 +1929,7 @@ static void tex_check_protrusion_shortfall(halfword breakpoint, halfword first,
static void tex_aux_set_quality(halfword active, halfword passive, scaled shrt, scaled glue, scaled width, halfword badness)
{
halfword quality = 0;
- halfword deficiency = 0;
+ scaled deficiency = 0;
active_short(active) = shrt;
active_glue(active) = glue;
active_line_width(active) = width;
@@ -2302,8 +2300,7 @@ static int tex_aux_same_snippet(const int * restrict snippetone, const int * res
static void tex_aux_report_linebreak_trace(int pass, int subpass)
{
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: pass %i, active counts %i, easy line %i, at active %i, got lost %i, loose %i]\n",
+ tex_print_format("%<%l[linebreak: pass %i, active counts %i, easy line %i, at active %i, got lost %i, loose %i]\n%>",
pass,
lmt_linebreak_state.trace_counter[linebreak_trace_going_active],
lmt_linebreak_state.trace_counter[linebreak_trace_easy_line],
@@ -2311,7 +2308,6 @@ static int tex_aux_same_snippet(const int * restrict snippetone, const int * res
lmt_linebreak_state.trace_counter[linebreak_trace_got_lost],
lmt_linebreak_state.trace_counter[linebreak_trace_getting_loose]
);
- tex_end_diagnostic();
}
# endif
@@ -2355,8 +2351,7 @@ static void tex_aux_trace_special_break(const line_break_properties *properties,
}
tracing_online_par = 1;
tex_aux_count_active(&hyphenated, &unhyphenated, &delta);
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: %s, easy %i, width %p, active %i, hyphenated %i, unhyphenated %i, delta %i, looseness %i, %s]",
+ tex_print_format("%<%l[linebreak: %s, easy %i, width %p, active %i, hyphenated %i, unhyphenated %i, delta %i, looseness %i, %s]%>",
special == 0 ? "normal" : special == 1 ? "special" : "weird",
old_line,
width,
@@ -2367,7 +2362,6 @@ static void tex_aux_trace_special_break(const line_break_properties *properties,
? (properties->par_shape ? "shape" : "hang")
: "regular"
);
- tex_end_diagnostic();
tracing_online_par = old;
}
@@ -2787,10 +2781,11 @@ static scaled tex_aux_try_break(
if (n_before) {
int n = tex_aux_get_before(passive_cur_break(prev_break), snippet);
if (tex_aux_same_snippet(s_before, snippet, n_before, n)) {
- if (properties->tracing_paragraphs > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: bumping demerits %i by right twin demerits %i]", active_total_demerits(active), properties->right_twin_demerits);
- tex_end_diagnostic();
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
+ tex_print_format(
+ "%<%l[linebreak: bumping demerits %i by right twin demerits %i]%>",
+ active_total_demerits(active), properties->right_twin_demerits
+ );
}
active_total_demerits(active) += properties->right_twin_demerits;
++lmt_linebreak_state.n_of_right_twins;
@@ -2805,10 +2800,11 @@ static scaled tex_aux_try_break(
if (n_after) {
int n = tex_aux_get_after(passive_cur_break(prev_break), snippet);
if (tex_aux_same_snippet(s_after, snippet, n_after, n)) {
- if (properties->tracing_paragraphs > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: bumping demerits %i by left twin demerits %i]", active_total_demerits(active), properties->left_twin_demerits);
- tex_end_diagnostic();
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
+ tex_print_format(
+ "%<%l[linebreak: bumping demerits %i by left twin demerits %i]%>",
+ active_total_demerits(active), properties->left_twin_demerits
+ );
}
active_total_demerits(active) += properties->left_twin_demerits;
++lmt_linebreak_state.n_of_left_twins;
@@ -2824,7 +2820,7 @@ static scaled tex_aux_try_break(
if (callback_id) {
active_total_demerits(active) = tex_aux_line_break_callback_report(callback_id, checks, pass, subpass, active, passive);
}
- if (properties->tracing_paragraphs > 0) {
+ if lmt_unlikely(properties->tracing_paragraphs > 0) {
tex_begin_diagnostic();
tex_print_levels();
tex_aux_print_break_node(active, passive, lmt_linebreak_state.do_last_line_fit);
@@ -2850,7 +2846,7 @@ static scaled tex_aux_try_break(
previous = delta;
}
} else {
- if (properties->tracing_paragraphs == -1) {
+ if lmt_unlikely(properties->tracing_paragraphs == -1) {
// to be checked: old_line == lmt_linebreak_state.easy_line is always true
if (lmt_linebreak_state.getting_loose || (old_line == lmt_linebreak_state.easy_line)) {
tex_aux_trace_special_break(properties, 1, line, old_line);
@@ -2928,7 +2924,7 @@ static scaled tex_aux_try_break(
results.
*/
if (shortfall > 0) {
- halfword total_stretch = current_active_width[font_stretch_amount];
+ scaled total_stretch = current_active_width[font_stretch_amount];
if (total_stretch > 0) {
if (total_stretch > shortfall) {
shortfall = total_stretch / 2;
@@ -2937,7 +2933,7 @@ static scaled tex_aux_try_break(
}
}
} else if (shortfall < 0) {
- halfword total_shrink = current_active_width[font_shrink_amount];
+ scaled total_shrink = current_active_width[font_shrink_amount];
if (total_shrink > 0) {
if (total_shrink > -shortfall) {
shortfall = - total_shrink / 2;
@@ -3176,7 +3172,7 @@ static scaled tex_aux_try_break(
demerits += tex_get_demerits(properties, distance, fit_current, fit_class);
}
prev_badness = badness;
- if (properties->tracing_paragraphs > 0) {
+ if lmt_unlikely(properties->tracing_paragraphs > 0) {
// tex_begin_diagnostic();
tex_aux_print_feasible_break(cur_p, current, badness, penalty, demerits, artificial_demerits, fit_class, lmt_linebreak_state.printed_node);
// tex_end_diagnostic();
@@ -3276,10 +3272,8 @@ static halfword tex_aux_inject_orphan_penalty(const line_break_properties *prope
halfword penalty = tex_new_penalty_node(amount, orphan_penalty_subtype);
tex_couple_nodes(prev, penalty);
tex_couple_nodes(penalty, current);
- if (properties->tracing_paragraphs > 1 || properties->tracing_orphans) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: adding orphanpenalty %i]\n", amount);
- tex_end_diagnostic();
+ if lmt_unlikely(properties->tracing_paragraphs > 1 || properties->tracing_orphans) {
+ tex_print_format("%<%l[linebreak: adding orphanpenalty %i]\n%>", amount);
}
if (orphaned) {
tex_add_penalty_option(penalty, penalty_option_orphaned);
@@ -3322,10 +3316,8 @@ static halfword tex_aux_inject_toddler_penalty(const line_break_properties *prop
tex_add_penalty_option(penalty, penalty_option_toddlered);
}
}
- if (properties->tracing_paragraphs > 1 || properties->tracing_toddlers) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: adding toddlerpenalty %i %i]\n", tnuoma, amount);
- tex_end_diagnostic();
+ if lmt_unlikely(properties->tracing_paragraphs > 1 || properties->tracing_toddlers) {
+ tex_print_format("%<%l[linebreak: adding toddlerpenalty %i %i]\n%>", tnuoma, amount);
}
lmt_linebreak_state.has_toddlers = 1;
return penalty;
@@ -3493,7 +3485,7 @@ static scaled tex_check_linebreak_quality(scaled shortfall, scaled *overfull, sc
static void tex_aux_quality_callback(
int callback_id, halfword par,
int id, int pass, int subpass, int subpasses, int state,
- halfword overfull, halfword underfull, halfword verdict, halfword classified
+ scaled overfull, scaled underfull, halfword verdict, halfword classified
)
{
lmt_run_callback(
@@ -3669,19 +3661,15 @@ static void tex_aux_fix_toddler_penalties(const line_break_properties *propertie
right = tex_get_specification_nepalty(properties->toddler_penalties, done);
penalty_amount(prev) = left;
penalty_amount(next) = right;
- if (trace) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: toddler penalties %i %i fixed]\n", left, right);
- tex_end_diagnostic();
+ if lmt_unlikely(trace) {
+ tex_print_format("%<%l[linebreak: toddler penalties %i %i fixed]\n%>", left, right);
}
} else {
next = node_next(tail);
right = tex_get_specification_penalty(properties->toddler_penalties, ++done);
penalty_amount(next) = right;
- if (trace) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: toddler penalty %i fixed]\n", right);
- tex_end_diagnostic();
+ if lmt_unlikely(trace) {
+ tex_print_format("%<%l[linebreak: toddler penalty %i fixed]\n%>", right);
}
}
}
@@ -3850,10 +3838,8 @@ static void tex_aux_set_toddler_penalties(const line_break_properties *propertie
halfword multiples = 0;
halfword duplex = tex_has_specification_option(properties->toddler_penalties, specification_option_double);
int trace = properties->tracing_paragraphs > 1 || properties->tracing_toddlers;
- if (trace) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: %i toddlers found]\n", found);
- tex_end_diagnostic();
+ if lmt_unlikely(trace) {
+ tex_print_format("%<%l[linebreak: %i toddlers found]\n%>", found);
}
while (current) {
if (node_type(current) == glyph_node) {
@@ -3895,10 +3881,8 @@ static void tex_aux_set_toddler_penalties(const line_break_properties *propertie
tex_aux_fix_toddler_penalties(properties, duplex, head, tail, trace, count);
multiples++;
}
- if (trace) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: %i multiple toddlers found]\n", multiples);
- tex_end_diagnostic();
+ if lmt_unlikely(trace) {
+ tex_print_format("%<%l[linebreak: %i multiple toddlers found]\n%>", multiples);
}
}
}
@@ -3907,17 +3891,13 @@ static void tex_aux_set_toddler_penalties(const line_break_properties *propertie
static void tex_aux_check_competing_penalties(const line_break_properties *properties, halfword current, halfword penalty, int orphaned)
{
if (penalty > penalty_amount(current)) {
- if (properties->tracing_paragraphs > 1 || properties->tracing_orphans) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: orphanpenalty %i wins over toddlerpenalty %i]\n", penalty, penalty_amount(current));
- tex_end_diagnostic();
+ if lmt_unlikely(properties->tracing_paragraphs > 1 || properties->tracing_orphans) {
+ tex_print_format("%<%l[linebreak: orphanpenalty %i wins over toddlerpenalty %i]\n%>", penalty, penalty_amount(current));
}
penalty_amount(current) = penalty;
} else {
- if (properties->tracing_paragraphs > 1 || properties->tracing_toddlers) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: toddlerpenalty %i wins over orphanpenalty %i]\n", penalty_amount(current), penalty);
- tex_end_diagnostic();
+ if lmt_unlikely(properties->tracing_paragraphs > 1 || properties->tracing_toddlers) {
+ tex_print_format("%<%l[linebreak: toddlerpenalty %i wins over orphanpenalty %i]\n%>", penalty_amount(current), penalty);
}
}
if (orphaned && tex_has_penalty_option(current, penalty_option_toddlered)) {
@@ -4174,11 +4154,11 @@ static int tex_aux_set_sub_pass_parameters(
halfword first,
int details,
halfword features,
- halfword overfull,
- halfword underfull,
+ scaled overfull,
+ scaled underfull,
halfword verdict,
halfword classified,
- halfword threshold,
+ scaled threshold,
halfword demerits,
halfword classes
) {
@@ -4228,7 +4208,7 @@ static int tex_aux_set_sub_pass_parameters(
if (okay & passes_emergencyunit_okay) {
halfword u = tex_get_passes_emergencyunit(passes, subpass);
if (u) {
- halfword v = 0;
+ scaled v = 0;
if (tex_get_userunit(u, &v)) {
properties->emergency_stretch = v;
properties->emergency_original = v; /* ! */
@@ -4237,7 +4217,7 @@ static int tex_aux_set_sub_pass_parameters(
properties->emergency_stretch = properties->emergency_original;
}
} else if (okay & passes_emergencystretch_okay) {
- halfword v = tex_get_passes_emergencystretch(passes, subpass);
+ scaled v = tex_get_passes_emergencystretch(passes, subpass);
if (v) {
properties->emergency_stretch = v;
properties->emergency_original = v; /* ! */
@@ -4375,7 +4355,7 @@ static int tex_aux_set_sub_pass_parameters(
tex_aux_set_toddler_penalties(properties, 1);
}
/* */
- if (details) {
+ if lmt_unlikely(details) {
# define is_okay(a) ((okay & a) == a ? ">" : " ")
@@ -4507,11 +4487,10 @@ static int tex_aux_set_sub_pass_parameters(
static void tex_aux_skip_message(halfword passes, int subpass, int nofsubpasses, const char *str)
{
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: id %i, subpass %i of %i, skip %s]\n",
+ tex_print_format(
+ "%<%l[linebreak: id %i, subpass %i of %i, skip %s]\n%>",
passes_identifier(passes), subpass, nofsubpasses, str
);
- tex_end_diagnostic();
}
static inline int tex_aux_next_subpass(const line_break_properties *properties, halfword passes, int subpass, int nofsubpasses, halfword state, int tracing)
@@ -4521,7 +4500,7 @@ static inline int tex_aux_next_subpass(const line_break_properties *properties,
if (features & passes_test_set) {
if (features & passes_if_text) {
if (! paragraph_has_text(state)) {
- if (tracing) {
+ if lmt_unlikely(tracing) {
tex_aux_skip_message(passes, subpass, nofsubpasses, "no text");
}
continue;
@@ -4529,7 +4508,7 @@ static inline int tex_aux_next_subpass(const line_break_properties *properties,
}
if (features & passes_if_math) {
if (! paragraph_has_math(state)) {
- if (tracing) {
+ if lmt_unlikely(tracing) {
tex_aux_skip_message(passes, subpass, nofsubpasses, "no math");
}
continue;
@@ -4537,7 +4516,7 @@ static inline int tex_aux_next_subpass(const line_break_properties *properties,
}
if (features & passes_unless_math) {
if (paragraph_has_math(state)) {
- if (tracing) {
+ if lmt_unlikely(tracing) {
tex_aux_skip_message(passes, subpass, nofsubpasses, "do math");
}
continue;
@@ -4545,7 +4524,7 @@ static inline int tex_aux_next_subpass(const line_break_properties *properties,
}
if (features & passes_if_glue) {
if (! paragraph_has_glue(state)) {
- if (tracing) {
+ if lmt_unlikely(tracing) {
tex_aux_skip_message(passes, subpass, nofsubpasses, "no glue");
}
continue;
@@ -4553,7 +4532,7 @@ static inline int tex_aux_next_subpass(const line_break_properties *properties,
}
if (features & passes_if_space_factor) {
if (! paragraph_has_factor(state)) {
- if (tracing) {
+ if lmt_unlikely(tracing) {
tex_aux_skip_message(passes, subpass, nofsubpasses, "no space factor");
}
continue;
@@ -4561,7 +4540,7 @@ static inline int tex_aux_next_subpass(const line_break_properties *properties,
}
if (features & passes_if_adjust_spacing && tex_aux_has_expansion()) {
if (! paragraph_has_text(state) || ! tex_get_passes_adjustspacing(passes, subpass)) {
- if (tracing) {
+ if lmt_unlikely(tracing) {
tex_aux_skip_message(passes, subpass, nofsubpasses, "adjust spacing");
}
continue;
@@ -4582,7 +4561,7 @@ static inline int tex_aux_next_subpass(const line_break_properties *properties,
)
) {
- if (tracing) {
+ if lmt_unlikely(tracing) {
tex_aux_skip_message(passes, subpass, nofsubpasses, "emergency stretch");
}
continue;
@@ -4590,7 +4569,7 @@ static inline int tex_aux_next_subpass(const line_break_properties *properties,
}
if (features & passes_if_looseness) {
if (! properties->looseness) {
- if (tracing) {
+ if lmt_unlikely(tracing) {
tex_aux_skip_message(passes, subpass, nofsubpasses, "no looseness");
}
continue;
@@ -4611,12 +4590,11 @@ static inline int tex_aux_check_sub_pass(line_break_properties *properties, half
int tracing = properties->tracing_paragraphs > 0 || properties->tracing_passes > 0;
int result = tex_check_linebreak_quality(shortfall, &overfull, &underfull, &verdict, &classified);
if (result) {
- if (tracing && result > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: id %i, subpass %i of %i, overfull %p, verdict %i, special case, entering subpasses]\n",
+ if lmt_unlikely(tracing && result > 1) {
+ tex_print_format(
+ "%<%l[linebreak: id %i, subpass %i of %i, overfull %p, verdict %i, special case, entering subpasses]\n%>",
passes_identifier(passes), subpass, nofsubpasses, overfull, verdict
);
- tex_end_diagnostic();
}
while (subpass < nofsubpasses) {
subpass = tex_aux_next_subpass(properties, passes, subpass, nofsubpasses, state, tracing);
@@ -4644,7 +4622,7 @@ static inline int tex_aux_check_sub_pass(line_break_properties *properties, half
|| ((okay & passes_demerits_okay ) && (verdict > demerits))
|| ((okay & passes_classes_okay ) && (classes && (classes & classified) != 0))
;
- if (properties->tracing_passes > 1) {
+ if lmt_unlikely(properties->tracing_passes > 1) {
int id = passes_identifier(passes);
tex_begin_diagnostic();
tex_print_format("%l[linebreak: id %i, criteria for entering subpass %i of %i: test]\n",
@@ -4670,7 +4648,7 @@ static inline int tex_aux_check_sub_pass(line_break_properties *properties, half
);
tex_end_diagnostic();
}
- if (tracing) {
+ if lmt_unlikely(tracing) {
int id = passes_identifier(passes);
tex_begin_diagnostic();
if (callback) {
@@ -4713,7 +4691,7 @@ static inline int tex_aux_check_sub_pass(line_break_properties *properties, half
overfull, underfull, verdict, classified, threshold, demerits, classes
);
}
- if (tracing) {
+ if lmt_unlikely(tracing) {
tex_end_diagnostic();
}
if (success) {
@@ -4796,9 +4774,7 @@ static inline void tex_aux_wipe_optionals(const line_break_properties *propertie
static void tex_aux_show_threshold(const char *what, halfword value)
{
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: %s threshold %i]", what, value);
- tex_end_diagnostic();
+ tex_print_format("%<%l[linebreak: %s threshold %i]%>", what, value);
}
/*tex
@@ -4850,6 +4826,18 @@ static inline halfword tex_aux_analyze_list(halfword current)
}
*/
+static inline int tex_aux_next_is_glue(halfword current)
+{
+ halfword next = node_next(current);
+ return next && (node_type(next) == glue_node);
+}
+
+static inline int tex_aux_next_no_auto_break(halfword current)
+{
+ halfword next = node_next(current);
+ return next && (node_type(next) == glue_node) && tex_has_glue_option(next, glue_option_no_auto_break);
+}
+
static inline halfword tex_aux_break_list(const line_break_properties *properties, halfword pass, halfword subpass, halfword current, halfword first, halfword *state, int artificial)
{
halfword callback_id = lmt_linebreak_state.callback_id;
@@ -4900,11 +4888,11 @@ static inline halfword tex_aux_break_list(const line_break_properties *propertie
halfword t = pass == linebreak_first_pass ? tex_get_local_pre_tolerance(current) : tex_get_local_tolerance(current);
if (t == 0) {
t = lmt_linebreak_state.global_threshold;
- if (properties->tracing_paragraphs > 1) {
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
tex_aux_show_threshold("global", t);
}
} else {
- if (properties->tracing_paragraphs > 1) {
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
tex_aux_show_threshold("local", t);
}
}
@@ -5093,7 +5081,7 @@ static inline halfword tex_aux_break_list(const line_break_properties *propertie
halfword post = disc_post_break_head(current);
scaled wpost = post ? tex_natural_hsize(post, NULL) : 0;
if (wpost > 0) {
- if (properties->tracing_paragraphs > 1) {
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
tex_begin_diagnostic();
tex_print_format("%l[linebreak: favour final prepost over replace, widths %p %p]", wpre + wpost, wreplace);
tex_print_format("%l[linebreak: stripe] ");
@@ -5105,7 +5093,7 @@ static inline halfword tex_aux_break_list(const line_break_properties *propertie
}
} else {
if (wreplace < wpre) {
- if (properties->tracing_paragraphs > 1) {
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
tex_begin_diagnostic();
tex_print_format("%l[linebreak: favour final replace over pre, widths %p %p]", wreplace, wpre);
tex_print_format("%l[linebreak: stripe] ");
@@ -5179,7 +5167,7 @@ static inline halfword tex_aux_break_list(const line_break_properties *propertie
lmt_linebreak_state.threshold = math_tolerance(current);
}
}
- if (properties->tracing_paragraphs > 1) {
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
tex_aux_show_threshold("math", lmt_linebreak_state.threshold);
}
break;
@@ -5190,7 +5178,7 @@ static inline halfword tex_aux_break_list(const line_break_properties *propertie
be wrong, which is why we save the old threshold and use that.
*/
lmt_linebreak_state.threshold = lmt_linebreak_state.saved_threshold;
- if (properties->tracing_paragraphs > 1) {
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
tex_aux_show_threshold("text", lmt_linebreak_state.threshold);
}
break;
@@ -5208,10 +5196,24 @@ static inline halfword tex_aux_break_list(const line_break_properties *propertie
break;
case end_inline_math:
{
- halfword penalty = math_penalty(current);
- if (node_type(node_next(current)) == glue_node) {
- if (properties->math_penalty_factor) {
+ if (tex_aux_next_no_auto_break(current)) {
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
+ tex_print_format("%<%l[linebreak: no autobreak after math, case 1]%>");
+ }
+ /* the next glue determines the break */
+ } else if (tex_aux_next_is_glue(current)) {
+ halfword penalty = math_penalty(current);
+ halfword gluepen = glue_penalty(node_next(current));
+ if (gluepen > penalty) {
+ penalty = gluepen;
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
+ tex_print_format("%<%l[linebreak: next is glue, use penalty %i]%>", penalty);
+ }
+ } else if (properties->math_penalty_factor) {
penalty = tex_xn_over_d_factor(penalty, properties->math_penalty_factor);
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
+ tex_print_format("%<%l[linebreak: next is glue, end penalty %i]%>", penalty);
+ }
}
tex_aux_try_break(properties, penalty, unhyphenated_node, first, current, callback_id, checks, pass, subpass, artificial);
}
@@ -5229,10 +5231,31 @@ static inline halfword tex_aux_break_list(const line_break_properties *propertie
break;
case end_inline_math:
{
- halfword penalty = math_penalty(current);
- if (tex_aux_valid_glue_break(current)) {
- if (properties->math_penalty_factor) {
+ if (tex_aux_next_no_auto_break(current)) {
+ /* the next glue determines the break */
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
+ tex_print_format("%<%l[linebreak: no autobreak after math, case 2]%>");
+ }
+ } else if (tex_aux_valid_glue_break(current)) {
+ halfword penalty = math_penalty(current);
+ if (tex_aux_next_is_glue(current)) {
+ halfword gluepen = glue_penalty(node_next(current));
+ if (gluepen > penalty) {
+ penalty = gluepen;
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
+ tex_print_format("%<%l[linebreak: next is glue, use penalty %i]%>", penalty);
+ }
+ } else if (properties->math_penalty_factor) {
+ penalty = tex_xn_over_d_factor(penalty, properties->math_penalty_factor);
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
+ tex_print_format("%<%l[linebreak: next is glue, end penalty %i]%>", penalty);
+ }
+ }
+ } else if (properties->math_penalty_factor) {
penalty = tex_xn_over_d_factor(penalty, properties->math_penalty_factor);
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
+ tex_print_format("%<%l[linebreak: next is glue, end penalty %i]%>", penalty);
+ }
}
tex_aux_try_break(properties, penalty, unhyphenated_node, first, current, callback_id, checks, pass, subpass, artificial);
}
@@ -5289,14 +5312,12 @@ static inline halfword tex_aux_break_list(const line_break_properties *propertie
static void tex_aux_report_fitness_classes(const line_break_properties *properties, int pass, int subpass)
{
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: fitnessclasses, pass %i, subpass %i]\n", pass, subpass);
+ tex_print_format("%<%l[linebreak: fitnessclasses, pass %i, subpass %i]\n%>", pass, subpass);
for (halfword c = 1; c <= tex_get_specification_count(properties->fitness_classes); c++) {
tex_print_format("%l %i : %i\n", c,
tex_get_specification_fitness_class(properties->fitness_classes, c)
);
}
- tex_end_diagnostic();
}
static void tex_aux_report_adjacent_demerits(const line_break_properties *properties, int pass, int subpass)
@@ -5381,7 +5402,7 @@ static void tex_aux_set_indentation(const line_break_properties *properties)
lmt_linebreak_state.second_width = properties->hsize;
lmt_linebreak_state.second_indent = 0;
} else {
- halfword used_hang_indent = swap_hang_indent(properties->paragraph_direction, properties->hang_indent);
+ scaled used_hang_indent = swap_hang_indent(properties->paragraph_direction, properties->hang_indent);
scaled used_hang_hsize = properties->hsize - abs(used_hang_indent);
/*tex
@@ -5531,7 +5552,7 @@ static int tex_aux_quit_linebreak(const line_break_properties *properties, int p
halfword best_line = lmt_linebreak_state.best_line;
int verdict = 0;
int tracing = tracing_looseness_par;
- if (tracing) {
+ if lmt_unlikely(tracing) {
tex_begin_diagnostic();
tex_print_format("%l[looseness: pass %i, lines %i, looseness %i]\n", pass, best_line - 1, properties->looseness);
}
@@ -5544,17 +5565,17 @@ static int tex_aux_quit_linebreak(const line_break_properties *properties, int p
lmt_linebreak_state.best_bet = r;
actual_looseness = line_difference;
lmt_linebreak_state.fewest_demerits = total_demerits;
- if (tracing) {
+ if lmt_unlikely(tracing) {
tex_print_format("%l[looseness: pass %i, line %i, difference %i, demerits %i, %s optimal]", pass, line_number - 1, line_difference, total_demerits, "sub");
}
} else if (line_difference == actual_looseness && total_demerits < lmt_linebreak_state.fewest_demerits) {
lmt_linebreak_state.best_bet = r;
lmt_linebreak_state.fewest_demerits = total_demerits;
- if (tracing) {
+ if lmt_unlikely(tracing) {
tex_print_format("%l[looseness: pass %i, line %i, difference %i, demerits %i, %s optimal]", pass, line_number - 1, line_difference, total_demerits, "more");
}
} else {
- if (tracing) {
+ if lmt_unlikely(tracing) {
tex_print_format("%l[looseness: pass %i, line %i, difference %i, demerits %i, %s optimal]", pass, line_number - 1, line_difference, total_demerits, "not");
}
}
@@ -5564,7 +5585,7 @@ static int tex_aux_quit_linebreak(const line_break_properties *properties, int p
lmt_linebreak_state.actual_looseness = actual_looseness;
lmt_linebreak_state.best_line = active_line_number(lmt_linebreak_state.best_bet);
verdict = actual_looseness == properties->looseness;
- if (tracing) {
+ if lmt_unlikely(tracing) {
/*tex
The finally reported demerits in the tracker lack the linepenalty squared etc. so
we cannot really compare these values.
@@ -5695,7 +5716,7 @@ void tex_do_line_break(line_break_properties *properties)
final pass : tolerance with hyphenation and emergencystretch and looseness
*/
lmt_linebreak_state.threshold = properties->pretolerance;
- if (properties->tracing_paragraphs > 1) {
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
tex_begin_diagnostic();
tex_print_format("%l[linebreak: original] ");
tex_short_display(first);
@@ -5704,7 +5725,7 @@ void tex_do_line_break(line_break_properties *properties)
if (subpasses) {
pass = linebreak_specification_pass;
lmt_linebreak_state.threshold = properties->pretolerance; /* or tolerance */
- if (properties->tracing_paragraphs > 0 || properties->tracing_passes > 0) {
+ if lmt_unlikely(properties->tracing_paragraphs > 0 || properties->tracing_passes > 0) {
if (specification_presets(passes)) {
tex_begin_diagnostic();
tex_print_format("%l[linebreak: specification presets]");
@@ -5730,10 +5751,8 @@ void tex_do_line_break(line_break_properties *properties)
routine returns either |null| or some place in the list that needs attention.
*/
/* state = tex_aux_analyze_list(first); */
- if (subpasses && properties->tracing_raggedness > 0) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: first final %i in %i]", passes_first_final(passes), subpasses);
- tex_end_diagnostic();
+ if lmt_unlikely(subpasses && properties->tracing_raggedness > 0) {
+ tex_print_format("%<%l[linebreak: first final %i in %i]%>", passes_first_final(passes), subpasses);
}
while (1) {
halfword current = first;
@@ -5745,7 +5764,7 @@ void tex_do_line_break(line_break_properties *properties)
case linebreak_no_pass:
goto DONE;
case linebreak_first_pass:
- if (properties->tracing_paragraphs > 0 || properties->tracing_passes > 0) {
+ if lmt_unlikely(properties->tracing_paragraphs > 0 || properties->tracing_passes > 0) {
tex_begin_diagnostic();
tex_print_format("%l[linebreak: first pass, used tolerance %i]", lmt_linebreak_state.threshold);
// tex_end_diagnostic();
@@ -5755,7 +5774,7 @@ void tex_do_line_break(line_break_properties *properties)
case linebreak_second_pass:
if (tex_aux_emergency(properties)) {
lmt_linebreak_state.passes[properties->par_context].n_of_second_passes++;
- if (properties->tracing_paragraphs > 0 || properties->tracing_passes > 0) {
+ if lmt_unlikely(properties->tracing_paragraphs > 0 || properties->tracing_passes > 0) {
tex_begin_diagnostic();
tex_print_format("%l[linebreak: second pass, used tolerance %i]", lmt_linebreak_state.threshold);
// tex_end_diagnostic();
@@ -5768,7 +5787,7 @@ void tex_do_line_break(line_break_properties *properties)
FALLTHROUGH
case linebreak_final_pass:
lmt_linebreak_state.passes[properties->par_context].n_of_final_passes++;
- if (properties->tracing_paragraphs > 0 || properties->tracing_passes > 0) {
+ if lmt_unlikely(properties->tracing_paragraphs > 0 || properties->tracing_passes > 0) {
tex_begin_diagnostic();
tex_print_format("%l[linebreak: final pass, used tolerance %i, used emergency stretch %p]", lmt_linebreak_state.threshold, properties->emergency_stretch);
// tex_end_diagnostic();
@@ -5809,7 +5828,7 @@ void tex_do_line_break(line_break_properties *properties)
break;
}
}
- if (properties->tracing_paragraphs > 0 || properties->tracing_passes > 0) {
+ if lmt_unlikely(properties->tracing_paragraphs > 0 || properties->tracing_passes > 0) {
tex_begin_diagnostic();
tex_print_format("%l[linebreak: specification subpass %i]\n", subpass);
}
@@ -5821,7 +5840,7 @@ void tex_do_line_break(line_break_properties *properties)
lmt_linebreak_state.threshold = infinite_bad; /* we can move this check to where threshold is set */
}
lmt_linebreak_state.global_threshold = lmt_linebreak_state.threshold;
- if (properties->tracing_fitness && properties->fitness_classes) {
+ if lmt_unlikely(properties->tracing_fitness && properties->fitness_classes) {
tex_aux_report_fitness_classes(properties, pass, subpass);
tex_aux_report_adjacent_demerits(properties, pass, subpass);
}
@@ -5955,7 +5974,7 @@ void tex_do_line_break(line_break_properties *properties)
if (force || lmt_linebreak_state.raggedness >= raggedness) {
if (subpass < passes_first_final(passes)) {
subpass += 1;
- if (! force && (properties->tracing_paragraphs > 0 || properties->tracing_passes > 0)) {
+ if lmt_unlikely(! force && (properties->tracing_paragraphs > 0 || properties->tracing_passes > 0)) {
tex_print_format("%l[linebreak: subpass %i, raggedness %i >= %i]\n", subpass, lmt_linebreak_state.raggedness, raggedness);
}
goto HERE;
@@ -5989,7 +6008,7 @@ void tex_do_line_break(line_break_properties *properties)
++subpass;
}
HERE:
- if (properties->tracing_paragraphs > 0 || properties->tracing_passes > 0) {
+ if lmt_unlikely(properties->tracing_paragraphs > 0 || properties->tracing_passes > 0) {
tex_end_diagnostic(); // see above
}
/*tex Clean up the memory by removing the break nodes. */
@@ -6024,7 +6043,7 @@ void tex_do_line_break(line_break_properties *properties)
if (lmt_linebreak_state.callback_id) {
tex_aux_line_break_callback_stop(lmt_linebreak_state.callback_id, properties->line_break_checks);
}
- if (properties->tracing_paragraphs > 0 || properties->tracing_passes > 0) {
+ if lmt_unlikely(properties->tracing_paragraphs > 0 || properties->tracing_passes > 0) {
tex_end_diagnostic(); // see above
}
INDEED:
@@ -6037,8 +6056,8 @@ void tex_do_line_break(line_break_properties *properties)
{
int callback_id = lmt_callback_defined(linebreak_quality_callback);
if (callback_id > 0) {
- halfword overfull = 0;
- halfword underfull = 0;
+ scaled overfull = 0;
+ scaled underfull = 0;
halfword verdict = 0;
halfword classified = 0;
tex_check_linebreak_quality(0, &overfull, &underfull, &verdict, &classified);
@@ -6175,10 +6194,8 @@ static halfword checked_penalty(long long p)
static void tex_aux_trace_penalty(const char *what, int line, int index, long long penalty, long long total)
{
- if (tracing_penalties_par > 0) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: %s penalty, line %i, index %i, delta %i, total %i]", what, line, index, checked_penalty(penalty), checked_penalty(total));
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_penalties_par > 0) {
+ tex_print_format("%<%l[linebreak: %s penalty, line %i, index %i, delta %i, total %i]%>", what, line, index, checked_penalty(penalty), checked_penalty(total));
}
}
@@ -6249,7 +6266,7 @@ static void tex_aux_post_line_break(const line_break_properties *properties, hal
}
}
/*tex Temporary: */
- if (properties->tracing_passes > 0) {
+ if lmt_unlikely(properties->tracing_passes > 0) {
halfword passive = cur_p;
tex_begin_diagnostic();
tex_print_format("%l[linebreak: (class demerits deficiency)");
@@ -6610,7 +6627,7 @@ static void tex_aux_post_line_break(const line_break_properties *properties, hal
if (properties->protrude_chars) {
if (line_break_dir == dir_righttoleft && properties->protrude_chars == protrude_chars_advanced) {
halfword p = tex_aux_find_protchar_left(q, 0);
- halfword w = tex_char_protrusion(p, left_margin_kern_subtype);
+ scaled w = tex_char_protrusion(p, left_margin_kern_subtype);
if (w && lmt_packaging_state.last_leftmost_char) {
halfword k = tex_new_kern_node(-w, left_margin_kern_subtype);
tex_attach_attribute_list_copy(k, p);
@@ -6619,7 +6636,7 @@ static void tex_aux_post_line_break(const line_break_properties *properties, hal
}
} else {
halfword p = tex_aux_find_protchar_left(q, 0);
- halfword w = tex_char_protrusion(p, left_margin_kern_subtype);
+ scaled w = tex_char_protrusion(p, left_margin_kern_subtype);
if (w && lmt_packaging_state.last_leftmost_char) {
halfword k = tex_new_kern_node(-w, left_margin_kern_subtype);
tex_attach_attribute_list_copy(k, p);
@@ -6772,10 +6789,8 @@ static void tex_aux_post_line_break(const line_break_properties *properties, hal
if (hasglyphs) {
++lmt_linebreak_state.n_of_text_lines;
}
- if (properties->tracing_paragraphs > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: flatten, line %i, count %i]", cur_line, count);
- tex_end_diagnostic();
+ if lmt_unlikely(properties->tracing_paragraphs > 1) {
+ tex_print_format("%<%l[linebreak: flatten, line %i, count %i]%>", cur_line, count);
}
}
/*tex
@@ -6795,8 +6810,8 @@ static void tex_aux_post_line_break(const line_break_properties *properties, hal
if (normalize_line_mode_option(normalize_line_mode)) {
halfword head = q;
halfword tail = rs ? rs : head;
- halfword lefthang = 0;
- halfword righthang = 0;
+ scaled lefthang = 0;
+ scaled righthang = 0;
// we already have the tail somewhere
while (node_next(tail)) {
tail = node_next(tail);
@@ -6995,7 +7010,7 @@ static void tex_aux_post_line_break(const line_break_properties *properties, hal
/*tex So only set when we normalize. */
if (last_line) {
halfword linebox = lmt_linebreak_state.just_box;
- halfword width = 0;
+ scaled width = 0;
if (linebox) {
width = box_width(linebox);
width -= tex_effective_glue(linebox, properties->left_skip);
@@ -7105,7 +7120,7 @@ static void tex_aux_post_line_break(const line_break_properties *properties, hal
if (! spm) {
shaping = 0;
}
- if (tracing_penalties_par > 1) {
+ if lmt_unlikely(tracing_penalties_par > 1) {
tex_begin_diagnostic();
tex_print_format("%l[linebreak: penalty, line %i, best line %i, prevgraf %i, mode %x (i=%i c=%i w=%i b=%i)]",
cur_line, lmt_linebreak_state.best_line, cur_list.prev_graf, spm,
@@ -7356,10 +7371,8 @@ static void tex_aux_post_line_break(const line_break_properties *properties, hal
}
/* We can clean up the par nodes. */
} while (cur_p);
- if (cur_line != lmt_linebreak_state.best_line) {
- tex_begin_diagnostic();
- tex_print_format("%l[linebreak: dubious situation, current line %i is not best line %i]", cur_line, lmt_linebreak_state.best_line);
- tex_end_diagnostic();
+ if lmt_unlikely(cur_line != lmt_linebreak_state.best_line) {
+ tex_print_format("%<%l[linebreak: dubious situation, current line %i is not best line %i]%>", cur_line, lmt_linebreak_state.best_line);
// tex_confusion("line breaking 1");
} else if (node_next(temp_head)) {
tex_confusion("line breaking 2");
diff --git a/source/luametatex/source/tex/texlocalboxes.c b/source/luametatex/source/tex/texlocalboxes.c
index b1d583c41..b6d1c4e03 100644
--- a/source/luametatex/source/tex/texlocalboxes.c
+++ b/source/luametatex/source/tex/texlocalboxes.c
@@ -330,7 +330,7 @@ void tex_set_local_interline_penalty (halfword p, halfword penalty ) { par
void tex_set_local_broken_penalty (halfword p, halfword penalty ) { par_broken_penalty(p) = penalty; }
void tex_set_local_tolerance (halfword p, halfword tolerance) { par_tolerance(p) = tolerance; }
void tex_set_local_pre_tolerance (halfword p, halfword tolerance) { par_pre_tolerance(p) = tolerance; }
-void tex_set_local_hang_indent (halfword p, halfword amount) { par_hang_indent(p) = amount; }
+void tex_set_local_hang_indent (halfword p, scaled amount) { par_hang_indent(p) = amount; }
void tex_set_local_hang_after (halfword p, halfword amount) { par_hang_after(p) = amount; }
typedef enum saved_localbox_entries {
diff --git a/source/luametatex/source/tex/texmaincontrol.c b/source/luametatex/source/tex/texmaincontrol.c
index 87b619884..49c1637d8 100644
--- a/source/luametatex/source/tex/texmaincontrol.c
+++ b/source/luametatex/source/tex/texmaincontrol.c
@@ -113,6 +113,7 @@ static void tex_aux_fixup_math_and_unsave(void)
int saved_math_scale = internal_math_scale_par;
tex_unsave();
if (cur_mode == mmode) {
+ /* We could combine these in one node but let's keep it simple. */
if (saved_math_style >= 0 && saved_math_style != cur_list.math_style) {
halfword noad = tex_new_node(style_node, (quarterword) saved_math_style);
cur_list.math_style = saved_math_style;
@@ -121,6 +122,7 @@ static void tex_aux_fixup_math_and_unsave(void)
if (saved_math_scale != cur_list.math_scale) {
halfword noad = tex_new_node(style_node, scaled_math_style);
style_scale(noad) = saved_math_scale;
+ style_glyph_scale(noad) = glyph_scale_par;
cur_list.math_scale = saved_math_scale;
tex_tail_append(noad);
}
@@ -373,7 +375,7 @@ static void tex_aux_run_node(void)
halfword n = cur_chr;
if (node_token_flagged(n)) {
tex_get_token();
- n = node_token_sum(n,cur_chr);
+ n = node_token_sum(n, cur_chr);
}
if (copy_lua_input_nodes_par) {
n = tex_copy_node_list(n, null);
@@ -700,10 +702,8 @@ static void tex_aux_run_ignore_something(void)
static void tex_aux_run_math_non_math(void)
{
- if (tracing_commands_par >= 4) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: pushing back %C]", cur_cmd, cur_chr);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_commands_par >= 4) {
+ tex_print_format("%<%l[math: pushing back %C]%>", cur_cmd, cur_chr);
}
tex_back_input(cur_tok);
tex_begin_paragraph(1, math_char_par_trigger);
@@ -976,7 +976,7 @@ static void tex_aux_scan_box(int boxcontext, int optional_equal, scaled shift, h
static void tex_aux_run_move(void)
{
int code = cur_chr;
- halfword val = tex_scan_dimension(0, 0, 0, 0, NULL, NULL);
+ scaled val = tex_scan_dimension(0, 0, 0, 0, NULL, NULL);
tex_aux_scan_box(direct_box_flag, 0, code == move_forward_code ? val : - val, -1, 0, 0);
}
@@ -1291,10 +1291,8 @@ static void tex_aux_run_new_paragraph(void)
context = normal_par_trigger;
break;
}
- if (tracing_commands_par >= 4) {
- tex_begin_diagnostic();
- tex_print_format("%l[text: pushing back %C]", cur_cmd, cur_chr);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_commands_par >= 4) {
+ tex_print_format("%<%l[text: pushing back %C]%>", cur_cmd, cur_chr);
}
tex_back_input(cur_tok);
tex_begin_paragraph(1, context);
@@ -1315,12 +1313,11 @@ static void tex_aux_run_new_paragraph(void)
void tex_page_boundary_message(const char *s, halfword b)
{
- if (tracing_pages_par > 0) {
- tex_begin_diagnostic();
- tex_print_format("%l[page: boundary, %s, trigger %i, detail %i]",
+ if lmt_unlikely(tracing_pages_par > 0) {
+ tex_print_format(
+ "%<%l[page: boundary, %s, trigger %i, detail %i]%>",
s, b ? boundary_data(b) : 0, b ? boundary_reserved(b) : 0
);
- tex_end_diagnostic();
}
}
@@ -1791,7 +1788,7 @@ static void tex_aux_run_catcode_table(void)
static void tex_aux_run_end_local(void)
{
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
tex_local_control_message("leaving token scanner due to local end token");
}
tex_end_local_control();
@@ -1852,7 +1849,7 @@ int tex_main_control(void)
Give diagnostic information, if requested. When a new token has just been fetched at
|big_switch|, we have an ideal place to monitor \TEX's activity.
*/
- if (tracing_commands_par > 0) {
+ if lmt_unlikely(tracing_commands_par > 0) {
tex_show_cmd_chr(cur_cmd, cur_chr);
}
/*tex Run the command: */
@@ -1869,9 +1866,7 @@ int tex_main_control(void)
void tex_local_control_message(const char *s)
{
- tex_begin_diagnostic();
- tex_print_format("%l[local control: level %i, %s]", lmt_main_control_state.local_level, s);
- tex_end_diagnostic();
+ tex_print_format("%<%l[local control: level %i, %s]%>", lmt_main_control_state.local_level, s);
}
/*tex
@@ -1904,19 +1899,19 @@ void tex_local_control(int obeymode)
} else {
tex_get_x_token();
}
- if (tracing_commands_par > 0) {
+ if lmt_unlikely(tracing_commands_par > 0) {
tex_show_cmd_chr(cur_cmd, cur_chr);
}
tex_aux_big_switch(cur_mode, cur_cmd);
if (lmt_main_control_state.local_level <= at_level) {
lmt_main_control_state.control_state = goto_next_state;
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
/*tex This is a kind of duplicate message, which can be confusing */
tex_local_control_message("leaving local control due to level change");
}
break;
} else if (lmt_main_control_state.control_state == goto_return_state) {
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
tex_local_control_message("leaving local control due to triggering");
}
break;
@@ -1998,7 +1993,7 @@ static inline void tex_update_stack_entry(halfword count)
void tex_begin_local_control(void)
{
halfword code = cur_chr;
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
tex_local_control_message("entering token scanner via primitive");
}
switch (code) {
@@ -2245,7 +2240,7 @@ halfword tex_local_scan_box(void)
tex_aux_scan_box(lua_scan_flag, 0, null_flag, -1, 0, 0);
if (lmt_main_control_state.local_level == old_level) {
/*tex |\directlua{print(token.scan_list())}\hbox{!}| (n n) */
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
tex_local_control_message("entering at end of box scanning");
}
tex_local_control(1);
@@ -2253,7 +2248,7 @@ halfword tex_local_scan_box(void)
} else {
/*tex |\directlua{print(token.scan_list())}\box0| (n-1 n) */
/*
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
local_control_message("setting level after box scanning");
}
*/
@@ -2274,7 +2269,7 @@ halfword tex_local_scan_box(void)
static void tex_aux_wrapup_local_scan_box(void)
{
/*
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
local_control_message("leaving box scanner");
}
*/
@@ -3060,7 +3055,7 @@ void tex_begin_paragraph(int doindent, int context)
if (every_before_par_par) {
tex_begin_inserted_list(tex_get_available_token(token_val(end_local_cmd, 0)));
tex_begin_token_list(every_before_par_par, every_before_par_text);
- if (tracing_nesting_par > 2) {
+ if lmt_unlikely(tracing_nesting_par > 2) {
tex_local_control_message("entering local control via \\everybeforepar");
}
tex_local_control(1);
@@ -3097,7 +3092,7 @@ void tex_begin_paragraph(int doindent, int context)
tex_append_dir_state();
}
tex_aux_insert_parindent(indented);
- if (tracing_paragraph_lists) {
+ if lmt_unlikely(tracing_paragraph_lists) {
tex_begin_diagnostic();
// tex_print_format("%l[paragraph: start, context %i]", context);
tex_print_format("%l[paragraph: start, context %s]", lmt_interface.par_trigger_values[context].name);
@@ -3175,7 +3170,7 @@ static void tex_aux_run_head_for_vmode(void)
/*
static void tex_aux_run_kern(void)
{
- halfword val = tex_scan_dimension(0, 0, 0, 0, NULL, NULL);
+ scaled val = tex_scan_dimension(0, 0, 0, 0, NULL, NULL);
tex_tail_append(tex_new_kern_node(val, explicit_kern));
}
*/
@@ -3214,7 +3209,7 @@ static void tex_aux_run_kern(void)
static void tex_aux_run_mkern(void)
{
- halfword val = tex_scan_dimension(1, 0, 0, 0, NULL, NULL);
+ scaled val = tex_scan_dimension(1, 0, 0, 0, NULL, NULL);
tex_tail_append(tex_new_kern_node(val, explicit_math_kern_subtype));
}
@@ -3485,6 +3480,7 @@ static void tex_aux_run_text_italic_correction(void)
return;
}
}
+ break;
case disc_node:
/*tex
Just in case we want this but here checking has to be done in the callback
@@ -5107,19 +5103,15 @@ static void tex_aux_set_def(int flags, int force)
if (global_defs_par < 0) {
if (is_global(flags)) {
remove_global_flag(flags);
- if (tracing_commands_par) {
- begin_diagnostic();
- tex_print_format("%l[global canceled]");
- end_diagnostic();
+ if lmt_unlikely(tracing_commands_par) {
+ tex_print_format("%<%l[global canceled]%>");
}
}
} else {
if (! is_global(flags)) {
add_global_flag(flags);
- if (tracing_commands_par) {
- begin_diagnostic();
- tex_print_format("%l[global enforced]");
- end_diagnostic();
+ if lmt_unlikely(tracing_commands_par) {
+ tex_print_format("%<%l[global enforced]%>");
}
}
}
@@ -6172,7 +6164,7 @@ static void tex_run_prefixed_command(void)
do {
tex_get_x_token();
} while (cur_cmd == spacer_cmd || cur_cmd == relax_cmd);
- if (tracing_commands_par > 2) {
+ if lmt_unlikely(tracing_commands_par > 2) {
tex_show_cmd_chr(cur_cmd, cur_chr);
}
}
@@ -6680,6 +6672,17 @@ void tex_assign_internal_integer_value(int a, halfword p, int val)
}
tex_word_define(a, p, val);
break;
+ case variable_family_code:
+ if (val == math_variable_mode_keep || val == math_variable_mode_unset) {
+ /* we're okay */
+ } else if (fam_par_in_range(val)) {
+ /* we're okay */
+ } else {
+ /* just silently ignore */
+ break;
+ }
+ tex_word_define(a, p, val);
+ break;
default:
DEFINE:
tex_word_define(a, p, val);
@@ -7465,7 +7468,7 @@ void tex_initialize_variables(void)
post_inline_penalty_par = max_integer;
pre_short_inline_penalty_par = max_integer;
post_short_inline_penalty_par = max_integer;
- variable_family_par = -1,
+ variable_family_par = math_variable_mode_keep,
ignore_depth_criterion_par = ignore_depth;
script_space_before_factor_par = scaling_factor;
script_space_between_factor_par = scaling_factor;
diff --git a/source/luametatex/source/tex/texmarks.c b/source/luametatex/source/tex/texmarks.c
index 971286822..65b4cdcd9 100644
--- a/source/luametatex/source/tex/texmarks.c
+++ b/source/luametatex/source/tex/texmarks.c
@@ -153,18 +153,18 @@ halfword tex_new_mark(quarterword subtype, halfword index, halfword ptr)
static void tex_aux_print_mark(const char *s, halfword t)
{
if (t) {
- /* todo: proper indentation */
+ /* todo: proper indentation when we are in a node list */
tex_print_token_list(s, token_link(t));
}
}
void tex_show_marks()
{
- if (tracing_marks_par > 0 && lmt_mark_state.min_used >= 0) {
+ if lmt_unlikely(tracing_marks_par > 0 && lmt_mark_state.min_used >= 0) {
tex_begin_diagnostic();
for (halfword m = lmt_mark_state.min_used; m <= lmt_mark_state.max_used; m++) {
if (tex_has_mark(m)) {
- tex_print_format("%l[mark: index %i, page state]",m);
+ tex_print_format("%l[mark: index %i, page state]", m);
tex_aux_print_mark("top", tex_get_mark(m, top_marks_code));
tex_aux_print_mark("first", tex_get_mark(m, first_marks_code));
tex_aux_print_mark("bot", tex_get_mark(m, bot_marks_code));
@@ -185,7 +185,7 @@ int tex_update_top_marks()
halfword bot = tex_get_mark(m, bot_marks_code);
if (bot) {
tex_set_mark(m, top_marks_code, bot);
- if (tracing_marks_par > 1) {
+ if lmt_unlikely(tracing_marks_par > 1) {
tex_begin_diagnostic();
tex_print_format("%l[mark: index %i, top becomes bot]", m);
tex_aux_print_mark(NULL, bot);
@@ -205,7 +205,7 @@ void tex_update_first_and_bot_mark(halfword n)
halfword ptr = mark_ptr(n);
if (node_subtype(n) == reset_mark_value_code) {
/*tex Work in progress. */
- if (tracing_marks_par > 1) {
+ if lmt_unlikely(tracing_marks_par > 1) {
tex_begin_diagnostic();
tex_print_format("%l[mark: index %i, reset]", index);
tex_end_diagnostic();
@@ -216,7 +216,7 @@ void tex_update_first_and_bot_mark(halfword n)
halfword first = tex_get_mark(index, first_marks_code);
if (! first) {
tex_set_mark(index, first_marks_code, ptr);
- if (tracing_marks_par > 1) {
+ if lmt_unlikely(tracing_marks_par > 1) {
tex_begin_diagnostic();
tex_print_format("%l[mark: index %i, first becomes mark]", index);
tex_aux_print_mark(NULL, ptr);
@@ -224,7 +224,7 @@ void tex_update_first_and_bot_mark(halfword n)
}
}
tex_set_mark(index, bot_marks_code, ptr);
- if (tracing_marks_par > 1) {
+ if lmt_unlikely(tracing_marks_par > 1) {
tex_begin_diagnostic();
tex_print_format("%l[mark: index %i, bot becomes mark]", index);
tex_aux_print_mark(NULL, ptr);
@@ -242,7 +242,7 @@ int tex_update_first_marks(void)
halfword first = tex_get_mark(m, first_marks_code);
if (top && ! first) {
tex_set_mark(m, first_marks_code, top);
- if (tracing_marks_par > 1) {
+ if lmt_unlikely(tracing_marks_par > 1) {
tex_begin_diagnostic();
tex_print_format("%l[mark: index %i, first becomes top]", m);
tex_aux_print_mark(NULL, top);
@@ -281,7 +281,7 @@ void tex_update_split_mark(halfword n)
tex_reset_mark(index);
} else if (tex_get_mark(index, split_first_marks_code)) {
tex_set_mark(index, split_bot_marks_code, ptr);
- if (tracing_marks_par > 1) {
+ if lmt_unlikely(tracing_marks_par > 1) {
tex_begin_diagnostic();
tex_print_format("%l[mark: index %i, split bot becomes mark]", index);
tex_aux_print_mark(NULL, tex_get_mark(index, split_bot_marks_code));
@@ -290,7 +290,7 @@ void tex_update_split_mark(halfword n)
} else {
tex_set_mark(index, split_first_marks_code, ptr);
tex_set_mark(index, split_bot_marks_code, ptr);
- if (tracing_marks_par > 1) {
+ if lmt_unlikely(tracing_marks_par > 1) {
tex_begin_diagnostic();
tex_print_format("%l[mark: index %i, split first becomes mark]", index);
tex_aux_print_mark(NULL, tex_get_mark(index, split_first_marks_code));
diff --git a/source/luametatex/source/tex/texmath.c b/source/luametatex/source/tex/texmath.c
index 6391945fe..8d56536a0 100644
--- a/source/luametatex/source/tex/texmath.c
+++ b/source/luametatex/source/tex/texmath.c
@@ -669,7 +669,7 @@ int tex_math_has_class_option(halfword cls, int option)
return 0;
}
halfword value = count_parameter(first_math_options_code + cls);
- if (value == no_class_options) {
+ if (value == (halfword) no_class_options) {
unsigned parent = (unsigned) count_parameter(first_math_parent_code + cls);
cls = (parent >> 16) & 0xFF;
if (! valid_math_class_code(cls)) {
@@ -686,7 +686,7 @@ int tex_math_has_class_parent(halfword cls)
return 0;
}
halfword value = count_parameter(first_math_options_code + cls);
- if (value == no_class_options) {
+ if (value == (halfword) no_class_options) {
unsigned parent = (unsigned) count_parameter(first_math_parent_code + cls);
return (parent >> 16) & 0xFF;
}
@@ -756,9 +756,7 @@ static void tex_aux_print_parameter(const char *what, halfword style, halfword p
static void tex_aux_print_fam(const char *what, halfword size, halfword fam)
{
- tex_begin_diagnostic();
- tex_print_format("%l{%s %C family %i: %F}", what, define_family_cmd, size, fam, tex_fam_fnt(fam, size));
- tex_end_diagnostic();
+ tex_print_format("%<%l{%s %C family %i: %F}%>", what, define_family_cmd, size, fam, tex_fam_fnt(fam, size));
}
/*tex
@@ -1205,7 +1203,11 @@ static quarterword tex_aux_set_math_char(halfword target, mathcodeval *mval, mat
{
halfword hmcode = tex_get_hm_code(mval->character_value);
math_kernel_character(target) = mval->character_value;
- if (variable_family_par == -2) {
+ /*tex
+ We default to |math_variable_mode_keep| because it makes most sense for us but other
+ macro packages might like |math_variable_mode_unset| more.
+ */
+ if (variable_family_par == math_variable_mode_keep) {
/*tex For those (read: context) who want to use this variable class as intended. */
math_kernel_family(target) = cur_fam_par_in_range ? cur_fam_par : mval->family_value;
node_subtype(target) = mval->class_value;
@@ -1213,7 +1215,8 @@ static quarterword tex_aux_set_math_char(halfword target, mathcodeval *mval, mat
/*tex For CMS chairman MS, so that he can answer a ltx question someplace. */
math_kernel_family(target) = cur_fam_par_in_range ? cur_fam_par : mval->family_value;
node_subtype(target) = ordinary_noad_subtype;
- } else if (mval->family_value == variable_family_par) {
+ } else if (mval->family_value == variable_family_par && fam_par_in_range(variable_family_par)) {
+ /*tex Actually we know that we're in range as |mval| is, but let's be explicit here. */
math_kernel_family(target) = cur_fam_par_in_range ? cur_fam_par : mval->family_value;
node_subtype(target) = mval->class_value;
} else {
@@ -1847,8 +1850,9 @@ static void tex_aux_enter_display_math(halfword cmd, int where)
} else {
tex_line_break(math_display_group, math_par_context, 1);
// size = tex_actual_box_width(lmt_linebreak_state.just_box, tex_x_over_n_factor(tex_get_font_em_width(cur_font_par)) * math_pre_display_gap_factor_par);
- size = tex_actual_box_width(lmt_linebreak_state.just_box, tex_get_font_em_width(cur_font_par) * math_pre_display_gap_factor_par / scaling_factor);
+ // size = tex_actual_box_width(lmt_linebreak_state.just_box, tex_get_font_em_width(cur_font_par) * math_pre_display_gap_factor_par / scaling_factor);
// size = tex_actual_box_width(lmt_linebreak_state.just_box, scaledround(tex_get_font_em_width(cur_font_par) * math_pre_display_gap_factor_par / scaling_factor_double));
+ size = tex_actual_box_width(lmt_linebreak_state.just_box, tex_xn_over_1000(tex_get_font_em_width(cur_font_par), math_pre_display_gap_factor_par));
}
/*tex
Now we are in vertical mode, working on the list that will contain the display. A displayed
@@ -1870,7 +1874,7 @@ static void tex_aux_enter_display_math(halfword cmd, int where)
indent = 0;
}
} else if ((hang_indent_par != 0) && (((hang_after_par >= 0) && (cur_list.prev_graf + 2 > hang_after_par)) || (cur_list.prev_graf + 1 < -hang_after_par))) {
- halfword hangindent = swap_hang_indent(pre_display_direction_par, hang_indent_par);
+ scaled hangindent = swap_hang_indent(pre_display_direction_par, hang_indent_par);
width = hsize_par - abs(hangindent);
indent = hangindent > 0 ? hangindent : 0;
} else {
@@ -2120,9 +2124,7 @@ mathcodeval tex_scan_delimiter_as_mathchar(int extcode)
static void tex_aux_report_active(int where, const char *what, int code, int character)
{
- tex_begin_diagnostic();
- tex_print_format("%l[active: location %i, %s, code %i, char %i]",where, what, code, character);
- tex_end_diagnostic();
+ tex_print_format("%<%l[active: location %i, %s, code %i, char %i]%>",where, what, code, character);
}
static void tex_aux_append_math_char(mathcodeval mval, mathdictval dval, int automatic);
@@ -2461,9 +2463,7 @@ static void tex_aux_append_math_fence_val(mathcodeval mval, mathdictval dval, qu
static void tex_trace_continuation_atom(const char *s)
{
if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: continuation atom %s]", s);
- tex_end_diagnostic();
+ tex_print_format("%<%l[math: continuation atom %s]%>", s);
}
}
@@ -3119,7 +3119,10 @@ void tex_run_math_modifier(void)
noad_options(tail) = unset_option(noad_options(tail), noad_option_limits);
noad_options(tail) |= noad_option_no_limits;
break;
+ default:
+ break;
}
+ break;
default:
switch (node_type(tail)) {
case accent_noad:
@@ -3130,6 +3133,8 @@ void tex_run_math_modifier(void)
}
noad_source(tail) = tex_scan_integer(0, NULL, NULL);
break;
+ default:
+ break;
}
}
@@ -4354,7 +4359,7 @@ void tex_run_math_fraction(void)
halfword symbolattrlist = null;
fullword options = 0;
halfword mathclass = fraction_noad_subtype;
- halfword rulethickness = preset_rule_thickness;
+ scaled rulethickness = preset_rule_thickness;
int ruledone = 0;
fraction_h_factor(fraction) = scaling_factor;
fraction_v_factor(fraction) = scaling_factor;
@@ -5900,7 +5905,7 @@ void tex_run_math_shift(void)
*/
-void tex_finish_display_alignment(halfword head, halfword tail, halfword prevdepth)
+void tex_finish_display_alignment(halfword head, halfword tail, scaled prevdepth)
{
tex_handle_assignments();
AGAIN:
@@ -6049,19 +6054,29 @@ static void tex_aux_define_all_math_parameters(int size, int param, scaled value
# define math_parameter(a,b) ((font_math_parameter_count(a) >= b) ? font_math_parameter(a,b) : undefined_math_parameter)
+# if lmt_float_math
+
+ static inline scaled tex_aux_get_font_math_quantity(scaled scale, halfword v)
+ {
+ return (v && scale) ? scaledround(0.001 * (double) scale * (double) v) : 0;
+ }
+
+# else
+
+ static inline scaled tex_aux_get_font_math_quantity(scaled scale, halfword v)
+ {
+ return (v && scale) ? tex_aux_scale_1000(v, scale) : 0;
+ }
+
+# endif
+
static inline scaled tex_aux_get_font_math_parameter(scaled scale, halfword f, int id)
{
scaled v = math_parameter(f, id);
if (v == undefined_math_parameter) {
- return v;
- } else {
- return v ? scaledround(0.001 * scale * v) : 0;
+ return undefined_math_parameter;
}
-}
-
-static inline scaled tex_aux_get_font_math_quantity(scaled scale, halfword v)
-{
- return v ? scaledround(0.001 * scale * v) : 0;
+ return tex_aux_get_font_math_quantity(scale, v);
}
/*tex
@@ -6074,9 +6089,7 @@ void tex_fixup_math_parameters(int fam, int size, int f, int level)
scaled scale = tex_get_math_font_scale(f, size);
if (tracing_math_par > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: fixing up font, family %i, size %i, font %i, level %i]", fam, size, f, level);
- tex_end_diagnostic();
+ tex_print_format("%<%l[math: fixing up font, family %i, size %i, font %i, level %i]%>", fam, size, f, level);
}
/*tex These apply to all: */
@@ -6586,16 +6599,38 @@ static inline scaled tex_aux_max_scale(int style, int param)
*/
+static int tex_aux_math_parameter_okay(int param)
+{
+ if (ignore_math_parameter(param) == 1) {
+ if (tracing_math_par > 1) {
+ tex_print_format("%<%l[math: parameter, name %s, ignored]%>", lmt_name_of_math_parameter(param));
+ }
+ return 0;
+ } else {
+ return 1;
+ }
+}
+
scaled tex_get_math_quad_style(int style)
{
- scaled scale = tex_aux_max_scale(style, math_parameter_x_scale);
+ if (! tex_aux_math_parameter_okay(math_parameter_quad)) {
+ return 0;
+ }
scaled value = tex_get_math_parameter(style, math_parameter_quad, NULL);
if (value == undefined_math_parameter) {
tex_aux_math_parameter_error(style, -1, "quad");
return 0;
- } else {
- return scaledround(0.001 * value * scale);
}
+ if (! value) {
+ return 0;
+ }
+# if lmt_float_math
+ scaled scale = tex_aux_max_scale(style, math_parameter_x_scale);
+ return scaledround(0.001 * (double) value * (double) scale);
+# else
+ scaled scale = tex_aux_max_scale(style, math_parameter_x_scale);
+ return tex_aux_scale_1000(value, scale);
+# endif
}
/*tex
@@ -6666,20 +6701,6 @@ scaled tex_get_math_quad_size_unscaled(int size) /* used in cur_mu */
return scaledround(tex_get_math_parameter(size, math_parameter_quad, NULL) / 18.0);
}
-static int tex_aux_math_parameter_okay(int param)
-{
- if (ignore_math_parameter(param) == 1) {
- if (tracing_math_par > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: parameter, name %s, ignored]", lmt_name_of_math_parameter(param));
- tex_end_diagnostic();
- }
- return 0;
- } else {
- return 1;
- }
-}
-
scaled tex_get_math_parameter_checked(int style, int param)
{
if (tex_aux_math_parameter_okay(param)) {
@@ -6717,141 +6738,268 @@ void tex_run_math_italic_correction(void) {
/* */
-scaled tex_get_math_x_parameter(int style, int param)
-{
- if (tex_aux_math_parameter_okay(param)) {
- scaled scale = tex_aux_max_scale(style, math_parameter_x_scale);
+# if lmt_float_math
+
+ static inline scaled tex_aux_math_scale_x_value(scaled value, scaled scale)
+ {
+ if (! value || ! scale) return 0;
+ double gs = glyph_scale_par ? glyph_scale_par : 1000.0;
+ double gx = glyph_x_scale_par ? glyph_x_scale_par : 1000.0;
+ return scaledround(0.000000001 * gs * gx * (double)value * (double)scale);
+ }
+
+ static inline scaled tex_aux_math_scale_y_value(scaled value, scaled scale)
+ {
+ if (! value || ! scale) return 0;
+ double gs = glyph_scale_par ? glyph_scale_par : 1000.0;
+ double gy = glyph_y_scale_par ? glyph_y_scale_par : 1000.0;
+ return scaledround(0.000000001 * gs * gy * (double)value * (double)scale);
+ }
+
+ scaled tex_get_math_x_parameter(int style, int param)
+ {
+ if (! tex_aux_math_parameter_okay(param)) {
+ return 0;
+ }
scaled value = tex_get_math_parameter(style, param, NULL);
if (value == undefined_math_parameter) {
- return value; // ?? scaledround(value * scale * 0.001);
- } else {
- return value ? scaledround(0.000000001 * glyph_scale_par * glyph_x_scale_par * value * scale) : 0;
+ return undefined_math_parameter;
}
- } else {
- return 0;
+ scaled scale = tex_aux_max_scale(style, math_parameter_x_scale);
+ return tex_aux_math_scale_x_value(value, scale);
}
-}
-scaled tex_get_math_x_parameter_checked(int style, int param)
-{
- if (tex_aux_math_parameter_okay(param)) {
- scaled scale = tex_aux_max_scale(style, math_parameter_x_scale);
+ scaled tex_get_math_x_parameter_checked(int style, int param)
+ {
+ if (! tex_aux_math_parameter_okay(param)) {
+ return 0;
+ }
scaled value = tex_get_math_parameter(style, param, NULL);
if (value == undefined_math_parameter) {
tex_aux_math_parameter_error(style, param, lmt_name_of_math_parameter(param));
return 0;
- } else {
- return value ? scaledround(0.000000001 * glyph_scale_par * glyph_x_scale_par * value * scale) : 0;
}
- } else {
- return 0;
+ scaled scale = tex_aux_max_scale(style, math_parameter_x_scale);
+ return tex_aux_math_scale_x_value(value, scale);
}
-}
-scaled tex_get_math_x_parameter_default(int style, int param, scaled dflt)
-{
- if (tex_aux_math_parameter_okay(param)) {
- scaled scale = tex_aux_max_scale(style, math_parameter_x_scale);
+ scaled tex_get_math_x_parameter_default(int style, int param, scaled dflt)
+ {
+ if (! tex_aux_math_parameter_okay(param)) {
+ return dflt;
+ }
scaled value = tex_get_math_parameter(style, param, NULL);
if (value == undefined_math_parameter) {
return dflt;
- } else{
- return value ? scaledround(0.000000001 * glyph_scale_par * glyph_x_scale_par * value * scale) : 0;
}
- } else {
- return dflt;
+ scaled scale = tex_aux_max_scale(style, math_parameter_x_scale);
+ return tex_aux_math_scale_x_value(value, scale);
}
-}
-scaled tex_get_math_y_parameter(int style, int param)
-{
- if (tex_aux_math_parameter_okay(param)) {
+ scaled tex_get_math_y_parameter(int style, int param)
+ {
+ if (! tex_aux_math_parameter_okay(param)) {
+ return 0;
+ }
+ scaled value = tex_get_math_parameter(style, param, NULL);
+ if (value == undefined_math_parameter) {
+ return undefined_math_parameter;
+ }
scaled scale = tex_aux_max_scale(style, math_parameter_y_scale);
+ return tex_aux_math_scale_y_value(value, scale);
+ }
+
+ scaled tex_get_math_y_parameter_checked(int style, int param)
+ {
+ if (! tex_aux_math_parameter_okay(param)) {
+ return 0;
+ }
scaled value = tex_get_math_parameter(style, param, NULL);
if (value == undefined_math_parameter) {
- return value;
- } else{
- return value ? scaledround(0.000000001 * glyph_scale_par * glyph_y_scale_par * value * scale) : 0;
+ tex_aux_math_parameter_error(style, param, lmt_name_of_math_parameter(param));
+ return 0;
}
- } else {
- return 0;
+ scaled scale = tex_aux_max_scale(style, math_parameter_y_scale);
+ return tex_aux_math_scale_y_value(value, scale);
}
-}
-scaled tex_get_math_y_parameter_checked(int style, int param)
-{
- if (tex_aux_math_parameter_okay(param)) {
+ scaled tex_get_math_y_parameter_default(int style, int param, scaled dflt)
+ {
+ if (! tex_aux_math_parameter_okay(param)) {
+ return dflt;
+ }
+ scaled value = tex_get_math_parameter(style, param, NULL);
+ if (value == undefined_math_parameter) {
+ return dflt;
+ }
scaled scale = tex_aux_max_scale(style, math_parameter_y_scale);
+ return tex_aux_math_scale_y_value(value, scale);
+ }
+
+ scaled tex_get_font_math_parameter(int font, int size, int param)
+ {
+ scaled scale = tex_get_math_font_scale(font, size);
+ scaled value = tex_aux_get_font_math_parameter(scale, font, param);
+ if (value == undefined_math_parameter) {
+ return undefined_math_parameter;
+ }
+ if (! value) {
+ return 0;
+ }
+ double gs = glyph_scale_par ? glyph_scale_par : 1000.0;
+ return scaledround(0.001 * gs * (double)value);
+ }
+
+ scaled tex_get_font_math_y_parameter(int font, int size, int param)
+ {
+ scaled scale = tex_get_math_font_scale(font, size);
+ scaled value = tex_aux_get_font_math_parameter(scale, font, param);
+ if (value == undefined_math_parameter) {
+ return undefined_math_parameter;
+ }
+ if (! value) {
+ return 0;
+ }
+ double gs = glyph_scale_par ? glyph_scale_par : 1000.0;
+ double gy = glyph_y_scale_par ? glyph_y_scale_par : 1000.0;
+ return scaledround(0.000001 * gs * gy * (double) value);
+ }
+
+ scaled tex_get_font_math_x_parameter(int font, int size, int param)
+ {
+ scaled scale = tex_get_math_font_scale(font, size);
+ scaled value = tex_aux_get_font_math_parameter(scale, font, param);
+ if (value == undefined_math_parameter) {
+ return undefined_math_parameter;
+ }
+ if (! value) {
+ return 0;
+ }
+ double gs = glyph_scale_par ? glyph_scale_par : 1000.0;
+ double gx = glyph_x_scale_par ? glyph_x_scale_par : 1000.0;
+ return scaledround(0.000001 * gs * gx * (double) value);
+ }
+
+# else
+
+ static inline scaled tex_aux_math_scale_x_value(scaled value, scaled scale)
+ {
+ if (! value || ! scale) return 0;
+ return tex_aux_scale_1e9(value, glyph_scale_par, glyph_x_scale_par, scale);
+ }
+
+ static inline scaled tex_aux_math_scale_y_value(scaled value, scaled scale)
+ {
+ if (! value || ! scale) return 0;
+ return tex_aux_scale_1e9(value, glyph_scale_par, glyph_y_scale_par, scale);
+ }
+
+ scaled tex_get_math_x_parameter(int style, int param)
+ {
+ if (! tex_aux_math_parameter_okay(param)) return 0;
+ scaled value = tex_get_math_parameter(style, param, NULL);
+ if (value == undefined_math_parameter) return undefined_math_parameter;
+ scaled scale = tex_aux_max_scale(style, math_parameter_x_scale);
+ return tex_aux_math_scale_x_value(value, scale);
+ }
+
+ scaled tex_get_math_x_parameter_checked(int style, int param)
+ {
+ if (! tex_aux_math_parameter_okay(param)) return 0;
scaled value = tex_get_math_parameter(style, param, NULL);
if (value == undefined_math_parameter) {
tex_aux_math_parameter_error(style, param, lmt_name_of_math_parameter(param));
return 0;
- } else {
- return value ? scaledround(0.000000001 * glyph_scale_par * glyph_y_scale_par * value * scale) : 0;
}
- } else {
- return 0;
+ scaled scale = tex_aux_max_scale(style, math_parameter_x_scale);
+ return tex_aux_math_scale_x_value(value, scale);
}
-}
-scaled tex_get_math_y_parameter_default(int style, int param, scaled dflt)
-{
- if (tex_aux_math_parameter_okay(param)) {
+ scaled tex_get_math_x_parameter_default(int style, int param, scaled dflt)
+ {
+ if (! tex_aux_math_parameter_okay(param)) return dflt;
+ scaled value = tex_get_math_parameter(style, param, NULL);
+ if (value == undefined_math_parameter) return dflt;
+ scaled scale = tex_aux_max_scale(style, math_parameter_x_scale);
+ return tex_aux_math_scale_x_value(value, scale);
+ }
+
+ scaled tex_get_math_y_parameter(int style, int param)
+ {
+ if (! tex_aux_math_parameter_okay(param)) return 0;
+ scaled value = tex_get_math_parameter(style, param, NULL);
+ if (value == undefined_math_parameter) return undefined_math_parameter;
scaled scale = tex_aux_max_scale(style, math_parameter_y_scale);
+ return tex_aux_math_scale_y_value(value, scale);
+ }
+
+ scaled tex_get_math_y_parameter_checked(int style, int param)
+ {
+ if (! tex_aux_math_parameter_okay(param)) return 0;
scaled value = tex_get_math_parameter(style, param, NULL);
if (value == undefined_math_parameter) {
- return dflt;
- } else {
- return value ? scaledround(0.000000001 * glyph_scale_par * glyph_y_scale_par * value * scale) : 0;
+ tex_aux_math_parameter_error(style, param, lmt_name_of_math_parameter(param));
+ return 0;
}
- } else {
- return dflt;
+ scaled scale = tex_aux_max_scale(style, math_parameter_y_scale);
+ return tex_aux_math_scale_y_value(value, scale);
}
-}
-scaled tex_get_font_math_parameter(int font, int size, int param)
-{
- scaled scale = tex_get_math_font_scale(font, size);
- scaled value = tex_aux_get_font_math_parameter(scale, font, param);
- if (value == undefined_math_parameter) {
- return undefined_math_parameter;
- } else {
- return value ? scaledround(0.001 * glyph_scale_par * value) : 0;
+ scaled tex_get_math_y_parameter_default(int style, int param, scaled dflt)
+ {
+ if (! tex_aux_math_parameter_okay(param)) return dflt;
+ scaled value = tex_get_math_parameter(style, param, NULL);
+ if (value == undefined_math_parameter) return dflt;
+ scaled scale = tex_aux_max_scale(style, math_parameter_y_scale);
+ return tex_aux_math_scale_y_value(value, scale);
}
-}
-/* maybe more precission, so multiply all and divide by 0.000000001 */
+ scaled tex_get_font_math_parameter(int font, int size, int param)
+ {
+ scaled scale = tex_get_math_font_scale(font, size);
+ scaled value = tex_aux_get_font_math_parameter(scale, font, param);
+ if (value == undefined_math_parameter) return undefined_math_parameter;
+ if (! value) return 0;
+ return tex_aux_scale_1000_default(value, glyph_scale_par);
+ }
-scaled tex_get_font_math_y_parameter(int font, int size, int param)
-{
- scaled scale = tex_get_math_font_scale(font, size);
- scaled value = tex_aux_get_font_math_parameter(scale, font, param);
- if (value == undefined_math_parameter) {
- return undefined_math_parameter;
- } else {
- return value ? scaledround(0.000001 * glyph_scale_par * glyph_y_scale_par * value) : 0;
+ scaled tex_get_font_math_y_parameter(int font, int size, int param)
+ {
+ scaled scale = tex_get_math_font_scale(font, size);
+ scaled value = tex_aux_get_font_math_parameter(scale, font, param);
+ if (value == undefined_math_parameter) {
+ return undefined_math_parameter;
+ }
+ if (! value) {
+ return 0;
+ }
+ return tex_aux_scale_1e6(value, glyph_scale_par, glyph_y_scale_par);
}
-}
-scaled tex_get_font_math_x_parameter(int font, int size, int param)
-{
- scaled scale = tex_get_math_font_scale(font, size);
- scaled value = tex_aux_get_font_math_parameter(scale, font, param);
- if (value == undefined_math_parameter) {
- return undefined_math_parameter;
- } else {
- return value ? scaledround(0.000001 * glyph_scale_par * glyph_x_scale_par * value) : 0;
+ scaled tex_get_font_math_x_parameter(int font, int size, int param)
+ {
+ scaled scale = tex_get_math_font_scale(font, size);
+ scaled value = tex_aux_get_font_math_parameter(scale, font, param);
+ if (value == undefined_math_parameter) {
+ return undefined_math_parameter;
+ }
+ if (! value) {
+ return 0;
+ }
+ return tex_aux_scale_1e6(value, glyph_scale_par, glyph_x_scale_par);
}
-}
+
+# endif
halfword tex_to_math_spacing_parameter(halfword left, halfword right)
{
if (valid_math_class_code(left) && valid_math_class_code(right)) {
- halfword param = math_parameter_spacing_pair(left,right);
- return (param >= math_parameter_atom_pairs_first && param <= math_parameter_atom_pairs_last) ? param : -1;
- } else {
- return -1;
+ halfword param = math_parameter_spacing_pair(left, right);
+ if (param >= math_parameter_atom_pairs_first && param <= math_parameter_atom_pairs_last) {
+ return param;
+ }
}
+ return -1;
}
halfword tex_to_math_rules_parameter(halfword left, halfword right)
diff --git a/source/luametatex/source/tex/texmath.h b/source/luametatex/source/tex/texmath.h
index c7fe4a588..7971aa6d4 100644
--- a/source/luametatex/source/tex/texmath.h
+++ b/source/luametatex/source/tex/texmath.h
@@ -50,6 +50,11 @@ typedef enum math_sizes {
# define undefined_math_parameter max_dimension
+typedef enum variable_family_modes {
+ math_variable_mode_keep = -2,
+ math_variable_mode_unset = -1,
+} variable_family_modes;
+
typedef enum math_indirect_types {
indirect_math_unset,
indirect_math_regular,
@@ -265,8 +270,8 @@ math_parameter_set_defaults,
# define math_first_user_class (last_noad_subtype + 1)
# define math_last_user_class (math_all_class - 1)
-# define valid_math_class_code(n) (n >= 0 && n < max_n_of_math_classes)
-# define real_math_class_code(n) (n >= 0 && n < math_all_class)
+static inline int valid_math_class_code(halfword n) { return n >= 0 && n < max_n_of_math_classes; }
+static inline int real_math_class_code (halfword n) { return n >= 0 && n < math_all_class; }
# define last_math_parameter math_parameter_stack_variant
# define math_parameter_first_variant math_parameter_over_line_variant
@@ -723,7 +728,7 @@ extern void tex_finish_math_choice (void);
extern void tex_finish_math_fraction (void);
extern void tex_finish_math_radical (void);
extern void tex_finish_math_operator (void);
-extern void tex_finish_display_alignment (halfword head, halfword tail, halfword prevdepth);
+extern void tex_finish_display_alignment (halfword head, halfword tail, scaled prevdepth);
extern void tex_show_math_fraction_group (void);
extern void tex_show_math_radical_group (void);
diff --git a/source/luametatex/source/tex/texmlist.c b/source/luametatex/source/tex/texmlist.c
index 0a6ebc924..7c189c95e 100644
--- a/source/luametatex/source/tex/texmlist.c
+++ b/source/luametatex/source/tex/texmlist.c
@@ -361,10 +361,14 @@ static inline halfword tex_aux_set_style_to_size(halfword style)
}
}
-static inline void tex_aux_set_current_math_scale(halfword scale)
+static inline void tex_aux_set_current_math_scale(halfword scale, halfword glyphscale)
{
- glyph_scale_par = scale;
- lmt_math_state.scale = glyph_scale_par;
+ lmt_math_state.scale = scale;
+ if (scale != 0) {
+ glyph_scale_par = scale;
+ } else if (glyphscale != 0) {
+ glyph_scale_par = glyphscale;
+ }
}
static inline void tex_aux_set_current_math_size(halfword style)
@@ -372,12 +376,12 @@ static inline void tex_aux_set_current_math_size(halfword style)
lmt_math_state.size = tex_aux_set_style_to_size(style);
}
-static inline void tex_aux_make_style(halfword current, halfword *current_style, halfword *current_mu)
+static inline void tex_aux_make_style(halfword current, halfword *current_style, scaled *current_mu)
{
halfword style = node_subtype(current);
switch (style) {
case scaled_math_style:
- tex_aux_set_current_math_scale(style_scale(current));
+ tex_aux_set_current_math_scale(style_scale(current), style_glyph_scale(current));
break;
default:
if (is_valid_math_style(style)) {
@@ -386,6 +390,7 @@ static inline void tex_aux_make_style(halfword current, halfword *current_style,
}
tex_aux_set_current_math_size(style);
if (current_mu) {
+ /* Here 18.0 is still hardcoded! */
*current_mu = scaledround(tex_get_math_parameter(style, math_parameter_quad, NULL) / 18.0);
// *current_mu = scaledround((double) tex_get_math_quad_style(style) / 18.0);
}
@@ -466,8 +471,7 @@ static inline scaled limited_scaled(long l) {
}
}
-static inline scaled limited_rounded(double d) {
- long l = scaledround(d);
+static inline scaled limited_scaled_ll(long long l) {
if (l > max_dimension) {
return max_dimension;
} else if (l < -max_dimension) {
@@ -477,6 +481,18 @@ static inline scaled limited_rounded(double d) {
}
}
+static inline scaled limited_rounded(double d) {
+ if (isnan(d)) {
+ return 0;
+ } else if (d >= (double) max_dimension) {
+ return max_dimension;
+ } else if (d <= (double) -max_dimension) {
+ return -max_dimension;
+ } else {
+ return (scaled) lround(d);
+ }
+}
+
static inline int tex_aux_math_engine_control(halfword fnt, halfword control)
{
// if (fnt && (math_font_control_par & math_control_use_font_control) == math_control_use_font_control) {
@@ -498,101 +514,302 @@ static inline int tex_aux_math_engine_control(halfword fnt, halfword control)
*/
-static inline scaled tex_aux_math_math_scale(scaled v)
-{
- return v ? scaledround(0.001 * lmt_math_state.scale * v) : 0;
-}
+# if lmt_float_math
-static inline scaled tex_aux_math_glyph_scale(scaled v)
-{
- return v ? scaledround(0.001 * glyph_scale_par * v) : 0;
-}
+ static inline scaled tex_aux_math_math_scale(scaled v)
+ {
+ if (! v) return 0;
+ double s = lmt_math_state.scale ? lmt_math_state.scale : 1000.0;
+ return scaledround(0.001 * s * (double) v);
+ }
-static inline scaled tex_aux_math_glyph_x_scale(scaled v)
-{
- return v ? scaledround(0.001 * glyph_x_scale_par * v) : 0;
-}
+ static inline scaled tex_aux_math_glyph_scale(scaled v)
+ {
+ if (! v) return 0;
+ double s = glyph_scale_par ? glyph_scale_par : 1000.0;
+ return scaledround(0.001 * s * (double) v);
+ }
-static inline scaled tex_aux_math_glyph_y_scale(scaled v)
-{
- return v ? scaledround(0.001 * glyph_y_scale_par * v) : 0;
-}
+ static inline scaled tex_aux_math_glyph_x_scale(scaled v)
+ {
+ if (! v) return 0;
+ double x = glyph_x_scale_par ? glyph_x_scale_par : 1000.0;
+ return scaledround(0.001 * x * (double) v);
+ }
-static inline scaled tex_aux_math_glyph_weight(scaled v)
-{
- return glyph_weight_par + v;
-}
+ static inline scaled tex_aux_math_glyph_y_scale(scaled v)
+ {
+ if (! v) return 0;
+ double y = glyph_y_scale_par ? glyph_y_scale_par : 1000.0;
+ return scaledround(0.001 * y * (double) v);
+ }
-static inline scaled tex_aux_math_x_scaled(scaled v, int style)
-{
- scaled scale = tex_get_math_parameter(style, math_parameter_x_scale, NULL);
- return v ? limited_rounded(0.000000001 * glyph_scale_par * glyph_x_scale_par * v * scale) : 0;
-}
+ static inline scaled tex_aux_math_glyph_weight(scaled v)
+ {
+ return glyph_weight_par + v;
+ }
-static inline scaled tex_aux_math_given_x_scaled(scaled v)
-{
- return v;
-}
+ static inline scaled tex_aux_math_x_scaled(scaled v, int style)
+ {
+ if (! v) return 0;
+ scaled scale = tex_get_math_parameter(style, math_parameter_x_scale, NULL);
+ if (! scale) return 0;
+ double gs = glyph_scale_par ? glyph_scale_par : 1000.0;
+ double gx = glyph_x_scale_par ? glyph_x_scale_par : 1000.0;
+ return limited_rounded(0.000000001 * gs * gx * (double) v * (double) scale);
+ }
-static inline scaled tex_aux_math_y_scaled(scaled v, int style)
-{
- scaled scale = tex_get_math_parameter(style, math_parameter_y_scale, NULL);
- return v ? limited_rounded(0.000000001 * glyph_scale_par * glyph_y_scale_par * v * scale) : 0;
-}
+ static inline scaled tex_aux_math_given_x_scaled(scaled v)
+ {
+ return v;
+ }
-static inline scaled tex_aux_math_given_y_scaled(scaled v)
-{
- return v;
-}
+ static inline scaled tex_aux_math_y_scaled(scaled v, int style)
+ {
+ if (! v) return 0;
+ scaled scale = tex_get_math_parameter(style, math_parameter_y_scale, NULL);
+ if (! scale) return 0;
+ double gs = glyph_scale_par ? glyph_scale_par : 1000.0;
+ double gy = glyph_y_scale_par ? glyph_y_scale_par : 1000.0;
+ return limited_rounded(0.000000001 * gs * gy * (double) v * (double) scale);
+ }
-scaled tex_math_parameter_x_scaled(int style, int param)
-{
- scaled scale = tex_get_math_parameter(style, math_parameter_x_scale, NULL);
- scaled value = tex_get_math_parameter(style, param, NULL);
- return value ? limited_rounded(0.000000001 * glyph_scale_par * glyph_x_scale_par * value * scale) : 0;
-}
+ static inline scaled tex_aux_math_given_y_scaled(scaled v)
+ {
+ return v;
+ }
-scaled tex_math_parameter_y_scaled(int style, int param)
-{
- scaled value = tex_get_math_parameter(style, math_parameter_y_scale, NULL);
- scaled scale = tex_get_math_parameter(style, param, NULL);
- return value ? limited_rounded(0.000000001 * glyph_scale_par * glyph_y_scale_par * value * scale) : 0;
-}
+ scaled tex_math_parameter_x_scaled(int style, int param)
+ {
+ scaled value = tex_get_math_parameter(style, param, NULL);
+ if (! value) return 0;
+ scaled scale = tex_get_math_parameter(style, math_parameter_x_scale, NULL);
+ double gs = glyph_scale_par ? glyph_scale_par : 1000.0;
+ double gx = glyph_x_scale_par ? glyph_x_scale_par : 1000.0;
+ return limited_rounded(0.000000001 * gs * gx * (double) value * (double) scale);
+ }
-static inline scaled tex_aux_math_axis(halfword size)
-{
- scaled v = tex_get_math_axis_size(size); /* already scaled to size and x_scale */
- return v ? limited_rounded(0.000001 * glyph_scale_par * glyph_y_scale_par * v) : 0;
-}
+ scaled tex_math_parameter_y_scaled(int style, int param)
+ {
+ scaled value = tex_get_math_parameter(style, param, NULL);
+ if (! value) return 0;
+ scaled scale = tex_get_math_parameter(style, math_parameter_y_scale, NULL);
+ double gs = glyph_scale_par ? glyph_scale_par : 1000.0;
+ double gy = glyph_y_scale_par ? glyph_y_scale_par : 1000.0;
+ return limited_rounded(0.000000001 * gs * gy * (double) value * (double) scale);
+ }
-static inline scaled tex_aux_math_exheight(halfword size)
-{
- scaled v = tex_get_math_exheight_size(size); /* already scaled to size and x_scale */
- return v ? limited_rounded(0.000001 * glyph_scale_par * glyph_y_scale_par * v) : 0;
-}
+ static inline scaled tex_aux_math_axis(halfword size)
+ {
+ scaled v = tex_get_math_axis_size(size);
+ if (! v) return 0;
+ double gs = glyph_scale_par ? glyph_scale_par : 1000.0;
+ double gy = glyph_y_scale_par ? glyph_y_scale_par : 1000.0;
+ return limited_rounded(0.000001 * gs * gy * (double) v);
+ }
-static inline scaled tex_aux_math_emwidth(halfword size)
-{
- scaled v = tex_get_math_quad_size(size); /* already scaled to size and x_scale */
- return v ? limited_rounded(0.000001 * glyph_scale_par * glyph_x_scale_par * v) : 0;
-}
+ static inline scaled tex_aux_math_exheight(halfword size)
+ {
+ scaled v = tex_get_math_exheight_size(size);
+ if (! v) return 0;
+ double gs = glyph_scale_par ? glyph_scale_par : 1000.0;
+ double gy = glyph_y_scale_par ? glyph_y_scale_par : 1000.0;
+ return limited_rounded(0.000001 * gs * gy * (double) v);
+ }
-static inline scaled tex_aux_math_x_size_scaled(halfword f, scaled v, halfword size)
-{
- return v ? limited_rounded(0.000000000001 * tex_get_math_font_scale(f, size) * tex_get_math_font_x_scale(f, size) * glyph_scale_par * glyph_x_scale_par * v) : 0;
-}
+ static inline scaled tex_aux_math_emwidth(halfword size)
+ {
+ scaled v = tex_get_math_quad_size(size);
+ if (! v) return 0;
+ double gs = glyph_scale_par ? glyph_scale_par : 1000.0;
+ double gx = glyph_x_scale_par ? glyph_x_scale_par : 1000.0;
+ return limited_rounded(0.000001 * gs * gx * (double) v);
+ }
-static inline scaled tex_aux_math_y_size_scaled(halfword f, scaled v, halfword size)
-{
- return v ? limited_rounded(0.000000000001 * tex_get_math_font_scale(f, size) * tex_get_math_font_y_scale(f, size) * glyph_scale_par * glyph_y_scale_par * v) : 0;
-}
+ static inline scaled tex_aux_math_x_size_scaled(halfword f, scaled v, halfword size)
+ {
+ if (! v) return 0;
+ double fs = tex_get_math_font_scale(f, size);
+ double fx = tex_get_math_font_x_scale(f, size);
+ double gs = glyph_scale_par ? glyph_scale_par : 1000.0;
+ double gx = glyph_x_scale_par ? glyph_x_scale_par : 1000.0;
+ double font_factor = (fs ? fs : 1000.0) * (fx ? fx : 1000.0);
+ double glyph_factor = gs * gx;
+ return limited_rounded(0.000000000001 * font_factor * glyph_factor * (double) v);
+ }
-halfword tex_math_font_char_ht(halfword fnt, halfword chr, halfword style)
+ static inline scaled tex_aux_math_y_size_scaled(halfword f, scaled v, halfword size)
+ {
+ if (! v) return 0;
+ double fs = tex_get_math_font_scale(f, size);
+ double fy = tex_get_math_font_y_scale(f, size);
+ double gs = glyph_scale_par ? glyph_scale_par : 1000.0;
+ double gy = glyph_y_scale_par ? glyph_y_scale_par : 1000.0;
+ double font_factor = (fs ? fs : 1000.0) * (fy ? fy : 1000.0);
+ double glyph_factor = gs * gy;
+ return limited_rounded(0.000000000001 * font_factor * glyph_factor * (double) v);
+ }
+
+# else
+
+ static inline scaled tex_aux_math_math_scale(scaled v)
+ {
+ return tex_aux_scale_1000_default(v, lmt_math_state.scale);
+ }
+
+ static inline scaled tex_aux_math_glyph_scale(scaled v)
+ {
+ return tex_aux_scale_1000_default(v, glyph_scale_par);
+ }
+
+ static inline scaled tex_aux_math_glyph_x_scale(scaled v)
+ {
+ return tex_aux_scale_1000_default(v, glyph_x_scale_par);
+ }
+
+ static inline scaled tex_aux_math_glyph_y_scale(scaled v)
+ {
+ return tex_aux_scale_1000_default(v, glyph_y_scale_par);
+ }
+
+ static inline scaled tex_aux_math_glyph_weight(scaled v)
+ {
+ return glyph_weight_par + v;
+ }
+
+ static inline scaled tex_aux_math_x_scaled(scaled v, int style)
+ {
+ scaled scale = tex_get_math_parameter(style, math_parameter_x_scale, NULL);
+ return limited_scaled_ll(tex_aux_round_product(
+ v,
+ glyph_scale_par ? glyph_scale_par : 1000,
+ glyph_x_scale_par ? glyph_x_scale_par : 1000,
+ scale,
+ 1,
+ 1000000000
+ ));
+ }
+
+ static inline scaled tex_aux_math_given_x_scaled(scaled v)
+ {
+ return v;
+ }
+
+ static inline scaled tex_aux_math_y_scaled(scaled v, int style)
+ {
+ scaled scale = tex_get_math_parameter(style, math_parameter_y_scale, NULL);
+ return limited_scaled_ll(tex_aux_round_product(
+ v,
+ glyph_scale_par ? glyph_scale_par : 1000,
+ glyph_y_scale_par ? glyph_y_scale_par : 1000,
+ scale,
+ 1,
+ 1000000000
+ ));
+ }
+
+ static inline scaled tex_aux_math_given_y_scaled(scaled v)
+ {
+ return v;
+ }
+
+ scaled tex_math_parameter_x_scaled(int style, int param)
+ {
+ scaled value = tex_get_math_parameter(style, param, NULL);
+ scaled scale = tex_get_math_parameter(style, math_parameter_x_scale, NULL);
+ return limited_scaled_ll(tex_aux_round_product(
+ value,
+ glyph_scale_par ? glyph_scale_par : 1000,
+ glyph_x_scale_par ? glyph_x_scale_par : 1000,
+ scale,
+ 1,
+ 1000000000
+ ));
+ }
+
+ scaled tex_math_parameter_y_scaled(int style, int param)
+ {
+ scaled value = tex_get_math_parameter(style, param, NULL);
+ scaled scale = tex_get_math_parameter(style, math_parameter_y_scale, NULL);
+ return limited_scaled_ll(tex_aux_round_product(
+ value,
+ glyph_scale_par ? glyph_scale_par : 1000,
+ glyph_y_scale_par ? glyph_y_scale_par : 1000,
+ scale,
+ 1,
+ 1000000000
+ ));
+ }
+
+ static inline scaled tex_aux_scale_math_dimension(scaled v, scaled scale, scaled axis_scale)
+ {
+ if (! v) return 0;
+ long long s = scale ? (long long) scale : 1000LL;
+ long long a = axis_scale ? (long long) axis_scale : 1000LL;
+ if (s == 1000LL && a == 1000LL) return v;
+
+ return limited_scaled_ll(tex_aux_round_product(v, s, a, 1, 1, 1000000));
+ }
+
+ static inline scaled tex_aux_math_axis(halfword size)
+ {
+ return tex_aux_scale_math_dimension(tex_get_math_axis_size(size), glyph_scale_par, glyph_y_scale_par);
+ }
+
+ static inline scaled tex_aux_math_exheight(halfword size)
+ {
+ return tex_aux_scale_math_dimension(tex_get_math_exheight_size(size), glyph_scale_par, glyph_y_scale_par);
+ }
+
+ static inline scaled tex_aux_math_emwidth(halfword size)
+ {
+ return tex_aux_scale_math_dimension(tex_get_math_quad_size(size), glyph_scale_par, glyph_x_scale_par);
+ }
+
+ /* Helper for 4-factor font + glyph scaling (divisor 1e12) */
+ static inline scaled tex_aux_math_font_glyph_scale(scaled v, long long fs, long long fx, long long gs, long long gy)
+ {
+ if (! v) return 0;
+ return limited_scaled_ll(tex_aux_round_product(
+ v,
+ fs ? fs : 1000LL,
+ fx ? fx : 1000LL,
+ gs ? gs : 1000LL,
+ gy ? gy : 1000LL,
+ 1000000000000LL
+ ));
+ }
+
+ static inline scaled tex_aux_math_x_size_scaled(halfword f, scaled v, halfword size)
+ {
+ return tex_aux_math_font_glyph_scale(
+ v,
+ tex_get_math_font_scale(f, size),
+ tex_get_math_font_x_scale(f, size),
+ glyph_scale_par,
+ glyph_x_scale_par
+ );
+ }
+
+ static inline scaled tex_aux_math_y_size_scaled(halfword f, scaled v, halfword size)
+ {
+ return tex_aux_math_font_glyph_scale(
+ v,
+ tex_get_math_font_scale(f, size),
+ tex_get_math_font_y_scale(f, size),
+ glyph_scale_par,
+ glyph_y_scale_par
+ );
+ }
+
+# endif
+
+scaled tex_math_font_char_ht(halfword fnt, halfword chr, halfword style)
{
return tex_aux_math_y_size_scaled(fnt, tex_char_height_from_font(fnt, chr), tex_aux_set_style_to_size(style));
}
-halfword tex_math_font_char_dp(halfword fnt, halfword chr, halfword style)
+scaled tex_math_font_char_dp(halfword fnt, halfword chr, halfword style)
{
return tex_aux_math_y_size_scaled(fnt, tex_char_depth_from_font(fnt, chr), tex_aux_set_style_to_size(style));
}
@@ -620,10 +837,8 @@ halfword tex_new_math_glyph(halfword fnt, halfword chr)
static void tex_aux_trace_kerns(halfword kern, const char *what, const char *detail)
{
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: %s, %s, amount %p]", what, detail, kern);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: %s, %s, amount %p]%>", what, detail, kern);
}
}
@@ -667,8 +882,8 @@ static int tex_aux_math_followed_by_italic_kern(halfword current, const char *tr
static inline int tex_aux_checked_left_kern_fnt_chr(halfword fnt, halfword chr, halfword state, halfword subtype, halfword size)
{
- halfword top = 0;
- halfword bot = 0;
+ scaled top = 0;
+ scaled bot = 0;
halfword hastop = (state & prime_script_state) || (state & post_super_script_state);
halfword hasbot = state & post_sub_script_state;
if (hastop && tex_math_has_class_option(subtype, left_top_kern_class_option)) {
@@ -697,8 +912,8 @@ static inline int tex_aux_checked_left_kern(halfword list, halfword state, halfw
static inline int tex_aux_checked_right_kern_fnt_chr(halfword fnt, halfword chr, halfword state, halfword subtype, halfword size)
{
- halfword top = 0;
- halfword bot = 0;
+ scaled top = 0;
+ scaled bot = 0;
halfword hastop = state & pre_super_script_state;
halfword hasbot = state & pre_sub_script_state;
if (hastop && tex_math_has_class_option(subtype, right_top_kern_class_option)) {
@@ -757,7 +972,7 @@ static halfword tex_aux_fake_nucleus(quarterword cls)
static void tex_aux_fake_delimiter(halfword result)
{
- halfword amount = tex_aux_math_given_x_scaled(null_delimiter_space_par);
+ scaled amount = tex_aux_math_given_x_scaled(null_delimiter_space_par);
if (amount) {
box_width(result) = amount;
box_list(result) = tex_new_kern_node(amount, horizontal_math_kern_subtype);
@@ -945,7 +1160,7 @@ static halfword tex_aux_overbar(halfword box, scaled gap, scaled height, scaled
}
/*tex Safeguard: */
if (topdelimiter > 0 && box_width(rule) > box_width(box)) {
- halfword delta = (box_width(rule) - box_width(box)) / 2;
+ scaled delta = (box_width(rule) - box_width(box)) / 2;
tex_aux_prepend_hkern_to_box_list(box, delta, horizontal_math_kern_subtype, "narrow delimiter");
tex_aux_append_hkern_to_box_list(box, delta, horizontal_math_kern_subtype, "narrow delimiter");
box_width(box) = box_width(rule);
@@ -1256,6 +1471,7 @@ static inline int tex_aux_valid_extensible(halfword result)
static halfword tex_made_extensible(halfword node, halfword fnt, halfword chr, halfword size, scaled width, scaled height, scaled depth, scaled linewidth, scaled axis, scaled exheight, scaled emwidth, int horizontal, halfword callback)
{
int callback_id = lmt_callback_defined(make_extensible_callback);
+ (void) horizontal; /* not yet / no longer used */
if (callback_id > 0) {
halfword boxed = null;
lmt_run_callback(lmt_lua_state.lua_instance, callback_id,
@@ -1395,6 +1611,7 @@ halfword tex_make_extensible(halfword fnt, halfword chr, scaled target, scaled m
back code.
*/
while (max_natural < target && n_of_extenders > 0) {
+ scaled previous_natural = max_natural;
overlap = 0;
max_natural = 0;
with_extenders++;
@@ -1483,6 +1700,10 @@ halfword tex_make_extensible(halfword fnt, halfword chr, scaled target, scaled m
}
}
}
+ if (max_natural <= previous_natural) {
+ tex_formatted_error("fonts", "non-increasing extensible character %i in font %i", chr, fnt);
+ break;
+ }
}
/*tex
Assemble box using |with_extenders| copies of each extender, with appropriate glue wherever
@@ -1552,12 +1773,11 @@ halfword tex_make_extensible(halfword fnt, halfword chr, scaled target, scaled m
scaled delta = target - max_natural;
/*tex Don't stretch more than |s_max|. */
if (delta > max_shrink) {
- if (tracing_math_par >= 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: extensible clipped, target %p, natural %p, shrink %p, clip %p]",
+ if lmt_unlikely(tracing_math_par >= 1) {
+ tex_print_format(
+ "%<%l[math: extensible clipped, target %p, natural %p, shrink %p, clip %p]%>",
target, max_natural, max_shrink, delta - max_shrink
);
- tex_end_diagnostic();
}
delta = max_shrink;
}
@@ -2139,7 +2359,7 @@ static halfword tex_aux_math_glue(halfword g, quarterword subtype, halfword deta
return glue;
}
-static halfword tex_aux_math_dimension(halfword g, quarterword subtype, halfword detail)
+static halfword tex_aux_math_dimension(scaled g, quarterword subtype, halfword detail)
{
halfword glue = tex_new_glue_node(null, subtype);
glue_amount(glue) = g;
@@ -2273,7 +2493,7 @@ void tex_run_mlist_to_hlist(halfword mlist, halfword penalties, halfword style,
math_begin_class_par = unset_noad_class;
math_end_class_par = unset_noad_class;
/* not on the stack ... yet */
- if (tracing_math_par >= 1) {
+ if lmt_unlikely(tracing_math_par >= 1) {
tex_begin_diagnostic();
tex_print_levels();
switch (style) {
@@ -2379,13 +2599,12 @@ void tex_run_mlist_to_hlist(halfword mlist, halfword penalties, halfword style,
} else {
node_next(temp_head) = box;
}
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: boxing inline, threshold %p, width %p, height %p, depth %p]",
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format(
+ "%<%l[math: boxing inline, threshold %p, width %p, height %p, depth %p]%>",
glue_amount(math_threshold_par), // todo: stretch and shrink
siz.wd, siz.ht, siz.dp
);
- tex_end_diagnostic();
}
}
}
@@ -2397,10 +2616,8 @@ void tex_run_mlist_to_hlist(halfword mlist, halfword penalties, halfword style,
while (current) {
/*tex Maybe |math_discretionary_code| but I need to check the impact on \CONTEXT\ first. */
if (node_type(current) == glyph_node && tex_has_glyph_option(current, glyph_option_math_discretionary)) {
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: promoting glyph with character %U to discretionary]", glyph_character(current));
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: promoting glyph with character %U to discretionary]%>", glyph_character(current));
}
current = tex_glyph_to_discretionary(current, mathematics_discretionary_code, tex_has_glyph_option(current, glyph_option_math_italics_too));
}
@@ -2613,7 +2830,7 @@ static void tex_aux_make_over(halfword target, halfword style, halfword size, ha
scaled vgap = tex_get_math_y_parameter_checked(style, math_parameter_overbar_vgap);
scaled kern = tex_get_math_y_parameter_checked(style, math_parameter_overbar_kern);
{
- halfword t = tex_aux_check_rule_thickness(target, size, &fam, math_control_over_rule, OverbarRuleThickness);
+ scaled t = tex_aux_check_rule_thickness(target, size, &fam, math_control_over_rule, OverbarRuleThickness);
if (t != undefined_math_parameter) {
thickness = t;
}
@@ -2644,7 +2861,7 @@ static void tex_aux_make_under(halfword target, halfword style, halfword size, h
scaled vgap = tex_get_math_y_parameter_checked(style, math_parameter_underbar_vgap);
scaled kern = tex_get_math_y_parameter_checked(style, math_parameter_underbar_kern);
{
- halfword t = tex_aux_check_rule_thickness(target, size, &fam, math_control_under_rule, UnderbarRuleThickness);
+ scaled t = tex_aux_check_rule_thickness(target, size, &fam, math_control_under_rule, UnderbarRuleThickness);
if (t != undefined_math_parameter) {
thickness = t;
}
@@ -2711,7 +2928,7 @@ static void tex_aux_make_hextension(halfword target, int style, int size)
halfword fnt = tex_fam_fnt(fam, size);
if (chr && fnt != null_font) {
halfword callback = noad_callback(target);
- halfword thickness = tex_get_math_y_parameter_checked(style, math_parameter_fraction_rule);
+ scaled thickness = tex_get_math_y_parameter_checked(style, math_parameter_fraction_rule);
scaled axis = tex_aux_math_axis(size);
scaled exheight = tex_aux_math_exheight(size);
scaled emwidth = tex_aux_math_emwidth(size);
@@ -2962,7 +3179,7 @@ static void tex_aux_make_root_radical(halfword target, int style, int size, kern
clear.
*/
{
- halfword delta = (box_total(delimiter) - theta) - (box_total(nucleus) + clearance);
+ scaled delta = (box_total(delimiter) - theta) - (box_total(nucleus) + clearance);
if (delta > 0) {
/*tex increase the actual clearance */
clearance += tex_half_scaled(delta);
@@ -2980,11 +3197,11 @@ static void tex_aux_make_root_radical(halfword target, int style, int size, kern
}
}
if (node_type(delimiter) == vlist_node && node_subtype(delimiter) == math_v_delimiter_list) {
- halfword before = tex_get_math_x_parameter_default(style, math_parameter_radical_extensible_before, 0);
+ scaled before = tex_get_math_x_parameter_default(style, math_parameter_radical_extensible_before, 0);
tex_aux_prepend_hkern_to_box_list(nucleus, before, horizontal_math_kern_subtype, "bad delimiter");
}
if (node_type(companion) == vlist_node && node_subtype(companion) == math_v_delimiter_list) {
- halfword after = tex_get_math_x_parameter_default(style, math_parameter_radical_extensible_after, 0);
+ scaled after = tex_get_math_x_parameter_default(style, math_parameter_radical_extensible_after, 0);
tex_aux_append_hkern_to_box_list(nucleus, after, horizontal_math_kern_subtype, "bad delimiter");
}
{
@@ -3000,7 +3217,7 @@ static void tex_aux_make_root_radical(halfword target, int style, int size, kern
or by |tex_aux_assign_radical|.
*/
/*tex The top delimiter is either consumed by the bar helper or flushed here. */
- halfword total = box_total(delimiter);
+ scaled total = box_total(delimiter);
if (norule && topdelimiter) {
tex_flush_node(topdelimiter);
topdelimiter = null;
@@ -3120,9 +3337,9 @@ static void tex_aux_make_delimited_radical(halfword target, int style, int size,
halfword delimiter = leftdelimiter ? leftdelimiter : rightdelimiter;
halfword companion = leftdelimiter ? rightdelimiter : null;
halfword radical = null;
- halfword depth = has_noad_option_exact(target) ? radical_depth(target) : (box_depth(nucleus) + radical_depth(target));
- halfword height = has_noad_option_exact(target) ? radical_height(target) : (box_height(nucleus) + radical_height(target));
- halfword targetsize = height + depth;
+ scaled depth = has_noad_option_exact(target) ? radical_depth(target) : (box_depth(nucleus) + radical_depth(target));
+ scaled height = has_noad_option_exact(target) ? radical_height(target) : (box_height(nucleus) + radical_height(target));
+ scaled targetsize = height + depth;
scaled linewidth = tex_get_math_y_parameter(style, math_parameter_radical_rule);
delimiterextremes extremes = { .tfont = null_font, .tchar = 0, .bfont = null_font, .bchar = 0, .height = 0, .depth = 0 };
halfword mergedattr = tex_merge_attribute_list(delimiter ? node_attr(delimiter) : null, noad_extra_attr(target));
@@ -3251,7 +3468,7 @@ static inline void tex_aux_fixup_radical_width(halfword target, halfword x, half
}
}
-static inline halfword tex_aux_get_radical_width(halfword target, halfword p)
+static inline scaled tex_aux_get_radical_width(halfword target, halfword p)
{
return noad_width(target) ? noad_width(target) : box_width(p);
}
@@ -3522,10 +3739,8 @@ static int tex_aux_compute_accent_skew(halfword target, int flags, scaled *skew,
} else {
*skew = 0;
}
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: accent skew, font %i, chr %x, skew %p, absolute %i]", fnt, chr, *skew, absolute);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: accent skew, font %i, chr %x, skew %p, absolute %i]%>", fnt, chr, *skew, absolute);
}
break;
}
@@ -3571,10 +3786,8 @@ static int tex_aux_compute_accent_skew(halfword target, int flags, scaled *skew,
break;
}
}
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: accent skew, absolute %i]", absolute);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: accent skew, absolute %i]%>", absolute);
}
break;
}
@@ -3703,7 +3916,7 @@ static void tex_aux_do_make_math_accent(halfword target, halfword source, halfwo
/* */
if (has_noad_option_use_callback(target)) {
halfword callback = noad_callback(target);
- halfword thickness = tex_get_math_y_parameter_checked(style, math_parameter_fraction_rule);
+ scaled thickness = tex_get_math_y_parameter_checked(style, math_parameter_fraction_rule);
scaled axis = tex_aux_math_axis(size);
scaled exheight = tex_aux_math_exheight(size);
scaled emwidth = tex_aux_math_emwidth(size);
@@ -3739,7 +3952,7 @@ static void tex_aux_do_make_math_accent(halfword target, halfword source, halfwo
This is a bit weird for an overlay but anyway, here we don't need a factor as
we don't step.
*/
- halfword overlap = tex_get_math_x_parameter_checked(style, math_parameter_connector_overlap_min);
+ scaled overlap = tex_get_math_x_parameter_checked(style, math_parameter_connector_overlap_min);
// accent = tex_aux_get_delimiter_box(accentfnt, accentchr, usedwidth, overlap, 1, attrlist);
accent = tex_make_extensible(accentfnt, accentchr, usedwidth, overlap, 1, mergedattr, lmt_math_state.size);
accent = register_extensible(accentfnt, accentchr, size, accent, mergedattr, 1);
@@ -3793,10 +4006,8 @@ static void tex_aux_do_make_math_accent(halfword target, halfword source, halfwo
}
tex_flush_node(accent);
accent = tex_aux_char_box(accentfnt, flatchr, mergedattr, NULL, glyph_math_accent_subtype, usedwidth, style, keep ? 0 : has_noad_option_shrink(target), keep ? 0 : has_noad_option_stretch(target), &isscaled);
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: flattening accent, old %x, new %x]", accentchr, flatchr);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: flattening accent, old %x, new %x]%>", accentchr, flatchr);
}
accentchr = flatchr;
}
@@ -3866,7 +4077,7 @@ static void tex_aux_do_make_math_accent(halfword target, halfword source, halfwo
box_shift_amount(accent) = tex_half_scaled(basewidth - box_width(accent));
box_width(accent) = 0; /* in gyre zero anyway */
} else {
- halfword accentwidth = box_width(accent);
+ scaled accentwidth = box_width(accent);
if (accentwidth > basewidth && has_noad_option_nooverflow(target)) {
/*tex
This likely only happens with (too wide base) rules so centering is quite okay then and a
@@ -4093,7 +4304,7 @@ static void tex_aux_wrap_fraction_result(halfword target, int style, int size, h
if (left_delimiter || right_delimiter) {
halfword left = null;
halfword right = null;
- halfword delta = tex_get_math_y_parameter(style, math_parameter_fraction_del_size);
+ scaled delta = tex_get_math_y_parameter(style, math_parameter_fraction_del_size);
delimiterextremes extremes = { .tfont = null_font, .tchar = 0, .bfont = null_font, .bchar = 0, .height = 0, .depth = 0 };
if (delta == undefined_math_parameter) {
delta = tex_aux_get_delimiter_height(box_height(fraction), box_depth(fraction), 1, size, style);
@@ -4211,7 +4422,7 @@ static scaled tex_aux_check_fraction_rule(halfword target, int style, int size,
preferfont = 1;
}
if (preferfont) {
- halfword t = tex_aux_check_rule_thickness(target, size, &fam, math_control_fraction_rule, FractionRuleThickness);
+ scaled t = tex_aux_check_rule_thickness(target, size, &fam, math_control_fraction_rule, FractionRuleThickness);
if (t != undefined_math_parameter) {
fraction_rule_thickness(target) = t;
}
@@ -4360,8 +4571,8 @@ static halfword tex_aux_make_skewed_fraction(halfword target, int style, int siz
halfword fnt = tex_fam_fnt(fam, size);
if (chr && fnt != null_font) {
halfword callback = noad_callback(target);
- // halfword thickness = tex_aux_check_fraction_rule(target, style, size, skewed_fraction_subtype, &fam);
- halfword thickness = tex_get_math_y_parameter_checked(style, math_parameter_fraction_rule);
+ // scaled thickness = tex_aux_check_fraction_rule(target, style, size, skewed_fraction_subtype, &fam);
+ scaled thickness = tex_get_math_y_parameter_checked(style, math_parameter_fraction_rule);
scaled exheight = tex_aux_math_exheight(size);
scaled emwidth = tex_aux_math_emwidth(size);
halfword result = tex_made_extensible(target, fnt, chr, size, 0, maxheight, maxdepth, thickness, axis, exheight, emwidth, 0, callback);
@@ -4432,7 +4643,7 @@ static halfword tex_aux_make_ruled_fraction(halfword target, int style, int size
scaled shift_down = 0;
scaled delta = 0;
halfword fam = 0;
- halfword thickness = tex_aux_check_fraction_rule(target, style, size, fractiontype, &fam);
+ scaled thickness = tex_aux_check_fraction_rule(target, style, size, fractiontype, &fam);
halfword fraction = tex_new_null_box_node(vlist_node, math_fraction_list);
halfword rule = null;
halfword mergedattr = tex_merge_attribute_list(null, noad_extra_attr(target));
@@ -4467,7 +4678,7 @@ static halfword tex_aux_make_stretched_fraction(halfword target, int style, int
scaled shift_up = 0;
scaled shift_down = 0;
scaled delta = 0;
- halfword thickness = tex_aux_check_fraction_rule(target, style, size, stretched_fraction_subtype, NULL);
+ scaled thickness = tex_aux_check_fraction_rule(target, style, size, stretched_fraction_subtype, NULL);
halfword fraction = tex_new_null_box_node(vlist_node, math_fraction_list);
halfword mergedattr = tex_merge_attribute_list(delimiter ? node_attr(delimiter) : null, noad_extra_attr(target));
(void) kerns;
@@ -4731,14 +4942,14 @@ static scaled tex_aux_op_do_limits(halfword target, int style, int size, int ita
would be to also adapt the width of the wrapped scripts but these are reboxed
with centering so we keep that as it is. We rebox anyway to get hboxes.
*/
- halfword savedwidth = boxwidth;
- halfword overshoot = 0;
+ scaled savedwidth = boxwidth;
+ scaled overshoot = 0;
superscript = tex_aux_rebox(superscript, supwidth, size);
kernel = tex_aux_rebox(kernel, boxwidth, size);
subscript = tex_aux_rebox(subscript, subwidth, size);
if (supwidth) {
- halfword shift = savedwidth/2 + topshift - supwidth/2;
- halfword delta = supwidth + shift - savedwidth;
+ scaled shift = savedwidth/2 + topshift - supwidth/2;
+ scaled delta = supwidth + shift - savedwidth;
box_shift_amount(superscript) = shift;
if (delta > 0) {
boxwidth = boxwidth + delta;
@@ -4753,7 +4964,7 @@ static scaled tex_aux_op_do_limits(halfword target, int style, int size, int ita
}
}
if (subwidth) {
- halfword shift = savedwidth/2 - bottomshift - subwidth/2 + overshoot;
+ scaled shift = savedwidth/2 - bottomshift - subwidth/2 + overshoot;
box_shift_amount(subscript) = shift;
if (shift < 0) {
box_shift_amount(superscript) -= shift;
@@ -5114,8 +5325,8 @@ static halfword tex_aux_check_ord(halfword current, halfword size, halfword next
}
tex_aux_fetch(nucleus, "ordinal", &curfnt, &curchr);
if (curfnt && curchr) {
- halfword kern = 0;
- halfword italic = 0;
+ scaled kern = 0;
+ scaled italic = 0;
/*tex
Contrary to \LUATEX which has also checks the class of the next atom
with something |node_subtype(next) < punct_noad_type|, we control it
@@ -5378,7 +5589,7 @@ static void tex_aux_get_math_sup_sub_shifts(halfword target, halfword sup, halfw
}
}
-static halfword tex_aux_combine_script(halfword target, halfword width, halfword pre, halfword post, halfword *k1, halfword *k2, quarterword subtype)
+static halfword tex_aux_combine_script(halfword target, scaled width, halfword pre, halfword post, halfword *k1, halfword *k2, quarterword subtype)
{
*k1 = tex_new_kern_node(-(width + box_width(pre)), horizontal_math_kern_subtype);
*k2 = tex_new_kern_node(width, horizontal_math_kern_subtype);
@@ -5916,8 +6127,8 @@ static void tex_aux_make_scripts(halfword target, halfword kernel, scaled italic
scriptdata presubdata = { .node = null, .fnt = null_font, .chr = 0, .box = null, .kern = 0, .slack = 0, .shifted = 0, .whatever = 0 };
scriptdata presupdata = { .node = null, .fnt = null_font, .chr = 0, .box = null, .kern = 0, .slack = 0, .shifted = 0, .whatever = 0 };
scriptdata primedata = { .node = null, .fnt = null_font, .chr = 0, .box = null, .kern = 0, .slack = 0, .shifted = 0, .whatever = 0 };
- halfword maxleftkern = 0;
- // halfword maxrightkern = 0;
+ scaled maxleftkern = 0;
+ // scaled maxrightkern = 0;
scaled leftslack = 0;
scaled rightslack = 0;
scaledwhd kernelsize = { .wd = 0, .ht = 0, .dp = 0, .ic = 0 };
@@ -6153,7 +6364,7 @@ static void tex_aux_make_scripts(halfword target, halfword kernel, scaled italic
maximum kern wins.
*/
if (noad_supscr(target)) {
- halfword extra = tex_get_math_y_parameter_checked(style, math_parameter_extra_superscript_shift);
+ scaled extra = tex_get_math_y_parameter_checked(style, math_parameter_extra_superscript_shift);
postsupdata.slack = tex_get_math_x_parameter_checked(style, math_parameter_extra_superscript_space);
postsupdata.slack += tex_round_xn_over_d(tex_get_math_x_parameter_default(style, math_parameter_space_after_script, 0), script_space_after_factor_par, scaling_factor);
postsupdata.box = tex_aux_clean_box(noad_supscr(target), (has_noad_option_nosupscript(target) ? style : tex_math_style_variant(style, math_parameter_superscript_variant)), style, math_sup_list, 0, NULL);
@@ -6169,7 +6380,7 @@ static void tex_aux_make_scripts(halfword target, halfword kernel, scaled italic
noad_supscr(target) = null;
}
if (noad_subscr(target)) {
- halfword extra = tex_get_math_y_parameter_checked(style, math_parameter_extra_subscript_shift);
+ scaled extra = tex_get_math_y_parameter_checked(style, math_parameter_extra_subscript_shift);
postsubdata.slack = tex_get_math_x_parameter_checked(style, math_parameter_extra_subscript_space);
postsubdata.slack += tex_round_xn_over_d(tex_get_math_x_parameter_default(style, math_parameter_space_after_script, 0), script_space_after_factor_par, scaling_factor);
postsubdata.box = tex_aux_clean_box(noad_subscr(target), (has_noad_option_nosubscript(target) ? style : tex_math_style_variant(style, math_parameter_subscript_variant)), style, math_sub_list, 0, NULL);
@@ -6185,7 +6396,7 @@ static void tex_aux_make_scripts(halfword target, halfword kernel, scaled italic
noad_subscr(target) = null;
}
if (noad_supprescr(target)) {
- halfword extra = tex_get_math_y_parameter_checked(style, math_parameter_extra_superprescript_shift);
+ scaled extra = tex_get_math_y_parameter_checked(style, math_parameter_extra_superprescript_shift);
presupdata.slack = tex_get_math_x_parameter_checked(style, math_parameter_extra_superprescript_space);
presupdata.slack += tex_round_xn_over_d(tex_get_math_x_parameter_default(style, math_parameter_space_before_script, 0), script_space_before_factor_par, scaling_factor);
presupdata.box = tex_aux_clean_box(noad_supprescr(target), (has_noad_option_nosupprescript(target) ? style : tex_math_style_variant(style, math_parameter_superscript_variant)), style, math_sup_list, 0, NULL);
@@ -6204,7 +6415,7 @@ static void tex_aux_make_scripts(halfword target, halfword kernel, scaled italic
noad_supprescr(target) = null;
}
if (noad_subprescr(target)) {
- halfword extra = tex_get_math_y_parameter_checked(style, math_parameter_extra_subprescript_shift);
+ scaled extra = tex_get_math_y_parameter_checked(style, math_parameter_extra_subprescript_shift);
presubdata.slack = tex_get_math_x_parameter_checked(style, math_parameter_extra_subprescript_space);
presubdata.slack += tex_round_xn_over_d(tex_get_math_x_parameter_default(style, math_parameter_space_before_script, 0), script_space_before_factor_par, scaling_factor);
presubdata.box = tex_aux_clean_box(noad_subprescr(target), (has_noad_option_nosubprescript(target) ? style : tex_math_style_variant(style, math_parameter_subscript_variant)), style, math_sub_list, 0, NULL);
@@ -6259,7 +6470,7 @@ static void tex_aux_make_scripts(halfword target, halfword kernel, scaled italic
halfword list = noad_new_hlist(target);
if (list) {
/*tex We want to keep the size for tracing! */
- halfword overshoot = box_width(primedata.box) - box_width(postsubdata.box);
+ scaled overshoot = box_width(primedata.box) - box_width(postsubdata.box);
halfword primebox = tex_hpack(primedata.box, 0, packing_additional, direction_unknown, holding_none_option, box_limit_none, null, null);
tex_attach_attribute_list_copy(primebox, primedata.box);
box_width(primebox) = 0;
@@ -6505,10 +6716,8 @@ static void tex_aux_make_scripts(halfword target, halfword kernel, scaled italic
if (math_slack_mode_par > 0) { /* brrr what with multiple scripts .... */
noad_left_slack(target) = leftslack;
noad_right_slack(target) = rightslack;
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: script slack, left %p, right %p]", leftslack, rightslack);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: script slack, left %p, right %p]%>", leftslack, rightslack);
}
}
if (presubdata.box || postsubdata.box) {
@@ -6566,7 +6775,7 @@ static halfword tex_aux_make_left_right(halfword target, int style, scaled max_d
halfword fnt = tex_fam_fnt(fam, size);
if (chr && fnt != null_font) {
halfword callback = noad_callback(target);
- halfword thickness = tex_get_math_y_parameter_checked(style, math_parameter_fraction_rule);
+ scaled thickness = tex_get_math_y_parameter_checked(style, math_parameter_fraction_rule);
scaled axis = tex_aux_math_axis(size);
scaled exheight = tex_aux_math_exheight(size);
scaled emwidth = tex_aux_math_emwidth(size);
@@ -6618,7 +6827,7 @@ static halfword tex_aux_make_left_right(halfword target, int style, scaled max_d
if (has_noad_option_noaxis(target) && stack) {
/*tex A sort of special case: see sized integrals in ctx examples. */
} else {
- halfword axis = tex_aux_math_axis(size);
+ scaled axis = tex_aux_math_axis(size);
height += axis;
depth -= axis;
box_shift_amount(tmp) -= axis;
@@ -6779,19 +6988,21 @@ static halfword tex_aux_math_spacing_glue(halfword ltype, halfword rtype, halfwo
break;
case dimension_val_level:
x = tex_aux_math_dimension(x, inter_math_skip_glue, c);
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: inter atom kern, left %n, right %n, resolved %i, amount %p]", ltype, rtype, s, glue_amount(x));
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format(
+ "%<%l[math: inter atom kern, left %n, right %n, resolved %i, amount %p]%>",
+ ltype, rtype, s, glue_amount(x)
+ );
}
return x;
case glue_val_level:
if (! tex_glue_is_zero(x)) {
x = tex_aux_math_glue(x, inter_math_skip_glue, c);
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: inter atom glue, left %n, right %n, resolved %i, amount %P]", ltype, rtype, s, glue_amount(x), glue_stretch(x), 0, 0, 0, 0, glue_shrink(x));
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format(
+ "%<%l[math: inter atom glue, left %n, right %n, resolved %i, amount %P]%>",
+ ltype, rtype, s, glue_amount(x), glue_stretch(x), 0, 0, 0, 0, glue_shrink(x)
+ );
}
return x;
}
@@ -6799,19 +7010,21 @@ static halfword tex_aux_math_spacing_glue(halfword ltype, halfword rtype, halfwo
case muglue_val_level:
if (! tex_math_glue_is_zero(x)) {
x = tex_aux_math_muglue(x, inter_math_skip_glue, mmu, c, style);
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: inter atom (mu) glue, left %n, right %n, resolved %i, amount %P]", ltype, rtype, s, glue_amount(x), glue_stretch(x), 0, 0, 0, 0, glue_shrink(x));
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format(
+ "%<%l[math: inter atom (mu) glue, left %n, right %n, resolved %i, amount %P]%>",
+ ltype, rtype, s, glue_amount(x), glue_stretch(x), 0, 0, 0, 0, glue_shrink(x)
+ );
}
return x;
}
goto NONE;
default:
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: inter atom (mu) glue, left %n, right %n, resolved %i, unset]", ltype, rtype, s);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format(
+ "%<%l[math: inter atom (mu) glue, left %n, right %n, resolved %i, unset]%>",
+ ltype, rtype, s
+ );
}
goto NONE;
}
@@ -6853,17 +7066,19 @@ static halfword tex_aux_math_spacing_glue(halfword ltype, halfword rtype, halfwo
goto FOUND;
}
/*tex Now we're lost. */
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: inter atom fallback, left %n, right %n, left parent %n, right parent %n, not resolved]", ltype, rtype, lparent, rparent);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format(
+ "%<%l[math: inter atom fallback, left %n, right %n, left parent %n, right parent %n, not resolved]%>",
+ ltype, rtype, lparent, rparent
+ );
}
goto NONE;
FOUND:
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: inter atom fallback, left %n, right %n, left parent %n, right parent %n, resolved %i]", ltype, rtype, lparent, rparent, s);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format(
+ "%<%l[math: inter atom fallback, left %n, right %n, left parent %n, right parent %n, resolved %i]%>",
+ ltype, rtype, lparent, rparent, s
+ );
}
}
} else {
@@ -6926,8 +7141,8 @@ static halfword tex_aux_math_ruling(halfword ltype, halfword rtype, halfword sty
halfword tex_math_spacing_glue(halfword ltype, halfword rtype, halfword style)
{
- // halfword mu = tex_get_math_quad_size_scaled(lmt_math_state.size); /* scales by math x scale */
- halfword mu = tex_get_math_quad_size_unscaled(lmt_math_state.size); /* scales by math x scale */
+ // scaled mu = tex_get_math_quad_size_scaled(lmt_math_state.size); /* scales by math x scale */
+ scaled mu = tex_get_math_quad_size_unscaled(lmt_math_state.size); /* scales by math x scale */
halfword sg = tex_aux_math_spacing_glue(ltype, rtype, style, mu);
if (node_type(sg) == glue_node) {
tex_add_glue_option(sg, glue_option_no_auto_break);
@@ -7231,10 +7446,8 @@ static int tex_aux_make_fenced(halfword current, halfword current_style, halfwor
noad_nucleus(n) = noad_supscr(current);
math_kernel_list(top) = n;
noad_supscr(current) = null;
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: promoting supscript to top delimiter]");
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: promoting supscript to top delimiter]%>");
}
}
if (noad_subscr(current) && ! (fence_delimiter_bottom(list) && math_kernel_list(fence_delimiter_bottom(list)))) {
@@ -7244,10 +7457,8 @@ static int tex_aux_make_fenced(halfword current, halfword current_style, halfwor
noad_nucleus(n) = noad_subscr(current);
math_kernel_list(bottom) = n;
noad_subscr(current) = null;
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: promoting subscript to bottom delimiter]");
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: promoting subscript to bottom delimiter]%>");
}
}
/*tex
@@ -7472,10 +7683,8 @@ static halfword tex_aux_check_source(halfword current, halfword list, int repack
break;
default:
if (repack) {
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: packing due to source field %i]", noad_source(current));
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: packing due to source field %i]%>", noad_source(current));
}
list = tex_hpack(list, 0, packing_additional, direction_unknown, holding_none_option, box_limit_none, null, null);
tex_attach_attribute_list_copy(list, current);
@@ -7493,7 +7702,7 @@ static halfword tex_aux_check_source(halfword current, halfword list, int repack
return list;
}
-static void tex_aux_wrapup_nucleus_and_add_scripts(halfword current, halfword nxt, int current_style, halfword *italic, kernset *kerns)
+static void tex_aux_wrapup_nucleus_and_add_scripts(halfword current, halfword nxt, int current_style, scaled *italic, kernset *kerns)
{
halfword p = tex_aux_check_nucleus_complexity(current, italic, current_style, lmt_math_state.size, kerns);
if (p && noad_source(current)) {
@@ -7569,11 +7778,11 @@ static void tex_mlist_to_hlist_preroll_radicals(mliststate *state)
{
halfword current = state->mlist;
halfword current_style = state->main_style;
- halfword height = 0;
- halfword depth = 0;
+ scaled height = 0;
+ scaled depth = 0;
tex_aux_set_current_math_size(current_style);
- tex_aux_set_current_math_scale(state->scale);
- if (tracing_math_par >= 2) {
+ tex_aux_set_current_math_scale(state->scale, 0);
+ if lmt_unlikely(tracing_math_par >= 2) {
tex_aux_show_math_list("[math: radical sizing pass, level %i]", state->mlist);
}
while (current) {
@@ -7655,10 +7864,10 @@ static void tex_mlist_to_hlist_preroll_dimensions(mliststate *state)
int blockrulebased = 0;
/*tex We set the math unit width corresponding to |size|: */
tex_aux_set_current_math_size(current_style);
- tex_aux_set_current_math_scale(state->scale);
+ tex_aux_set_current_math_scale(state->scale, 0);
// current_mu = tex_get_math_quad_size_scaled(lmt_math_state.size);
current_mu = tex_get_math_quad_size_unscaled(lmt_math_state.size);
- if (tracing_math_par >= 2) {
+ if lmt_unlikely(tracing_math_par >= 2) {
tex_aux_show_math_list("[math: preroll dimensions pass, level %i]", state->mlist);
}
while (current) {
@@ -8057,7 +8266,7 @@ static void tex_mlist_to_hlist_preroll_continuation(mliststate *state)
halfword current = state->mlist;
halfword first = null;
halfword last = null;
- if (tracing_math_par >= 2) {
+ if lmt_unlikely(tracing_math_par >= 2) {
tex_aux_show_math_list("[math: continuation pass, level %i]", state->mlist);
}
while (current) {
@@ -8111,8 +8320,8 @@ static void tex_mlist_to_hlist_size_fences(mliststate *state)
scaled height = 0;
scaled depth = 0;
tex_aux_set_current_math_size(current_style);
- tex_aux_set_current_math_scale(state->scale);
- if (tracing_math_par >= 2) {
+ tex_aux_set_current_math_scale(state->scale, 0);
+ if lmt_unlikely(tracing_math_par >= 2) {
tex_aux_show_math_list("[math: fence sizing pass, level %i]", state->mlist);
}
/* first pass */
@@ -8167,8 +8376,8 @@ static void tex_mlist_to_hlist_finalize_list(mliststate *state)
halfword current_style = state->main_style;
halfword fenced = null;
halfword packedfence = null;
- halfword recent_left_slack = 0;
- halfword recent_right_slack = 0;
+ scaled recent_left_slack = 0;
+ scaled recent_right_slack = 0;
halfword recent_class_overload = unset_noad_class;
halfword recent_script_state = 0;
halfword recent_plus_glyph = null;
@@ -8181,12 +8390,12 @@ static void tex_mlist_to_hlist_finalize_list(mliststate *state)
int nestingfactor = scaling_factor;
node_next(p) = null;
tex_aux_set_current_math_size(current_style);
- tex_aux_set_current_math_scale(state->scale);
+ tex_aux_set_current_math_scale(state->scale, 0);
current_mu = tex_get_math_quad_size_unscaled(lmt_math_state.size); /* not _scaled */
if (math_penalties_mode_par) {
state->penalties = 1; /* move to caller ? */
}
- if (tracing_math_par >= 2) {
+ if lmt_unlikely(tracing_math_par >= 2) {
tex_aux_show_math_list("[math: finalize pass, level %i]", state->mlist);
}
RESTART:
@@ -8214,8 +8423,8 @@ static void tex_mlist_to_hlist_finalize_list(mliststate *state)
halfword post_penalty = infinite_penalty;
halfword pre_penalty = infinite_penalty;
/*tex experiment */
- halfword current_left_slack = 0;
- halfword current_right_slack = 0;
+ scaled current_left_slack = 0;
+ scaled current_right_slack = 0;
halfword current_script_state = 0;
halfword current_plus_glyph = 0;
halfword old_recent = 0;
@@ -8357,6 +8566,8 @@ static void tex_mlist_to_hlist_finalize_list(mliststate *state)
default:
break;
}
+ /* Ordinary math glue is picked up below together with boundary nodes. */
+ FALLTHROUGH
case boundary_node:
if (node_subtype(current) == math_boundary) {
halfword l = boundary_data(current);
@@ -8475,14 +8686,18 @@ static void tex_mlist_to_hlist_finalize_list(mliststate *state)
current_subtype = value & 0xFF;
}
}
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
if (old_recent != recent_subtype || old_current != current_subtype) {
- tex_print_format("%l[math: atom ruling, recent %n, current %n, new recent %n, new current %n]", old_recent, old_current, recent_subtype, current_subtype);
+ tex_print_format(
+ "%<%l[math: atom ruling, recent %n, current %n, new recent %n, new current %n]%>",
+ old_recent, old_current, recent_subtype, current_subtype
+ );
} else {
- tex_print_format("%l[math: atom ruling, recent %n, current %n]", old_recent, old_current);
+ tex_print_format(
+ "%<%l[math: atom ruling, recent %n, current %n]%>",
+ old_recent, old_current
+ );
}
- tex_end_diagnostic();
}
}
/*tex Now we set the inter-atom penalties: */
@@ -8495,16 +8710,14 @@ static void tex_mlist_to_hlist_finalize_list(mliststate *state)
/*tex Append inter-element spacing based on |r_type| and |t| */
if (current_plus_glyph && recent_script_state) {
/*tex This is a very special case and used {x^2 / 3| kind of situations: */
- halfword plus = tex_aux_checked_left_kern(current_plus_glyph, recent_script_state, current_subtype, lmt_math_state.size);
+ scaled plus = tex_aux_checked_left_kern(current_plus_glyph, recent_script_state, current_subtype, lmt_math_state.size);
if (plus) {
halfword kern = tex_new_kern_node(plus, math_shape_kern_subtype);
tex_attach_attribute_list_copy(kern, current);
tex_couple_nodes(p, kern);
p = kern;
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: state driven left shape kern %p]", plus);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: state driven left shape kern %p]%>", plus);
}
}
}
@@ -8527,25 +8740,21 @@ static void tex_mlist_to_hlist_finalize_list(mliststate *state)
} else {
glue_amount(glue) += recent_right_slack;
}
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: migrating right slack %p]", recent_right_slack);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: migrating right slack %p]%>", recent_right_slack);
}
recent_right_slack = 0;
}
if (recent_plus_glyph && current_script_state) {
/*tex This is a very special case and used {x^2 / 3| kind of situations: */
- halfword plus = tex_aux_checked_right_kern(recent_plus_glyph, current_script_state, recent_subtype, lmt_math_state.size);
+ scaled plus = tex_aux_checked_right_kern(recent_plus_glyph, current_script_state, recent_subtype, lmt_math_state.size);
if (plus) {
halfword kern = tex_new_kern_node(plus, math_shape_kern_subtype);
tex_attach_attribute_list_copy(kern, current);
tex_couple_nodes(p, kern);
p = kern;
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: state driven right shape kern %p]", plus);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: state driven right shape kern %p]%>", plus);
}
}
}
@@ -8595,10 +8804,8 @@ static void tex_mlist_to_hlist_finalize_list(mliststate *state)
tex_attach_attribute_list_copy(penalty, current);
tex_couple_nodes(p, penalty);
p = penalty;
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: pre penalty, left %n, right %n, amount %i]", recent_subtype, current_subtype, penalty_amount(penalty));
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: pre penalty, left %n, right %n, amount %i]%>", recent_subtype, current_subtype, penalty_amount(penalty));
}
}
}
@@ -8606,10 +8813,8 @@ static void tex_mlist_to_hlist_finalize_list(mliststate *state)
if (node_type(p) == kern_node && node_subtype(p) == italic_kern_subtype) {
halfword prv = node_prev(p);
if (prv) {
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: removing italic correction %p between %i and %i]", kern_amount(p), recent_subtype, current_subtype);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: removing italic correction %p between %i and %i]%>", kern_amount(p), recent_subtype, current_subtype);
}
tex_flush_node(p);
p = prv;
@@ -8701,10 +8906,8 @@ static void tex_mlist_to_hlist_finalize_list(mliststate *state)
tex_attach_attribute_list_copy(penalty, current);
tex_couple_nodes(p, penalty);
p = penalty;
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: post penalty, left %n, right %n, amount %i]", recent_subtype, current_subtype, penalty_amount(penalty));
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: post penalty, left %n, right %n, amount %i]%>", recent_subtype, current_subtype, penalty_amount(penalty));
}
}
}
@@ -8734,10 +8937,8 @@ static void tex_mlist_to_hlist_finalize_list(mliststate *state)
tex_attach_attribute_list_copy(kern, head);
tex_couple_nodes(kern, head);
node_next(temp_head) = kern;
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: nilling recent left slack %p]", recent_left_slack);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: nilling recent left slack %p]%>", recent_left_slack);
}
}
recent = current;
@@ -8747,10 +8948,8 @@ static void tex_mlist_to_hlist_finalize_list(mliststate *state)
tex_attach_attribute_list_copy(kern, p);
tex_couple_nodes(p, kern);
p = kern;
- if (tracing_math_par >= 2) {
- tex_begin_diagnostic();
- tex_print_format("%l[math: nilling recent right slack %p]", recent_right_slack);
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_math_par >= 2) {
+ tex_print_format("%<%l[math: nilling recent right slack %p]%>", recent_right_slack);
}
}
// first = 0;
@@ -8763,7 +8962,7 @@ static void tex_mlist_to_hlist_finalize_list(mliststate *state)
WIPE:
tex_aux_wipe_noad(recent);
}
- if (tracing_math_par >= 3) {
+ if lmt_unlikely(tracing_math_par >= 3) {
tex_aux_show_math_list("[math: result, level %i]", node_next(temp_head));
}
}
@@ -8787,7 +8986,7 @@ static void tex_mlist_to_hlist_prepare(mliststate *state)
if (state->mlist) {
halfword current = state->mlist;
halfword first = null;
- if (tracing_math_par >= 2) {
+ if lmt_unlikely(tracing_math_par >= 2) {
tex_aux_show_math_list("[math: prescript reordering pass, level %i]", state->mlist);
}
while (current) {
diff --git a/source/luametatex/source/tex/texmlist.h b/source/luametatex/source/tex/texmlist.h
index 10a30a398..3c0f0761a 100644
--- a/source/luametatex/source/tex/texmlist.h
+++ b/source/luametatex/source/tex/texmlist.h
@@ -36,8 +36,8 @@ extern halfword tex_make_extensible (halfword fnt, halfword chr, scaled
extern halfword tex_new_math_glyph (halfword fnt, halfword chr);
extern halfword tex_math_spacing_glue (halfword ltype, halfword rtype, halfword style);
-extern halfword tex_math_font_char_ht (halfword fnt, halfword chr, halfword style);
-extern halfword tex_math_font_char_dp (halfword fnt, halfword chr, halfword style);
+extern scaled tex_math_font_char_ht (halfword fnt, halfword chr, halfword style);
+extern scaled tex_math_font_char_dp (halfword fnt, halfword chr, halfword style);
extern void tex_set_math_text_font (halfword style, int usefamfont);
extern scaled tex_math_parameter_x_scaled (int style, int param);
diff --git a/source/luametatex/source/tex/texnesting.c b/source/luametatex/source/tex/texnesting.c
index bc64f0b39..90911d229 100644
--- a/source/luametatex/source/tex/texnesting.c
+++ b/source/luametatex/source/tex/texnesting.c
@@ -425,9 +425,11 @@ void tex_show_activities(void)
while (r != page_insert_head) {
halfword index = insert_index(r);
halfword multiplier = tex_get_insert_multiplier(index);
- halfword size = multiplier == scaling_factor ? insert_total_height(r) : tex_x_over_n_factor(insert_total_height(r)) * multiplier;
- // halfword size = multiplier == scaling_factor ? insert_total_height(r) : insert_total_height(r) * multiplier / scaling_factor;
- // halfword size = multiplier == scaling_factor ? insert_total_height(r) : scaledround(insert_total_height(r) * multiplier / scaling_factor_double) ;
+ // scaled size = multiplier == scaling_factor ? insert_total_height(r) : tex_x_over_n_factor(insert_total_height(r)) * multiplier;
+ // scaled size = multiplier == scaling_factor ? insert_total_height(r) : insert_total_height(r) * multiplier / scaling_factor;
+ // scaled size = multiplier == scaling_factor ? insert_total_height(r) : scaledround(insert_total_height(r) * multiplier / scaling_factor_double) ;
+ scaled height = insert_total_height(r);
+ scaled size = (multiplier == scaling_factor) ? height : tex_xn_over_1000(height, multiplier);
if (node_type(r) == split_node && node_subtype(r) == insert_split_subtype) {
halfword q = page_head;
halfword n = 0;
@@ -792,7 +794,7 @@ void tex_start_mvl(void)
{
halfword index = 0;
halfword options = 0;
- halfword prevdepth = max_dimen;
+ scaled prevdepth = max_dimen;
while (1) {
switch (tex_scan_character("iop", 0, 1, 0)) {
case 'i':
@@ -835,10 +837,8 @@ void tex_start_mvl(void)
} else if (prevdepth == max_dimen) {
prevdepth = lmt_mvl_state.mvl[index].prev_depth;
}
- if (tracing_mvl_par) {
- tex_begin_diagnostic();
- tex_print_format("%l[mvl: index %i, options %x, prevdepth %p, %s]", index, options, prevdepth, start ? "start" : "restart");
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_mvl_par) {
+ tex_print_format("%<%l[mvl: index %i, options %x, prevdepth %p, %s]%>", index, options, prevdepth, start ? "start" : "restart");
}
if (start) {
mvl->head = tex_new_temp_node();
@@ -857,10 +857,8 @@ void tex_stop_mvl(void)
if (index) {
list_state_record *mvl = &lmt_mvl_state.mvl[index];
int something = mvl->tail != mvl->head;
- if (tracing_mvl_par) {
- tex_begin_diagnostic();
- tex_print_format("%l[mvl: index %i, options %x, stop with%s contributions]", index, mvl->options, something ? "" : "out");
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_mvl_par) {
+ tex_print_format("%<%l[mvl: index %i, options %x, stop with%s contributions]%>", index, mvl->options, something ? "" : "out");
}
if (something && (mvl->options & mvl_discard_bottom)) {
halfword last = mvl->tail;
@@ -907,10 +905,8 @@ halfword tex_flush_mvl(halfword index)
halfword head = node_next(lmt_mvl_state.mvl[index].head);
tex_flush_node(lmt_mvl_state.mvl[index].head);
tex_aux_reset_mvl(index);
- if (tracing_mvl_par) {
- tex_begin_diagnostic();
- tex_print_format("%l[mvl: index %i, %s]", index, "flush");
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_mvl_par) {
+ tex_print_format("%<%l[mvl: index %i, %s]%>", index, "flush");
}
node_prev(head) = null;
# if page_callback
@@ -978,10 +974,8 @@ int tex_appended_mvl(halfword context, halfword boundary)
}
}
if (contribute_head != contribute_tail && first) {
- if (tracing_mvl_par) {
- tex_begin_diagnostic();
- tex_print_format("%l[mvl: index %i, %s]", lmt_mvl_state.slot, assign ? "assign" : "append");
- tex_end_diagnostic();
+ if lmt_unlikely(tracing_mvl_par) {
+ tex_print_format("%<%l[mvl: index %i, %s]%>", lmt_mvl_state.slot, assign ? "assign" : "append");
}
if (assign) {
tex_couple_nodes(lmt_mvl_state.mvl[lmt_mvl_state.slot].head, first);
diff --git a/source/luametatex/source/tex/texnesting.h b/source/luametatex/source/tex/texnesting.h
index f40452065..b75b7c1b1 100644
--- a/source/luametatex/source/tex/texnesting.h
+++ b/source/luametatex/source/tex/texnesting.h
@@ -27,7 +27,7 @@ typedef struct list_state_record {
halfword tail;
int prev_graf;
int mode_line;
- halfword prev_depth; // scaled
+ scaled prev_depth;
halfword space_factor;
halfword space_penalty;
halfword direction_stack;
diff --git a/source/luametatex/source/tex/texnodes.c b/source/luametatex/source/tex/texnodes.c
index b4c4aae08..0311157ed 100644
--- a/source/luametatex/source/tex/texnodes.c
+++ b/source/luametatex/source/tex/texnodes.c
@@ -830,11 +830,12 @@ void lmt_nodelib_initialize(void) {
set_value_entry_val(lmt_node_fields_rule, 15, integer_field, off);
set_value_entry_val(lmt_node_fields_rule, 16, integer_field, thickness);
- lmt_node_fields_style = lmt_aux_allocate_value_info(3);
+ lmt_node_fields_style = lmt_aux_allocate_value_info(4);
set_value_entry_val(lmt_node_fields_style, 0, attribute_field, attr);
set_value_entry_val(lmt_node_fields_style, 1, integer_field, style);
set_value_entry_val(lmt_node_fields_style, 2, integer_field, scale);
+ set_value_entry_val(lmt_node_fields_style, 3, integer_field, glyphscale);
lmt_node_fields_parameter = lmt_aux_allocate_value_info(3);
@@ -883,73 +884,79 @@ void lmt_nodelib_initialize(void) {
Subtypes in nodes and codes in commands sometimes are sort of in sync but don't rely on
that!
+
*/
- lmt_interface.node_data[hlist_node] = (node_info) { .id = hlist_node, .size = box_node_size, .first = 0, .last = last_list_subtype, .subtypes = subtypes_list, .fields = lmt_node_fields_list, .name = lua_key(hlist), .lua = lua_key_index(hlist), .visible = 1, .definable = 1 };
- lmt_interface.node_data[vlist_node] = (node_info) { .id = vlist_node, .size = box_node_size, .first = 0, .last = last_list_subtype, .subtypes = subtypes_list, .fields = lmt_node_fields_list, .name = lua_key(vlist), .lua = lua_key_index(vlist), .visible = 1, .definable = 1 };
- lmt_interface.node_data[rule_node] = (node_info) { .id = rule_node, .size = rule_node_size, .first = 0, .last = last_rule_subtype, .subtypes = subtypes_rule, .fields = lmt_node_fields_rule, .name = lua_key(rule), .lua = lua_key_index(rule), .visible = 1, .definable = 1 };
- lmt_interface.node_data[insert_node] = (node_info) { .id = insert_node, .size = insert_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = lmt_node_fields_insert, .name = lua_key(insert), .lua = lua_key_index(insert), .visible = 1, .definable = 1 };
- lmt_interface.node_data[mark_node] = (node_info) { .id = mark_node, .size = mark_node_size, .first = 0, .last = last_mark_subtype, .subtypes = subtypes_mark, .fields = lmt_node_fields_mark, .name = lua_key(mark), .lua = lua_key_index(mark), .visible = 1, .definable = 1 };
- lmt_interface.node_data[adjust_node] = (node_info) { .id = adjust_node, .size = adjust_node_size, .first = 0, .last = last_adjust_subtype, .subtypes = subtypes_adjust, .fields = lmt_node_fields_adjust, .name = lua_key(adjust), .lua = lua_key_index(adjust), .visible = 1, .definable = 1 };
- lmt_interface.node_data[boundary_node] = (node_info) { .id = boundary_node, .size = boundary_node_size, .first = 0, .last = last_boundary_subtype, .subtypes = subtypes_boundary, .fields = lmt_node_fields_boundary, .name = lua_key(boundary), .lua = lua_key_index(boundary), .visible = 1, .definable = 1 };
- lmt_interface.node_data[disc_node] = (node_info) { .id = disc_node, .size = disc_node_size, .first = 0, .last = last_discretionary_subtype, .subtypes = subtypes_disc, .fields = lmt_node_fields_disc, .name = lua_key(disc), .lua = lua_key_index(disc), .visible = 1, .definable = 1 };
- lmt_interface.node_data[whatsit_node] = (node_info) { .id = whatsit_node, .size = whatsit_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = lmt_node_fields_whatsit, .name = lua_key(whatsit), .lua = lua_key_index(whatsit), .visible = 1, .definable = 1 };
- lmt_interface.node_data[par_node] = (node_info) { .id = par_node, .size = par_node_size, .first = 0, .last = last_par_subtype, .subtypes = subtypes_par, .fields = lmt_node_fields_par, .name = lua_key(par), .lua = lua_key_index(par), .visible = 1, .definable = 1 };
- lmt_interface.node_data[dir_node] = (node_info) { .id = dir_node, .size = dir_node_size, .first = 0, .last = last_dir_subtype, .subtypes = subtypes_dir, .fields = lmt_node_fields_dir, .name = lua_key(dir), .lua = lua_key_index(dir), .visible = 1, .definable = 1 };
- lmt_interface.node_data[math_node] = (node_info) { .id = math_node, .size = math_node_size, .first = 0, .last = last_math_subtype, .subtypes = subtypes_math, .fields = lmt_node_fields_math, .name = lua_key(math), .lua = lua_key_index(math), .visible = 1, .definable = 1 };
- lmt_interface.node_data[glue_node] = (node_info) { .id = glue_node, .size = glue_node_size, .first = 0, .last = last_glue_subtype, .subtypes = subtypes_glue, .fields = lmt_node_fields_glue, .name = lua_key(glue), .lua = lua_key_index(glue), .visible = 1, .definable = 1 };
- lmt_interface.node_data[kern_node] = (node_info) { .id = kern_node, .size = kern_node_size, .first = 0, .last = last_kern_subtype, .subtypes = subtypes_kern, .fields = lmt_node_fields_kern, .name = lua_key(kern), .lua = lua_key_index(kern), .visible = 1, .definable = 1 };
- lmt_interface.node_data[penalty_node] = (node_info) { .id = penalty_node, .size = penalty_node_size, .first = 0, .last = last_penalty_subtype, .subtypes = subtypes_penalty, .fields = lmt_node_fields_penalty, .name = lua_key(penalty), .lua = lua_key_index(penalty), .visible = 1, .definable = 1 };
- lmt_interface.node_data[style_node] = (node_info) { .id = style_node, .size = style_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = lmt_node_fields_style, .name = lua_key(style), .lua = lua_key_index(style), .visible = 1, .definable = 1 };
- lmt_interface.node_data[choice_node] = (node_info) { .id = choice_node, .size = choice_node_size, .first = 0, .last = last_choice_subtype, .subtypes = subtypes_choice, .fields = lmt_node_fields_choice, .name = lua_key(choice), .lua = lua_key_index(choice), .visible = 1, .definable = 1 };
- lmt_interface.node_data[parameter_node] = (node_info) { .id = parameter_node, .size = parameter_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = lmt_node_fields_parameter, .name = lua_key(parameter), .lua = lua_key_index(parameter), .visible = 1, .definable = 1 };
- lmt_interface.node_data[simple_noad] = (node_info) { .id = simple_noad, .size = noad_size, .first = 0, .last = last_noad_subtype, .subtypes = subtypes_noad, .fields = lmt_node_fields_noad, .name = lua_key(noad), .lua = lua_key_index(noad), .visible = 1, .definable = 1 };
- lmt_interface.node_data[radical_noad] = (node_info) { .id = radical_noad, .size = radical_noad_size, .first = 0, .last = last_radical_subtype, .subtypes = subtypes_radical, .fields = lmt_node_fields_radical, .name = lua_key(radical), .lua = lua_key_index(radical), .visible = 1, .definable = 1 };
- lmt_interface.node_data[fraction_noad] = (node_info) { .id = fraction_noad, .size = fraction_noad_size, .first = 0, .last = last_fraction_subtype, .subtypes = subtypes_fraction, .fields = lmt_node_fields_fraction, .name = lua_key(fraction), .lua = lua_key_index(fraction), .visible = 1, .definable = 1 };
- lmt_interface.node_data[accent_noad] = (node_info) { .id = accent_noad, .size = accent_noad_size, .first = 0, .last = last_accent_subtype, .subtypes = subtypes_accent, .fields = lmt_node_fields_accent, .name = lua_key(accent), .lua = lua_key_index(accent), .visible = 1, .definable = 1 };
- lmt_interface.node_data[fence_noad] = (node_info) { .id = fence_noad, .size = fence_noad_size, .first = 0, .last = last_fence_subtype, .subtypes = subtypes_fence, .fields = lmt_node_fields_fence, .name = lua_key(fence), .lua = lua_key_index(fence), .visible = 1, .definable = 1 };
- lmt_interface.node_data[math_char_node] = (node_info) { .id = math_char_node, .size = math_kernel_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = lmt_node_fields_math_kernel, .name = lua_key(mathchar), .lua = lua_key_index(mathchar), .visible = 1, .definable = 1 };
- lmt_interface.node_data[math_text_char_node] = (node_info) { .id = math_text_char_node, .size = math_kernel_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = lmt_node_fields_math_kernel, .name = lua_key(mathtextchar), .lua = lua_key_index(mathtextchar), .visible = 1, .definable = 1 };
- lmt_interface.node_data[sub_box_node] = (node_info) { .id = sub_box_node, .size = math_kernel_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = lmt_node_fields_math_sub, .name = lua_key(subbox), .lua = lua_key_index(subbox), .visible = 1, .definable = 1 };
- lmt_interface.node_data[sub_mlist_node] = (node_info) { .id = sub_mlist_node, .size = math_kernel_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = lmt_node_fields_math_sub, .name = lua_key(submlist), .lua = lua_key_index(submlist), .visible = 1, .definable = 1 };
- lmt_interface.node_data[delimiter_node] = (node_info) { .id = delimiter_node, .size = math_delimiter_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = lmt_node_fields_delimiter, .name = lua_key(delimiter), .lua = lua_key_index(delimiter), .visible = 1, .definable = 1 };
- lmt_interface.node_data[glyph_node] = (node_info) { .id = glyph_node, .size = glyph_node_size, .first = 0, .last = last_glyph_subtype, .subtypes = subtypes_glyph, .fields = lmt_node_fields_glyph, .name = lua_key(glyph), .lua = lua_key_index(glyph), .visible = 1, .definable = 1 };
+ // # define max_subtype_class max_math_class_code /* ideal: 0 .. 63 */
+ // # define max_subtype_class max_singleword /* practical: we clamp singleword anyway */
+ # define max_subtype_class max_quarterword /* for now */
+ # define max_subtype_user max_quarterword /* plenty */
+
+ lmt_interface.node_data[hlist_node] = (node_info) { .id = hlist_node, .size = box_node_size, .first = 0, .last = last_list_subtype, .max = max_subtype_class, .subtypes = subtypes_list, .fields = lmt_node_fields_list, .name = lua_key(hlist), .lua = lua_key_index(hlist), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[vlist_node] = (node_info) { .id = vlist_node, .size = box_node_size, .first = 0, .last = last_list_subtype, .max = max_subtype_class, .subtypes = subtypes_list, .fields = lmt_node_fields_list, .name = lua_key(vlist), .lua = lua_key_index(vlist), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[rule_node] = (node_info) { .id = rule_node, .size = rule_node_size, .first = 0, .last = last_rule_subtype, .max = max_subtype_class, .subtypes = subtypes_rule, .fields = lmt_node_fields_rule, .name = lua_key(rule), .lua = lua_key_index(rule), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[insert_node] = (node_info) { .id = insert_node, .size = insert_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = lmt_node_fields_insert, .name = lua_key(insert), .lua = lua_key_index(insert), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[mark_node] = (node_info) { .id = mark_node, .size = mark_node_size, .first = 0, .last = last_mark_subtype, .max = 0, .subtypes = subtypes_mark, .fields = lmt_node_fields_mark, .name = lua_key(mark), .lua = lua_key_index(mark), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[adjust_node] = (node_info) { .id = adjust_node, .size = adjust_node_size, .first = 0, .last = last_adjust_subtype, .max = 0, .subtypes = subtypes_adjust, .fields = lmt_node_fields_adjust, .name = lua_key(adjust), .lua = lua_key_index(adjust), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[boundary_node] = (node_info) { .id = boundary_node, .size = boundary_node_size, .first = 0, .last = last_boundary_subtype, .max = max_subtype_user, .subtypes = subtypes_boundary, .fields = lmt_node_fields_boundary, .name = lua_key(boundary), .lua = lua_key_index(boundary), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[disc_node] = (node_info) { .id = disc_node, .size = disc_node_size, .first = 0, .last = last_discretionary_subtype, .max = max_subtype_class, .subtypes = subtypes_disc, .fields = lmt_node_fields_disc, .name = lua_key(disc), .lua = lua_key_index(disc), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[whatsit_node] = (node_info) { .id = whatsit_node, .size = whatsit_node_size, .first = 0, .last = 0, .max = max_subtype_user, .subtypes = NULL, .fields = lmt_node_fields_whatsit, .name = lua_key(whatsit), .lua = lua_key_index(whatsit), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[par_node] = (node_info) { .id = par_node, .size = par_node_size, .first = 0, .last = last_par_subtype, .max = 0, .subtypes = subtypes_par, .fields = lmt_node_fields_par, .name = lua_key(par), .lua = lua_key_index(par), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[dir_node] = (node_info) { .id = dir_node, .size = dir_node_size, .first = 0, .last = last_dir_subtype, .max = 0, .subtypes = subtypes_dir, .fields = lmt_node_fields_dir, .name = lua_key(dir), .lua = lua_key_index(dir), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[math_node] = (node_info) { .id = math_node, .size = math_node_size, .first = 0, .last = last_math_subtype, .max = 0, .subtypes = subtypes_math, .fields = lmt_node_fields_math, .name = lua_key(math), .lua = lua_key_index(math), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[glue_node] = (node_info) { .id = glue_node, .size = glue_node_size, .first = 0, .last = last_glue_subtype, .max = max_subtype_user, .subtypes = subtypes_glue, .fields = lmt_node_fields_glue, .name = lua_key(glue), .lua = lua_key_index(glue), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[kern_node] = (node_info) { .id = kern_node, .size = kern_node_size, .first = 0, .last = last_kern_subtype, .max = max_subtype_user, .subtypes = subtypes_kern, .fields = lmt_node_fields_kern, .name = lua_key(kern), .lua = lua_key_index(kern), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[penalty_node] = (node_info) { .id = penalty_node, .size = penalty_node_size, .first = 0, .last = last_penalty_subtype, .max = max_subtype_user, .subtypes = subtypes_penalty, .fields = lmt_node_fields_penalty, .name = lua_key(penalty), .lua = lua_key_index(penalty), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[style_node] = (node_info) { .id = style_node, .size = style_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = lmt_node_fields_style, .name = lua_key(style), .lua = lua_key_index(style), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[choice_node] = (node_info) { .id = choice_node, .size = choice_node_size, .first = 0, .last = last_choice_subtype, .max = 0, .subtypes = subtypes_choice, .fields = lmt_node_fields_choice, .name = lua_key(choice), .lua = lua_key_index(choice), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[parameter_node] = (node_info) { .id = parameter_node, .size = parameter_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = lmt_node_fields_parameter, .name = lua_key(parameter), .lua = lua_key_index(parameter), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[simple_noad] = (node_info) { .id = simple_noad, .size = noad_size, .first = 0, .last = last_noad_subtype, .max = max_singleword, .subtypes = subtypes_noad, .fields = lmt_node_fields_noad, .name = lua_key(noad), .lua = lua_key_index(noad), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[radical_noad] = (node_info) { .id = radical_noad, .size = radical_noad_size, .first = 0, .last = last_radical_subtype, .max = 0, .subtypes = subtypes_radical, .fields = lmt_node_fields_radical, .name = lua_key(radical), .lua = lua_key_index(radical), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[fraction_noad] = (node_info) { .id = fraction_noad, .size = fraction_noad_size, .first = 0, .last = last_fraction_subtype, .max = 0, .subtypes = subtypes_fraction, .fields = lmt_node_fields_fraction, .name = lua_key(fraction), .lua = lua_key_index(fraction), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[accent_noad] = (node_info) { .id = accent_noad, .size = accent_noad_size, .first = 0, .last = last_accent_subtype, .max = 0, .subtypes = subtypes_accent, .fields = lmt_node_fields_accent, .name = lua_key(accent), .lua = lua_key_index(accent), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[fence_noad] = (node_info) { .id = fence_noad, .size = fence_noad_size, .first = 0, .last = last_fence_subtype, .max = 0, .subtypes = subtypes_fence, .fields = lmt_node_fields_fence, .name = lua_key(fence), .lua = lua_key_index(fence), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[math_char_node] = (node_info) { .id = math_char_node, .size = math_kernel_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = lmt_node_fields_math_kernel, .name = lua_key(mathchar), .lua = lua_key_index(mathchar), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[math_text_char_node] = (node_info) { .id = math_text_char_node, .size = math_kernel_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = lmt_node_fields_math_kernel, .name = lua_key(mathtextchar), .lua = lua_key_index(mathtextchar), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[sub_box_node] = (node_info) { .id = sub_box_node, .size = math_kernel_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = lmt_node_fields_math_sub, .name = lua_key(subbox), .lua = lua_key_index(subbox), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[sub_mlist_node] = (node_info) { .id = sub_mlist_node, .size = math_kernel_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = lmt_node_fields_math_sub, .name = lua_key(submlist), .lua = lua_key_index(submlist), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[delimiter_node] = (node_info) { .id = delimiter_node, .size = math_delimiter_node_size, .first = 0, .last = 0, .max = max_subtype_class, .subtypes = NULL, .fields = lmt_node_fields_delimiter, .name = lua_key(delimiter), .lua = lua_key_index(delimiter), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[glyph_node] = (node_info) { .id = glyph_node, .size = glyph_node_size, .first = 0, .last = last_glyph_subtype, .max = max_subtype_class, .subtypes = subtypes_glyph, .fields = lmt_node_fields_glyph, .name = lua_key(glyph), .lua = lua_key_index(glyph), .visible = 1, .definable = 1 };
/*tex
Who knows when someone needs is, so for now we keep it exposed.
*/
- lmt_interface.node_data[unset_node] = (node_info) { .id = unset_node, .size = box_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = lmt_node_fields_unset, .name = lua_key(unset), .lua = lua_key_index(unset), .visible = 1, .definable = 1 };
- lmt_interface.node_data[specification_node] = (node_info) { .id = specification_node, .size = specification_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(specification), .lua = lua_key_index(specification), .visible = 0, .definable = 0 };
- lmt_interface.node_data[align_record_node] = (node_info) { .id = align_record_node, .size = box_node_size, .first = 0, .last = last_align_record_subtype, .subtypes = subtypes_align_record, .fields = lmt_node_fields_align_record, .name = lua_key(alignrecord), .lua = lua_key_index(alignrecord), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[unset_node] = (node_info) { .id = unset_node, .size = box_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = lmt_node_fields_unset, .name = lua_key(unset), .lua = lua_key_index(unset), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[specification_node] = (node_info) { .id = specification_node, .size = specification_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(specification), .lua = lua_key_index(specification), .visible = 0, .definable = 0 };
+ lmt_interface.node_data[align_record_node] = (node_info) { .id = align_record_node, .size = box_node_size, .first = 0, .last = last_align_record_subtype, .max = 0, .subtypes = subtypes_align_record, .fields = lmt_node_fields_align_record, .name = lua_key(alignrecord), .lua = lua_key_index(alignrecord), .visible = 1, .definable = 1 };
/*tex
These nodes never show up in node lists and are managed special. Messing with such nodes
directly is not a good idea.
*/
- lmt_interface.node_data[attribute_list_node] = (node_info) { .id = attribute_list_node, .size = attribute_list_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = lmt_node_fields_attribute_list, .name = lua_key(attributelist), .lua = lua_key_index(attributelist), .visible = 1, .definable = 0 };
- lmt_interface.node_data[attribute_node] = (node_info) { .id = attribute_node, .size = attribute_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = lmt_node_fields_attribute, .name = lua_key(attribute), .lua = lua_key_index(attribute), .visible = 1, .definable = 0 };
+ lmt_interface.node_data[attribute_list_node] = (node_info) { .id = attribute_list_node, .size = attribute_list_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = lmt_node_fields_attribute_list, .name = lua_key(attributelist), .lua = lua_key_index(attributelist), .visible = 1, .definable = 0 };
+ lmt_interface.node_data[attribute_node] = (node_info) { .id = attribute_node, .size = attribute_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = lmt_node_fields_attribute, .name = lua_key(attribute), .lua = lua_key_index(attribute), .visible = 1, .definable = 0 };
/*
We still expose the glue spec as they are the containers for skip registers but there is no
real need to use them at the user end.
*/
- lmt_interface.node_data[glue_spec_node] = (node_info) { .id = glue_spec_node, .size = glue_spec_size, .first = 0, .last = 0, .subtypes = NULL, .fields = lmt_node_fields_glue_spec, .name = lua_key(gluespec), .lua = lua_key_index(gluespec), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[glue_spec_node] = (node_info) { .id = glue_spec_node, .size = glue_spec_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = lmt_node_fields_glue_spec, .name = lua_key(gluespec), .lua = lua_key_index(gluespec), .visible = 1, .definable = 1 };
/*tex
This one sometimes shows up, especially when we temporarily need an alternative head pointer,
simply because we want to retain some head in case the original head is replaced.
*/
- lmt_interface.node_data[temp_node] = (node_info) { .id = temp_node, .size = temp_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(temp), .lua = lua_key_index(temp), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[temp_node] = (node_info) { .id = temp_node, .size = temp_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(temp), .lua = lua_key_index(temp), .visible = 1, .definable = 1 };
/*tex
The split nodes are used for insertions.
*/
- lmt_interface.node_data[split_node] = (node_info) { .id = split_node, .size = split_node_size, .first = 0, .last = last_split_subtype, .subtypes = subtypes_split, .fields = lmt_node_fields_split, .name = lua_key(split), .lua = lua_key_index(split), .visible = 1, .definable = 1 };
+ lmt_interface.node_data[split_node] = (node_info) { .id = split_node, .size = split_node_size, .first = 0, .last = last_split_subtype, .max = 0, .subtypes = subtypes_split, .fields = lmt_node_fields_split, .name = lua_key(split), .lua = lua_key_index(split), .visible = 1, .definable = 1 };
/*tex
The following nodes are not meant for users. They are used internally for different purposes
@@ -957,22 +964,22 @@ void lmt_nodelib_initialize(void) {
allocated using fast methods so they never show up in the new, copy and flush handlers.
*/
- lmt_interface.node_data[expression_node] = (node_info) { .id = expression_node, .size = expression_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(expression), .lua = lua_key_index(expression), .visible = 0, .definable = 0 };
- lmt_interface.node_data[lmtx_expression_node]= (node_info) { .id = lmtx_expression_node,.size = lmtx_expression_node_size,.first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(lmtxexpression), .lua = lua_key_index(lmtxexpression), .visible = 0, .definable = 0 };
- lmt_interface.node_data[rpn_expression_node] = (node_info) { .id = rpn_expression_node, .size = rpn_expression_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(rpnexpression), .lua = lua_key_index(rpnexpression), .visible = 0, .definable = 0 };
- lmt_interface.node_data[loop_state_node] = (node_info) { .id = loop_state_node, .size = loop_state_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(loopstate), .lua = lua_key_index(loopstate), .visible = 0, .definable = 0 };
- lmt_interface.node_data[math_spec_node] = (node_info) { .id = math_spec_node, .size = math_spec_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(mathspec), .lua = lua_key_index(mathspec), .visible = 0, .definable = 0 };
- lmt_interface.node_data[font_spec_node] = (node_info) { .id = font_spec_node, .size = font_spec_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(fontspec), .lua = lua_key_index(fontspec), .visible = 0, .definable = 0 };
- lmt_interface.node_data[nesting_node] = (node_info) { .id = nesting_node, .size = nesting_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(nestedlist), .lua = lua_key_index(nestedlist), .visible = 0, .definable = 0 };
- lmt_interface.node_data[span_node] = (node_info) { .id = span_node, .size = span_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(span), .lua = lua_key_index(span), .visible = 0, .definable = 0 };
- lmt_interface.node_data[align_stack_node] = (node_info) { .id = align_stack_node, .size = align_stack_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(alignstack), .lua = lua_key_index(alignstack), .visible = 0, .definable = 0 };
- // lmt_interface.node_data[noad_state_node] = (node_info) { .id = noad_state_node, .size = noad_state_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(noadstate), .lua = lua_key_index(noadstate), .visible = 0, .definable = 0 };
- lmt_interface.node_data[if_node] = (node_info) { .id = if_node, .size = if_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(ifstack), .lua = lua_key_index(ifstack), .visible = 0, .definable = 0 };
- lmt_interface.node_data[unhyphenated_node] = (node_info) { .id = unhyphenated_node, .size = active_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(unhyphenated), .lua = lua_key_index(unhyphenated), .visible = 0, .definable = 0 };
- lmt_interface.node_data[hyphenated_node] = (node_info) { .id = hyphenated_node, .size = active_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(hyphenated), .lua = lua_key_index(hyphenated), .visible = 0, .definable = 0 };
- lmt_interface.node_data[delta_node] = (node_info) { .id = delta_node, .size = delta_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(delta), .lua = lua_key_index(delta), .visible = 0, .definable = 0 };
- lmt_interface.node_data[passive_node] = (node_info) { .id = passive_node, .size = passive_node_size, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(passive), .lua = lua_key_index(passive), .visible = 0, .definable = 0 };
- lmt_interface.node_data[passive_node + 1] = (node_info) { .id = -1, .size = -1, .first = 0, .last = 0, .subtypes = NULL, .fields = NULL, .name = NULL, .lua = 0, .visible = 0, .definable = 0 };
+ lmt_interface.node_data[expression_node] = (node_info) { .id = expression_node, .size = expression_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(expression), .lua = lua_key_index(expression), .visible = 0, .definable = 0 };
+ lmt_interface.node_data[lmtx_expression_node]= (node_info) { .id = lmtx_expression_node,.size = lmtx_expression_node_size,.first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(lmtxexpression), .lua = lua_key_index(lmtxexpression), .visible = 0, .definable = 0 };
+ lmt_interface.node_data[rpn_expression_node] = (node_info) { .id = rpn_expression_node, .size = rpn_expression_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(rpnexpression), .lua = lua_key_index(rpnexpression), .visible = 0, .definable = 0 };
+ lmt_interface.node_data[loop_state_node] = (node_info) { .id = loop_state_node, .size = loop_state_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(loopstate), .lua = lua_key_index(loopstate), .visible = 0, .definable = 0 };
+ lmt_interface.node_data[math_spec_node] = (node_info) { .id = math_spec_node, .size = math_spec_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(mathspec), .lua = lua_key_index(mathspec), .visible = 0, .definable = 0 };
+ lmt_interface.node_data[font_spec_node] = (node_info) { .id = font_spec_node, .size = font_spec_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(fontspec), .lua = lua_key_index(fontspec), .visible = 0, .definable = 0 };
+ lmt_interface.node_data[nesting_node] = (node_info) { .id = nesting_node, .size = nesting_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(nestedlist), .lua = lua_key_index(nestedlist), .visible = 0, .definable = 0 };
+ lmt_interface.node_data[span_node] = (node_info) { .id = span_node, .size = span_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(span), .lua = lua_key_index(span), .visible = 0, .definable = 0 };
+ lmt_interface.node_data[align_stack_node] = (node_info) { .id = align_stack_node, .size = align_stack_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(alignstack), .lua = lua_key_index(alignstack), .visible = 0, .definable = 0 };
+ // lmt_interface.node_data[noad_state_node] = (node_info) { .id = noad_state_node, .size = noad_state_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(noadstate), .lua = lua_key_index(noadstate), .visible = 0, .definable = 0 };
+ lmt_interface.node_data[if_node] = (node_info) { .id = if_node, .size = if_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(ifstack), .lua = lua_key_index(ifstack), .visible = 0, .definable = 0 };
+ lmt_interface.node_data[unhyphenated_node] = (node_info) { .id = unhyphenated_node, .size = active_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(unhyphenated), .lua = lua_key_index(unhyphenated), .visible = 0, .definable = 0 };
+ lmt_interface.node_data[hyphenated_node] = (node_info) { .id = hyphenated_node, .size = active_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(hyphenated), .lua = lua_key_index(hyphenated), .visible = 0, .definable = 0 };
+ lmt_interface.node_data[delta_node] = (node_info) { .id = delta_node, .size = delta_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(delta), .lua = lua_key_index(delta), .visible = 0, .definable = 0 };
+ lmt_interface.node_data[passive_node] = (node_info) { .id = passive_node, .size = passive_node_size, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = lua_key(passive), .lua = lua_key_index(passive), .visible = 0, .definable = 0 };
+ lmt_interface.node_data[passive_node + 1] = (node_info) { .id = -1, .size = -1, .first = 0, .last = 0, .max = 0, .subtypes = NULL, .fields = NULL, .name = NULL, .lua = 0, .visible = 0, .definable = 0 };
lmt_interface.par_data = lmt_memory_malloc(par_n_of_codes * sizeof(par_info));
@@ -1038,6 +1045,33 @@ void lmt_nodelib_initialize(void) {
}
/*tex
+ You can set basically any subtype on (user) definable nodes but with some limitations:
+
+ |hlist|, |vlist|, |rule|, |glyph|, |disc| : official + class : singleword
+ |kern|, |glue|, |penalty| : official + any : quarterword
+ |boundary|, |whatsit| : official + any : quarterword
+ |noad|, |delimiter| : official + class : singleword
+
+ The rest is protected by the official subtype range, if only because there a change can have
+ unwanted side effects.
+*/
+
+int tex_set_subtype(halfword n, quarterword subtype)
+{
+ quarterword s = tex_valid_subtype(node_type(n), subtype);
+ if lmt_likely(s == subtype) {
+ node_subtype(n) = s;
+ return 1;
+ } else {
+ tex_formatted_warning(
+ "nodes", "ignoring invalid subtype %i assignment to node '%s'",
+ subtype, lmt_interface.node_data[node_type(n)].name
+ );
+ return 0;
+ }
+}
+
+/*tex
When we copy a node list, there are several possibilities: we do the same as a new node, we
copy the entry to the table in properties (a reference), we do a deep copy of a table in the
@@ -3666,6 +3700,9 @@ void tex_show_node_list(halfword p, int threshold, int max)
tex_print_format("%l..<content>"); /* one level */
tex_print_token_list(NULL, align_record_post_part(p)); /*tex No ref count token here. */
break;
+ case style_node:
+ tex_print_format(", style %i, scale %i, glyphscale", style_style(p), style_scale(p), style_glyph_scale(p));
+ break;
case temp_node:
break;
default:
@@ -3686,7 +3723,7 @@ void tex_show_node_list(halfword p, int threshold, int max)
*/
-static halfword tex_aux_get_actual_box_width(halfword r, halfword p, scaled initial_width)
+static scaled tex_aux_get_actual_box_width(halfword r, halfword p, scaled initial_width)
{
/*tex calculated |size| */
scaled w = -max_dimension;
@@ -3784,7 +3821,7 @@ static halfword tex_aux_get_actual_box_width(halfword r, halfword p, scaled init
return w;
}
-halfword tex_actual_box_width(halfword r, scaled base_width)
+scaled tex_actual_box_width(halfword r, scaled base_width)
{
/*tex
@@ -4166,14 +4203,14 @@ int tex_glyph_has_dimensions(halfword p)
}
}
-halfword tex_kern_dimension(halfword p)
+scaled tex_kern_dimension(halfword p)
{
return kern_amount(p);
}
-halfword tex_kern_dimension_ex(halfword p)
+scaled tex_kern_dimension_ex(halfword p)
{
- halfword k = kern_amount(p);
+ scaled k = kern_amount(p);
if (k && kern_expansion(p)) {
k = tex_ext_xn_over_d(k, scaling_factor_squared + kern_expansion(p), scaling_factor_squared);
}
@@ -5556,7 +5593,7 @@ int tex_flatten_leaders(halfword box, int grp, int just_pack, int location, int
halfword leader = glue_leader_ptr(current);
if (leader && (node_type(leader) == hlist_node || node_type(leader) == vlist_node)) {
halfword packed = null;
- halfword amount = glue_amount(current);
+ scaled amount = glue_amount(current);
halfword callback = glue_callback(current);
double width = (double) amount;
switch (box_glue_sign(box)) {
diff --git a/source/luametatex/source/tex/texnodes.h b/source/luametatex/source/tex/texnodes.h
index 34dd41ad6..b05820e82 100644
--- a/source/luametatex/source/tex/texnodes.h
+++ b/source/luametatex/source/tex/texnodes.h
@@ -2030,7 +2030,7 @@ static inline int tex_same_mathspec(halfword a, halfword b)
# define style_node_size 3
# define style_style node_subtype
# define style_scale(a) memone(a,2)
-# define style_reserved(a) memtwo(a,2)
+# define style_glyph_scale(a) memtwo(a,2)
# define choice_node_size 5
//define choice_style node_subtype
@@ -3468,6 +3468,8 @@ extern halfword tex_list_node_mem_usage (void);
extern halfword tex_reversed_node_list (halfword list);
extern int tex_n_of_used_nodes (int counts[]);
+extern int tex_set_subtype (halfword n, quarterword subtype);
+
# define _valid_node_(p) ((p > lmt_node_memory_state.reserved) && (p < lmt_node_memory_state.nodes_data.allocated) && (lmt_node_memory_state.nodesizes[p] > 0))
static inline int tex_valid_node(halfword n)
@@ -3475,6 +3477,17 @@ static inline int tex_valid_node(halfword n)
return n && _valid_node_(n) ? n : null;
}
+static inline quarterword tex_valid_subtype(halfword type, quarterword subtype)
+{
+ if lmt_likely(tex_nodetype_has_subtype(type)) {
+ node_info *info = &lmt_interface.node_data[type];
+ if lmt_likely(info->definable && (subtype <= info->max || (subtype >= info->first && subtype <= info->last))) {
+ return subtype;
+ }
+ }
+ return 0;
+}
+
/*tex This is a bit strange place but better than a macro elsewhere: */
static inline int tex_math_skip_boundary(halfword n)
diff --git a/source/luametatex/source/tex/texpackaging.c b/source/luametatex/source/tex/texpackaging.c
index 2eabad89c..8e743f093 100644
--- a/source/luametatex/source/tex/texpackaging.c
+++ b/source/luametatex/source/tex/texpackaging.c
@@ -1033,7 +1033,7 @@ int tex_ignore_math_skip(halfword p)
# define fix_int(val,min,max) (val < min ? min : (val > max ? max : val))
-static inline halfword tex_aux_used_order(halfword *total)
+static inline halfword tex_aux_used_order(scaled *total)
{
if (total[filll_glue_order]) {
return filll_glue_order;
@@ -1311,6 +1311,18 @@ void tex_repack(halfword p, scaled w, int m)
When |limitate| equals the node type we indeed limitate. Otherwise we freeze.
*/
+static inline double tex_aux_apply_glue_factor(double set, scaled factor)
+{
+ if (factor > 0) {
+ return set * ((double) factor * 0.001);
+ }
+ if (factor < 0) {
+ double max_set = (double) (-factor) * 0.001;
+ return (set > max_set) ? max_set : set;
+ }
+ return set;
+}
+
void tex_freeze(halfword p, int recurse, int limitate, halfword factor)
{
if (p) {
@@ -1318,17 +1330,9 @@ void tex_freeze(halfword p, int recurse, int limitate, halfword factor)
case hlist_node:
{
halfword c = box_list(p);
- double set = (double) box_glue_set(p);
halfword order = box_glue_order(p);
singleword sign = box_glue_sign(p);
- if (factor > 0) {
- set *= factor * 0.001;
- } else if (factor < 0) {
- double max = - factor * 0.001;
- if (set > max) {
- set = max;
- }
- }
+ double set = tex_aux_apply_glue_factor((double) box_glue_set(p), factor);
while (c) {
switch (node_type(c)) {
case glue_node:
@@ -1386,17 +1390,9 @@ void tex_freeze(halfword p, int recurse, int limitate, halfword factor)
case vlist_node:
{
halfword c = box_list(p);
- double set = (double) box_glue_set(p);
halfword order = box_glue_order(p);
singleword sign = box_glue_sign(p);
- if (factor > 0) {
- set *= factor * 0.001;
- } else if (factor < 0) {
- double max = - factor * 0.001;
- if (set > max) {
- set = max;
- }
- }
+ double set = tex_aux_apply_glue_factor((double) box_glue_set(p), factor);
while (c) {
switch (node_type(c)) {
case glue_node:
@@ -1706,6 +1702,57 @@ static void tex_aux_adapt_just_skips(halfword ls, halfword rs)
}
}
+# if lmt_float_math
+
+ static inline void tex_aux_adjust_glue_amount(halfword p, scaled target)
+ {
+ if (target < 0) {
+ if (glue_shrink_order(p) == normal_glue_order) {
+ scaled shrink = glue_shrink(p);
+ if (shrink) {
+ glue_amount(p) -= scaledround(-0.001 * (double) target * (double) shrink);
+ }
+ }
+ } else if (target > 0) {
+ if (glue_stretch_order(p) == normal_glue_order) {
+ scaled stretch = glue_stretch(p);
+ if (stretch) {
+ glue_amount(p) += scaledround(0.001 * (double) target * (double) stretch);
+ }
+ }
+ }
+ }
+
+# else
+
+ static inline scaled tex_aux_round_div_1000(long long val)
+ {
+ return (scaled) ((val >= 0) ? (val + 500LL) / 1000LL : (val - 500LL) / 1000LL);
+ }
+
+ static inline void tex_aux_adjust_glue_amount(halfword p, scaled target)
+ {
+ if (target < 0) {
+ if (glue_shrink_order(p) == normal_glue_order) {
+ scaled shrink = glue_shrink(p);
+ if (shrink) {
+ long long product = - (long long) target * (long long) shrink;
+ glue_amount(p) -= tex_aux_round_div_1000(product);
+ }
+ }
+ } else if (target > 0) {
+ if (glue_stretch_order(p) == normal_glue_order) {
+ scaled stretch = glue_stretch(p);
+ if (stretch) {
+ long long product = (long long) target * (long long) stretch;
+ glue_amount(p) += tex_aux_round_div_1000(product);
+ }
+ }
+ }
+ }
+
+# endif
+
halfword tex_hpack(halfword p, scaled target, int method, singleword pack_direction, int retain, int limit, halfword ls, halfword rs)
{
halfword tail = null;
@@ -1823,7 +1870,7 @@ halfword tex_hpack(halfword p, scaled target, int method, singleword pack_direct
it.
*/
- halfword shift = box_shift_amount(p);
+ scaled shift = box_shift_amount(p);
scaledwhd whd = tex_pack_dimensions(p);
width += whd.wd;
if (whd.ht - shift > height) {
@@ -1867,15 +1914,7 @@ halfword tex_hpack(halfword p, scaled target, int method, singleword pack_direct
{
switch (method) {
case packing_adapted:
- if (target < 0) {
- if (glue_shrink_order(p) == normal_glue_order) {
- glue_amount(p) -= scaledround(-0.001 * target * (double) glue_shrink(p));
- }
- } else if (target > 0) {
- if (glue_stretch_order(p) == normal_glue_order) {
- glue_amount(p) += scaledround( 0.001 * target * (double) glue_stretch(p));
- }
- }
+ tex_aux_adjust_glue_amount(p, target);
width += glue_amount(p);
glue_shrink_order(p) = normal_glue_order;
glue_shrink(p) = 0;
@@ -2080,7 +2119,8 @@ halfword tex_hpack(halfword p, scaled target, int method, singleword pack_direct
*/
halfword order = tex_aux_used_order(lmt_packaging_state.total_stretch);
if ((method == packing_expanded) && (order == normal_glue_order) && (font_stretch > 0)) {
- lmt_packaging_state.font_expansion_ratio = tex_divide_scaled_n(excess, font_stretch, scaling_factor_double);
+ // lmt_packaging_state.font_expansion_ratio = tex_divide_scaled_n(excess, font_stretch, scaling_factor_double);
+ lmt_packaging_state.font_expansion_ratio = tex_divide_scaled_factor(excess, font_stretch);
goto EXIT;
}
box_glue_order(result) = order;
@@ -2141,7 +2181,8 @@ halfword tex_hpack(halfword p, scaled target, int method, singleword pack_direct
*/
halfword order = tex_aux_used_order(lmt_packaging_state.total_shrink);
if ((method == packing_expanded) && (order == normal_glue_order) && (font_shrink > 0)) {
- lmt_packaging_state.font_expansion_ratio = tex_divide_scaled_n(excess, font_shrink, scaling_factor_double);
+ // lmt_packaging_state.font_expansion_ratio = tex_divide_scaled_n(excess, font_shrink, scaling_factor_double);
+ lmt_packaging_state.font_expansion_ratio = tex_divide_scaled_factor(excess, font_shrink);
goto EXIT;
}
box_glue_order(result) = order;
@@ -2225,7 +2266,7 @@ halfword tex_hpack(halfword p, scaled target, int method, singleword pack_direct
}
tex_print_ln();
lmt_print_state.font_in_short_display = null_font;
- if (tracing_full_boxes_par > 0) {
+ if lmt_unlikely(tracing_full_boxes_par > 0) {
halfword detail = show_node_details_par;
show_node_details_par = tracing_full_boxes_par;
tex_print_format("%l[package: result] ");
@@ -2632,7 +2673,7 @@ scaledwhd tex_natural_vsizes(halfword p, halfword pp, glueratio g_mult, int g_si
siz.dp = 0;
if (is_leader(p)) {
halfword gl = glue_leader_ptr(p);
- halfword wd = 0;
+ scaled wd = 0;
switch (node_type(gl)) {
case hlist_node:
case vlist_node:
@@ -2666,7 +2707,7 @@ scaledwhd tex_natural_vsizes(halfword p, halfword pp, glueratio g_mult, int g_si
break;
case insert_node:
if (inserts) {
- halfword height = tex_insert_height(p);
+ scaled height = tex_insert_height(p);
if (height > 0) {
siz.ht += siz.dp + height;
siz.dp = 0;
@@ -2702,7 +2743,7 @@ scaledwhd tex_natural_vsizes(halfword p, halfword pp, glueratio g_mult, int g_si
/*tex simplified variant with less memory access */
-halfword tex_natural_width(halfword p, halfword pp, glueratio g_mult, int g_sign, int g_order)
+scaled tex_natural_width(halfword p, halfword pp, glueratio g_mult, int g_sign, int g_order)
{
scaled wd = 0;
scaled gp = 0;
@@ -2777,7 +2818,7 @@ halfword tex_natural_width(halfword p, halfword pp, glueratio g_mult, int g_sign
return wd;
}
-halfword tex_natural_hsize(halfword p, halfword *correction)
+scaled tex_natural_hsize(halfword p, halfword *correction)
{
scaled wd = 0;
halfword c = null;
@@ -2824,7 +2865,7 @@ halfword tex_natural_hsize(halfword p, halfword *correction)
return wd;
}
-halfword tex_natural_vsize(halfword p)
+scaled tex_natural_vsize(halfword p)
{
scaled ht = 0;
scaled dp = 0;
@@ -3500,7 +3541,7 @@ void tex_package(singleword nature)
box_options(boxnode) |= box_option_align_split;
}
if (options & saved_box_swap_htdp_option) {
- halfword ht = box_height(boxnode);
+ scaled ht = box_height(boxnode);
box_height(boxnode) = box_depth(boxnode);
box_depth(boxnode) = ht;
}
@@ -3600,9 +3641,7 @@ void tex_run_unpackage(void)
node_prev(list) = null;
}
if (pre_adjusted && tracing_adjusts_par > 1) {
- tex_begin_diagnostic();
- tex_print_format("%l[adjust: topskip moved]");
- tex_end_diagnostic();
+ tex_print_format("%<%l[adjust: topskip moved]%>");
}
}
}
@@ -3752,8 +3791,8 @@ static halfword tex_aux_depth_correction(halfword b, const line_break_properties
{
/*tex The deficiency of space between baselines: */
halfword p;
- halfword height = has_box_package_state(b, dbox_package_state) ? tex_aux_first_height(b) : box_height(b);
- halfword depth = cur_list.prev_depth;
+ scaled height = has_box_package_state(b, dbox_package_state) ? tex_aux_first_height(b) : box_height(b);
+ scaled depth = cur_list.prev_depth;
if (properties) {
if (properties->line_snapping) {
p = tex_new_glue_node(zero_glue, baseline_skip_glue);
@@ -3782,7 +3821,7 @@ void tex_append_to_vlist(halfword b, int location, const line_break_properties *
{
if (location >= 0) {
halfword result = null;
- halfword next_depth = ignore_depth_criterion_par;
+ scaled next_depth = ignore_depth_criterion_par;
int prev_set = 0;
int check_depth = 0;
if (b && lmt_append_to_vlist_callback(b, location, cur_list.prev_depth, &result, &next_depth, &prev_set, &check_depth)) {
@@ -3856,7 +3895,7 @@ halfword tex_prune_page_top(halfword p, int s)
case rule_node:
{
/*tex Insert glue for |split_top_skip| and set |p| to |null|. */
- halfword h = node_type(p) == rule_node ? rule_height(p) : box_height(p);
+ scaled h = node_type(p) == rule_node ? rule_height(p) : box_height(p);
halfword q = tex_new_param_glue_node(split_top_skip_code, split_top_skip_glue);
// node_next(prev_p) = q;
tex_couple_nodes(prev_p, q); /* there is no real need to point back to temp */
@@ -4406,7 +4445,7 @@ void tex_begin_box(int boxcontext, scaled shift, halfword slot, halfword callbac
*/
halfword mode = packing_exactly ;
halfword index = tex_scan_box_register_number();
- halfword size = 0;
+ scaled size = 0;
halfword attrlist = null;
while (1) {
switch (tex_scan_character("atu", 0, 1, 0)) {
diff --git a/source/luametatex/source/tex/texpackaging.h b/source/luametatex/source/tex/texpackaging.h
index 84f2f137c..1a5ac2d05 100644
--- a/source/luametatex/source/tex/texpackaging.h
+++ b/source/luametatex/source/tex/texpackaging.h
@@ -142,9 +142,9 @@ extern halfword tex_filtered_vpack (halfword p, scaled h, int m, scaled
extern scaledwhd tex_natural_hsizes (halfword p, halfword pp, glueratio g_mult, int g_sign, int g_order);
extern scaledwhd tex_natural_vsizes (halfword p, halfword pp, glueratio g_mult, int g_sign, int g_order, int inserts);
extern scaledwhd tex_natural_msizes (halfword p, int ignoreprime);
-extern halfword tex_natural_width (halfword p, halfword pp, glueratio g_mult, int g_sign, int g_order);
-extern halfword tex_natural_hsize (halfword p, halfword *correction);
-extern halfword tex_natural_vsize (halfword p);
+extern scaled tex_natural_width (halfword p, halfword pp, glueratio g_mult, int g_sign, int g_order);
+extern scaled tex_natural_hsize (halfword p, halfword *correction);
+extern scaled tex_natural_vsize (halfword p);
extern halfword tex_hpack (halfword p, scaled w, int m, singleword d, int retain, int limit, halfword ls, halfword rs);
extern halfword tex_vpack (halfword p, scaled h, int m, scaled l, singleword d, int retain, int *excess);
diff --git a/source/luametatex/source/tex/texprinting.c b/source/luametatex/source/tex/texprinting.c
index b1e0750af..c4a057ff0 100644
--- a/source/luametatex/source/tex/texprinting.c
+++ b/source/luametatex/source/tex/texprinting.c
@@ -435,7 +435,7 @@ void tex_print_banner(void)
fprintf(
stdout,
"%s %s\n",
- lmt_engine_state.luatex_banner,
+ lmt_engine_state.luametatex_banner,
lmt_engine_state.dump_name
);
}
@@ -445,7 +445,7 @@ void tex_print_log_banner(void)
fprintf(
lmt_print_state.logfile,
"engine: %s, format id: %s, time stamp: %d-%d-%d %d:%d, startup file: %s, job name: %s",
- lmt_engine_state.luatex_banner,
+ lmt_engine_state.luametatex_banner,
lmt_engine_state.dump_name,
year_par, month_par > 12 ? 0 : month_par, day_par, time_par / 60, time_par % 60,
lmt_engine_state.startup_filename ? lmt_engine_state.startup_filename : "-",
@@ -455,7 +455,7 @@ void tex_print_log_banner(void)
void tex_print_version_banner(void)
{
- fputs(lmt_engine_state.luatex_banner, stdout);
+ fputs(lmt_engine_state.luametatex_banner, stdout);
}
/*tex
@@ -1476,6 +1476,7 @@ void tex_short_display(halfword p)
void tex_print_token_list(const char *s, halfword p)
{
+ /* tex_print_format("%l%.%s {",nesting,s) */
tex_print_levels();
tex_print_str_len("..", 2);
if (s) {
@@ -1579,7 +1580,7 @@ static void tex_print_padding(void)
static void tex_print_nesting(int n)
{
- static const char periods[32] = "................................";
+ static const char periods[32+1] = "................................";
while (n > 0) {
int chunk = (n > 32) ? 32 : n;
tex_print_str_len(periods, chunk);
@@ -1659,6 +1660,9 @@ void tex_print_levels(void)
%X int unicode
%# int group count : n*{}
+ %. int nesting
+ %< begin diagnostics
+ %> end diagnostics
%2 int direction
@@ -1912,6 +1916,16 @@ inline const char *tex_print_format_args(const char *format, va_list args)
tex_print_nesting(n);
break;
}
+ case '<':
+ {
+ tex_begin_diagnostic();
+ break;
+ }
+ case '>':
+ {
+ tex_end_diagnostic();
+ break;
+ }
default:
/* ignore bad one */
break;
diff --git a/source/luametatex/source/tex/texscanning.c b/source/luametatex/source/tex/texscanning.c
index ab263dcee..3983037c5 100644
--- a/source/luametatex/source/tex/texscanning.c
+++ b/source/luametatex/source/tex/texscanning.c
@@ -1,4 +1,4 @@
-/*
+/*
See license.txt in the root of this project.
*/
@@ -242,6 +242,7 @@ static inline void tex_aux_downgrade_cur_val(int level, int succeeded, int negat
if (level == glue_val_level) {
goto COPYGLUE;
}
+ FALLTHROUGH
case glue_val_level:
if (level == posit_val_level) {
cur_val_level = level;
@@ -537,14 +538,10 @@ static int tex_aux_set_cur_val_by_some_cmd(int code)
cur_val = lmt_version_state.release;
cur_val_level = integer_val_level;
break;
- case luatex_version_code:
+ case luametatex_version_code:
cur_val = lmt_version_state.version; /* combined major and minor */
cur_val_level = integer_val_level;
break;
- case luatex_revision_code:
- cur_val = lmt_version_state.revision; /* always zero */
- cur_val_level = integer_val_level;
- break;
case current_group_level_code:
cur_val = cur_level - level_one;
cur_val_level = integer_val_level;
@@ -3393,7 +3390,7 @@ void tex_initialize_units(void)
unit_parameter(unit_parameter_hash('i','n')) = - tex_unit_class;
}
-static int tex_aux_scan_unit(halfword *num, halfword *denom, halfword *value, halfword *order)
+static int tex_aux_scan_unit(halfword *num, halfword *denom, scaled *value, halfword *order)
{
//AGAIN: /* only for true */
do {
@@ -3526,7 +3523,7 @@ static int tex_aux_scan_unit(halfword *num, halfword *denom, halfword *value, ha
}
}
-static int tex_aux_scan_unit_only(halfword *value)
+static int tex_aux_scan_unit_only(scaled *value)
{
int chrone, chrtwo, index;
halfword tokone, toktwo;
@@ -3630,7 +3627,7 @@ static int tex_aux_scan_unit_only(halfword *value)
# define posit_as_factor 0
-halfword tex_scan_dimension(int mu, int inf, int shortcut, int optional_equal, halfword *order, int *grouped)
+scaled tex_scan_dimension(int mu, int inf, int shortcut, int optional_equal, halfword *order, int *grouped)
{
bool negative = false;
int fraction = 0;
@@ -4003,7 +4000,7 @@ halfword tex_scan_glue(int level, int optional_equal, int options_too, halfword
}
while (1) {
// switch (tex_scan_character(options_too ? "pmlsd" : "pms", 0, 1, 0)) {
- switch (tex_scan_character(options_too ? "pmls" : "pms", 0, 1, 0)) {
+ switch (tex_scan_character(options_too ? "pmlsnd" : "pms", 0, 1, 0)) {
case 0:
return q;
case 'p':
@@ -4035,6 +4032,11 @@ halfword tex_scan_glue(int level, int optional_equal, int options_too, halfword
glue_stretch_order(q) = order;
}
break;
+ case 'n':
+ if (tex_scan_mandate_keyword("nobreak", 1)) {
+ glue_options(q) |= glue_option_no_auto_break;
+ }
+ break;
case 'm':
if (tex_scan_mandate_keyword("minus", 1)) {
halfword order = normal_glue_order;
@@ -4445,7 +4447,7 @@ void tex_set_font_dimension(void)
}
}
-halfword tex_get_font_dimension(void)
+scaled tex_get_font_dimension(void)
{
halfword fnt = null;
int n = 0;
@@ -4460,7 +4462,7 @@ void tex_set_scaled_font_dimension(int n)
}
}
-halfword tex_get_scaled_font_dimension(int n)
+scaled tex_get_scaled_font_dimension(int n)
{
halfword fnt = null;
return (tex_aux_scan_font_id_and_parameter(&fnt, &n)) ? tex_get_scaled_parameter(fnt, n) : null;
@@ -4824,6 +4826,7 @@ halfword tex_scan_toks_expand(int left_brace_found, halfword *tail, int expandco
cur_tok = token_val(prefix_cmd, always_code);
goto APPENDTOKEN;
}
+ FALLTHROUGH
default:
if (cur_cmd > max_command_cmd) {
tex_expand_current_token();
@@ -4855,6 +4858,8 @@ halfword tex_scan_toks_expand(int left_brace_found, halfword *tail, int expandco
goto FINALYDONE;
}
break;
+ default:
+ break;
}
}
APPENDTOKEN:
@@ -5523,16 +5528,38 @@ static inline int tex_aux_add_or_sub(int x, int y, int max_answer, int operation
// }
// }
+// static inline int tex_aux_quotient(int n, int d, int rounded)
+// {
+// if (d == 0) {
+// lmt_scanner_state.arithmetic_error = 1;
+// return 0;
+// } else if (rounded) {
+// return lround((double) n / (double) d);
+// } else {
+// return n / d;
+// }
+// }
+
static inline int tex_aux_quotient(int n, int d, int rounded)
{
if (d == 0) {
lmt_scanner_state.arithmetic_error = 1;
return 0;
- } else if (rounded) {
- return lround((double) n / (double) d);
- } else {
- return n / d;
}
+ if (rounded) {
+ long long num = (long long) n;
+ long long den = (long long) d;
+ int negative = (num < 0) != (den < 0);
+ unsigned long long unum = num < 0 ? 0ULL - (unsigned long long) num : (unsigned long long) num;
+ unsigned long long uden = den < 0 ? 0ULL - (unsigned long long) den : (unsigned long long) den;
+ unsigned long long quotient = unum / uden;
+ unsigned long long remainder = unum % uden;
+ if (remainder >= uden - remainder) {
+ ++quotient;
+ }
+ return (int) (negative ? -(long long) quotient : (long long) quotient);
+ }
+ return n / d;
}
static inline int tex_aux_modulo(int n, int d)
@@ -7130,6 +7157,135 @@ static inline long long tex_aux_double_rounded_long_long(double d)
}
}
+static inline long long tex_aux_multiply_long_long(long long term, long long factor)
+{
+ if (term == 0 || factor == 0) {
+ return 0;
+ }
+# if defined(__SIZEOF_INT128__)
+ __int128 product = (__int128) term * (__int128) factor;
+ if (product >= (__int128) min_longinteger && product <= (__int128) max_longinteger) {
+ return (long long) product;
+ }
+# else
+ if (term > 0) {
+ if (factor > 0) {
+ if (term <= max_longinteger / factor) return term * factor;
+ } else if (factor >= min_longinteger / term) {
+ return term * factor;
+ }
+ } else if (factor > 0) {
+ if (term >= min_longinteger / factor) return term * factor;
+ } else if (term >= max_longinteger / factor) {
+ return term * factor;
+ }
+# endif
+ tex_aux_scan_integer_out_of_range_error(10);
+ return (term < 0) != (factor < 0) ? min_longinteger : max_longinteger;
+}
+
+static inline long long tex_aux_divide_long_long(long long term, long long factor)
+{
+ if (factor == 0) {
+ tex_aux_scan_integer_out_of_range_error(10);
+ return (term >= 0) ? max_longinteger : min_longinteger;
+ }
+ if (term == 0) {
+ return 0;
+ }
+ /* Symmetric round-to-nearest: ties round away from zero. */
+ int negative = (term < 0) != (factor < 0);
+ unsigned long long uterm = term < 0 ? 0ULL - (unsigned long long) term : (unsigned long long) term;
+ unsigned long long ufactor = factor < 0 ? 0ULL - (unsigned long long) factor : (unsigned long long) factor;
+ unsigned long long quotient = uterm / ufactor;
+ unsigned long long remainder = uterm % ufactor;
+ if (remainder >= ufactor - remainder) {
+ ++quotient;
+ }
+ if (quotient > (unsigned long long) max_longinteger) {
+ tex_aux_scan_integer_out_of_range_error(10);
+ return negative ? min_longinteger : max_longinteger;
+ }
+ {
+ long long result = (long long) quotient;
+ return negative ? -result : result;
+ }
+}
+
+static inline long long tex_aux_integer_divide_long_long(long long term, long long factor)
+{
+ int negative;
+ unsigned long long uterm, ufactor, quotient;
+ if (term == 0) {
+ return 0;
+ }
+ negative = (term < 0) != (factor < 0);
+ uterm = term < 0 ? 0ULL - (unsigned long long) term : (unsigned long long) term;
+ ufactor = factor < 0 ? 0ULL - (unsigned long long) factor : (unsigned long long) factor;
+ quotient = uterm / ufactor;
+ if (quotient > (unsigned long long) max_longinteger) {
+ tex_aux_scan_integer_out_of_range_error(10);
+ return negative ? min_longinteger : max_longinteger;
+ }
+ {
+ long long result = (long long) quotient;
+ return negative ? -result : result;
+ }
+}
+
+static inline long long tex_aux_scale_long_long(long long term, long long numerator, long long factor)
+{
+ if (factor == 0) {
+ tex_aux_scan_integer_out_of_range_error(10);
+ return ((term < 0) != (numerator < 0)) ? min_longinteger : max_longinteger;
+ }
+ if (term == 0 || numerator == 0) {
+ return 0;
+ }
+# if defined(__SIZEOF_INT128__)
+ /* 128-bit widening guarantees zero intermediate overflow for the supported input range. */
+ __int128 prod = (__int128) term * (__int128) numerator;
+ int negative = (prod < 0) != (factor < 0);
+ if (prod < 0) {
+ prod = -prod;
+ }
+ __int128 den = factor < 0 ? -(__int128) factor : (__int128) factor;
+ __int128 q = prod / den;
+ __int128 remainder = prod % den;
+ if (remainder >= den - remainder) {
+ ++q;
+ }
+ if (negative) {
+ q = -q;
+ }
+ if (q < (__int128) min_longinteger) {
+ tex_aux_scan_integer_out_of_range_error(10);
+ return min_longinteger;
+ } else if (q > (__int128) max_longinteger) {
+ tex_aux_scan_integer_out_of_range_error(10);
+ return max_longinteger;
+ }
+ return (long long) q;
+# else
+ /* MSVC / Fallback path using double bridge if 128-bit integers aren't supported */
+ double r = ((double) term * (double) numerator) / (double) factor;
+ return tex_aux_double_rounded_long_long(r);
+# endif
+}
+
+static inline long long tex_aux_modulo_long_long(long long term, long long factor)
+{
+ if (factor == 0) {
+ tex_aux_scan_integer_out_of_range_error(10);
+ return 0;
+ }
+ if (term == LLONG_MIN && factor == -1) {
+ return 0;
+ }
+ /* Standard C % operator matches C99/C11 sign semantics (remainder has dividend's sign). */
+ return term % factor;
+}
+
/*
static inline long long tex_aux_double_floored_long_long(double d)
{
@@ -7159,6 +7315,48 @@ static inline long long tex_aux_long_long(long long l)
}
}
+static inline long long tex_aux_add_long_long(long long a, long long b)
+{
+# if defined(__SIZEOF_INT128__)
+ __int128 sum = (__int128) a + (__int128) b;
+ if (sum < (__int128) min_longinteger) {
+ tex_aux_scan_integer_out_of_range_error(10);
+ return min_longinteger;
+ } else if (sum > (__int128) max_longinteger) {
+ tex_aux_scan_integer_out_of_range_error(10);
+ return max_longinteger;
+ }
+ return (long long) sum;
+# else
+ if ((b > 0 && a > max_longinteger - b) || (b < 0 && a < min_longinteger - b)) {
+ tex_aux_scan_integer_out_of_range_error(10);
+ return b < 0 ? min_longinteger : max_longinteger;
+ }
+ return a + b;
+# endif
+}
+
+static inline long long tex_aux_subtract_long_long(long long a, long long b)
+{
+# if defined(__SIZEOF_INT128__)
+ __int128 difference = (__int128) a - (__int128) b;
+ if (difference < (__int128) min_longinteger) {
+ tex_aux_scan_integer_out_of_range_error(10);
+ return min_longinteger;
+ } else if (difference > (__int128) max_longinteger) {
+ tex_aux_scan_integer_out_of_range_error(10);
+ return max_longinteger;
+ }
+ return (long long) difference;
+# else
+ if ((b < 0 && a > max_longinteger + b) || (b > 0 && a < min_longinteger + b)) {
+ tex_aux_scan_integer_out_of_range_error(10);
+ return b < 0 ? max_longinteger : min_longinteger;
+ }
+ return a - b;
+# endif
+}
+
static inline long long tex_aux_shift_left(long long value, long long shift)
{
if (shift < 0 || shift >= (long long) (sizeof(unsigned long long) * 8)) {
@@ -7299,6 +7497,7 @@ static void tex_aux_scan_integer_expression(int braced)
default:
break;
}
+ break; /* was missing */
case tilde_token_l:
case tilde_token_o:
if (tex_scan_aux_tilde(&alreadygotten) == expression_bnot) {
@@ -7464,13 +7663,15 @@ static void tex_aux_scan_integer_expression(int braced)
numerator = factor;
operation = expression_scale;
} else {
- term = tex_aux_double_rounded_long_long((double) term * (double) factor);
+ // term = tex_aux_double_rounded_long_long((double) term * (double) factor);
+ term = tex_aux_multiply_long_long(term, factor);
}
break;
case expression_divide:
/* round */
if lmt_likely(factor != 0) {
- term = tex_aux_double_rounded_long_long((double) term / (double) factor);
+ // term = tex_aux_double_rounded_long_long((double) term / (double) factor);
+ term = tex_aux_divide_long_long(term, factor);
} else {
tex_aux_scan_zero_divide_error();
lmt_scanner_state.arithmetic_error = 1;
@@ -7479,7 +7680,8 @@ static void tex_aux_scan_integer_expression(int braced)
break;
case expression_scale:
if lmt_likely(factor != 0) {
- term = tex_aux_double_rounded_long_long((double) term * (double) numerator / (double) factor);
+ // term = tex_aux_double_rounded_long_long((double) term * (double) numerator / (double) factor);
+ term = tex_aux_scale_long_long(term, numerator, factor);
} else {
tex_aux_scan_zero_divide_error();
lmt_scanner_state.arithmetic_error = 1;
@@ -7488,7 +7690,7 @@ static void tex_aux_scan_integer_expression(int braced)
break;
case expression_idivide:
if lmt_likely(factor != 0) {
- term = term / factor;
+ term = tex_aux_integer_divide_long_long(term, factor);
} else {
tex_aux_scan_zero_divide_error();
lmt_scanner_state.arithmetic_error = 1;
@@ -7497,7 +7699,8 @@ static void tex_aux_scan_integer_expression(int braced)
break;
case expression_imodulo:
if lmt_likely(factor != 0) {
- term = tex_aux_double_rounded_long_long(fmod((double) term, (double) factor));
+ // term = tex_aux_double_rounded_long_long(fmod((double) term, (double) factor));
+ term = tex_aux_modulo_long_long(term, factor);
} else {
tex_aux_scan_zero_divide_error();
lmt_scanner_state.arithmetic_error = 1;
@@ -7537,8 +7740,8 @@ static void tex_aux_scan_integer_expression(int braced)
} else {
state = expression_none;
switch (result) {
- case expression_add : expression = tex_aux_long_long(expression + term); break;
- case expression_subtract: expression = tex_aux_long_long(expression - term); break;
+ case expression_add : expression = tex_aux_add_long_long(expression, term); break;
+ case expression_subtract: expression = tex_aux_subtract_long_long(expression, term); break;
/* */
case expression_not : expression = term ? 0 : 1; break;
case expression_bnot : expression = ~ term; break;
@@ -7963,6 +8166,7 @@ static void tex_aux_scan_dimension_expression(int braced)
default:
break;
}
+ break; /* was missing */
case exclamation_token_l:
case exclamation_token_o:
if (tex_scan_aux_exclamation(&alreadygotten) == expression_not) {
@@ -8236,12 +8440,12 @@ static void tex_aux_scan_dimension_expression(int braced)
switch (result) {
case expression_add:
/* depends on term type: float / dimen ok, int is sp */
- expression = expression + term;
+ expression = tex_aux_add_long_long(expression, term);
expressiontype = expression_type_dimension;
break;
case expression_subtract:
/* depends on term type: float / dimen ok, int is sp */
- expression = expression - term;
+ expression = tex_aux_subtract_long_long(expression, term);
expressiontype = expression_type_dimension;
break;
case expression_not:
@@ -8723,6 +8927,8 @@ static inline halfword tex_scan_aux_function(int *alreadygotten)
switch (cur_tok) {
case s_token_l: case s_token_o:
return bit_expression_abs;
+ default:
+ break;
}
break;
case c_token_l: case c_token_o:
@@ -8740,9 +8946,12 @@ static inline halfword tex_scan_aux_function(int *alreadygotten)
*alreadygotten = 1;
return bit_expression_acos;
}
+ default:
+ break;
}
break;
}
+ break;
case s_token_l: case s_token_o:
tex_get_x_token();
switch (cur_tok) {
@@ -8761,6 +8970,7 @@ static inline halfword tex_scan_aux_function(int *alreadygotten)
}
break;
}
+ break;
case t_token_l: case t_token_o:
tex_get_x_token();
switch (cur_tok) {
@@ -8779,6 +8989,7 @@ static inline halfword tex_scan_aux_function(int *alreadygotten)
}
break;
}
+ break;
}
break;
case c_token_l: case c_token_o:
@@ -9120,6 +9331,8 @@ static void tex_aux_scan_expression(int level, int braced)
case bar_token_l: case bar_token_o:
operation = bit_expression_or;
goto OKAY;
+ default:
+ break;
}
operation = bit_expression_bor;
alreadygotten = 1;
@@ -9130,6 +9343,7 @@ static void tex_aux_scan_expression(int level, int braced)
case less_token : operation = bit_expression_bleft ; goto OKAY;
case equal_token: operation = bit_expression_lessequal; goto OKAY;
case more_token : operation = bit_expression_unequal ; goto OKAY;
+ default: break;
}
operation = bit_expression_less;
alreadygotten = 1;
@@ -9139,6 +9353,7 @@ static void tex_aux_scan_expression(int level, int braced)
switch (cur_tok) {
case more_token : operation = bit_expression_bright ; goto OKAY;
case equal_token: operation = bit_expression_moreequal; goto OKAY;
+ default: break;
}
operation = bit_expression_more;
alreadygotten = 1;
@@ -9164,6 +9379,8 @@ static void tex_aux_scan_expression(int level, int braced)
case equal_token:
operation = bit_expression_unequal;
goto OKAY;
+ default:
+ break;
}
operation = bit_expression_bnot;
alreadygotten = 1;
@@ -9174,6 +9391,8 @@ static void tex_aux_scan_expression(int level, int braced)
case equal_token:
operation = bit_expression_unequal;
goto OKAY;
+ default:
+ break;
}
operation = bit_expression_not; /* better bitwise ~ */
alreadygotten = 1;
@@ -9187,27 +9406,35 @@ static void tex_aux_scan_expression(int level, int braced)
case d_token_l: case d_token_o:
operation = bit_expression_mod;
goto OKAY;
+ default:
+ break;
}
+ default:
+ break;
}
goto UNEXPECTED;
case d_token_l: case d_token_o:
tex_get_x_token();
switch (cur_tok) {
case i_token_l: case i_token_o:
- tex_get_x_token();
- switch (cur_tok) {
- case v_token_l: case v_token_o:
- operation = bit_expression_div;
- goto OKAY;
- }
+ tex_get_x_token();
+ switch (cur_tok) {
+ case v_token_l: case v_token_o:
+ operation = bit_expression_div;
+ goto OKAY;
+ default:
+ break;
+ }
+ default:
+ break;
}
goto UNEXPECTED;
case n_token_l: case n_token_o:
tex_get_x_token();
switch (cur_tok) {
case o_token_l: case o_token_o:
- tex_get_x_token();
- switch (cur_tok) {
+ tex_get_x_token();
+ switch (cur_tok) {
case t_token_l: case t_token_o:
if (lastoperation != bit_expression_none || initial) {
operation = bit_expression_none;
@@ -9217,10 +9444,13 @@ static void tex_aux_scan_expression(int level, int braced)
operation = bit_expression_not;
goto OKAY;
}
- }
+ default:
+ break;
+ }
+ break; /* was missing */
case p_token_l: case p_token_o:
- tex_get_x_token();
- switch (cur_tok) {
+ tex_get_x_token();
+ switch (cur_tok) {
case m_token_l: case m_token_o:
if (lastoperation != bit_expression_none || initial) {
operation = bit_expression_none;
@@ -9230,10 +9460,13 @@ static void tex_aux_scan_expression(int level, int braced)
operation = bit_expression_pm;
goto OKAY;
}
- }
+ default:
+ break;
+ }
+ break; /* was missing */
case m_token_l: case m_token_o:
- tex_get_x_token();
- switch (cur_tok) {
+ tex_get_x_token();
+ switch (cur_tok) {
case p_token_l: case p_token_o:
if (lastoperation != bit_expression_none || initial) {
operation = bit_expression_none;
@@ -9243,7 +9476,12 @@ static void tex_aux_scan_expression(int level, int braced)
operation = bit_expression_mp;
goto OKAY;
}
- }
+ default:
+ break;
+ }
+ break;
+ default:
+ break;
}
goto UNEXPECTED;
case a_token_l: case a_token_o:
@@ -9326,6 +9564,8 @@ static void tex_aux_scan_expression(int level, int braced)
}
}
break;
+ default:
+ break;
}
goto UNEXPECTED;
case c_token_l: case c_token_o:
@@ -9351,6 +9591,8 @@ static void tex_aux_scan_expression(int level, int braced)
goto OKAY;
}
break;
+ default:
+ break;
}
goto UNEXPECTED;
case o_token_l: case o_token_o:
@@ -9359,6 +9601,8 @@ static void tex_aux_scan_expression(int level, int braced)
case r_token_l: case r_token_o:
operation = bit_expression_or;
goto OKAY;
+ default:
+ break;
}
goto UNEXPECTED;
case v_token_l: case v_token_o:
diff --git a/source/luametatex/source/tex/texscanning.h b/source/luametatex/source/tex/texscanning.h
index f7c90b2f5..7291e9475 100644
--- a/source/luametatex/source/tex/texscanning.h
+++ b/source/luametatex/source/tex/texscanning.h
@@ -85,7 +85,7 @@ extern halfword tex_scan_scale (int optional_equal);
extern halfword tex_scan_scale_factor (int optional_equal);
extern halfword tex_scan_clipped_scale_factor (int optional_equal);
extern halfword tex_scan_posit (int optional_equal);
-extern halfword tex_scan_dimension (int mu, int inf, int shortcut, int optional_equal, halfword *order, int *grouped);
+extern scaled tex_scan_dimension (int mu, int inf, int shortcut, int optional_equal, halfword *order, int *grouped);
extern void tex_scan_dimension_validate (void);
extern halfword tex_scan_glue (int level, int optional_equal, int options_too, halfword *penalty);
extern halfword tex_scan_font (int optional_equal);
@@ -150,9 +150,9 @@ extern void tex_detokenize_list (halfword head);
extern strnumber tex_the_scanned_result (void);
extern void tex_set_font_dimension (void);
-extern halfword tex_get_font_dimension (void);
+extern scaled tex_get_font_dimension (void);
extern void tex_set_scaled_font_dimension (int n);
-extern halfword tex_get_scaled_font_dimension (int n);
+extern scaled tex_get_scaled_font_dimension (int n);
extern int tex_get_unit_class (halfword index);
diff --git a/source/luametatex/source/tex/texsnapping.c b/source/luametatex/source/tex/texsnapping.c
index 7360f9b56..406c837a2 100644
--- a/source/luametatex/source/tex/texsnapping.c
+++ b/source/luametatex/source/tex/texsnapping.c
@@ -260,7 +260,7 @@ static inline scaled tex_aux_snap_dimen(scaled amount, halfword local_factor, ha
return amount;
}
-void tex_snapping_done(halfword *ht, halfword *dp, halfword snapping)
+void tex_snapping_done(scaled *ht, scaled *dp, halfword snapping)
{
if (snapping && specification_count(snapping) > 0) {
int options = tex_get_line_snapping_options(snapping, 1);
diff --git a/source/luametatex/source/tex/texstringpool.c b/source/luametatex/source/tex/texstringpool.c
index 64d98010e..ab2d133e4 100644
--- a/source/luametatex/source/tex/texstringpool.c
+++ b/source/luametatex/source/tex/texstringpool.c
@@ -372,12 +372,12 @@ int tex_str_eq_str(strnumber s, strnumber t)
return (str_getlen(s) == str_getlen(t)) && ! memcmp(str_getstr(s),str_getstr(t),str_getlen(s));
} else {
int length;
- unsigned value = aux_str2uni_len(str_getstr(s), &length);
+ unsigned value = aux_str2uni_len(str_getstr(s), str_getsizlen(s), &length);
return length == str_getintlen(s) && value == (unsigned) t;
}
} else if (t >= cs_offset_value) {
int length;
- unsigned value = aux_str2uni_len(str_getstr(t), &length);
+ unsigned value = aux_str2uni_len(str_getstr(t), str_getsizlen(t), &length);
return length == str_getintlen(t) && value == (unsigned) s;
} else {
/* s and t are unicode characters */
diff --git a/source/luametatex/source/tex/textoken.c b/source/luametatex/source/tex/textoken.c
index 5a9049394..5c7f90a0f 100644
--- a/source/luametatex/source/tex/textoken.c
+++ b/source/luametatex/source/tex/textoken.c
@@ -834,11 +834,12 @@ void tex_show_token_list_context(halfword p, halfword q)
static inline halfword get_unichar_from_buffer(int *b)
{
halfword a = (halfword) ((const unsigned char) *(lmt_fileio_state.io_buffer + *b));
- if (a <= 0x80) {
+ if (a < 0x80) {
*b += 1;
} else {
int al;
- a = (halfword) aux_str2uni_len(lmt_fileio_state.io_buffer + *b, &al);
+ size_t available = (size_t) (lmt_input_state.cur_input.limit - *b + 1);
+ a = (halfword) aux_str2uni_len(lmt_fileio_state.io_buffer + *b, available, &al);
*b += al;
}
return a;
@@ -2182,7 +2183,7 @@ static inline next_line_retval tex_aux_next_line(void)
groups entered or conditionals started while reading from that file are still incomplete.
*/
if (lmt_token_state.force_eof) {
- if (tracing_nesting_par > 0) {
+ if lmt_unlikely(tracing_nesting_par > 0) {
if ((lmt_input_state.in_stack[lmt_input_state.in_stack_data.ptr].group != cur_boundary) || (lmt_input_state.in_stack[lmt_input_state.in_stack_data.ptr].if_ptr != lmt_condition_state.cond_ptr)) {
if (! io_token_input(lmt_input_state.cur_input.name)) {
/*tex Check for unfinished groups: */
@@ -2191,7 +2192,7 @@ static inline next_line_retval tex_aux_next_line(void)
tex_conditional_catch_up();
/*tex Show the context, when asked for: */
tex_print_nlp();
- if (tracing_nesting_par > 1) {
+ if lmt_unlikely(tracing_nesting_par > 1) {
tex_show_context();
}
/*tex Recover if needed: */
@@ -2528,7 +2529,7 @@ void tex_get_x_or_protected(void)
// /*tex new node being added to the token list via |store_new_token| */
// while (s < se) {
// int tl;
-// halfword t = (halfword) aux_str2uni_len((const unsigned char *) s, &tl);
+// halfword t = (halfword) aux_str2uni_len((const unsigned char *) s, strlen(s), &tl);
// s += tl;
// if (t == ' ') {
// t = space_token;
@@ -2566,7 +2567,7 @@ static halfword lmt_str_toks(lstring b) /* returns head */
halfword tail = head;
while (k < (unsigned char *) (b.str + b.len)) {
int tl;
- halfword t = aux_str2uni_len(k, &tl);
+ halfword t = aux_str2uni_len(k, (size_t) ((unsigned char *) (b.str + b.len) - k), &tl);
k += tl;
if (t == ' ') {
t = space_token;
@@ -2609,7 +2610,7 @@ halfword tex_str_toks(lstring s, halfword *tail)
unsigned char *l = (unsigned char *) (k + s.len);
while (k < l) {
int tl;
- halfword t = aux_str2uni_len(k, &tl);
+ halfword t = aux_str2uni_len(k, (size_t) (l - k), &tl);
if (t == ' ') {
t = space_token;
} else {
@@ -2639,7 +2640,7 @@ halfword tex_cur_str_toks(halfword *tail)
while (k < l) {
/*tex token being appended */
int tl;
- halfword t = aux_str2uni_len(k, &tl);
+ halfword t = aux_str2uni_len(k, (size_t) (l - k), &tl);
if (t == ' ') {
t = space_token;
} else {
@@ -2681,7 +2682,7 @@ halfword tex_str_scan_toks(int ct, lstring ls)
int cc;
/*tex token being appended */
int lt;
- halfword t = aux_str2uni_len(k, &lt);
+ halfword t = aux_str2uni_len(k, (size_t) (l - k), &lt);
k += lt;
cc = tex_get_cat_code(ct, t);
if (cc == 0) {
@@ -2692,7 +2693,7 @@ halfword tex_str_scan_toks(int ct, lstring ls)
unsigned char *name = k ;
while (k < l) {
int c = 0 ;
- t = (halfword) aux_str2uni_len((const unsigned char *) k, &s);
+ t = (halfword) aux_str2uni_len((const unsigned char *) k, (size_t) (l - k), &s);
c = tex_get_cat_code(ct, t);
if (c == letter_cmd) {
k += s ;
@@ -3092,7 +3093,7 @@ void tex_run_convert_tokens(halfword code)
{
int saved_selector;
int grouped = 0;
- halfword v = tex_scan_dimension(0, 0, 0, 0, NULL, &grouped);
+ scaled v = tex_scan_dimension(0, 0, 0, 0, NULL, &grouped);
if (! grouped) {
tex_get_x_token(); /* maybe not x here */
if (cur_cmd != relax_cmd) {
@@ -3499,11 +3500,11 @@ void tex_run_convert_tokens(halfword code)
pop_selector;
break;
}
- case luatex_banner_code:
+ case luametatex_banner_code:
{
int saved_selector;
push_selector;
- tex_print_str(lmt_engine_state.luatex_banner);
+ tex_print_str(lmt_engine_state.luametatex_banner);
pop_selector;
break;
}
@@ -3578,8 +3579,8 @@ strnumber tex_the_convert_string(halfword c, int i)
case format_name_code:
tex_print_str(lmt_engine_state.dump_name);
break;
- case luatex_banner_code:
- tex_print_str(lmt_engine_state.luatex_banner);
+ case luametatex_banner_code:
+ tex_print_str(lmt_engine_state.luametatex_banner);
break;
case font_identifier_code:
tex_print_font_identifier(i);
@@ -3927,7 +3928,7 @@ char *tex_tokenlist_to_tstring(int pp, int inhibit_par, int *siz, int skippreamb
/* The bin gets 1.2K smaller if we inline these. */
-halfword tex_get_tex_dimension_register (int j, int internal) { return internal ? dimension_parameter(j) : dimension_register(j) ; }
+scaled tex_get_tex_dimension_register (int j, int internal) { return internal ? dimension_parameter(j) : dimension_register(j) ; }
halfword tex_get_tex_skip_register (int j, int internal) { return internal ? glue_parameter(j) : skip_register(j) ; }
halfword tex_get_tex_muskip_register (int j, int internal) { return internal ? muglue_parameter(j) : muskip_register(j); }
halfword tex_get_tex_count_register (int j, int internal) { return internal ? count_parameter(j) : count_register(j) ; }
@@ -3939,7 +3940,7 @@ halfword tex_get_tex_box_register (int j, int internal) { return internal
// flags = add_global_flag(flags);
// }
-int tex_set_tex_dimension_register(int j, halfword v, int flags, int internal)
+int tex_set_tex_dimension_register(int j, scaled v, int flags, int internal)
{
halfword p = internal ? internal_dimension_location(j) : register_dimension_location(j);
if (tex_mutation_permitted(p)) {
@@ -4086,7 +4087,7 @@ halfword tex_parse_str_to_tok(halfword head, halfword *tail, halfword ct, const
while (str < se) {
/*tex hh: |str2uni| could return len too (also elsewhere) */
int ul;
- halfword u = (halfword) aux_str2uni_len((const unsigned char *) str, &ul);
+ halfword u = (halfword) aux_str2uni_len((const unsigned char *) str, (size_t) (se - str), &ul);
halfword t = null;
halfword cc = tex_get_cat_code(ct, u);
str += ul;
@@ -4102,7 +4103,7 @@ halfword tex_parse_str_to_tok(halfword head, halfword *tail, halfword ct, const
const char *name = str;
while (str < se) {
int s;
- halfword u = (halfword) aux_str2uni_len((const unsigned char *) str, &s);
+ halfword u = (halfword) aux_str2uni_len((const unsigned char *) str, (size_t) (se - str), &s);
int c = tex_get_cat_code(ct, u);
if (c == letter_cmd) {
str += s;
diff --git a/source/luametatex/source/tex/textoken.h b/source/luametatex/source/tex/textoken.h
index e6ff943ec..6209ab847 100644
--- a/source/luametatex/source/tex/textoken.h
+++ b/source/luametatex/source/tex/textoken.h
@@ -1,4 +1,4 @@
-/*
+/*
See license.txt in the root of this project.
*/
@@ -580,7 +580,7 @@ extern strnumber tex_the_convert_string (halfword c, int i);
extern strnumber tex_tokens_to_string (halfword p);
extern char *tex_tokenlist_to_tstring (int p, int inhibit_par, int *siz, int skip, int nospace, int strip, int wipe, int single);
-extern halfword tex_get_tex_dimension_register (int j, int internal);
+extern scaled tex_get_tex_dimension_register (int j, int internal);
extern halfword tex_get_tex_skip_register (int j, int internal);
extern halfword tex_get_tex_muskip_register (int j, int internal);
extern halfword tex_get_tex_count_register (int j, int internal);
@@ -589,7 +589,7 @@ extern halfword tex_get_tex_attribute_register (int j, int internal);
extern halfword tex_get_tex_box_register (int j, int internal);
extern halfword tex_get_tex_toks_register (int j, int internal);
-extern int tex_set_tex_dimension_register (int j, halfword v, int flags, int internal);
+extern int tex_set_tex_dimension_register (int j, scaled v, int flags, int internal);
extern int tex_set_tex_skip_register (int j, halfword v, int flags, int internal);
extern int tex_set_tex_muskip_register (int j, halfword v, int flags, int internal);
extern int tex_set_tex_count_register (int j, halfword v, int flags, int internal);
diff --git a/source/luametatex/source/tex/textypes.h b/source/luametatex/source/tex/textypes.h
index 3b57274fe..bd121caef 100644
--- a/source/luametatex/source/tex/textypes.h
+++ b/source/luametatex/source/tex/textypes.h
@@ -197,6 +197,9 @@ extern halfword tex_badness(
# define default_rule 26214 /*tex 0.4pt */
# define ignore_depth (-65536000) /*tex The magic dimension value to mean \quote {ignore me}: -1000pt */
+# define min_singleword 0 /*tex The smallest allowable value in a |singleword|. */
+# define max_singleword 255 /*tex The largest allowable value in a |singleword|. */
+
# define min_quarterword 0 /*tex The smallest allowable value in a |quarterword|. */
# define max_quarterword 65535 /*tex The largest allowable value in a |quarterword|. */
diff --git a/source/luametatex/source/utilities/auxarithmetic.h b/source/luametatex/source/utilities/auxarithmetic.h
index 6c3124faa..ed1d1a14f 100644
--- a/source/luametatex/source/utilities/auxarithmetic.h
+++ b/source/luametatex/source/utilities/auxarithmetic.h
@@ -66,6 +66,131 @@ static inline int fastceil (double x) { return (int) x >= x ? (int) x : (int) x
# define clippedround(r) ((r>2147483647.0) ? 2147483647 : ((r<-2147483647.0) ? -2147483647 : (int) lround(r)))
# define glueround(x) clippedround((double) (x))
-static inline scaled scaledround(double x) { return (scaled) (x >= 0.0 ? (x + 0.5) : (x - 0.5)); }
+static inline scaled scaledround(double x) { return (scaled) lround(x); }
+
+# if lmt_float_math
+
+ /* nothing */
+
+# else
+
+ /*
+ The float path evaluates these expressions in double precision. On compilers with
+ __int128, keep the integer path exact until the final division instead of multiplying
+ in long long first. The largest dimension products use four scale factors, so 64 bits
+ are not sufficient. The fallback keeps the wider intermediate in long double.
+ */
+
+ static inline long long tex_aux_round_product(long long value, long long a, long long b, long long c, long long d, long long divisor)
+ {
+ if (! value || ! a || ! b || ! c || ! d) {
+ return 0;
+ }
+ # if defined(__SIZEOF_INT128__)
+ __int128 numerator = (__int128) value;
+ numerator *= a;
+ numerator *= b;
+ numerator *= c;
+ numerator *= d;
+ int negative = numerator < 0;
+ if (negative) {
+ numerator = -numerator;
+ }
+ __int128 denominator = divisor < 0 ? -(__int128) divisor : (__int128) divisor;
+ __int128 quotient = numerator / denominator;
+ __int128 remainder = numerator % denominator;
+ if (remainder >= denominator - remainder) {
+ ++quotient;
+ }
+ if (negative) {
+ quotient = -quotient;
+ }
+ if (quotient > LLONG_MAX) {
+ return LLONG_MAX;
+ } else if (quotient < LLONG_MIN) {
+ return LLONG_MIN;
+ } else {
+ return (long long) quotient;
+ }
+ # else
+ long double result = ((long double) value * (long double) a * (long double) b * (long double) c * (long double) d) / (long double) divisor;
+ long double rounded = result >= 0.0L ? result + 0.5L : result - 0.5L;
+ if (rounded >= (long double) LLONG_MAX) {
+ return LLONG_MAX;
+ } else if (rounded <= (long double) LLONG_MIN) {
+ return LLONG_MIN;
+ } else {
+ return (long long) rounded;
+ }
+ # endif
+ }
+
+ static inline long long tex_aux_round_sum_products(long long value, long long a, long long b, long long c, long long d, long long divisor)
+ {
+ if (! value || (! a && ! c) || (! b && ! d)) {
+ return 0;
+ }
+ # if defined(__SIZEOF_INT128__)
+ __int128 numerator = (__int128) value * a * b + (__int128) value * c * d;
+ int negative = numerator < 0;
+ if (negative) {
+ numerator = -numerator;
+ }
+ __int128 denominator = divisor < 0 ? -(__int128) divisor : (__int128) divisor;
+ __int128 quotient = numerator / denominator;
+ __int128 remainder = numerator % denominator;
+ if (remainder >= denominator - remainder) {
+ ++quotient;
+ }
+ if (negative) {
+ quotient = -quotient;
+ }
+ if (quotient > LLONG_MAX) {
+ return LLONG_MAX;
+ } else if (quotient < LLONG_MIN) {
+ return LLONG_MIN;
+ } else {
+ return (long long) quotient;
+ }
+ # else
+ long double result = ((long double) value * (long double) a * (long double) b + (long double) value * (long double) c * (long double) d) / (long double) divisor;
+ long double rounded = result >= 0.0L ? result + 0.5L : result - 0.5L;
+ if (rounded >= (long double) LLONG_MAX) {
+ return LLONG_MAX;
+ } else if (rounded <= (long double) LLONG_MIN) {
+ return LLONG_MIN;
+ } else {
+ return (long long) rounded;
+ }
+ # endif
+ }
+
+ /* Explicit scale: zero remains zero. */
+
+ static inline scaled tex_aux_scale_1000(scaled v, long long scale)
+ {
+ return (scaled) tex_aux_round_product(v, scale, 1, 1, 1, 1000);
+ }
+
+ /* A zero scale means the default 100% scale in these font and glyph paths. */
+
+ static inline scaled tex_aux_scale_1000_default(scaled v, long long scale)
+ {
+ return tex_aux_scale_1000(v, scale ? scale : 1000LL);
+ }
+
+ static inline scaled tex_aux_scale_1e6(scaled value, long long s1, long long s2)
+ {
+ return (scaled) tex_aux_round_product(value, s1 ? s1 : 1000LL, s2 ? s2 : 1000LL, 1, 1, 1000000);
+ }
+
+ /* The first two scales default to 100%, the explicit third scale may be zero. */
+
+ static inline scaled tex_aux_scale_1e9(scaled value, long long s1, long long s2, long long s3)
+ {
+ return (scaled) tex_aux_round_product(value, s1 ? s1 : 1000LL, s2 ? s2 : 1000LL, s3, 1, 1000000000);
+ }
+
+# endif
# endif
diff --git a/source/luametatex/source/utilities/auxcompiler.h b/source/luametatex/source/utilities/auxcompiler.h
index 1afd48f6d..ff4abd6fa 100644
--- a/source/luametatex/source/utilities/auxcompiler.h
+++ b/source/luametatex/source/utilities/auxcompiler.h
@@ -141,14 +141,19 @@
# define FALLTHROUGH ((void) 0);
# endif
-# if (! defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L) && ! defined(hypot)
+# if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(_MSC_VER)
- static inline double hypot(double x, double y)
+ # define lmt_hypot hypot
+
+# else
+
+ static inline double lmt_hypot(double x, double y)
{
double ax = fabs(x);
double ay = fabs(y);
- if (ax == 0.0 && ay == 0.0) return 0.0;
- if (ax > ay) {
+ if (ax == 0.0 && ay == 0.0) {
+ return 0.0;
+ } else if (ax > ay) {
double r = ay / ax;
return ax * sqrt(1.0 + r * r);
} else {
@@ -181,4 +186,34 @@ static inline bool odd_double (double a) { return fabs(fmod(a, 2.0))
# define SAFE __attribute__((annotate("safe")))
+// void enforce_fpu_consistency(void)
+// {
+// /* Force round-to-nearest (IEEE-754 default). */
+// fesetround(FE_TONEAREST);
+// // Flush Denormals To Zero (FTZ) and Denormals Are Zero (DAZ) if needed.
+// // Denormal behavior varies between x86 and ARM processors. Disabling
+// // denormals ensures both speed and deterministic behavior.
+// # if defined(__x86_64__) || defined(_M_X64)
+// _mm_setcsr(_mm_getcsr() | 0x8000 | 0x0040); // Sets FTZ and DAZ on SSE/AVX
+// # endif
+// }
+//
+// # include <fenv.h>
+//
+// void enforce_cross_platform_fpu()
+// {
+// // Force standard IEEE round-to-nearest
+// std::fesetround(FE_TONEAREST);
+// # if defined(__x86_64__) || defined(_M_X64)
+// // Enable Flush-to-Zero (FTZ) and Denormals-are-Zero (DAZ) on x86
+// _mm_setcsr(_mm_getcsr() | 0x8000 | 0x0040);
+// # elif defined(__aarch64__)
+// // Enable Flush-to-Zero on ARM64 FPSCR register
+// uint64_t fpcr;
+// asm volatile("mrs %0, fpcr" : "=r"(fpcr));
+// fpcr |= (1ULL << 24); // Set FZ bit
+// asm volatile("msr fpcr, %0" :: "r"(fpcr));
+// # endif
+// }
+
# endif
diff --git a/source/luametatex/source/utilities/auxfile.h b/source/luametatex/source/utilities/auxfile.h
index 9dd995e76..ff2892df9 100644
--- a/source/luametatex/source/utilities/auxfile.h
+++ b/source/luametatex/source/utilities/auxfile.h
@@ -69,8 +69,8 @@
- lfs setexecutable : done (needs testing)
- lfs isdir : done
- lfs isfile : done
- - lfs iswriteabledir : done
- - lfs iswriteablefile : done
+ - lfs iswritabledir : done
+ - lfs iswritablefile : done
- lfs isreadabledir : done
- lfs isreadablefile : done
\stoptyping
diff --git a/source/luametatex/source/utilities/auxserialize.c b/source/luametatex/source/utilities/auxserialize.c
new file mode 100644
index 000000000..4ff657a79
--- /dev/null
+++ b/source/luametatex/source/utilities/auxserialize.c
@@ -0,0 +1,562 @@
+/*tex
+
+ See license.txt in the root of this project. The credits for the basics of this code
+ (the inline functions go to wherever gemini got it from. In principle it is published
+ code based on some research. The two public helpers are tuned for our purpose,
+ especially striping the redundant zeros and precision. Here is a Gemini wrapup of the
+ inline functions:
+
+ \startquotation
+ The technique implemented here uses a two-digit lookup table optimization—frequently
+ associated with Terence Parr's dtoa algorithm and popularized by Milo Yip's rapidjson
+ library as well as Ryu/Grisu variant implementations. The primary goal of the
+ 200-character array |DIGIT_TABLE| is to eliminate slow division and modulo operations
+ during binary-to-decimal string formatting. Rather than dividing a number by 10 in a
+ loop to extract one digit at a time, the code processes numbers two digits (base 100)
+ at a time. The DIGIT_TABLE array stores all two-digit decimal combinations from |00|
+ to |99| continuously (100 pairs = 200 characters). By taking |(val % 100) * 2| as the
+ array index, the routine directly retrieves both ASCII characters simultaneously.
+ Because CPU instruction sets execute division by 100 faster via fixed-point
+ multiplication tricks, processing numbers in pairs halves the total number of division
+ instructions, significantly boosting performance in low-latency and high-throughput
+ C code.
+ \stopquotaiton
+
+*/
+
+/*tex
+
+ In the meantiem we added soem more than \quote {f} and \quote {g} formatting because I
+ decided to use al this in the formatting helpers. So more might end up here. All this
+ is rather \CONTEXT\ specific.
+
+*/
+
+# include <stdint.h>
+# include <stdbool.h>
+# include <string.h>
+# include <stdio.h>
+# include <limits.h>
+# include <lua.h>
+
+typedef struct {
+ uint64_t significand;
+ int32_t exponent;
+} decimal_rep_t;
+
+static const char DIGIT_TABLE[] =
+ "0001020304050607080910111213141516171819"
+ "2021222324252627282930313233343536373839"
+ "4041424344454647484950515253545556575859"
+ "6061626364656667686970717273747576777879"
+ "8081828384858687888990919293949596979899";
+
+static const double POW10[] = {
+ 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
+ 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19
+};
+
+# define pow_10_max 19
+# define max_decimal_precision (INT_MAX - 350)
+
+static inline int normalize_decimal_precision(int precision)
+{
+ if (precision < 0) {
+ return 0;
+ } else if (precision > max_decimal_precision) {
+ return max_decimal_precision;
+ } else {
+ return precision;
+ }
+}
+
+static inline decimal_rep_t fast_double_to_decimal(double v, bool *is_neg)
+{
+ union { double d; uint64_t u; } bits = { v };
+ *is_neg = (bits.u >> 63) != 0;
+ if (*is_neg) v = -v;
+ decimal_rep_t dec = {0, 0};
+ if (v == 0.0) {
+ return dec;
+ }
+ // fast integer scaling to extract exact 15-17 significant decimal digits
+ int exp10 = 0;
+ // scale into normalized double range [1e14, 1e15)
+ if (v >= 1e15) {
+ while (v >= 1e23) { v /= 1e8; exp10 += 8; }
+ while (v >= 1e15) { v /= 10.0; exp10++; }
+ } else if (v < 1e14) {
+ while (v < 1e6 ) { v *= 1e8; exp10 -= 8; }
+ while (v < 1e14) { v *= 10.0; exp10--; }
+ }
+ // fast rounding to nearest integer
+ uint64_t sig = (uint64_t) (v + 0.5);
+ // strip trailing zeros to keep representation minimal
+ while (sig > 0 && (sig % 10 == 0)) {
+ sig /= 10;
+ exp10++;
+ }
+ dec.significand = sig;
+ dec.exponent = exp10;
+ return dec;
+}
+
+static inline int render_digits(uint64_t val, char *buf)
+{
+ if (val == 0) {
+ buf[0] = '0';
+ buf[1] = '\0';
+ return 1;
+ }
+ char temp[32];
+ int pos = 0;
+ while (val >= 100) {
+ uint32_t ind = (uint32_t) ((val % 100) * 2);
+ val /= 100;
+ temp[pos++] = DIGIT_TABLE[ind + 1];
+ temp[pos++] = DIGIT_TABLE[ind];
+ }
+ if (val < 10) {
+ temp[pos++] = (char) ('0' + val);
+ } else {
+ uint32_t ind = (uint32_t) (val * 2);
+ temp[pos++] = DIGIT_TABLE[ind + 1];
+ temp[pos++] = DIGIT_TABLE[ind];
+ }
+ for (int i = 0; i < pos; i++) {
+ buf[i] = temp[pos - 1 - i];
+ }
+ buf[pos] = '\0';
+ return pos;
+}
+
+int double_to_string_f(double val, char *buf, int precision)
+{
+ precision = normalize_decimal_precision(precision);
+ bool is_neg;
+ union { double d; uint64_t u; } bits = { val };
+ uint32_t exp = (bits.u >> 52) & 0x7FF;
+ if (exp == 0x7FF) {
+ if (bits.u & 0x000FFFFFFFFFFFFFULL) {
+ buf[0]='N'; buf[1]='a'; buf[2]='N'; buf[3]='\0';
+ return 3;
+ } else if (bits.u >> 63) {
+ buf[0]='-'; buf[1]='I'; buf[2]='n'; buf[3]='f'; buf[4]='\0';
+ return 4;
+ } else {
+ buf[0]='I'; buf[1]='n'; buf[2]='f'; buf[3]='\0';
+ return 3;
+ }
+ }
+ decimal_rep_t dec = fast_double_to_decimal(val, &is_neg);
+ char digits[32];
+ int len = render_digits(dec.significand, digits);
+ int dot_pos = len + dec.exponent;
+ if (dot_pos < len) {
+ // total fractional digits after '.' includes leading zeros when dot_pos <= 0
+ int avail_frac = len - dot_pos;
+ if (avail_frac > precision) {
+ int drop = avail_frac - precision;
+ if (drop > 0) {
+ if (drop <= pow_10_max) {
+ uint64_t p10 = (uint64_t) POW10[drop];
+ dec.significand = (dec.significand + (p10 / 2)) / p10;
+ dec.exponent += drop;
+ } else {
+ dec.significand = 0;
+ dec.exponent = -precision;
+ }
+ len = render_digits(dec.significand, digits);
+ dot_pos = len + dec.exponent;
+ }
+ }
+ }
+ int p = 0;
+ if (is_neg && val != 0.0) buf[p++] = '-';
+ if (dot_pos <= 0) {
+ buf[p++] = '0';
+ buf[p++] = '.';
+ for (int i = 0; i < -dot_pos; i++) {
+ buf[p++] = '0';
+ }
+ for (int i = 0; i < len; i++) {
+ buf[p++] = digits[i];
+ }
+ } else if (dot_pos >= len) {
+ for (int i = 0; i < len; i++) {
+ buf[p++] = digits[i];
+ }
+ for (int i = 0; i < (dot_pos - len); i++) {
+ buf[p++] = '0';
+ }
+ } else {
+ for (int i = 0; i < len; i++) {
+ if (i == dot_pos) {
+ buf[p++] = '.';
+ }
+ buf[p++] = digits[i];
+ }
+ }
+ buf[p] = '\0';
+ // trim trailing zeros after the decimal point
+ if (memchr(buf, '.', p)) {
+ while (p > 0 && buf[p - 1] == '0') {
+ p--;
+ }
+ if (p > 0 && buf[p - 1] == '.') {
+ p--;
+ }
+ buf[p] = '\0';
+ }
+ return p;
+}
+
+int double_to_string_g(double val, char *buf, int precision)
+{
+ precision = normalize_decimal_precision(precision);
+ if (precision == 0) {
+ precision = 1;
+ } else if (precision > 17) {
+ precision = 17;
+ }
+ union { double d; uint64_t u; } bits = { val };
+ uint32_t exp = (bits.u >> 52) & 0x7FF;
+ if (exp == 0x7FF) {
+ if (bits.u & 0x000FFFFFFFFFFFFFULL) {
+ buf[0]='N'; buf[1]='a'; buf[2]='N'; buf[3]='\0';
+ return 3;
+ }
+ if (bits.u >> 63) {
+ buf[0]='-'; buf[1]='I'; buf[2]='n'; buf[3]='f'; buf[4]='\0';
+ return 4;
+ }
+ buf[0]='I'; buf[1]='n'; buf[2]='f'; buf[3]='\0';
+ return 3;
+ }
+ char formatted[64];
+ int len = snprintf(formatted, sizeof(formatted), "%.*g", precision, val);
+ if (len <= 0 || len >= (int) sizeof(formatted)) {
+ buf[0] = '\0';
+ return 0;
+ }
+ memcpy(buf, formatted, (size_t) len + 1);
+ return len;
+}
+
+int double_to_string_z(double val, char *buf, size_t buf_size, int precision)
+{
+ precision = normalize_decimal_precision(precision);
+ bool is_neg;
+ union { double d; uint64_t u; } bits = { val };
+ uint32_t exp = (bits.u >> 52) & 0x7FF;
+ if (exp == 0x7FF) {
+ if (bits.u & 0x000FFFFFFFFFFFFFULL) {
+ if (buf_size < 4) {
+ return -1;
+ }
+ buf[0]='N'; buf[1]='a'; buf[2]='N'; buf[3]='\0';
+ return 3;
+ } else if (bits.u >> 63) {
+ if (buf_size < 5) {
+ return -1;
+ }
+ buf[0]='-'; buf[1]='I'; buf[2]='n'; buf[3]='f'; buf[4]='\0';
+ return 4;
+ } else {
+ if (buf_size < 4) {
+ return -1;
+ }
+ buf[0]='I'; buf[1]='n'; buf[2]='f'; buf[3]='\0';
+ return 3;
+ }
+ }
+ decimal_rep_t dec = fast_double_to_decimal(val, &is_neg);
+ char digits[32];
+ int len = render_digits(dec.significand, digits);
+ int dot_pos = len + dec.exponent;
+ if (dot_pos < len) {
+ // total fractional digits after '.' includes leading zeros when dot_pos <= 0
+ int avail_frac = len - dot_pos;
+ if (avail_frac > precision) {
+ int drop = avail_frac - precision;
+ if (drop > 0) {
+ if (drop <= pow_10_max) {
+ uint64_t p10 = (uint64_t) POW10[drop];
+ dec.significand = (dec.significand + (p10 / 2)) / p10;
+ dec.exponent += drop;
+ } else {
+ dec.significand = 0;
+ dec.exponent = -precision;
+ }
+ len = render_digits(dec.significand, digits);
+ dot_pos = len + dec.exponent;
+ }
+ }
+ }
+ size_t required = (is_neg && val != 0.0) ? 1 : 0;
+ if (dot_pos <= 0) {
+ required += 1;
+ if (precision > 0) {
+ int leading = -dot_pos;
+ if (leading > precision) {
+ leading = precision;
+ }
+ size_t fractional = (size_t) leading + (size_t) len;
+ required += 1 + fractional;
+ if ((size_t) precision > fractional) {
+ required += (size_t) precision - fractional;
+ }
+ }
+ } else if (dot_pos >= len) {
+ required += (size_t) dot_pos;
+ if (precision > 0) {
+ required += 1 + (size_t) precision;
+ }
+ } else {
+ required += (size_t) len;
+ if (precision > 0) {
+ required += 1;
+ if ((size_t) precision > (size_t) (len - dot_pos)) {
+ required += (size_t) precision - (size_t) (len - dot_pos);
+ }
+ }
+ }
+ if (required >= buf_size) {
+ if (buf_size > 0) {
+ buf[0] = '\0';
+ }
+ return -1;
+ }
+ int p = 0;
+ if (is_neg && val != 0.0) buf[p++] = '-';
+ if (dot_pos <= 0) {
+ buf[p++] = '0';
+ if (precision > 0) {
+ buf[p++] = '.';
+ for (int i = 0; i < -dot_pos && (p - (is_neg ? 3 : 2)) < precision; i++) {
+ buf[p++] = '0';
+ }
+ for (int i = 0; i < len; i++) {
+ buf[p++] = digits[i];
+ }
+ }
+ } else if (dot_pos >= len) {
+ for (int i = 0; i < len; i++) {
+ buf[p++] = digits[i];
+ }
+ for (int i = 0; i < (dot_pos - len); i++) {
+ buf[p++] = '0';
+ }
+ if (precision > 0) {
+ buf[p++] = '.';
+ }
+ } else {
+ for (int i = 0; i < len; i++) {
+ if (i == dot_pos && precision > 0) {
+ buf[p++] = '.';
+ }
+ buf[p++] = digits[i];
+ }
+ }
+ if (precision > 0) {
+ int dot_idx = -1;
+ for (int i = 0; i < p; i++) {
+ if (buf[i] == '.') {
+ dot_idx = i;
+ break;
+ }
+ }
+ if (dot_idx != -1) {
+ int current_frac_digits = p - (dot_idx + 1);
+ for (int i = current_frac_digits; i < precision; i++) {
+ buf[p++] = '0';
+ }
+ }
+ }
+ buf[p] = '\0';
+ return p;
+}
+
+/*tex
+ The rounding formatter.
+*/
+
+int double_to_string_r(double val, char *buf)
+{
+ // fast path for NaN / Inf
+ union { double d; uint64_t u; } bits = { val };
+ uint32_t exp = (bits.u >> 52) & 0x7FF;
+ if (exp == 0x7FF) {
+ if (bits.u & 0x000FFFFFFFFFFFFFULL) {
+ buf[0]='N'; buf[1]='a'; buf[2]='N'; buf[3]='\0';
+ return 3;
+ } else if (bits.u >> 63) {
+ buf[0]='-'; buf[1]='I'; buf[2]='n'; buf[3]='f'; buf[4]='\0';
+ return 4;
+ } else {
+ buf[0]='I'; buf[1]='n'; buf[2]='f'; buf[3]='\0';
+ return 3;
+ }
+ }
+ bool is_neg = (bits.u >> 63) != 0;
+ if (is_neg) {
+ val = -val;
+ }
+ // standard half-up rounding to nearest integer
+ double rounded = val + 0.5;
+ // safe upper bound strictly less than 2^64 (18446744073709551616.0)
+ if (rounded >= 0.0 && rounded < 18446744073709551616.0) {
+ uint64_t uval = (uint64_t) rounded;
+ int p = 0;
+ if (is_neg && uval != 0) {
+ buf[p++] = '-';
+ }
+ p += render_digits(uval, buf + p);
+ return p;
+ }
+ // fallback for extremely large doubles: use double_to_string_f with 0 precision
+ return double_to_string_f(is_neg ? -val : val, buf, 0);
+}
+
+/*tex
+ We need a formatter for money and countries differ wrt command and periods. We also want to
+ seperate thousands. A |string.formatter| that we did ith |lpeg|.
+*/
+
+int double_to_string_m(double val, char *buf, const char *thousand_sep, size_t thousand_sep_len, char decimal_sep)
+{
+ // fast path for NaN / Inf
+ union { double d; uint64_t u; } bits = { val };
+ uint32_t exp = (bits.u >> 52) & 0x7FF;
+ if (exp == 0x7FF) {
+ if (bits.u & 0x000FFFFFFFFFFFFFULL) {
+ buf[0]='N'; buf[1]='a'; buf[2]='N'; buf[3]='\0'; return 3;
+ } else if (bits.u >> 63) {
+ buf[0]='-'; buf[1]='I'; buf[2]='n'; buf[3]='f'; buf[4]='\0'; return 4;
+ } else {
+ buf[0]='I'; buf[1]='n'; buf[2]='f'; buf[3]='\0'; return 3;
+ }
+ }
+ bool is_neg = (bits.u >> 63) != 0;
+ if (is_neg) {
+ val = -val;
+ }
+ // round to 2 decimal places: val * 100 + 0.5 but beyond 2^53 we let the c library do that
+ double scaled = val * 100.0 + 0.5;
+ char raw_digits[320];
+ int raw_len;
+ uint32_t frac;
+ if (scaled < 9007199254740992.0) {
+ uint64_t cents = (uint64_t) scaled;
+ raw_len = render_digits(cents / 100, raw_digits);
+ frac = (uint32_t) (cents % 100);
+ } else {
+ // at most 309 digits, a period and two decimals
+ raw_len = snprintf(raw_digits, sizeof(raw_digits), "%.2f", val) - 3;
+ frac = (uint32_t) ((raw_digits[raw_len + 1] - '0') * 10 + (raw_digits[raw_len + 2] - '0'));
+ }
+ int p = 0;
+ if (is_neg && (raw_len > 1 || raw_digits[0] != '0' || frac != 0)) {
+ buf[p++] = '-';
+ }
+ // insert thousands separators during integer rendering
+ for (int i = 0; i < raw_len; i++) {
+ int remaining = raw_len - i;
+ if (i > 0 && (remaining % 3 == 0)) {
+ memcpy(buf + p, thousand_sep, thousand_sep_len);
+ p += thousand_sep_len;
+ }
+ buf[p++] = raw_digits[i];
+ }
+ // append decimal separator and 2 fixed decimal places
+ buf[p++] = decimal_sep;
+ buf[p++] = DIGIT_TABLE[frac * 2];
+ buf[p++] = DIGIT_TABLE[frac * 2 + 1];
+ buf[p] = '\0';
+ return p;
+}
+
+/*tex
+ Another formatter turned C, this time integer thousands seperators.
+*/
+
+int integer_to_string_v(lua_Integer val, char *buf, const char *thousand_sep, size_t thousand_sep_len)
+{
+ bool is_neg = (val < 0);
+ uint64_t uval = is_neg ? (uint64_t)(-(val + 1)) + 1 : (uint64_t)val;
+ char raw_digits[32];
+ int raw_len = render_digits(uval, raw_digits);
+ int p = 0;
+ if (is_neg) {
+ buf[p++] = '-';
+ }
+ for (int i = 0; i < raw_len; i++) {
+ int remaining = raw_len - i;
+ if (i > 0 && (remaining % 3 == 0)) {
+ memcpy(buf + p, thousand_sep, thousand_sep_len);
+ p += thousand_sep_len;
+ }
+ buf[p++] = raw_digits[i];
+ }
+ buf[p] = '\0';
+ return p;
+}
+
+/*tex
+ This is the |string.formatters| lpeg turned into C.
+*/
+
+int double_to_string_j(double val, char *dest, size_t dest_size, char exp_char, int req_prec)
+{
+ if (dest_size == 0) {
+ return -1;
+ }
+ req_prec = normalize_decimal_precision(req_prec);
+ /* we format in place (the caller has room for the precision) so we can only get shorter */
+ int len = snprintf(dest, dest_size, "%.*e", req_prec, val);
+ if (len <= 0 || (size_t) len >= dest_size) {
+ dest[0] = '\0';
+ return -1;
+ }
+ /* find decimal point and exponent marker, without the latter we have inf or nan */
+ char *dot = strchr(dest, '.');
+ char *exp = strchr(dest, 'e');
+ if (! exp) {
+ return len;
+ }
+ /* parse exponent part (e.g. "+004", "-005", "+000") */
+ char *e_ptr = exp + 1;
+ int sign = 1;
+ if (*e_ptr == '+') {
+ sign = 1;
+ e_ptr++;
+ } else if (*e_ptr == '-') {
+ sign = -1;
+ e_ptr++;
+ }
+ int exp_val = 0;
+ while (*e_ptr >= '0' && *e_ptr <= '9') {
+ exp_val = (exp_val * 10) + (*e_ptr - '0');
+ e_ptr++;
+ }
+ /* trim trailing zeros between '.' and 'e', and the decimal point if all fractional digits were zero */
+ char *end = exp;
+ if (dot) {
+ while (end - 1 > dot && end[-1] == '0') {
+ end--;
+ }
+ if (end - 1 == dot) {
+ end--;
+ }
+ }
+ /* append sparse exponent only if exp_val != 0 */
+ if (exp_val != 0) {
+ *end++ = exp_char;
+ if (sign < 0) {
+ *end++ = '-';
+ }
+ end += snprintf(end, dest_size - (size_t) (end - dest), "%d", exp_val);
+ }
+ *end = '\0';
+ return (int) (end - dest);
+}
diff --git a/source/luametatex/source/utilities/auxserialize.h b/source/luametatex/source/utilities/auxserialize.h
new file mode 100644
index 000000000..376ccdbb7
--- /dev/null
+++ b/source/luametatex/source/utilities/auxserialize.h
@@ -0,0 +1,19 @@
+/*
+ See license.txt in the root of this project.
+*/
+
+# ifndef LMT_UTILITIES_SERIALIZE_H
+# define LMT_UTILITIES_SERIALIZE_H
+
+# include <lua.h>
+
+extern int double_to_string_f (double val, char *buf, int n);
+extern int double_to_string_g (double val, char *buf, int n);
+extern int double_to_string_z (double val, char *buf, size_t buf_size, int n);
+extern int double_to_string_r (double val, char *buf);
+extern int double_to_string_m (double val, char *buf, const char *thousand_sep, size_t thousand_sep_len, char decimal_sep);
+extern int double_to_string_j (double val, char *dest, size_t dest_size, char exp_char, int req_prec);
+
+extern int integer_to_string_v (lua_Integer val, char *buf, const char *thousand_sep, size_t thousand_sep_len);
+
+# endif
diff --git a/source/luametatex/source/utilities/auxunistring.c b/source/luametatex/source/utilities/auxunistring.c
index fa24f85e4..e3ea099e2 100644
--- a/source/luametatex/source/utilities/auxunistring.c
+++ b/source/luametatex/source/utilities/auxunistring.c
@@ -6,89 +6,66 @@
/*tex
- The 5- and 6-byte UTF-8 sequences generate integers that are outside of the valid UCS range,
- and therefore unsupported. We recover from an error with |0xFFFD|.
+ Invalid UTF-8 sequences and values outside the Unicode scalar range are unsupported. We recover
+ from an error with |0xFFFD|.
*/
-unsigned aux_str2uni(const unsigned char *text)
+static inline int aux_is_utf8_follow(unsigned char c)
{
- if (text[0] < 0x80) {
- return (unsigned) text[0];
- } else if (text[0] <= 0xBF) {
- return 0xFFFD;
- } else if (text[0] <= 0xDF) {
- if (text[1] >= 0x80 && text[1] < 0xC0) {
- return (unsigned) (((text[0] & 0x1F) << 6) | (text[1] & 0x3F));
- } else {
- return 0xFFFD;
- }
- } else if (text[0] <= 0xEF) {
- if (text[1] >= 0x80 && text[1] < 0xC0 && text[2] >= 0x80 && text[2] < 0xC0) {
- return (unsigned) (((text[0] & 0xF) << 12) | ((text[1] & 0x3F) << 6) | (text[2] & 0x3F));
- } else {
- return 0xFFFD;
- }
- } else if (text[0] <= 0xF7) {
- if (text[1] < 0x80 || text[2] < 0x80 || text[3] < 0x80 ||
- text[1] >= 0xC0 || text[2] >= 0xC0 || text[3] >= 0xC0) {
- return 0xFFFD;
- } else {
- int w1 = (((text[0] & 0x7) << 2) | ((text[1] & 0x30) >> 4)) - 1;
- int w2 = ((text[2] & 0xF) << 6) | (text[3] & 0x3F);
- w1 = (w1 << 6) | ((text[1] & 0xF) << 2) | ((text[2] & 0x30) >> 4);
- return (unsigned) (w1 * 0x400 + w2 + 0x10000);
- }
- }
- return 0xFFFD;
+ return c >= 0x80 && c <= 0xBF;
}
-unsigned aux_str2uni_len(const unsigned char *text, int *len)
+static inline unsigned aux_normalize_unicode(unsigned unic)
{
- if (text[0] < 0x80) {
- *len = 1;
- return (unsigned) text[0];
- } else if (text[0] <= 0xBF) {
- *len = 1;
+ return unic <= 0x10FFFF && !(unic >= 0xD800 && unic <= 0xDFFF) ? unic : 0xFFFD;
+}
+
+unsigned aux_str2uni_len(const unsigned char *text, size_t size, int *len)
+{
+ unsigned char first;
+
+ if (size == 0) {
+ *len = 0;
return 0xFFFD;
- } else if (text[0] <= 0xDF) {
- if (text[1] >= 0x80 && text[1] < 0xC0) {
+ }
+ first = text[0];
+ if (first < 0x80) {
+ *len = 1;
+ return (unsigned) first;
+ } else if (first >= 0xC2 && first <= 0xDF) {
+ if (size >= 2 && aux_is_utf8_follow(text[1])) {
*len = 2;
- return (unsigned) (((text[0] & 0x1F) << 6) | (text[1] & 0x3F));
- } else {
- *len = 1;
- return 0xFFFD;
+ return (unsigned) (((first & 0x1F) << 6) | (text[1] & 0x3F));
}
- } else if (text[0] <= 0xEF) {
- if (text[1] >= 0x80 && text[1] < 0xC0 && text[2] >= 0x80 && text[2] < 0xC0) {
+ } else if (first >= 0xE0 && first <= 0xEF) {
+ if (size >= 3 && aux_is_utf8_follow(text[1]) && aux_is_utf8_follow(text[2]) &&
+ ! (first == 0xE0 && text[1] < 0xA0) && !(first == 0xED && text[1] >= 0xA0)) {
*len = 3;
- return (unsigned) (((text[0] & 0xF) << 12) | ((text[1] & 0x3F) << 6) | (text[2] & 0x3F));
- } else {
- *len = 1;
- return 0xFFFD;
+ return (unsigned) (((first & 0x0F) << 12) | ((text[1] & 0x3F) << 6) | (text[2] & 0x3F));
}
- } else if (text[0] <= 0xF7) {
- if (text[1] < 0x80 || text[2] < 0x80 || text[3] < 0x80 ||
- text[1] >= 0xC0 || text[2] >= 0xC0 || text[3] >= 0xC0) {
- *len = 4;
- return 0xFFFD;
- } else {
- int w1 = (((text[0] & 0x7) << 2) | ((text[1] & 0x30) >> 4)) - 1;
- int w2 = ((text[2] & 0xF) << 6) | (text[3] & 0x3F);
- w1 = (w1 << 6) | ((text[1] & 0xF) << 2) | ((text[2] & 0x30) >> 4);
+ } else if (first >= 0xF0 && first <= 0xF4) {
+ if (size >= 4 && aux_is_utf8_follow(text[1]) && aux_is_utf8_follow(text[2]) && aux_is_utf8_follow(text[3]) &&
+ ! (first == 0xF0 && text[1] < 0x90) && !(first == 0xF4 && text[1] > 0x8F)) {
*len = 4;
- return (unsigned) (w1 * 0x400 + w2 + 0x10000);
+ return (unsigned) (((first & 0x07) << 18) | ((text[1] & 0x3F) << 12) | ((text[2] & 0x3F) << 6) | (text[3] & 0x3F));
}
- } else {
- *len = 1;
- return 0xFFFD;
}
+ *len = 1;
+ return 0xFFFD;
+}
+
+unsigned aux_str2uni(const unsigned char *text)
+{
+ int len;
+ return aux_str2uni_len(text, 4, &len);
}
unsigned char *aux_uni2str(unsigned unic)
{
unsigned char *buf = lmt_memory_malloc(5);
if (buf) {
+ unic = aux_normalize_unicode(unic);
if (unic < 0x80) {
buf[0] = (unsigned char) unic;
buf[1] = '\0';
@@ -97,28 +74,55 @@ unsigned char *aux_uni2str(unsigned unic)
buf[1] = (unsigned char) (0x80 | (unic & 0x3F));
buf[2] = '\0';
} else if (unic < 0x10000) {
- buf[0] = (unsigned char) (0xE0 | (unic >> 12));
- buf[1] = (unsigned char) (0x80 | ((unic >> 6) & 0x3F));
- buf[2] = (unsigned char) (0x80 | (unic & 0x3F));
+ buf[0] = (unsigned char) (0xE0 | (unic >> 12));
+ buf[1] = (unsigned char) (0x80 | ((unic >> 6) & 0x3F));
+ buf[2] = (unsigned char) (0x80 | (unic & 0x3F));
buf[3] = '\0';
} else if (unic < 0x110000) {
- int u;
- unic -= 0x10000;
- u = (int) (((unic & 0xF0000) >> 16) + 1);
- buf[0] = (unsigned char) (0xF0 | (u >> 2));
- buf[1] = (unsigned char) (0x80 | ((u & 3) << 4) | ((unic & 0xF000) >> 12));
- buf[2] = (unsigned char) (0x80 | ((unic & 0xFC0) >> 6));
- buf[3] = (unsigned char) (0x80 | (unic & 0x3F));
+ buf[0] = (unsigned char) (0xF0 | (unic >> 18));
+ buf[1] = (unsigned char) (0x80 | ((unic >> 12) & 0x3F));
+ buf[2] = (unsigned char) (0x80 | ((unic >> 6) & 0x3F));
+ buf[3] = (unsigned char) (0x80 | (unic & 0x3F));
buf[4] = '\0';
- } else {
- buf[0] = '\0';
}
}
return buf;
}
+int aux_uni2strlen(unsigned unic, char *buf)
+{
+ unic = aux_normalize_unicode(unic);
+ if (unic < 0x80) {
+ buf[0] = (unsigned char) unic;
+ buf[1] = '\0';
+ return 1;
+ } else if (unic < 0x800) {
+ buf[0] = (unsigned char) (0xC0 | (unic >> 6));
+ buf[1] = (unsigned char) (0x80 | (unic & 0x3F));
+ buf[2] = '\0';
+ return 2;
+ } else if (unic < 0x10000) {
+ buf[0] = (unsigned char) (0xE0 | (unic >> 12));
+ buf[1] = (unsigned char) (0x80 | ((unic >> 6) & 0x3F));
+ buf[2] = (unsigned char) (0x80 | (unic & 0x3F));
+ buf[3] = '\0';
+ return 3;
+ } else if (unic < 0x110000) {
+ buf[0] = (unsigned char) (0xF0 | (unic >> 18));
+ buf[1] = (unsigned char) (0x80 | ((unic >> 12) & 0x3F));
+ buf[2] = (unsigned char) (0x80 | ((unic >> 6) & 0x3F));
+ buf[3] = (unsigned char) (0x80 | (unic & 0x3F));
+ buf[4] = '\0';
+ return 4;
+ } else {
+ buf[0] = '\0';
+ return 0;
+ }
+}
+
void aux_uni2str_callback(unsigned unic, void (*handle) (int))
{
+ unic = aux_normalize_unicode(unic);
if (unic < 0x80) {
handle((unsigned char) unic);
} else if (unic < 0x800) {
@@ -129,13 +133,10 @@ void aux_uni2str_callback(unsigned unic, void (*handle) (int))
handle((unsigned char) (0x80 | ((unic >> 6) & 0x3F)));
handle((unsigned char) (0x80 | (unic & 0x3F)));
} else if (unic < 0x110000) {
- int u;
- unic -= 0x10000;
- u = (int) (((unic & 0xF0000) >> 16) + 1);
- handle((unsigned char) (0xF0 | (u >> 2)));
- handle((unsigned char) (0x80 | ((u & 3) << 4) | ((unic & 0xF000) >> 12)));
- handle((unsigned char) (0x80 | ((unic & 0xFC0) >> 6)));
- handle((unsigned char) (0x80 | (unic & 0x3F)));
+ handle((unsigned char) (0xF0 | (unic >> 18)));
+ handle((unsigned char) (0x80 | ((unic >> 12) & 0x3F)));
+ handle((unsigned char) (0x80 | ((unic >> 6) & 0x3F)));
+ handle((unsigned char) (0x80 | (unic & 0x3F)));
}
}
@@ -150,6 +151,7 @@ void aux_uni2str_callback(unsigned unic, void (*handle) (int))
char *aux_uni2string(char *utf8_text, unsigned unic)
{
+ unic = aux_normalize_unicode(unic);
/*tex Increment and deposit character: */
if (unic <= 0x7F) {
*utf8_text++ = (char) unic;
@@ -161,13 +163,10 @@ char *aux_uni2string(char *utf8_text, unsigned unic)
*utf8_text++ = (char) (0x80 | ((unic >> 6) & 0x3F));
*utf8_text++ = (char) (0x80 | (unic & 0x3F));
} else if (unic < 0x110000) {
- unsigned u;
- unic -= 0x10000;
- u = ((unic & 0xF0000) >> 16) + 1;
- *utf8_text++ = (char) (0xF0 | (u >> 2));
- *utf8_text++ = (char) (0x80 | ((u & 3) << 4) | ((unic & 0xF000) >> 12));
- *utf8_text++ = (char) (0x80 | ((unic & 0xFC0) >> 6));
- *utf8_text++ = (char) (0x80 | (unic & 0x3F));
+ *utf8_text++ = (char) (0xF0 | (unic >> 18));
+ *utf8_text++ = (char) (0x80 | ((unic >> 12) & 0x3F));
+ *utf8_text++ = (char) (0x80 | ((unic >> 6) & 0x3F));
+ *utf8_text++ = (char) (0x80 | (unic & 0x3F));
}
return utf8_text;
}
@@ -176,33 +175,15 @@ char *aux_uni2string(char *utf8_text, unsigned unic)
unsigned aux_splitutf2uni(unsigned int *ubuf, const char *utf8buf)
{
- int len = (int) strlen(utf8buf);
+ size_t len = strlen(utf8buf);
unsigned int *upt = ubuf;
unsigned int *uend = ubuf + len;
const unsigned char *pt = (const unsigned char *) utf8buf;
const unsigned char *end = pt + len;
- while (pt < end && *pt != '\0' && upt < uend) {
- /*
- if (*pt <= 0x7F) {
- *upt = *pt++;
- } else if (*pt <= 0xDF) {
- *upt = (unsigned int) (((*pt & 0x1F) << 6) | (pt[1] & 0x3F));
- pt += 2;
- } else if (*pt <= 0xEF) {
- *upt = (unsigned int) (((*pt & 0xF) << 12) | ((pt[1] & 0x3F) << 6) | (pt[2] & 0x3F));
- pt += 3;
- } else {
- int w1 = (((*pt & 0x7) << 2) | ((pt[1] & 0x30) >> 4)) - 1;
- int w2 = ((pt[2] & 0xF) << 6) | (pt[3] & 0x3F);
- w1 = (w1 << 6) | ((pt[1] & 0xF) << 2) | ((pt[2] & 0x30) >> 4);
- *upt = (unsigned int) (w1 * 0x400 + w2 + 0x10000);
- pt += 4;
- }
- ++upt;
- */
+ while (pt < end && upt < uend) {
int ulen;
- *upt = aux_str2uni_len(pt, &ulen);
- pt += ulen;
+ *upt = aux_str2uni_len(pt, (size_t) (end - pt), &ulen);
+ pt += (size_t) ulen;
++upt;
}
*upt = 0; /*tex We have integers here, so assigning |\0| is a bit misleading. */
@@ -214,19 +195,72 @@ size_t aux_utf8len(const char *text, size_t size)
size_t ind = 0;
size_t num = 0;
while (ind < size) {
- unsigned char i = (unsigned char) *(text + ind);
- if (i < 0x80) {
- ind += 1;
- } else if (i >= 0xF0) {
- ind += 4;
- } else if (i >= 0xE0) {
- ind += 3;
- } else if (i >= 0xC0) {
- ind += 2;
- } else {
- ind += 1;
- }
+ int len;
+ aux_str2uni_len((const unsigned char *) text + ind, size - ind, &len);
+ ind += (size_t) len;
num += 1;
}
return num;
}
+
+/*tex
+ We can process 8 bytes at a time on 64-bit architectures. The memcpy is needed because
+ we dont operate with (aligned) copies on the stack so we need to obey strict alignment
+ conditions. We use the fact that > 127 means one bit is set. And the accumulator check
+ does that for 8 bytes at once.
+
+ Checking inside the loop gives bad branch prediction and we seldom have a hit and
+ compilers will optimize this kind of loops anyway.
+
+*/
+
+# ifdef _MSC_VER
+ # define fast_memcpy(dest, src, count) memcpy(dest, src, count)
+# else
+ # define fast_memcpy(dest, src, count) __builtin_memcpy(dest, src, count)
+# endif
+
+/*tex
+
+ As we can apply this to whole files chunking makes more sense, so we add an extra outer
+ loop. As usual this one went through a few steps, like figuring out how to optimize for
+ small strings.
+
+*/
+
+inline int aux_onlyascii(const char *str, size_t len)
+{
+
+ if (! str) {
+ return 0;
+ }
+
+ const unsigned char *s = (const unsigned char *) str;
+
+ size_t i = 0;
+ uint64_t acc = 0;
+
+ /* fast (8 byte) word loop (automatically skipped if len < 8) */
+
+ for (; i + 8 <= len; i += 8) {
+ uint64_t chunk;
+ fast_memcpy(&chunk, s + i, 8);
+ acc |= chunk;
+ }
+
+ /* set initial status based on the accumulator */
+
+ if ((acc & 0x8080808080808080ULL) != 0) {
+ return 0;
+ }
+
+ /* only check the remainder (< 8 bytes) if the main chunks were clean */
+
+ for (; i < len; i++) {
+ if (s[i] > 127) {
+ return 0;
+ }
+ }
+
+ return 1;
+} \ No newline at end of file
diff --git a/source/luametatex/source/utilities/auxunistring.h b/source/luametatex/source/utilities/auxunistring.h
index 4e2f4cdee..56bf0f7f9 100644
--- a/source/luametatex/source/utilities/auxunistring.h
+++ b/source/luametatex/source/utilities/auxunistring.h
@@ -6,15 +6,33 @@
# define LMT_UTILITIES_UNISTRING_H
extern unsigned char *aux_uni2str (unsigned unic);
+extern int aux_uni2strlen (unsigned unic, char *buf);
extern void aux_uni2str_callback(unsigned unic, void (*handle) (int));
extern unsigned aux_str2uni (const unsigned char *text);
-extern unsigned aux_str2uni_len (const unsigned char *text, int *len);
+extern unsigned aux_str2uni_len (const unsigned char *text, size_t size, int *len);
extern char *aux_uni2string (char *utf8_text, unsigned ch);
extern unsigned aux_splitutf2uni (unsigned int *ubuf, const char *utf8buf);
extern size_t aux_utf8len (const char *text, size_t size);
+extern int aux_onlyascii (const char *str, size_t len);
# define is_utf8_follow(a) (a >= 0x80 && a < 0xC0)
-# define utf8_size(a) (a > 0xFFFF ? 4 : (a > 0x7FF ? 3 : (a > 0x7F ? 2 : 1)))
+
+static inline unsigned aux_utf8_size(unsigned a)
+{
+ if (a > 0x10FFFF || (a >= 0xD800 && a <= 0xDFFF)) {
+ return 3;
+ } else if (a > 0xFFFF) {
+ return 4;
+ } else if (a > 0x7FF) {
+ return 3;
+ } else if (a > 0x7F) {
+ return 2;
+ } else {
+ return 1;
+ }
+}
+
+# define utf8_size(a) aux_utf8_size((unsigned) (a))
# define buffer_to_unichar(k) aux_str2uni((const unsigned char *)(lmt_fileio_state.io_buffer+k))
# endif