May 16, 2006

RaiseEvent macro

— Update —
I Just found out Boo already does this!! When raising an event by:
Done(self, EventArgs.Empty)
the compiler knows it's an event (not a method) and puts in the null check, etc, on your behalf – so the macro I wrote is not needed. Ah well – was good practice I suppose :)
— End Update —

This is a handy macro I cooked up to generate the boring event raising code. Basically it looks like VB.NET's RaiseEvent keyword.

namespace Equin.Bootilities

import System
import Boo.Lang.Compiler
import Boo.Lang.Compiler.Ast

class RaiseEventMacro(AbstractAstMacro):

override def Expand(macro as MacroStatement):
assert macro.Arguments.Count >= 1
assert macro.Arguments[0] isa MethodInvocationExpression

method = macro.Arguments[0] as MethodInvocationExpression

# create event reference
evt = MemberReferenceExpression(SelfLiteralExpression(), method.Target.ToCodeString())

# prototype code for event invocation
code as IfStatement = ast:
if Thing is not null:
Thing.Invoke()

# change 'Thing' to actual event expression
be = code.Condition as BinaryExpression
be.Left = evt

mie = (code.TrueBlock.Statements[0] as ExpressionStatement).Expression as MethodInvocationExpression
(mie.Target as MemberReferenceExpression).Target = evt

# add arguments for the invoke
for re in method.Arguments:
mie.Arguments.Add(re)

return code
Sample usage:
class Foo:

event Done as EventHandler

def Test():
RaiseEvent Done(self, EventArgs.Empty)
# This creates the following
#if Done is not null:
# Done.Invoke(self, EventArgs.Empty)

f = Foo()
f.Done += { print "done" }
f.Test()

- No comments Not publicly viewable


Add a comment

You are not allowed to comment on this entry as it has restricted commenting permissions.

Google Ads

Search this blog

Most recent comments

  • I scratched my eye while i was holding some kind of plastic packaging.. Anyways the corner of the pl… by Ercan on this entry
  • About a year ago my contacts that i was wearing, i guess were fautly, because shortly after they wer… by Jon on this entry
  • I got shower gel in my eye 4 and a half days ago, and becasue i rubbed my eyes a lot, i have scratch… by Chris on this entry
  • This website may help http://www.webmd.com/eye–health/tc/Eye–Injuries–Home–Treatment by S on this entry
  • I somehow got dirt, or debris in my eye. The terrible pain sent me in a tailspin. I was afraid of sa… by Bobbi on this entry

Tags

May 2006

Mo Tu We Th Fr Sa Su
Apr |  Today  | Jun
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31            

Galleries

Blog archive

Loading…
Not signed in
Sign in

Powered by BlogBuilder
© MMXX