A Swift package for parsing Clang module map files

Last update: Apr 7, 2022

Build Status codecov Platforms License

Clangler is a Swift package used to parse Clang module map files into an abstract syntax tree (AST) representation. Once parsed, you can inspect or manipulate the nodes in the file, then generate and save a new file reflecting your changes.

Examples

Find the names of all modules in a file:

func findAllTopLevelModuleNames(fileURL: URL) throws -> [String] {
    let moduleMap = try Parser().parseFile(at: fileURL).get()
    return moduleMap.moduleDeclarations.map(\.moduleId.rawValue)
}

Remove an existing umbrella header declaration and replace it with an umbrella directory:

func convertToUmbrellaDirectory(fileURL: URL) throws {
    var moduleMap = try Parser().parseFile(at: fileURL).get()

    // Find the module declaration and the existing umbrella header
    guard var declaration = moduleMap.moduleDeclarations.first?.local,
          let umbrellaHeaderMemberIndex = declaration.members
            .firstIndex(where: { $0.header?.kind == .umbrella })
    else { return }

    // Replace the umbrella header with an umbrella directory
    declaration.members[umbrellaHeaderMemberIndex] = .umbrellaDirectory(
        UmbrellaDirectoryDeclaration(filePath: "Headers")
    )

    // Replace the module declaration with the new one
    moduleMap.moduleDeclarations[0] = .local(declaration)

    // Save the modified file
    let generator = Generator(indentationStyle: .spaces(4))
    let newFileContents = generator.generateFileContents(with: moduleMap)
    try newFileContents.write(to: fileURL, atomically: true, encoding: .utf8)
}

Create a brand new module map from scratch instead of parsing one:

func buildModuleMapFromScratch(moduleName: String, headerPaths: [String]) throws {
    let moduleMap = ModuleMapFile(
        moduleDeclarations: [
            .local(LocalModuleDeclaration(
                explicit: false,
                framework: true,
                moduleId: ModuleId(rawValue: moduleName),
                attributes: [],
                members: headerPaths.map { filePath in
                    .header(HeaderDeclaration(
                        kind: .standard(private: false),
                        filePath: filePath,
                        headerAttributes: []
                    ))
                }
            ))
        ]
    )

    // Save the file
    let generator = Generator(indentationStyle: .spaces(4))
    let fileContents = generator.generateFileContents(with: moduleMap)
    let fileURL = URL(fileURLWithPath: "path/to/\(moduleName)/module.modulemap")
    try fileContents.write(to: fileURL, atomically: true, encoding: .utf8)
}

Discover syntax errors in a file:

func printAllSyntaxErrors(fileURL: URL) throws {
    let result = try Parser().parseFile(at: fileURL)
    guard case .failure(let syntaxErrors) = result else {
        return print("No syntax errors")
    }

    for error in syntaxErrors {
        print("line: \(error.line), column: \(error.column), description: \(error.description)")
    }
}

Notable types

  • Parser — Used to parse the contents of a Clang module map file into an abstract syntax tree (AST) representation
  • Lexer — Scans a module map string and produces tokens in the module map grammar. You will typically not instantiate this type directly as Parser uses it under the hood.
  • Generator — Used to generate module map file contents from an abstract syntax tree (AST) representation. This is the reverse of Parser.
  • ModuleMapFile — The root node in the module map AST. This represents a complete module map file as a collection of declarations.

Installation

In Xcode, you can add this package to your project by selecting File -> Swift Packages -> Add Package Dependency… Enter the Clangler GitHub URL and follow the prompts.

If you use a Package.swift file instead, add the following line inside of your package dependencies array:

.package(url: "https://github.com/daltonclaybrook/Clangler", from: "0.1.0"),

Now add Clangler as a dependency of any relevant targets:

.target(name: "MyApp", dependencies: ["Clangler"]),

License

Clangler is available under the MIT license. See LICENSE.md for more information.

GitHub

https://github.com/daltonclaybrook/Clangler
You might also like...

LOL Champions app: a small Multi-Module demo application to demonstrate modern iOS application tech-stacks with a Multi-module and MVVM architecture

LOL Champions app: a small Multi-Module demo application to demonstrate modern iOS application tech-stacks with a Multi-module and MVVM architecture

LOL Champions app: a small Multi-Module demo application to demonstrate modern iOS application tech-stacks with a Multi-module and MVVM architecture

Jun 9, 2022

NotionDrive - A swift package that can upload files to Notion.so or download files from Notion.so

NotionDrive NotionDrive is a swift package that can upload files to Notion.so or

Apr 9, 2022

Elevate is a JSON parsing framework that leverages Swift to make parsing simple, reliable and composable

Elevate is a JSON parsing framework that leverages Swift to make parsing simple, reliable and composable. Elevate should no longer be used for

Mar 1, 2022

CoreML-Face-Parsing - how to use face-parsing CoreML model in iOS

CoreML-Face-Parsing - how to use face-parsing CoreML model in iOS

CoreML-Face-Parsing The simple sample how to use face-parsing CoreML model in iO

Apr 2, 2022

Swift Modules, a swift module (or package) manager

Swift Modules The Swift Modules manager similar to the JavaScript world's npm and bower

Jun 3, 2021

M3UKit - A µ framework for parsing m3u files

M3UKit - A µ framework for parsing m3u files

May 28, 2022

Swift Markdown is a Swift package for parsing, building, editing, and analyzing Markdown documents.

Swift Markdown is a Swift package for parsing, building, editing, and analyzing Markdown documents.

Jun 27, 2022

Math expression parser built with Point•Free's swift-parsing package

swift-math-parser Basic math expression parser built with Point•Free's swift-parsing package. NOTE: currently, this uses a fork of that fixes a parsin

Jun 22, 2022

TwitchIRC - A Swift package for parsing/serializing Twitch IRC messages

TwitchIRC A Swift package to take of parsing/serializing Twitch IRC messages for

May 22, 2022

Localization/I18n: Incrementally update/translate your Strings files from .swift, .h, .m(m), .storyboard or .xib files.

Localization/I18n: Incrementally update/translate your Strings files from .swift, .h, .m(m), .storyboard or .xib files.

Installation • Configuration • Usage • Build Script • Donation • Migration Guides • Issues • Contributing • License BartyCrouch BartyCrouch incrementa

Jun 15, 2022

A Swift sample code to reads ISO 10303-21 exchange structures (STEP P21 files for AP242) split into multiple files using external references approach.

multipleP21ReadsSample A Swift sample code to reads ISO 10303-21 exchange structures (STEP P21 files for AP242) split into multiple files using extern

Nov 23, 2021

BeatboxiOS - A sample implementation for merging multiple video files and/or image files using AVFoundation

MergeVideos This is a sample implementation for merging multiple video files and

Feb 24, 2022

A Swift package for encoding and decoding Swift Symbol Graph files.

A Swift package for encoding and decoding Swift Symbol Graph files.

SymbolKit The specification and reference model for the Symbol Graph File Format. A Symbol Graph models a module, also known in various programming la

Jun 11, 2022

Swift package that uses WebKit to render PDF files from URLs

Swift package for generating a PDF file from a URL (rendered by WebKit)

Feb 25, 2022

Package for creating, modifying, and managing subtitle files, such as SubRip (.srt).

SubtitleKit Package for creating, modifying, and managing subtitle files, such as SubRip (.srt). Supported formats Format File extension Is supported

Jun 19, 2022

A simple way to map XML to Objects written in Swift

XMLMapper XMLMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from XML. Ex

Jun 7, 2022

Async and concurrent versions of Swift’s forEach, map, flatMap, and compactMap APIs.

CollectionConcurrencyKit Welcome to CollectionConcurrencyKit, a lightweight Swift package that adds asynchronous and concurrent versions of the standa

Jun 18, 2022

A promises library written in Swift featuring combinators like map, flatMap, whenAll, whenAny.

A promises library written in Swift featuring combinators like map, flatMap, whenAll, whenAny.

Promissum is a promises library written in Swift. It features some known functions from Functional Programming like, map and flatMap. It has useful co

Jan 3, 2022

:octocat: AdaptiveController is a 'Progressive Reduction' Swift UI module for adding custom states to Native or Custom iOS UI elements. Swift UI component by @Ramotion

:octocat: AdaptiveController is a 'Progressive Reduction' Swift UI module for adding custom states to Native or Custom iOS UI elements. Swift UI component by @Ramotion

ADAPTIVE TAB BAR 'Progressive Reduction' module for adding custom states to Native or Custom UI elements. We specialize in the designing and coding of

Jun 19, 2022
Related tags
An iOS map clustering framework targeting MapKit, Google Maps and Mapbox.
An iOS map clustering framework targeting MapKit, Google Maps and Mapbox.

ClusterKit is an elegant and efficiant clustering controller for maps. Its flexible architecture make it very customizable, you can use your own algor

May 27, 2022
MSFlightMapView allows you to easily add and animate geodesic flights to Google map

MSFlightMapView Demo Requirements iOS 10.0+ Xcode 9.0+ Installation Just add the MSFlightMapView folder to your project. or use CocoaPods: pod 'MSFlig

Apr 24, 2022
The Swift Geometry Engine.
The Swift Geometry Engine.

Easily handle a geometric object model (points, linestrings, polygons etc.) and related topological operations (intersections, overlapping etc.). A ty

Jun 24, 2022
A Swift wrapper for forward and reverse geocoding of OpenStreetMap data

Nominatim NominatimKit is a Swift wrapper for forward and reverse geocoding of OpenStreetMap data. Why? Geocoding location data on iOS requires the us

Feb 5, 2022
Google Directions API helper for iOS, written in Swift
Google Directions API helper for iOS, written in Swift

PXGoogleDirections Google Directions API SDK for iOS, entirely written in Swift. ?? Features Supports all features from the Google Directions API as o

Mar 11, 2022
Aplicativo criado para estudos de desenvolvimento de Mapa e GPS usando Swift
Aplicativo criado para estudos de desenvolvimento de Mapa e GPS usando Swift

Onde_estou_iOS Aplicativo criado para estudos de desenvolvimento de Mapa e GPS usando Swift, onde ele pede autorização para usar GPS e localização do

Nov 14, 2021
Use Swift in the macOS command line to build maps.
Use Swift in the macOS command line to build maps.

Use Swift in the macOS command line to build maps. imagefrom A Swift command line utility that gets an image from a URL. Saves the web image as JPEG o

Dec 30, 2021
A spatial analysis library written in Swift for native iOS, macOS, tvOS, watchOS, and Linux applications, ported from Turf.js.

Turf for Swift ?? ?? ?? ?? ⌚️ A spatial analysis library written in Swift for native iOS, macOS, tvOS, watchOS, and Linux applications, ported from Tu

Jun 16, 2022
iOS sandboxed terminal with Python, Lua and Clang

LibTerm LibTerm is a terminal for iOS with Python 3.7 and Lua 5.3. Supports iOS 13 dark mode and multi window. Features The app supports most of OpenT

Jun 24, 2022
An exercise to use a map(google map) for navigation.

map-navigation An exercise to use a map(google map) for navigation. It have the features of navigating your for a destination, drawing your travel pat

May 30, 2022