expandMacros function

List<String> expandMacros(
  1. List<String> args,
  2. Map<String, String> macros
)

Expand macros in argument list.

Finds tokens starting with @ and expands them using the provided macros map. Placeholders in the macro value are substituted with arguments following the macro invocation.

Returns a new list with macros expanded. Missing positional arguments are replaced with empty strings.

Implementation

List<String> expandMacros(List<String> args, Map<String, String> macros) {
  if (args.isEmpty || macros.isEmpty) return List.of(args);

  final result = <String>[];
  var i = 0;

  while (i < args.length) {
    final arg = args[i];

    // Check if this is a macro invocation (starts with @ and has content)
    if (arg.startsWith('@') && arg.length > 1 && !arg.contains('@', 1)) {
      final macroName = arg.substring(1);
      final macroValue = macros[macroName];

      if (macroValue != null) {
        // Expand this macro
        final (expanded, consumed) = _expandMacro(
          macroName,
          macroValue,
          args,
          i + 1,
          macros,
        );
        result.addAll(expanded);
        i += 1 + consumed; // Skip macro token + consumed args
      } else {
        // Undefined macro - keep as-is
        result.add(arg);
        i++;
      }
    } else {
      // Not a macro - keep as-is
      result.add(arg);
      i++;
    }
  }

  return result;
}