Page 1 of 1

Improve Macro Handling with MacroIf and MacroParam()

Posted: Sat Nov 21, 2015 12:01 pm
by c4s
Can we please have macros that are just a tiny little bit more intelligent? I'm talking about two simple but powerful missing features (that are processed before the macro gets expanded):
  • MacroParam(): Tests if a parameter is set (see discussion here for something that doesn't work with strings).
  • MacroIf: Macros are processed with highest priority so to control its behavior even CompilerIf won't work. However in certain cases this is necessary, e.g. to be able to simulate a return type (see example below).

The context is that I'm desperately trying to make something like the following work (and in the past I came across variations several times). Unfortunately there are a couple of problems:

Code: Select all

Macro _Quote
	"
EndMacro
Macro _MacroParam(parameter=)
	Bool(_Quote parameter _Quote <> "  ")  ; Not working if parameter is a string. :(
EndMacro


Macro Test(String, Character=)
	CompilerIf _MacroParam(Character)
		Trim(String, Character)
	CompilerElse
		Trim(String)
	CompilerEndIf
EndMacro

result$ = Test("-abc-", "-")  ; Problem with "CompilerIf". :(
result$ = Test(" abc ")  ; Proper handling of optional parameter is tricky. :(
With the new features it could look like this (spoiler alert: code is compiling fine! :) ):

Code: Select all

Macro Test(String, Character=)
	MacroIf MacroParam(Character)
		Trim(String, Character)
	MacroElse
		Trim(String)
	MacroEndIf
EndMacro

result$ = Test("-abc-", "-")  ; Works fine.
result$ = Test(" abc ")  ; Amazing, this truly is the future! :)
There are quite a lot of feature requests for improved macro handling going back many years. I think using this approach it could be implemented easily without you (the PB team) having to think of new syntax concepts. I can imagine that with only those two additional features the PureBasic language could be adjusted to a whole new level: Custom ternary operator (without having to use a procedure for the return value), primitive generic/template programming (very important!) and many more...

Re: Improve Macro Handling with MacroIf and MacroParam()

Posted: Sat Jun 24, 2023 6:34 am
by Rinzwind
Wishing..

How to solve:

Code: Select all

Macro IsKeyDown(key, async = #False)
  CompilerIf async
    Bool(GetKeyState_(key) & $8000)
  CompilerElse
    Bool(GetAsyncKeyState_(key) & $8000)
  CompilerEndIf
EndMacro

If IsKeyDown(#VK_A, #True)
	Debug "Key Down"
EndIf

Re: Improve Macro Handling with MacroIf and MacroParam()

Posted: Sat Jun 24, 2023 6:40 am
by Fred
Create 2 macros in a compilerif

Re: Improve Macro Handling with MacroIf and MacroParam()

Posted: Sat Jun 24, 2023 1:31 pm
by Rinzwind
Fred wrote: Sat Jun 24, 2023 6:40 am Create 2 macros in a compilerif
Maybe, but that is missing the point.