ExSwiftParser

An Elixir wrapper for Swift AST parsing using swift-ast-explorer. This library allows you to parse Swift source code and extract its Abstract Syntax Tree (AST) from within Elixir applications.

Features

Installation

Add ex_swift_parser to your list of dependencies in mix.exs:

def deps do
  [
    {:ex_swift_parser, "~> 0.1.0"}
  ]
end

Prerequisites

This library requires Swift to be installed on your system for building the native parsers. The build process will compile Swift parser executables for different Swift versions.

Usage

Basic Parsing

# Parse Swift code with Swift 5.10
{:ok, result} = ExSwiftParser.parse("let x = 5", "5.10")

# The result contains version info and the parsed AST
%{
  "version" => "5.10.0",
  "ast" => %{
    "kind" => "SourceFile",
    "layout" => [...]
  }
}

Supported Swift Versions

Command Line Usage

The library can also be used as an escript:

# Build the escript
mix escript.build

# Use it from command line
./ex_swift_parser "5.10" "let x = 5"

Example: Parsing a Swift Function

swift_code = """
func greet(name: String) -> String {
    return "Hello, \\(name)!"
}
"""

{:ok, result} = ExSwiftParser.parse(swift_code, "5.10")
IO.inspect(result["ast"])

Building

The library uses native Swift parsers that need to be built:

# Initialize and build all parsers
make all

# Or build individual components
make submodules  # Initialize git submodules
make             # Build all parsers

Architecture

The library consists of:

The parsing process:

  1. Validates the requested Swift version
  2. Spawns the appropriate Swift parser executable
  3. Sends Swift source code to the parser via stdin
  4. Receives JSON AST output and parses it
  5. Returns structured Elixir data

Error Handling

The library returns {:ok, result} on success or {:error, reason} on failure:

case ExSwiftParser.parse("invalid swift code", "5.10") do
  {:ok, ast} -> 
    # Process the AST
    IO.inspect(ast)
  {:error, reason} -> 
    # Handle parsing error
    IO.puts("Parse error: #{inspect(reason)}")
end

Development

# Get dependencies
mix deps.get

# Build native parsers
make all

# Run tests
mix test

# Generate documentation
mix docs

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments