Skip to content

Commit b36e831

Browse files
committed
Added predefinded macros @@Assert() and @@log().
Added params.release and params.logLevel. CL: Added --release and --loglevel options.
1 parent 2d5ecf3 commit b36e831

File tree

4 files changed

+132
-8
lines changed

4 files changed

+132
-8
lines changed

preprocess-cl.lua

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,11 @@ exec lua "$0" "$@"
6161
--linenumbers
6262
Add comments with line numbers to the output.
6363
64+
--loglevel=levelName
65+
Set maximum log level for the @@LOG() macro. Can be "off",
66+
"error", "warning", "info", "debug" or "trace". The default is
67+
"trace", which enables all logging.
68+
6469
--macroprefix=prefix
6570
String to prepend to macro names.
6671
@@ -92,6 +97,9 @@ exec lua "$0" "$@"
9297
This flag makes every other specified path be the output path
9398
for the previous path.
9499
100+
--release
101+
Enable release mode. Currently only disables the @@ASSERT() macro.
102+
95103
--saveinfo|-i=pathToSaveProcessingInfoTo
96104
Processing information includes what files had any preprocessor
97105
code in them, and things like that. The format of the file is a
@@ -192,6 +200,8 @@ local silent = false
192200
local validate = true
193201
local macroPrefix = ""
194202
local macroSuffix = ""
203+
local releaseMode = false
204+
local maxLogLevel = "trace"
195205

196206
--==============================================================
197207
--= Local Functions ============================================
@@ -344,6 +354,12 @@ for _, arg in ipairs(args) do
344354
elseif arg:find"^%-%-macrosuffix=" then
345355
macroSuffix = arg:gsub("^.-=", "")
346356

357+
elseif arg == "--release" then
358+
releaseMode = true
359+
360+
elseif arg:find"^%-%-loglevel=" then
361+
maxLogLevel = arg:gsub("^.-=", "")
362+
347363
else
348364
errorLine("Unknown option '"..arg:gsub("=.*", "").."'.")
349365
end
@@ -506,6 +522,9 @@ for i, pathIn in ipairs(pathsIn) do
506522
macroPrefix = macroPrefix,
507523
macroSuffix = macroSuffix,
508524

525+
release = releaseMode,
526+
logLevel = maxLogLevel,
527+
509528
onInsert = (hasMessageHandler("insert") or nil) and function(name)
510529
local lua = sendMessage("insert", pathIn, name)
511530

preprocess.lua

