# ================================================================================================
# FastLED WASM Compilation Flags Configuration
# ================================================================================================
# 
# This file centralizes ALL compilation flags used by both sketch compilation and libfastled 
# compilation to ensure they remain synchronized and compatible across the entire build system.
#
# Key Features:
# - Single source of truth for all compiler flags, defines, and build settings
# - Supports fallback loading from FastLED source tree
# - Dynamic DWARF source resolution with ~1 second reload interval
# - Consistent flags across Docker and native builds (direct emcc)
#
# Performance Optimization Override:
# - Set FASTLED_FORCE_BUILTIN_FLAGS=1 to force using this optimized configuration
# - This bypasses any build_flags.toml in the FastLED source tree
# - Useful for testing performance optimizations or when FastLED source has older config
# - Example: export FASTLED_FORCE_BUILTIN_FLAGS=1 && your-build-command
#
# Architecture:
# - [all] section: Common flags shared by ALL compilation targets
# - [sketch] section: Additional flags specific to sketch compilation only  
# - [library] section: Additional flags specific to libfastled compilation only
# - [build_modes.*] sections: Build-specific flags (debug/quick/release)
# - [linking.*] sections: Linker-specific flags for different targets
# - [dwarf] section: DWARF debug info and source path resolution settings
# - [strict_mode] section: Additional warning flags for strict compilation
#
# ================================================================================================

[all]
# ================================================================================================
# UNIVERSAL COMPILATION FLAGS
# ================================================================================================
# These flags are applied to ALL compilation targets (both sketch and library builds).
# They provide the foundation for consistent compilation across the entire build system.

# Core preprocessor defines that control FastLED behavior
defines = [
    # FastLED Engine Configuration
    "-DFASTLED_ENGINE_EVENTS_MAX_LISTENERS=50",  # Max event listeners for FastLED engine
    "-DFASTLED_FORCE_NAMESPACE=1",               # Force namespace usage to avoid conflicts
    "-DFASTLED_USE_PROGMEM=0",                   # Disable PROGMEM usage (not needed in WASM)
    "-DUSE_OFFSET_CONVERTER=0",                  # Disable offset converter optimization
    "-DGL_ENABLE_GET_PROC_ADDRESS=0",           # Disable OpenGL proc address lookup
    
    # Threading and Concurrency Support
    "-D_REENTRANT=1",                           # Enable reentrant library functions
    
    # Emscripten-Specific Configuration
    "-DEMSCRIPTEN_HAS_UNBOUND_TYPE_NAMES=0",    # Disable unbound type name reflection
]

# Core compiler flags that control compilation behavior
compiler_flags = [
    # Language Standard and Compatibility
    "-std=c++20",                               # Use C++20 standard (enables header unit imports)
    "-fpermissive",                             # Allow some non-conforming code patterns

    # Warning Configuration
    "-Wno-constant-logical-operand",            # Suppress constant logical operand warnings
    "-Wnon-c-typedef-for-linkage",             # Warn about non-C typedef issues
    "-Werror=bad-function-cast",               # Error on bad function casts
    "-Werror=cast-function-type",              # Error on function type cast issues
    "-Werror=unused-private-field",            # Unused private fields are dead code

    # Thread Safety and Runtime Behavior
    "-pthread",                                 # Enable Emscripten pthreads (SAB + Web Workers) — required by the cooperative coroutine back-end (issue #2452)
    "-fno-threadsafe-statics",                 # Disable thread-safe static initialization (performance)
    "-fno-exceptions",                         # Disable C++ exceptions for all targets (size/performance)
    "-fno-rtti",                              # Disable RTTI for all targets (size/performance, consistent)

    # C++20 Header Unit Support
    "-Wno-experimental-header-units",         # Suppress experimental header unit warning
]

# Include directory flags (paths added dynamically by build system)
include_flags = [
    "-I.",                                    # Current directory
    # Note: FastLED source includes are added dynamically based on installation path
    # Additional includes: -I{fastled_src_path} and -I{fastled_src_path}/platforms/wasm/compiler
]

[sketch]
# ================================================================================================
# SKETCH-SPECIFIC COMPILATION FLAGS
# ================================================================================================
# These flags are ONLY applied to sketch compilation (user Arduino/FastLED sketches).
# They enable sketch-specific features and JavaScript interop capabilities.

# Sketch-specific preprocessor defines
defines = [
    "-DSKETCH_COMPILE=1",                       # Identifies this as sketch compilation (vs library)
    "-DFASTLED_WASM_USE_CCALL",                # Enable JavaScript ccall interface for sketches
]

# Additional sketch-specific compiler flags
compiler_flags = [
    # Currently no additional sketch-specific compiler flags
    # This section is ready for future sketch-specific compilation requirements
]

[library]
# ================================================================================================
# LIBRARY-SPECIFIC COMPILATION FLAGS
# ================================================================================================
# These flags are ONLY applied to libfastled compilation (the core FastLED library).
# They enable LLVM bitcode generation, ThinLTO, and additional warnings for library builds.

# Library-specific preprocessor defines
defines = [
    # Currently no library-specific defines
    # This section is ready for future library-specific requirements
]

# Library-specific compiler flags
compiler_flags = [
    "-flto=thin",                              # Enable ThinLTO for fast incremental builds
    "-Wall",                                   # Enable comprehensive warnings for library code
]

[build_modes.debug]
# ================================================================================================
# DEBUG BUILD MODE
# ================================================================================================
# Optimized for debugging experience with maximum debug information and runtime checking.
# Includes address/undefined behavior sanitizers and comprehensive debug info generation.

# Debug compilation flags
flags = [
    # Debug Information Generation
    "-g3",                                     # Maximum debug info (includes macros and preprocessor info)
    "-gsource-map",                           # Generate source maps for browser debugging
    # Note: -ffile-prefix-map flag is generated dynamically from [dwarf] config for path mapping

    # Optimization Control
    "-fno-inline",                           # Disable function inlining for clearer debugging
    "-O0",                                   # No optimization (fastest compilation, clearest debugging)
]

# Debug-specific linking flags (applied only during final linking in debug mode)
link_flags = [
    # Debug Info and Error Detection
    "--profiling-funcs",                     # Enable function profiling in debug builds
    "-sSEPARATE_DWARF_URL=fastled.wasm.dwarf", # Separate DWARF debug info file
    "-sSTACK_OVERFLOW_CHECK=2",              # Maximum stack overflow detection
    "-sASSERTIONS=1",                        # Enable runtime assertions
]

[build_modes.fast_debug]
# ================================================================================================
# FAST DEBUG BUILD MODE
# ================================================================================================
# Optimized for rapid development iteration with essential debugging features but faster builds.
# Trades off some runtime safety checks and detailed debug info for significantly faster compilation.
# Ideal for: frequent rebuilds, development iteration, basic debugging needs.

# Fast debug compilation flags
flags = [
    # Debug Information Generation - Reduced for speed
    "-g2",                                   # Standard debug info (faster than g3, excludes macros)
    "-gsource-map",                         # Generate source maps for browser debugging
    # Note: -ffile-prefix-map flag is generated dynamically from [dwarf] config for path mapping
    
    # Optimization Control - Minimal optimization for speed
    "-O1",                                  # Light optimization (much faster than O0, still debuggable)
    "-fno-inline-functions",                # Disable automatic function inlining (preserve call stack)
    
    # Runtime Safety - Essential checks only
    # Note: Sanitizers removed for faster compilation - add back with environment variable if needed
    # Set FASTLED_DEBUG_SANITIZERS=1 to enable sanitizers when needed for specific debugging
]

# Fast debug linking flags - minimal overhead, preserves debug info for stack traces
link_flags = [
    # Note: No --strip-debug here — fast_debug keeps minimal DWARF for stack traces
    # Note: No separate DWARF file (unlike full debug) for faster linking

    # Error Detection - Essential only
    "-sSTACK_OVERFLOW_CHECK=1",             # Basic stack overflow detection (faster than level 2)
    "-sASSERTIONS=1",                       # Keep runtime assertions for error detection
]

[build_modes.quick]
# ================================================================================================
# QUICK BUILD MODE
# ================================================================================================
# Optimized for fastest iteration during development. Prioritizes compilation and linking speed
# over runtime performance. Uses ThinLTO with incremental cache for fast rebuilds.

# Quick build compilation flags — default for library (sketch uses sketch_flags below)
# NOTE: library_flags below overrides BOTH [library].compiler_flags AND these flags.
flags = [
    # Optimization Control - Optimized for build speed
    "-O1",                                   # Light optimization (faster than O0 with better performance)
    "-g0",                                   # No debug info (fastest compilation, smallest size)

    # Aggressive Build Speed Optimizations
    "-fno-inline-functions",                 # Disable function inlining
    "-fno-vectorize",                       # Disable vectorization optimizations
    "-fno-unroll-loops",                    # Disable loop unrolling
    "-fno-strict-aliasing",                 # Disable strict aliasing assumptions

    # Template and Instantiation Optimizations
    "-fno-delayed-template-parsing",        # Parse templates immediately (faster compilation)
    "-fmax-type-align=4",                   # Limit type alignment (smaller object files)

    # Code Generation Optimizations for Speed
    "-ffast-math",                          # Enable fast math optimizations (if acceptable)
    "-fno-finite-math-only",                # Allow NaN/Inf even with fast-math (fixes __builtin_nan warnings)
    "-fno-math-errno",                      # Don't set errno for math functions
    "-fno-exceptions",                      # Explicitly disable exceptions (already in base but emphasize)
    "-fno-rtti",                           # Explicitly disable RTTI (already in base but emphasize)
]

# Library-specific quick mode flags — replaces [library].compiler_flags + flags above.
# NO -flto=thin: library compiles to native wasm objects instead of LLVM bitcode.
# Trade-off: library rebuild is slower (~10s more), but LINKING is much faster because
# the linker does simple wasm merging instead of ThinLTO backend compilation each link.
# This is a huge win for iterative sketch development (link runs on every sketch change).
library_flags = [
    # From [library] section — keep -Wall, drop -flto=thin
    "-Wall",
    # Optimization and debug
    "-O1",
    "-g0",
    # Build speed optimizations
    "-fno-inline-functions",
    "-fno-vectorize",
    "-fno-unroll-loops",
    "-fno-strict-aliasing",
    "-fno-delayed-template-parsing",
    "-fmax-type-align=4",
    # Code generation
    "-ffast-math",
    "-fno-finite-math-only",
    "-fno-math-errno",
    "-fno-exceptions",
    "-fno-rtti",
]

# Sketch-specific quick mode flags — optimized for absolute fastest sketch compilation.
# The sketch is a single translation unit; LTO/vectorization/unrolling are meaningless.
# PCH handles header parsing; this just needs to emit code as fast as possible.
sketch_flags = [
    "-O0",                                   # Zero optimization — fastest possible compilation
    "-g0",                                   # No debug info
    "-fno-exceptions",                       # Disable exceptions (consistent with base)
    "-fno-rtti",                            # Disable RTTI (consistent with base)
]

# Quick build linking flags - optimized for fastest linking without LTO
link_flags = [
    # Note: No ThinLTO cache needed — library is compiled without -flto=thin in quick mode.
    # Note: --profiling-funcs and --emit-symbol-map removed for faster linking.
    # Use debug or fast_debug mode if you need function names in profiling.

    # Skip binaryen/wasm-opt — saves ~0.3s per link in quick mode
    "-O0",

    # Strip and Disable Non-Essential Runtime Features for Speed
    "-Wl,--strip-debug",                    # Strip debug info (quick mode has -g0, nothing to keep)
    "-sASSERTIONS=0",                       # Disable runtime assertions
    "-sSTACK_OVERFLOW_CHECK=0",             # Disable stack overflow checking

    # Compatibility and Performance Options
    "-sWASM_BIGINT=0",                      # Disable BigInt for faster execution
    "-sERROR_ON_UNDEFINED_SYMBOLS=1",       # Error on undefined symbols (was hiding missing addLeds)
]

