Embedding the Swift compiler in my app

A few apps I've written in the past have used domain-specific languages to enhance their functionality. One cool app I wrote used LLVM to generate binary data parsers from data structure definitions, and show the parsed results in a browsable UI. The magical thing here was that the generated LLVM code could call back into my application.

I'd like to do something similar, but with Swift. Is this possible? It would mean embedding the compiler, but it would also mean constraining and expanding the libraries available to this embedded Swift. That is, I'd want to maybe prevent filesystem access, but add domain-specific API calls.

In this way, I could make a scriptable app that uses Swift as its scripting language. I gotta believe there's already some work done toward this, but googling for variations of "embed swift compiler in app" just turned up a lot about adding Frameworks written in Swift to iOS projects.

I did find this, but I think they stop at source-level analysis.

Thanks!

4 Likes

Would love to see this as well. This could open up the language in creative ways for application based scripting modules.

1 Like

I am looking for a similar capability. I would love to have a Swift
API that lets me submit a string to the compiler for analysis. If the
string doesn't parse as Swift, then the compiler returns a list of
errors.

If the string parses as Swift code, then the compiler tells me:

  1. which names are bound in the outermost scope, and (optionally)
    the type of each,

  2. which names are unbound and (optionally) any type information the
    compiler inferred about those names

  3. (optionally) an AST for the code labeled with source locations

With that information I can sort the strings and concatenate them inside
a function (say) that I submit for compilation into a function that my
program calls.

Dave

Linking this which appears to be a project using LLVM + clang under the hood to compile C code on device. Doesn't seem TOO far from doing the same with the swift compiler.