'&$%CSE 341:Programming LanguagesDan GrossmanFall 2004Lecture 15— MacrosDan Grossman CSE341 Fall 2004, 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 variables in macros– Bound variables in macros– Why hygiene is usually what you want• What macros are good and not good forDan Grossman CSE341 Fall 2004, Lecture 15 2'&$%MacrosTo oversimplify, a macro is just a rule for rewriting 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 doesDan Grossman CSE341 Fall 2004, 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.Dan Grossman CSE341 Fall 2004, 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 macro 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 sometimes is not what you want.Note: Letting variables shadow macros is also useful, but a separateissue.Dan Grossman CSE341 Fall 2004, 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 senseDan Grossman CSE341 Fall 2004, Lecture 15
View Full Document