Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Evolution of Macros

375 views

Published on

Code examples of macros in programming languages from Assembler to Rust.

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Evolution of Macros

  1. 1. MACROS Osvaldas Grigas | @ogrigas Inventi
  2. 2. ETYMOLOGY μακρο = "long" (Greek)
  3. 3. HISTORY OF MACROS 195x - Assembler 1963 - Lisp 1964 - PL/1 1972 - C 1978 - TeX 2002 - Racket 2013 - Scala 2015 - Rust
  4. 4. ASSEMBLER MACROS (mid 1950s) min2 MACRO first, second     LOCAL firstIsMin     mov eax, first     cmp eax, second     jle firstIsMin     mov eax, second firstIsMin: ENDM min2 value1 value2 preprocessor mini language
  5. 5. C/C++ MACROS (since 1972) #define MIN2(x, y) ((x) * (y)) MIN2(3, 5 + 1) preprocessor mini language
  6. 6. TEX MACROS (since 1978) newcommand{greet}[1]{   Hello, #1} greet{Donald Knuth} text substitution mini language LaTeX = TeX + macros
  7. 7. PL/1 MACROS (since 1964) %Parse: procedure (Upper, Val, With) statement returns (char);   dcl (Upper, Value, With) char;   return ('do;' || /* some PL/1 statements */ || 'end;'); %end; parse val (Filename) with (Name, '.', Ext); procedural preprocessor subset of PL/1 syntax
  8. 8. SCALA MACROS (since 2013) Google it :-)
  9. 9. SCALA MACROS def log(msg: String): Unit = macro logImpl def logImpl(c: Context)(msg: c.Expr[String]): c.Expr[Unit] = {   import c.universe._   reify {     if (Config.loggingEnabled)       Config.logger.log(Severity.TRACE, msg.splice)   } } syntactic non-hygienic full Scala syntax, but... can't change it, can't generate defs
  10. 10. RUST MACROS (since 2015) macro_rules! vec {     ( $( $x:expr ),* ) => {{         let mut temp_vec = Vec::new();         $( temp_vec.push($x); )*         temp_vec     }}; } let x: Vec<u32> = vec![1, 2, 3]; syntactic hygienic full Rust syntax, but... can't generate function declarations
  11. 11. LISP MACROS (since 1963) (define­macro (unless test body)       ; Scheme   `(if ,test '() (begin ,@body))) (defmacro unless (test body)           ; Common Lisp   `(if ,test nil (progn ,@body))) (defmacro unless [test body]           ; Clojure   `(if ~test nil ~body)) syntactic non-hygienic full Lisp syntax
  12. 12. RACKET MACROS (since 2002) (define­syntax­rule (swap x y)   (let ([tmp x])     (set! x y)     (set! y tmp))) syntactic hygienic full Racket syntax
  13. 13. THE RULES OF MACRO CLUB (1) You do not write macros
  14. 14. THE RULES OF MACRO CLUB (2) Write macros if that is the only way to encapsulate a pattern
  15. 15. THE RULES OF MACRO CLUB (3) If this is your first time in Clojure, you have to write a macro

×