[build_modes.release]
# ================================================================================================
# RELEASE BUILD MODE
# ================================================================================================
# Optimized for production deployment with maximum size and performance optimization.
# Minimal debug info and aggressive optimization for smallest possible output.

# Release compilation flags
flags = [
    # Size Optimization
    "-Oz",                                   # Optimize aggressively for size (smaller than -Os)
    "-g0",                                   # No debug info (not needed in production)
]

# Release linking flags - no --strip-debug needed since -g0 prevents debug info generation
link_flags = [
]

[linking.base]
# ================================================================================================
# BASE LINKING FLAGS
# ================================================================================================
# Common linking flags shared by ALL linking operations (both sketch and library).
# These provide the foundation for WASM generation and threading support.
#
# Performance Notes:
# - Emscripten automatically parallelizes Binaryen/JS optimizations based on available cores
# - Control parallelism with EMCC_CORES=N environment variable (defaults to hardware_concurrency)
# - For ThinLTO builds, wasm-ld uses all available cores by default
#   (configure with --thinlto-jobs=N if needed, but default is optimal)

flags = [
    # Note: Linker selection is set dynamically: -fuse-ld={linker} (mold/lld)

    # WebAssembly Configuration
    "-sWASM=1",                                # Generate WebAssembly output (not asm.js)

    # Linker Performance Optimization
    "-fuse-ld=wasm-ld",                      # Explicitly use wasm-ld (default, but explicit for clarity)

    # Coroutine back-end — pthreads + SharedArrayBuffer. Cooperative semantics
    # are provided by fl::thread + fl::mutex + fl::condition_variable in
    # src/platforms/wasm/coroutine_platform_wasm.hpp. Works in every
    # cross-origin-isolated webview (WebKit/Safari, WebKitGTK, WebView2,
    # Firefox, Chromium). See issue #2452 for the migration history from
    # JSPI to pthreads.
    "-pthread",                              # Enable Emscripten pthreads (SAB + Web Workers)
    "-sPROXY_TO_PTHREAD",                    # Run main() on a worker pthread so it can block
    "-sPTHREAD_POOL_SIZE=4",                 # Pre-allocate 4 workers (tune after benchmarking)
]

[linking.sketch]
# ================================================================================================
# SKETCH-SPECIFIC LINKING FLAGS
# ================================================================================================
# Linking flags ONLY applied to sketch compilation. These create the final JavaScript/WASM
# module that can be loaded in browsers with full FastLED functionality and networking support.

