Chapter 3 · Level 2

🎯 Macro Mastery

Code Generation at Compile Time

Introduction to Rust Macros

Macros in Rust allow you to write code that writes code (metaprogramming). Unlike functions, macros are expanded at compile time, enabling powerful abstractions and reducing boilerplate. Rust has two types of macros: declarative macros (macro_rules!) and procedural macros.

ℹ️ Why Macros? Macros can operate on syntax trees, take variable numbers of arguments, and generate code based on patterns - things functions cannot do.

1. Declarative Macros (macro_rules!)

Basic Syntax

📝 Example: Simple Declarative Macro
// Basic macro that creates a function
macro_rules! create_function {
    ($func_name:ident) => {
        fn $func_name() {
            println!("You called {:?}()", stringify!($func_name));
        }
    };
}

create_function!(foo);
create_function!(bar);

fn main() {
    foo(); // You called "foo"()
    bar(); // You called "bar"()
}

Pattern Matching

📝 Example: Vec-like Macro
macro_rules! vec_custom {
    // No arguments: empty vector
    () => {
        Vec::new()
    };

    // Single element
    ($elem:expr) => {
        {
            let mut v = Vec::new();
            v.push($elem);
            v
        }
    };

    // Multiple elements
    ($($elem:expr),+ $(,)?) => {
        {
            let mut v = Vec::new();
            $(
                v.push($elem);
            )+
            v
        }
    };
}

fn main() {
    let v1 = vec_custom![];
    let v2 = vec_custom![1];
    let v3 = vec_custom![1, 2, 3, 4, 5];

    println!("{:?}", v1); // []
    println!("{:?}", v2); // [1]
    println!("{:?}", v3); // [1, 2, 3, 4, 5]
}

Advanced Pattern Matching

📝 Example: HashMap Literal Macro
macro_rules! hashmap {
    ($($key:expr => $value:expr),* $(,)?) => {
        {
            let mut map = std::collections::HashMap::new();
            $(
                map.insert($key, $value);
            )*
            map
        }
    };
}

fn main() {
    let map = hashmap! {
        "name" => "Alice",
        "age" => "30",
        "city" => "NYC",
    };

    println!("{:?}", map);
}

Repetition Patterns

📝 Example: Calculation Macro with Repetition
macro_rules! calculate {
    // Base case: single number
    ($value:expr) => {
        $value
    };

    // Addition
    ($left:expr + $($rest:tt)*) => {
        $left + calculate!($($rest)*)
    };

    // Multiplication
    ($left:expr * $($rest:tt)*) => {
        $left * calculate!($($rest)*)
    };
}

fn main() {
    let result1 = calculate!(5 + 3 + 2);
    let result2 = calculate!(5 * 3 * 2);

    println!("Addition: {}", result1);      // 10
    println!("Multiplication: {}", result2); // 30
}

2. Procedural Macros

Procedural macros are more powerful and flexible. They operate on the token stream and can generate arbitrary Rust code. There are three types:

Derive Macros

📝 Example: Custom Derive Macro
// In your procedural macro crate (separate crate)
// Cargo.toml:
// [lib]
// proc-macro = true
//
// [dependencies]
// syn = "2.0"
// quote = "1.0"
// proc-macro2 = "1.0"

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(Builder)]
pub fn derive_builder(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;
    let builder_name = syn::Ident::new(
        &format!("{}Builder", name),
        name.span()
    );

    let fields = if let syn::Data::Struct(data) = &input.data {
        if let syn::Fields::Named(fields) = &data.fields {
            &fields.named
        } else {
            panic!("Builder only works with named fields");
        }
    } else {
        panic!("Builder only works with structs");
    };

    let field_names: Vec<_> = fields.iter()
        .map(|f| &f.ident)
        .collect();

    let field_types: Vec<_> = fields.iter()
        .map(|f| &f.ty)
        .collect();

    let expanded = quote! {
        pub struct #builder_name {
            #(#field_names: Option<#field_types>,)*
        }

        impl #builder_name {
            pub fn new() -> Self {
                Self {
                    #(#field_names: None,)*
                }
            }

            #(
                pub fn #field_names(mut self, value: #field_types) -> Self {
                    self.#field_names = Some(value);
                    self
                }
            )*

            pub fn build(self) -> Result<#name, String> {
                Ok(#name {
                    #(
                        #field_names: self.#field_names
                            .ok_or(format!("{} is required", stringify!(#field_names)))?,
                    )*
                })
            }
        }

        impl #name {
            pub fn builder() -> #builder_name {
                #builder_name::new()
            }
        }
    };

    TokenStream::from(expanded)
}
📝 Using the Builder Macro
#[derive(Builder)]
pub struct User {
    name: String,
    age: u32,
    email: String,
}

