'&$%CSE 341:Programming LanguagesWinter 2005Lecture 15— MacrosCSE341 Winter 2005, Lecture 15 1'&$%Today• What are macros and what do they mean?– Why do they have a bad reputation?• Scheme’s macro system and hygiene– Free v ariables in macros– Bound variables in macros– Why hygiene is usually what you want• What macros are good and not good forCSE341 Winter 2005, Lecture 15 2'&$%MacrosTo oversimplify, a macro is just a rule for re writing programs as aprepass to evaluation. So it’s very syntactic.The “level” at which macros are defined affects their usefulness.• “Sublexical” e.g.: Replace car with hd would turn cart into hdt.– No macro system does this; so macro-expander must knowhow to break programs into tokens.• “Pre-parsing” e.g.: Replace add(x,y) with x + y (where x and ystand for expressions) would turn add(x,y) * z into x + y * z.– Some macro systems are this “dumb” (i.e., token-based);macro writers use more parens than Schemers.• “Pre-binding” e.g.: Replace car with hd would turn (let* ([hd0] [car 1]) hd) into (let* ([hd 0] [hd 1]) hd).– Few macro systems let bindings shadow macros; Scheme doesCSE341 Winter 2005, Lecture 15 3'&$%The bad news• Macros are very hard to use well.• Most macro systems are so impoverished they make it harder.• Most actual uses of macros are making up for shortcomings in theunderlying language.But:• Macros have some good uses• Scheme has a very sensible, integrated macro system• So let’s “do macros justice” for the day.CSE341 Winter 2005, Lecture 15 4'&$%HygieneA “hygienic” macro system:• Gives fresh names to local variables in macros at each use of themacro• Binds free variables in macros where the m acro is definedWithout hygiene, macro programmers:• Get very creative with local-variable names• Get creative with helper-function names too• Try to avoid loc al variables, which conflicts with predictable effectsHygiene is a big idea for macros, but som etim es is not what you want.Note: Letting variables shadow macros is also useful, but a separateissue.CSE341 Winter 2005, Lecture 15 5'&$%Why macrosNon-reasons:• Anything where an ordinary binding would work just as well.• Including manual control of inlining.Reasons:• Cosmetics• “Compiling” a domain-specific language– Error messages a tough issue though• Changing evaluation-order rules– Function application will not do here• Introducing binding constructs– A function here makes no senseCSE341 Winter 2005, Lecture 15
View Full Document