CSE 341:Programming LanguagesAutumn 2005Lecture 20 — MacrosCSE 341 Autumn 2005, Lecture 20 1Today• What are macros and what do they m ean?– 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 forCSE 341 Autumn 2005, Lecture 20 2MacrosTo 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 doesCSE 341 Autumn 2005, Lecture 20 3The bad news• Macros are very hard to use well.• Most macro systems are so impoverished they make it harder.• Actual uses of macros often used to ameliorate shortcomings inthe underlying language.But:• Macros have some good uses• Scheme has a very sensible, integrated macro system• So let’s “do macros justice” for the day.CSE 341 Autumn 2005, Lecture 20 4HygieneA “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 helpe r-function names too• Try to avoid local variables, which conflicts with predictable effectsHygiene is a big idea for m acros, but some time s is not what you want.Note: Letting variables shadow m acros is also useful, but a separateissue.CSE 341 Autumn 2005, Lecture 20 5Why macrosNon-reasons:• Anything where an ordinary binding would work just as well.• Including manual control of inlining.Reasons:• Cosmetics• “Compiling” a domain-specific language– But error messages a tough issue• Changing evaluation-order rules– Function application will not do here• Introducing binding constructs– A function here makes no se nseCSE 341 Autumn 2005, Lecture 20
View Full Document