fn main() {
    let user = User::builder()
        .name("Alice".to_string())
        .age(30)
        .email("alice@example.com".to_string())
        .build()
        .unwrap();

    println!("User: {} ({}) - {}", user.name, user.age, user.email);
}

Attribute Macros

📝 Example: Timing Attribute Macro
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, ItemFn};

#[proc_macro_attribute]
pub fn time_execution(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemFn);

    let fn_name = &input.sig.ident;
    let fn_block = &input.block;
    let fn_sig = &input.sig;
    let fn_vis = &input.vis;

    let expanded = quote! {
        #fn_vis #fn_sig {
            let start = std::time::Instant::now();
            let result = (|| #fn_block)();
            let duration = start.elapsed();
            println!(
                "Function '{}' took {:.2?}",
                stringify!(#fn_name),
                duration
            );
            result
        }
    };

    TokenStream::from(expanded)
}

// Usage:
#[time_execution]
fn slow_function() {
    std::thread::sleep(std::time::Duration::from_millis(100));
    println!("Doing work...");
}

Function-like Macros

📝 Example: SQL Query Macro
use proc_macro::TokenStream;
use quote::quote;

#[proc_macro]
pub fn sql(input: TokenStream) -> TokenStream {
    let input_str = input.to_string();

    // Basic SQL validation
    let query = input_str.trim_matches('"');

    if !query.to_uppercase().starts_with("SELECT") &&
       !query.to_uppercase().starts_with("INSERT") &&
       !query.to_uppercase().starts_with("UPDATE") &&
       !query.to_uppercase().starts_with("DELETE") {
        panic!("Invalid SQL query");
    }

    let expanded = quote! {
        {
            const QUERY: &str = #query;
            QUERY
        }
    };

    TokenStream::from(expanded)
}

// Usage:
fn main() {
    let query = sql!("SELECT * FROM users WHERE age > 18");
    println!("Query: {}", query);
}

3. Advanced Macro Techniques

Hygiene and Scope

📝 Example: Hygienic Macros
// Macros are hygienic - they don't capture external variables
macro_rules! using_a {
    ($e:expr) => {
        {
            let a = 42;
            $e
        }
    };
}

fn main() {
    let four = using_a!(a / 10); // This works
    println!("{}", four); // 4

    // But external 'a' is not affected
    let a = 100;
    let result = using_a!(a); // Uses macro's 'a', not external
    println!("{}", result); // 42, not 100
}

Debugging Macros

📝 Example: Debug Macro Expansion
// Use cargo expand to see expanded macros
// Install: cargo install cargo-expand
// Run: cargo expand

macro_rules! debug_vars {
    ($($var:ident),*) => {
        $(
            println!("{} = {:?}", stringify!($var), $var);
        )*
    };
}

fn main() {
    let x = 10;
    let y = 20;
    let z = 30;

    debug_vars!(x, y, z);
    // Output:
    // x = 10
    // y = 20
    // z = 30
}

4. Real-World Example: Testing Framework