flags = [
    # Entry Point and Module Configuration
    # Note: Uses proper main() entry point from src/platforms/wasm/entry_point.cpp
    # Note: --emit-symbol-map removed in quick mode (override with -sEMIT_SYMBOL_MAP=1 if needed)
    "-sMODULARIZE=1",                        # Create a factory function (not global)
    "-sEXPORT_NAME=fastled",                 # Name of the exported factory function
    
    # Memory Management — fixed 250MB, no dynamic growth.
    # Removes ALLOW_MEMORY_GROWTH which required an expensive acorn JS rewrite
    # pass (apply_wasm_memory_growth) on every link (~0.3s).
    "-sINITIAL_MEMORY=262144000",            # Fixed 250 MB (250 * 1024 * 1024, page-aligned)
    "-sAUTO_NATIVE_LIBRARIES=0",             # Disable automatic native library inclusion
    
    # JavaScript Interop - Runtime Methods
    "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','stringToUTF8','UTF8ToString','lengthBytesUTF8','HEAPU8','getValue']",
    
    # JavaScript Interop - C Functions
    # Note: _extern_setup and _extern_loop are now compatibility functions; _main is the primary entry point
    "-sEXPORTED_FUNCTIONS=['_malloc','_free','_main','_extern_setup','_extern_loop','_fastled_declare_files','_getStripPixelData','_getFrameData','_getScreenMapData','_freeFrameData','_getFrameVersion','_hasNewFrameData','_js_fetch_success_callback','_js_fetch_error_callback','_pushAudioSamples']",
    
    # Runtime Behavior
    "-sEXIT_RUNTIME=0",                      # Keep runtime alive after main() exits
    "-sFILESYSTEM=0",                        # Disable filesystem support (not needed)
    
    # Optimization and Debugging
    # Note: --gc-sections disabled in quick mode for faster linking (saves ~1-2s)
    # Re-enable for release builds: "-Wl,--gc-sections"
    # Note: -Wl,--strip-debug is in quick link_flags only; debug/fast_debug preserve DWARF for stack traces
    "-Wl,--no-export-dynamic",              # Don't export all symbols (faster symbol processing)
    # Note: --source-map-base removed in quick mode for faster linking
]

[linking.library]
# ================================================================================================
# LIBRARY-SPECIFIC LINKING FLAGS
# ================================================================================================
# Linking flags ONLY applied to libfastled compilation. Currently minimal but maintained
# for future library-specific linking requirements.

flags = [
    # Currently no library-specific linking flags
    # This section is ready for future library-specific linking requirements
]

[dwarf]
# ================================================================================================
# DWARF DEBUG INFO AND SOURCE RESOLUTION
# ================================================================================================
# Configuration for DWARF debug information generation and dynamic source path resolution.
# This system supports hot-reloading (~1 second interval) for real-time debugging configuration.
#
# Key Features:
# - Dynamic prefix resolution for source path mapping
# - Periodic configuration reloading without restart
# - Centralized debug path mapping control
# - Cross-platform source path normalization

# Source path resolution prefixes (reloaded every ~1 second)
fastled_prefix = "fastledsource"                # Prefix for FastLED library sources in debug info
sketch_prefix = "sketchsource"                  # Prefix for user sketch sources in debug info  
dwarf_prefix = "dwarfsource"                    # Prefix for generic dwarf-resolved sources

# Debug file naming
dwarf_filename = "fastled.wasm.dwarf"           # Name of separate DWARF debug info file

# File prefix mapping for source path resolution in debug info.
# ci/wasm_flags.py synthesizes known-root maps for FastLED library compiles:
#   <repo>/src -> fastled_prefix
# Build drivers that know the user sketch and Emscripten roots should map:
#   <sketch> -> sketch_prefix
#   <emsdk>  -> dwarf_prefix/emsdk

[strict_mode]
# ================================================================================================
# STRICT MODE COMPILATION
# ================================================================================================
# Additional warning flags enabled in strict mode for enhanced code quality checking.
# These flags catch common programming errors and enforce coding best practices.

flags = [
    # Error Escalation
    "-Werror",                                  # Treat all warnings as errors (zero-tolerance)
    
    # Enhanced Warning Detection
    "-Wextra",                                  # Enable extra warning checks beyond -Wall
    
    # Type Safety and Conversion Warnings
    "-Wconversion",                             # Warn about implicit type conversions
    "-Wsign-conversion",                        # Warn about signed/unsigned conversions
    
    # Code Quality Warnings
    "-Wunused",                                 # Warn about unused variables, functions, etc.
    "-Wuninitialized",                          # Warn about uninitialized variable usage
    "-Wdouble-promotion",                       # Warn about float->double promotions
    
    # Format and Safety Warnings
    "-Wformat=2",                               # Enhanced format string checking
    "-Wcast-align",                             # Warn about alignment-breaking casts
    "-Wcast-qual",                              # Warn about qualifier-removing casts
    
    # Critical Error Detection
    "-Werror=return-type",                      # Always error on missing return statements
] 
