A Swift package for parsing Clang module map files

Related tags

Maps Clangler
Overview

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.

You might also like...
Demo in SwiftUI of Apple Map, Google Map, and Mapbox map
Demo in SwiftUI of Apple Map, Google Map, and Mapbox map

SNMapServices SNMapServices is a serices for iOS written in SwiftUI. It provides Map capability by subclassing Mapbox, Google map and Apple map. This

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

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

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

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

Creates SpriteKit game maps from TMX Map files.
Creates SpriteKit game maps from TMX Map files.

PEMTileMap is a Swift package that generates SpriteKit game maps from TMX Map files. Maps, layers, tiles and objects are automatically rendered as SKN

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

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

Swift Modules, a swift module (or package) manager

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

M3UKit - A µ framework for parsing m3u files

M3UKit - A µ framework for parsing m3u files

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.

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

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

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

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

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

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

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

Swift package that uses WebKit to render PDF files from URLs

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

Swift Package Manager plug-in to compile Metal files that can be debugged in Xcode Metal Debugger.

MetalCompilerPlugin Swift Package Manager plug-in to compile Metal files that can be debugged in Xcode Metal Debugger. Description Swift Package Manag

Releases(0.1.0)
  • 0.1.0(Nov 6, 2021)

    This is the initial beta release of Clangler! If you are using it in your project and find any bugs, or if you have a use-case that's not easily accommodated by the current API, please feel free to open an issue or pull request.

    Source code(tar.gz)
    Source code(zip)
Owner
Dalton Claybrook
iOS Developer @ Peloton
Dalton Claybrook
Easy Map Annotation Clustering 📍

Cluster is an easy map annotation clustering library. This repository uses an efficient method (QuadTree) to aggregate pins into a cluster. Features R

Lasha Efremidze 1.2k Dec 25, 2022
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

null 502 Dec 25, 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

Muhammad Abdul Subhan 48 Aug 13, 2022
The Swift Geometry Engine.

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

GEOSwift 1.4k Dec 25, 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

Josef Moser 53 Feb 5, 2022
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

Romain L 268 Aug 18, 2022
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

Jeff Araujo 0 Nov 14, 2021
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

Rob Labs 0 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

Mapbox 187 Dec 19, 2022
GitHub Action for Swift with warning/error annotations.

GitHub Action for Swift This action executes Swift and generates github action annotations from swift warnings/errors. Usage An example to executing S

Jaehong Kang 2 Aug 18, 2022