Files
2026-06-01 18:27:40 -07:00

40 lines
1.6 KiB
Swift

// NameValidation.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
// MARK: - Swift identifier validation
/// Validates that `name` is a non-empty, valid Swift module/type identifier.
///
/// A valid identifier:
/// - Is non-empty
/// - Contains only letters, digits, and underscores
/// - Does not start with a digit
///
/// - Parameters:
/// - name: The string to validate.
/// - invalidNameError: The error to throw when validation fails. Callers
/// supply their own typed error so error messages carry the correct domain.
/// - Throws: `invalidNameError` if any rule is violated.
func validateSwiftIdentifier(_ name: String, invalidNameError: some Error) throws {
guard !name.isEmpty else {
throw invalidNameError
}
// Restrict to ASCII [A-Za-z0-9_] — SPM module names and filesystem directory names
// must be ASCII-safe. Using CharacterSet.alphanumerics would incorrectly accept
// Cyrillic, CJK, Arabic, etc., which break `swift package resolve` and toolchain paths.
let asciiAlphanumerics: CharacterSet = CharacterSet(
charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
let validChars: CharacterSet = asciiAlphanumerics.union(CharacterSet(charactersIn: "_"))
let hasInvalidChars: Bool = name.unicodeScalars.contains { !validChars.contains($0) }
let startsWithDigit: Bool = name.first.map({ $0 >= "0" && $0 <= "9" }) ?? false
guard !hasInvalidChars && !startsWithDigit else {
throw invalidNameError
}
}