Metaprogramming

What it is, how to use it, and why you should care

Billy Buchanan

Sr Research Scientist, SAG Corporation

Logo for SAG Corporation Service Disabled Veteran Owned Small Business Emblem

Slides available at: https://wbuchanan.github.io/stataConference2023

What it is

  • Programs that write or modify programs
  • Inputs are data, metadata, and/or sourcecode
  • Processes Concept Classes used (see Damaševičius & Štuikys, 2008 for details):
    • Code Generation
    • Transformation
    • Reflection
    • Generalization
  • Output is static or dynamic

How is it implemented in Stata?

Macros

  • Macros can be used to compose syntax
  • Evaluation of macros enables flexible composition
  • Control evaluation with \ or macval()
  • Access metadata with extended macro functions

Mata Strings

  • Use string variables to create and modify syntax
  • Incorporate values stored in Stata macros as needed
  • Mata function stata() can execute your code
  • Mata classes persist across Stata commands

How to use it

Dynamic Code Generation

					
						
					
				

Static Code Generation

					
						
					
				

Transformation

					
						
					
				

Code Templates

					
						
					
				

Code Templates

					
						
					
				

Stata/Java "Reflection"

					
						
					
				

Why you should care

  • Abstraction
  • Time Savings
  • Automation/Reproducibility

Remember

  • Programs that write or manipulate other programs
  • Use macros and Mata strings variables
  • Proper use = reduced time and effort