📝 Example: Custom Test Framework
macro_rules! test_suite {
    (
        suite: $suite_name:ident,
        $(
            test $test_name:ident $body:block
        )*
    ) => {
        mod $suite_name {
            use super::*;

            pub fn run_all() {
                println!("\nRunning test suite: {}", stringify!($suite_name));
                let mut passed = 0;
                let mut failed = 0;

                $(
                    print!("  Test {}: ", stringify!($test_name));
                    match std::panic::catch_unwind(|| $body) {
                        Ok(_) => {
                            println!("✓ PASSED");
                            passed += 1;
                        }
                        Err(_) => {
                            println!("✗ FAILED");
                            failed += 1;
                        }
                    }
                )*

                println!("\nResults: {} passed, {} failed", passed, failed);
            }
        }
    };
}

test_suite! {
    suite: math_tests,

    test addition {
        assert_eq!(2 + 2, 4);
    }

    test subtraction {
        assert_eq!(5 - 3, 2);
    }

    test multiplication {
        assert_eq!(3 * 4, 12);
    }

    test division {
        assert_eq!(10 / 2, 5);
    }
}

fn main() {
    math_tests::run_all();
}

5. Macro Best Practices

🔑 Best Practices

  1. Keep it Simple: Prefer functions when possible
  2. Document Well: Explain what the macro does and how to use it
  3. Test Thoroughly: Macros can hide bugs
  4. Use Hygiene: Don't capture external variables unexpectedly
  5. Provide Good Errors: Use compile_error! for clear messages
  6. Limit Scope: Make macros as specific as possible
📝 Example: Good Error Messages
macro_rules! must_be_positive {
    ($val:expr) => {
        if $val <= 0 {
            compile_error!(
                "Value must be positive! Use a positive literal."
            );
        }
        $val
    };
}

// This will cause a compile error:
// let x = must_be_positive!(-5);

Summary

✅ You've learned:

  • Declarative macros with macro_rules!
  • Pattern matching and repetition in macros
  • Procedural macros: derive, attribute, and function-like
  • Advanced techniques: hygiene, debugging
  • Real-world applications and best practices

Macros are a powerful feature that sets Rust apart from many other languages. Master them to write more expressive, maintainable, and DRY code. Remember: with great power comes great responsibility - use macros wisely!

Korea Standardization Infrastructure Mapping