Lines changed: 97 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@
2727
- getOutputSoFar, getOutputSizeSoFar, getCurrentLineNumberInOutput
2828
- outputValue, outputLua, outputLuaTemplate
2929
- startInterceptingOutput, stopInterceptingOutput
30+
Macros (search for 'PredefinedMacros'):
31+
- ASSERT
32+
- LOG
3033
Search this file for 'EnvironmentTable' for more info.
3134
3235
Exported stuff from the library:
@@ -167,6 +170,15 @@ local ESCAPE_SEQUENCES = {
167170

168171
local USELESS_TOKENS = {whitespace=true, comment=true}
169172

173+
local LOG_LEVELS = {
174+
["off"] = 0,
175+
["error"] = 1,
176+
["warning"] = 2,
177+
["info"] = 3,
178+
["debug"] = 4,
179+
["trace"] = 5,
180+
}
181+
170182
local major, minor = _VERSION:match"Lua (%d+)%.(%d+)"
171183
if not major then
172184
io.stderr:write("[LuaPreprocess] Warning: Could not detect Lua version.\n")
@@ -181,7 +193,8 @@ local IS_LUA_51_OR_LATER = (major == 5 and minor >= 1) or (major ~= nil and majo
181193
local IS_LUA_52_OR_LATER = (major == 5 and minor >= 2) or (major ~= nil and major > 5)
182194
local IS_LUA_53_OR_LATER = (major == 5 and minor >= 3) or (major ~= nil and major > 5)
183195

184-
local metaEnv = nil
196+
local metaEnv = nil
197+
local dummyEnv = {}
185198

186199
local isDebug = false -- Controlled by processFileOrString().
187200

@@ -195,6 +208,8 @@ local canOutputNil = true
195208
local fastStrings = false
196209
local macroPrefix = ""
197210
local macroSuffix = ""
211+
local releaseMode = false
212+
local maxLogLevel = "trace"
198213

199214

200215

@@ -1854,6 +1869,71 @@ function metaFuncs.stopInterceptingOutput()
18541869
return table.concat(interceptedLua)
18551870
end
18561871

1872+
-- :PredefinedMacros
1873+
1874+
-- ASSERT()
1875+
-- @@ASSERT( condition [, message=auto ] )
1876+
-- Macro. Does nothing if params.release is set, otherwise calls error() if
1877+
-- the condition fails. The message is only evaluated if the condition fails.
1878+
function metaFuncs.ASSERT(conditionCode, messageCode)
1879+
errorIfNotRunningMeta(2)
1880+
if not conditionCode then error("missing argument #1 to 'ASSERT'", 2) end
1881+
1882+
if releaseMode then return end
1883+
1884+
tableInsert(outputFromMeta, "if not (")
1885+
tableInsert(outputFromMeta, conditionCode)
1886+
tableInsert(outputFromMeta, ") then error(")
1887+
1888+
if messageCode then
1889+
tableInsert(outputFromMeta, "(")
1890+
tableInsert(outputFromMeta, messageCode)
1891+
tableInsert(outputFromMeta, ")")
1892+
else
1893+
tableInsert(outputFromMeta, F("%q", "Assertion failed: "..conditionCode))
1894+
end
1895+
1896+
tableInsert(outputFromMeta, ") end")
1897+
end
1898+
1899+
-- LOG()
1900+
-- @@LOG( logLevel, value ) -- [1]
1901+
-- @@LOG( logLevel, format, value1, ... ) -- [2]
1902+
--
1903+
-- Macro. Does nothing if logLevel is lower than params.logLevel,
1904+
-- otherwise prints a value[1] or a formatted message[2].
1905+
--
1906+
-- logLevel can be "error" (level 1), "warning" (level 2),
1907+
-- "info" (level 3), "debug" (level 4) or "trace" (level 5).
1908+
--
1909+
function metaFuncs.LOG(logLevelCode, valueOrFormatCode, ...)
1910+
errorIfNotRunningMeta(2)
1911+
if not logLevelCode then error("missing argument #1 to 'LOG'", 2) end
1912+
if not valueOrFormatCode then error("missing argument #2 to 'LOG'", 2) end
1913+
1914+
local chunk = loadLuaString("return _,"..logLevelCode, "@", dummyEnv)
1915+
if not chunk then errorf(2, "Invalid logLevel expression. Got: %s", logLevelCode) end
1916+
1917+
local ok, _, logLevel = pcall(chunk)
1918+
if not ok then errorf(2, "logLevel must be a constant expression. Got: %s", logLevelCode) end
1919+
if not LOG_LEVELS[logLevel] then errorf(2, "Invalid logLevel '%s'.", tostring(logLevel)) end
1920+
if logLevel == "off" then errorf(2, "Invalid logLevel '%s'.", tostring(logLevel)) end
1921+
1922+
if LOG_LEVELS[logLevel] > LOG_LEVELS[maxLogLevel] then return end
1923+
1924+
tableInsert(outputFromMeta, "print(")
1925+
1926+
if ... then
1927+
tableInsert(outputFromMeta, "string.format(")
1928+
tableInsert(outputFromMeta, table.concat({valueOrFormatCode, ...}, ", "))
1929+
tableInsert(outputFromMeta, ")")
1930+
else
1931+
tableInsert(outputFromMeta, valueOrFormatCode)
1932+
end
1933+
1934+
tableInsert(outputFromMeta, ")")
1935+
end
1936+
18571937
-- Extra stuff used by the command line program:
18581938
metaFuncs.tryToFormatError = tryToFormatError
18591939

@@ -3046,6 +3126,12 @@ local function _processFileOrString(params, isFile)
30463126
outputFromMetaStack = {outputFromMeta}
30473127
canOutputNil = params.canOutputNil ~= false
30483128
fastStrings = params.fastStrings
3129+
releaseMode = params.release
3130+
maxLogLevel = params.logLevel or "trace"
3131+
3132+
if not LOG_LEVELS[maxLogLevel] then
3133+
errorf(2, "Invalid 'logLevel' value in params. (%s)", maxLogLevel)
3134+
end
30493135

30503136
if params.pathMeta then
30513137
local file = assert(io.open(params.pathMeta, "wb"))
@@ -3084,6 +3170,8 @@ local function _processFileOrString(params, isFile)
30843170
outputFromMetaStack = nil
30853171
outputFromMeta = nil
30863172
canOutputNil = true
3173+
releaseMode = false
3174+
maxLogLevel = "trace"
30873175

30883176
if params.onAfterMeta then
30893177
local luaModified = params.onAfterMeta(lua)
@@ -3194,6 +3282,8 @@ local function processFileOrString(params, isFile)
31943282
fastStrings = false
31953283
macroPrefix = ""
31963284
macroSuffix = ""
3285+
releaseMode = false
3286+
maxLogLevel = "trace"
31973287

31983288
if xpcallOk then
31993289
return unpack(returnValues, 1, returnValues.n)
@@ -3245,6 +3335,9 @@ local pp = {
32453335
-- macroPrefix = prefix -- [Optional] String to prepend to macro names. (Default: "")
32463336
-- macroSuffix = suffix -- [Optional] String to append to macro names. (Default: "")
32473337
--
3338+
-- release = boolean -- [Optional] Enable release mode. Currently only disables the @@ASSERT() macro when true. (Default: false)
3339+
-- logLevel = levelName -- [Optional] Maximum log level for the @@LOG() macro. Can be "off", "error", "warning", "info", "debug" or "trace". (Default: "trace", which enables all logging)
3340+
--
32483341
-- onInsert = function( name ) -- [Optional] Called for each @insert"name" instruction. It's expected to return a Lua code string. By default 'name' is a path to a file to be inserted.
32493342
-- onBeforeMeta = function( ) -- [Optional] Called before the metaprogram runs.
32503343
-- onAfterMeta = function( luaString ) -- [Optional] Here you can modify and return the Lua code before it's written to 'pathOut'.
@@ -3274,6 +3367,9 @@ local pp = {
32743367
-- macroPrefix = prefix -- [Optional] String to prepend to macro names. (Default: "")
32753368
-- macroSuffix = suffix -- [Optional] String to append to macro names. (Default: "")
32763369
--
3370+
-- release = boolean -- [Optional] Enable release mode. Currently only disables the @@ASSERT() macro when true. (Default: false)
3371+
-- logLevel = levelName -- [Optional] Maximum log level for the @@LOG() macro. Can be "off", "error", "warning", "info", "debug" or "trace". (Default: "trace", which enables all logging)
3372+
--
32773373
-- onInsert = function( name ) -- [Optional] Called for each @insert"name" instruction. It's expected to return a Lua code string. By default 'name' is a path to a file to be inserted.
32783374
-- onBeforeMeta = function( ) -- [Optional] Called before the metaprogram runs.
32793375
-- onError = function( error ) -- [Optional] You can use this to get traceback information. 'error' is the same value as the second returned value from processString().

tests/quickTest.lua2p

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -97,22 +97,22 @@ print("Final program - uhh: "..uhh1..", "..uhh2)
9797
!(
9898
local DEBUG = 1==1
9999

100-
local function ASSERT(cond, message)
100+
local function MY_ASSERT(cond, message)
101101
if not DEBUG then return "" end
102102

103-
message = message or "'Asertion failed!'"
103+
message = message or "'Assertion failed!'"
104104

105105
return "if not ("..cond..") then error("..message..") end"
106106
end
107107
)
108108

109109
local ok = 1==1
110110

111-
@insert ASSERT ( ok , "Oh "..tonumber("7",10).." noes!" )
112-
-- @insert ASSERT ( 1 1 ) -- Syntax error!
113-
-- @insert ASSERT ( ok , ) -- Syntax error!
114-
-- @insert ASSERT ( , ok ) -- Syntax error!
115-
-- @insert ASSERT ( --[[]] , ok ) -- Syntax error!
111+
@insert MY_ASSERT ( ok , "Oh "..tonumber("7",10).." noes!" )
112+
-- @insert MY_ASSERT ( 1 1 ) -- Syntax error!
113+
-- @insert MY_ASSERT ( ok , ) -- Syntax error!
114+
-- @insert MY_ASSERT ( , ok ) -- Syntax error!
115+
-- @insert MY_ASSERT ( --[[]] , ok ) -- Syntax error!
116116

117117
!local function PASS_THROUGH(lua) return lua end
118118
local s = @insert PASS_THROUGH "foo"
@@ -156,6 +156,13 @@ other = 500921
156156

157157

158158

159+
-- Predefined macros.
160+
@@ASSERT(1 < 2)
161+
@@LOG("warning", "Things may be bad - who knows!?")
162+
@@LOG("info", "%s number %d", "foo", 5)
163+
164+
165+
159166
-- Symbols.
160167
!local RANDOM = "math.random()"
161168
local rand = $RANDOM

tests/runQuickTest.cmd

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ IF NOT EXIST local MD local
66
lua ./preprocess-cl.lua --debug --saveinfo=local/info.lua --data="Hello, world!" tests/quickTest.lua2p
77
REM lua ./preprocess-cl.lua --debug --saveinfo=local/info.lua --data="Hello, world!" tests/quickTest.lua2p --backtickstrings
88
REM lua ./preprocess-cl.lua --debug --saveinfo=local/info.lua --data="Hello, world!" tests/quickTest.lua2p --linenumbers
9+
REM lua ./preprocess-cl.lua --debug --saveinfo=local/info.lua --data="Hello, world!" tests/quickTest.lua2p --release
10+
REM lua ./preprocess-cl.lua --debug --saveinfo=local/info.lua --data="Hello, world!" tests/quickTest.lua2p --loglevel=warning
911

1012
REM lua ./preprocess-cl.lua --debug --saveinfo=local/info.lua --data="Hello, world!" --outputpaths tests/quickTest.lua2p local/quickTest.output.lua
1113
REM lua ./preprocess-cl.lua --debug --saveinfo=local/info.lua --data="Hello, world!" --outputpaths tests/quickTest.lua2p local/quickTest.output.lua --linenumbers

0 commit comments

Comments
 (0)