Korea operates a comprehensive standards governance system through inter-ministerial cooperation. National Standards Council (under Prime Minister's Office, per Framework Act on National Standards Article 5) coordinates KATS (Korean Agency for Technology and Standards), MFDS (Ministry of Food and Drug Safety), MOTIE (Ministry of Trade, Industry and Energy), MSIT (Ministry of Science and ICT), MOIS (Ministry of the Interior and Safety), MOE (Ministry of Environment), MOHW (Ministry of Health and Welfare), MND (Ministry of National Defense), MCST (Ministry of Culture, Sports and Tourism), MOFA (Ministry of Foreign Affairs), MOJ (Ministry of Justice), and FSC (Financial Services Commission). Accreditation and Testing: KOLAS (Korea Laboratory Accreditation Scheme) accredits 800+ testing laboratories. KAS (Korea Accreditation System) accredits 50+ certification bodies. KTC (Korea Testing Certification), KTR (Korea Testing & Research Institute), KTL (Korea Testing Laboratory), and KCL (Korea Conformity Laboratories) provide conformance testing. Telecom and Cyber: KCC (Korea Communications Commission), KCA (Korea Communications Agency), TTA (Telecommunications Technology Association), IITP (Institute for Information & Communications Technology Planning & Evaluation), NIPA (National IT Industry Promotion Agency), KISA (Korea Internet & Security Agency), KCMVP (Korea Cryptographic Module Validation Program), NIS (National Intelligence Service), NSR (National Security Research Institute), and NCSC (National Cyber Security Center). National R&D Centers: KIST, ETRI, KAIST, Seoul National University, Yonsei University, Korea University, POSTECH, UNIST, GIST, DGIST, KISTI, KIER, KIMM, KRICT, KFRI, KRIBB. International Standards Cooperation: ISO TC/SC Korean secretariats, IEC TC/SC Korean secretariats, ITU-T Study Group Korean chairs, 3GPP RAN/SA Korean chairs, IEEE 802 Korean chairs, W3C Korea office, OASIS Korea office, IETF Korea cooperation, OECD CSTP, UN ESCAP, APEC SCSC Korean cooperation. Korean Industrial Standards (KS) Catalog: KS X (Information) 25,000+, KS A (Basic) 15,000+, KS B (Machinery) 25,000+, KS C (Electrical) 18,000+, KS D (Metallurgy) 12,000+, KS E (Mining) 5,000+, KS F (Construction) 18,000+, KS H (Food) 8,000+, KS I (Environment) 5,000+, KS J (Biology) 3,000+, KS K (Textile) 15,000+, KS L (Ceramics) 7,000+, KS M (Chemistry) 12,000+, KS P (Medical) 5,000+, KS Q (Quality Mgmt) 4,000+, KS R (Transport) 12,000+, KS S (Service) 3,000+, KS T (Packaging) 4,000+, KS V (Shipbuilding) 5,000+, KS W (Aerospace) 3,000+ — totaling 220,000+ Korean Industrial Standards. Key Acts: Personal Information Protection Act (Act 19234, effective Sept 15, 2024), Electronic Government Act, Electronic Signature Act, Act on Promotion of Information and Communications Network Utilization and Information Protection, Information and Communications Infrastructure Protection Act, Data Industry Act, Public Data Act, AI Framework Act (Act 20212, effective July 2026), Industrial Technology Innovation Promotion Act, Framework Act on Science and Technology — 70+ Korean standardization-related laws.

Korea Digital Transformation Detailed Mapping

Korea operates digital transformation through a comprehensive governance system. Digital Government: Digital Platform Government Committee (established September 2022, under the President)·Ministry of the Interior and Safety Digital Government Bureau·e-Government Support Center·Gov.kr·National Citizen Service·KDIS (Korea Digital Information Society)·NIA (National Information Society Agency)·MOIS (Ministry of the Interior and Safety). K-DNS Infrastructure: Korea Internet & Security Agency (KISA) Korea Internet Center·KISA DNS Root Server·KRNIC (Korea Network Information Center)·BGP Korea·National Cyber Security Center (NCSC)·KCC (Korea Communications Commission)·MSIT (Ministry of Science and ICT)·NIA·NIPA. Korean Cloud Infrastructure: KT Cloud·NAVER Cloud (NCloud)·Samsung SDS Cloud·LG U+ Cloud·NHN Cloud·Kakao Enterprise Cloud·SK Telecom Cloud·KISA Cloud Security Assurance Program (CSAP)·KCMVP-validated cloud·ISMS-P (Information Security & Personal Information Management System). Korean Security Certifications: KISA ISMS-P certification·KCMVP (Korean Cryptographic Module Validation Program)·NIS (National Intelligence Service) "National Cryptographic Technology Operation Standards"·NCSC "National Cyber Security Strategy 2024-2028"·CC (Common Criteria) Korean evaluation bodies·EAL4·EAL5·KS X ISO/IEC 15408·19790·24759 Korean Profile. Korean Data Standards: NIA AI Hub·National Data Standardization Committee·Statistics Korea (KOSTAT)·MyData 4 Designated Combination Specialists (Samsung SDS, KICI, KOSTAT, KFTC)·National Institute of Korean Language·National Law Information Center·National Spatial Information Platform·National Spatial Data Center·Korean Spatial Information Standards. Finance and Fintech Standards: FSC (Financial Services Commission)·FSS (Financial Supervisory Service)·FIU (Financial Intelligence Unit)·BOK (Bank of Korea)·FSEC (Financial Security Institute)·KFTC (Korea Financial Telecommunications)·KSD (Korea Securities Depository)·KRX (Korea Exchange) 8-agency cooperation. 5G/6G Communications Infrastructure: 5G subscribers 35 million (2024)·5G base stations 350,000·6G commercialization target 2028·5G dedicated networks 16 operators·6G Acceleration Council (MSIT, 2024). K-Content: KOCCA (Korea Creative Content Agency)·MCST (Ministry of Culture, Sports and Tourism)·KCA (Korea Communications Agency)·Korea Culture Information Service Agency·Korean Film Archive·Korea Publishing Industry Promotion Agency. Data 3 Acts (Personal Information Protection Act·Credit Information Act·Telecommunications Network Act, 2020 enforcement)·Data Industry Act (2021)·Public Data Act (2013)·AI Framework Act (2026)·Digital Platform Government Framework Act (2024 proposed) — Korea digital transformation core legislation.

Korea Industrial, Research, Education Infrastructure Mapping

Korea operates its industrial ecosystem and standardization system through the following core infrastructure. Korea Top 5 Groups: Samsung, Hyundai Motor, LG, SK, Lotte. Each group operates standardization committees and ISO/IEC TC Korean secretariats. Samsung Electronics (semiconductors, displays, home appliances, telecom)·Hyundai Motor (automobiles, mobility)·LG Electronics (home appliances, displays, OLED)·SK hynix (memory)·LG Energy Solution·Samsung SDI (batteries)·POSCO Future M (materials)·Hyundai Mobis (parts). Korean IT Big Tech: NAVER (search, cloud, AI HyperCLOVA)·Kakao (messenger, payment, mobility, banking)·Coupang (e-commerce, logistics)·Karrot Market·Toss·Woowa Brothers. Korea Telcos: SK Telecom·KT·LG U+. 5G·5G dedicated networks·B2B cloud·AI businesses operating. Korea Top 7 Research Universities: Seoul National University·KAIST·POSTECH·Yonsei University·Korea University·UNIST·DGIST·GIST. All serve as standardization R&D bases and ISO/IEC/IEEE Korean chairs. Korea Government-affiliated National Research Institutes (26): KIST, KAERI, KIMM, KIER, KFRI, KRICT, KRIBB, KARI, KASI, KIGAM, KICT, KISTI, KETI, ETRI, NIMS, KIMS, KISDI, KOTRA, STEPI, KOEN, KICCE, KIET, KIPF, KIHASA, KICJ, KLRI. Korea Industrial Complexes / Tech Valleys: Pangyo Techno Valley·Dongtan·Gwanggyo·Songdo IBD·Yeouido·Gangnam·Sihwa·Banwol·Gumi·Ulsan·Changwon·Geoje·Yeosu·Onsan·Cheongju·Iksan·Gwangyang·POSCO Gwangyang Steel Mill·Asan Bay·Seosan·Songdo·Incheon Airport·Sejong·Cheongna·Geomdan. Korea Trade and Finance Infrastructure: Korea International Trade Association (KITA)·Korea Trade-Investment Promotion Agency (KOTRA)·Export-Import Bank of Korea (KEXIM)·Bank of Korea·Kookmin Bank·Shinhan·Hana·Woori·NH Nonghyup·IBK Industrial Bank·SC First Bank·Citi Bank Korea·HSBC Korea·DBS Korea — 14 Korean major banks and foreign banks. Korea K-POP / K-Content: HYBE·SM·YG·JYP 4 major entertainment companies·CJ ENM·tvN·MBC·KBS·SBS·EBS·YTN·Yonhap News TV·JTBC Korean broadcasting·NETFLIX Korea·Disney Plus·TVING·Wavve·Watcha·Coupang Play. Korea Gaming Industry: Nexon·NCsoft·Krafton·Netmarble·Kakao Games·Pearl Abyss·Com2uS·Gamevil·NHN·Smilegate·Webzen. Korea Automotive / Battery: Hyundai Motor·Kia·Genesis·LG Energy Solution·Samsung SDI·SK On·POSCO Future M·EcoPro·L&F battery cathode material suppliers. Korea Semiconductor: Samsung Electronics (HBM3E·HBM4)·SK hynix (HBM3E 12-Hi)·DB HiTek·SK siltron·SK Enpulse·Dongjin Semichem·Seoul Semiconductor·Simmtech·Samsung Display·LG Display.