├── .devcontainer ├── devcontainer.json ├── docker-compose.yml └── dockerfile ├── .github └── workflows │ └── build.yml ├── .gitignore ├── Examples ├── InvalidExamples │ ├── IdentifierSafety.spf │ ├── InvalidBasis.spf │ ├── InvalidBasisSyntax.spf │ ├── InvalidMatrix.spf │ ├── InvalidMatrix.spf.swift │ ├── InvalidRetro.spf │ ├── InvalidRetroProtocol.spf │ └── UndefinedBasis.spf └── ValidExamples │ ├── Basic.spf │ ├── Basic.spf.swift │ ├── ContainerTypes.spf │ ├── ContainerTypes.spf.swift │ ├── DocComments.spf │ ├── DocComments.spf.swift │ ├── Empty.swift │ ├── Nested.spf │ ├── Nested.spf.swift │ ├── OtherAttributes.spf │ ├── OtherAttributes.spf.swift │ ├── PrimaryAssociatedtypeDowngrade.spf │ ├── PrimaryAssociatedtypeDowngrade.spf.swift │ ├── Scopes.spf │ ├── Scopes.spf.swift │ ├── Zip.spf │ └── Zip.spf.swift ├── LICENSE ├── NOTICE ├── Package.resolved ├── Package.swift ├── Plugins └── FactoryPlugin │ ├── Main.swift │ ├── MissingTargetError.swift │ └── ToolError.swift ├── README.md └── Sources ├── Factory ├── Error.swift ├── Factory.swift ├── Instantiator.swift ├── LexicalScope.swift ├── Loop.swift ├── MatrixElement.swift └── Transformer.swift └── swift-package-factory └── Main.swift /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "swift-package-factory-container", 3 | "dockerComposeFile": "docker-compose.yml", 4 | "service": "swift", 5 | "workspaceFolder": "/swift-package-factory", 6 | "remoteUser": "ec2-user", 7 | "extensions": 8 | [ 9 | "sswg.swift-lang" 10 | ] 11 | } -------------------------------------------------------------------------------- /.devcontainer/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.9" 2 | services: 3 | swift: 4 | image: swift-2022-12-17-a 5 | build: 6 | dockerfile: 'dockerfile' 7 | volumes: 8 | - ..:/swift-package-factory 9 | # cap_add: 10 | # - NET_ADMIN 11 | # ports: 12 | # - '80:80' 13 | # - '443:443' -------------------------------------------------------------------------------- /.devcontainer/dockerfile: -------------------------------------------------------------------------------- 1 | FROM amazonlinux:latest 2 | 3 | RUN yum -y update 4 | # install sysadmin basics 5 | RUN yum -y install sudo useradd passwd 6 | # install swift dependencies 7 | RUN yum -y install \ 8 | binutils \ 9 | gcc \ 10 | git \ 11 | unzip \ 12 | glibc-static \ 13 | gzip \ 14 | libbsd \ 15 | libcurl-devel \ 16 | libedit \ 17 | libicu \ 18 | libsqlite \ 19 | libstdc++-static \ 20 | libuuid \ 21 | libxml2-devel \ 22 | tar \ 23 | tzdata \ 24 | zlib-devel 25 | 26 | # create the `ec2-user`, and switch to her 27 | RUN useradd -ms /bin/bash ec2-user 28 | RUN passwd -d ec2-user 29 | RUN usermod -aG wheel ec2-user 30 | USER ec2-user 31 | 32 | WORKDIR /home/ec2-user/ 33 | # download a copy of `swiftenv` 34 | ADD https://github.com/kylef/swiftenv/archive/1.5.0.tar.gz swiftenv.tar.gz 35 | # allow `ec2-user` to access it 36 | RUN sudo chown ec2-user swiftenv.tar.gz 37 | 38 | # also overrides any `.swift-version` local configurations 39 | ENV SWIFT_VERSION DEVELOPMENT-SNAPSHOT-2022-12-17-a 40 | ENV SWIFTENV_ROOT /home/ec2-user/.swiftenv 41 | # install `swiftenv` 42 | RUN mkdir -p $SWIFTENV_ROOT 43 | RUN tar -xzf swiftenv.tar.gz -C $SWIFTENV_ROOT --strip 1 44 | RUN rm swiftenv.tar.gz 45 | ENV PATH $SWIFTENV_ROOT/bin:$SWIFTENV_ROOT/shims:$PATH 46 | # install `swift` 47 | RUN swiftenv install https://download.swift.org/development/amazonlinux2/swift-$SWIFT_VERSION/swift-$SWIFT_VERSION-amazonlinux2.tar.gz 48 | 49 | # optional, but python, and iptables are very useful in a container 50 | RUN sudo yum -y install python3 libpython3-dev iptables nc 51 | 52 | # generate script that will run on terminal creation, 53 | # enables showing the PWD prompt 54 | RUN echo "PS1='\w\$ '" >> .bashrc 55 | RUN echo "force_color_prompt=yes" >> .bashrc 56 | ENV TERM xterm-256color 57 | # generate script that will run on container startup 58 | RUN echo 'sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080' >> setup 59 | RUN echo 'sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 8443' >> setup 60 | RUN echo 'sleep infinity' >> setup 61 | RUN chmod +x setup 62 | 63 | CMD ./setup -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | macos-nightly: 11 | runs-on: ${{ matrix.os }} 12 | name: ${{ matrix.os }} (${{ matrix.swift }}) 13 | env: 14 | SWIFT_TOOLCHAIN_DIRECTORY: /Library/Developer/Toolchains/swift-${{ matrix.swift }}.xctoolchain 15 | strategy: 16 | matrix: 17 | os: 18 | - macos-12 19 | swift: 20 | - DEVELOPMENT-SNAPSHOT-2022-12-17-a 21 | steps: 22 | - uses: actions/checkout@v2 23 | 24 | - name: cache swift toolchains 25 | uses: actions/cache@v2 26 | with: 27 | path: swift-${{ matrix.swift }}.pkg 28 | key: ${{ matrix.os }}:swift:${{ matrix.swift }} 29 | 30 | - name: cache status 31 | id: cache_status 32 | uses: andstor/file-existence-action@v1 33 | with: 34 | files: swift-${{ matrix.swift }}.pkg 35 | 36 | - name: download swift toolchain 37 | if: steps.cache_status.outputs.files_exists == 'false' 38 | run: "curl https://download.swift.org/development/xcode/\ 39 | swift-${{ matrix.swift }}/\ 40 | swift-${{ matrix.swift }}-osx.pkg \ 41 | --output swift-${{ matrix.swift }}.pkg" 42 | 43 | - name: set up swift 44 | run: | 45 | sudo installer -pkg swift-${{ matrix.swift }}.pkg -target / 46 | 47 | - name: build-factory 48 | run: | 49 | $SWIFT_TOOLCHAIN_DIRECTORY/usr/bin/swift --version 50 | $SWIFT_TOOLCHAIN_DIRECTORY/usr/bin/swift build --product swift-package-factory 51 | $SWIFT_TOOLCHAIN_DIRECTORY/usr/bin/swift build --product FactoryPlugin 52 | - name: run-factory 53 | # need to (re)create empty swift file to satisfy the SPM 54 | # also need to manually symlink lib_InternalSwiftSyntaxParser.dylib since SPM 55 | # sets the wrong @rpath. 56 | run: | 57 | ln -s $SWIFT_TOOLCHAIN_DIRECTORY/usr/lib/swift/macosx/lib_InternalSwiftSyntaxParser.dylib .build/debug/lib_InternalSwiftSyntaxParser.dylib 58 | rm Examples/ValidExamples/*.swift 59 | touch Examples/ValidExamples/Empty.swift 60 | $SWIFT_TOOLCHAIN_DIRECTORY/usr/bin/swift package --allow-writing-to-package-directory factory ValidExamples 61 | - name: test-factory 62 | # check that none of the generated .swift files have changed 63 | run: | 64 | $SWIFT_TOOLCHAIN_DIRECTORY/usr/bin/swift build --target ValidExamples 65 | if [[ -z $(git status -s) ]]; then (exit 0); else (exit 1); fi 66 | 67 | linux: 68 | runs-on: ${{ matrix.os.runner }} 69 | name: ${{ matrix.os.runner }} (${{ matrix.swift.toolchain }}) 70 | strategy: 71 | matrix: 72 | os: 73 | - runner: ubuntu-22.04 74 | prefix: ubuntu2204 75 | suffix: ubuntu22.04 76 | - runner: ubuntu-20.04 77 | prefix: ubuntu2004 78 | suffix: ubuntu20.04 79 | swift: 80 | - toolchain: DEVELOPMENT-SNAPSHOT-2022-12-17-a 81 | branch: development 82 | steps: 83 | - uses: actions/checkout@v2 84 | 85 | - name: cache swift toolchains 86 | uses: actions/cache@v2 87 | with: 88 | path: swift-${{ matrix.swift.toolchain }}.tar.gz 89 | key: ${{ matrix.os.runner }}:swift:${{ matrix.swift.toolchain }} 90 | 91 | - name: cache status 92 | id: cache_status 93 | uses: andstor/file-existence-action@v1 94 | with: 95 | files: swift-${{ matrix.swift.toolchain }}.tar.gz 96 | 97 | - name: download swift toolchain 98 | if: steps.cache_status.outputs.files_exists == 'false' 99 | run: "curl https://download.swift.org/\ 100 | ${{ matrix.swift.branch }}/\ 101 | ${{ matrix.os.prefix }}/\ 102 | swift-${{ matrix.swift.toolchain }}/\ 103 | swift-${{ matrix.swift.toolchain }}-${{ matrix.os.suffix }}.tar.gz \ 104 | --output swift-${{ matrix.swift.toolchain }}.tar.gz" 105 | 106 | - name: set up swift 107 | run: | 108 | mkdir -p $GITHUB_WORKSPACE/swift-${{ matrix.swift.toolchain }} 109 | tar -xzf swift-${{ matrix.swift.toolchain }}.tar.gz -C $GITHUB_WORKSPACE/swift-${{ matrix.swift.toolchain }} --strip 1 110 | echo "$GITHUB_WORKSPACE/swift-${{ matrix.swift.toolchain }}/usr/bin" >> $GITHUB_PATH 111 | 112 | - name: build-factory 113 | run: | 114 | swift --version 115 | swift build --product swift-package-factory 116 | swift build --product FactoryPlugin 117 | - name: run-factory 118 | # need to (re)create empty swift file to satisfy the SPM 119 | run: | 120 | rm Examples/ValidExamples/*.swift 121 | touch Examples/ValidExamples/Empty.swift 122 | swift package --allow-writing-to-package-directory factory ValidExamples 123 | - name: test-factory 124 | # check that none of the generated .swift files have changed 125 | run: | 126 | swift build --target ValidExamples 127 | if [[ -z $(git status -s) ]]; then (exit 0); else (exit 1); fi -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .build/ 2 | .vscode/ 3 | Packages/ 4 | /swift-DEVELOPMENT-SNAPSHOT-*.tar.gz 5 | /swift-DEVELOPMENT-SNAPSHOT-* 6 | /swift-*-RELEASE.tar.gz 7 | /swift-*-RELEASE -------------------------------------------------------------------------------- /Examples/InvalidExamples/IdentifierSafety.spf: -------------------------------------------------------------------------------- 1 | @basis 2 | let floats:[Never] = 3 | [ 4 | 0.25, 5 | 0.5, 6 | 0.75 7 | ] 8 | 9 | enum E 10 | { 11 | @matrix(__member__: floats) 12 | func __member__() 13 | { 14 | } 15 | } -------------------------------------------------------------------------------- /Examples/InvalidExamples/InvalidBasis.spf: -------------------------------------------------------------------------------- 1 | @basis 2 | let notABasis:[Never] = 0 -------------------------------------------------------------------------------- /Examples/InvalidExamples/InvalidBasisSyntax.spf: -------------------------------------------------------------------------------- 1 | @basis 2 | var notABasis:[Never] { [test] } -------------------------------------------------------------------------------- /Examples/InvalidExamples/InvalidMatrix.spf: -------------------------------------------------------------------------------- 1 | func foo() 2 | { 3 | @basis 4 | let variables:[Never] = [x, y, z] 5 | 6 | // this works because this is a declaration 7 | @matrix(__variable__: variables) 8 | var __variable__:Int = 0 9 | 10 | #if NEVER 11 | for _:Int in 0 ..< 10 12 | { 13 | // this does not work, because this is 14 | // not a declaration, and @matrix is 15 | // for declarations only 16 | @matrix(__variable__: variables) 17 | __variable__ += 1 18 | } 19 | #endif 20 | } -------------------------------------------------------------------------------- /Examples/InvalidExamples/InvalidMatrix.spf.swift: -------------------------------------------------------------------------------- 1 | func foo() 2 | { 3 | 4 | // this works because this is a declaration 5 | var x:Int = 0 6 | 7 | // this works because this is a declaration 8 | var y:Int = 0 9 | 10 | // this works because this is a declaration 11 | var z:Int = 0 12 | 13 | #if NEVER 14 | for _:Int in 0 ..< 10 15 | { 16 | // this does not work, because this is 17 | // not a declaration, and @matrix is 18 | // for declarations only 19 | @matrix(__variable__: variables) 20 | __variable__ += 1 21 | } 22 | #endif 23 | } -------------------------------------------------------------------------------- /Examples/InvalidExamples/InvalidRetro.spf: -------------------------------------------------------------------------------- 1 | @retro struct NotAProtocol 2 | { 3 | } -------------------------------------------------------------------------------- /Examples/InvalidExamples/InvalidRetroProtocol.spf: -------------------------------------------------------------------------------- 1 | @retro protocol ProtocolWithNoPrimaryAssociatedTypes 2 | { 3 | } -------------------------------------------------------------------------------- /Examples/InvalidExamples/UndefinedBasis.spf: -------------------------------------------------------------------------------- 1 | struct S 2 | { 3 | @basis 4 | let lexicallyScopedBasis:[Never] = 5 | [ 6 | foo, 7 | bar 8 | ] 9 | } 10 | extension S 11 | { 12 | // this is a different code block, 13 | // so `lexicallyScopedBasis` is not defined here. 14 | @matrix(__member__: lexicallyScopedBasis) 15 | subscript(__member__ __member__:Int) -> Int 16 | { 17 | 0 18 | } 19 | } -------------------------------------------------------------------------------- /Examples/ValidExamples/Basic.spf: -------------------------------------------------------------------------------- 1 | import Swift 2 | 3 | // this comment should disappear 4 | @basis 5 | let typenames:[Never] = 6 | [ 7 | FooType, 8 | BarType, 9 | BazType, 10 | ] 11 | 12 | @basis 13 | let members:[Never] = 14 | [ 15 | foo, 16 | bar, 17 | baz 18 | ] 19 | 20 | @basis 21 | let values:[Never] = 22 | [ 23 | 0, 24 | 1, 25 | 2, 26 | ] 27 | 28 | /// Models a `\(__Type__)`. Has a member 29 | /// named ``\(__member__)``. 30 | @matrix(__Type__: typenames, __member__: members, __value__: values) 31 | @frozen public 32 | enum __Type__ 33 | { 34 | /// Returns the number `\(__value__)` 35 | @inlinable public 36 | var __member__:Int 37 | { 38 | __value__ 39 | } 40 | } 41 | 42 | extension Int 43 | { 44 | @matrix(__ordinal__: [i, j, k], __value__: [0, 1, 2]) 45 | @inlinable public 46 | var __ordinal__:Int 47 | { 48 | __value__ 49 | } 50 | 51 | @basis 52 | let cases:[Never] = [a, b] 53 | 54 | enum Cases:Int 55 | { 56 | @matrix(__case__: cases) 57 | case __case__ 58 | } 59 | 60 | @matrix(__case__: cases) 61 | public static 62 | var __case__:Self 63 | { 64 | Cases.__case__.rawValue 65 | } 66 | } -------------------------------------------------------------------------------- /Examples/ValidExamples/Basic.spf.swift: -------------------------------------------------------------------------------- 1 | import Swift 2 | 3 | /// Models a `FooType`. Has a member 4 | /// named ``foo``. 5 | @frozen public 6 | enum FooType 7 | { 8 | /// Returns the number `0` 9 | @inlinable public 10 | var foo:Int 11 | { 12 | 0 13 | } 14 | } 15 | 16 | /// Models a `BarType`. Has a member 17 | /// named ``bar``. 18 | @frozen public 19 | enum BarType 20 | { 21 | /// Returns the number `1` 22 | @inlinable public 23 | var bar:Int 24 | { 25 | 1 26 | } 27 | } 28 | 29 | /// Models a `BazType`. Has a member 30 | /// named ``baz``. 31 | @frozen public 32 | enum BazType 33 | { 34 | /// Returns the number `2` 35 | @inlinable public 36 | var baz:Int 37 | { 38 | 2 39 | } 40 | } 41 | 42 | extension Int 43 | { 44 | @inlinable public 45 | var i:Int 46 | { 47 | 0 48 | } 49 | @inlinable public 50 | var j:Int 51 | { 52 | 1 53 | } 54 | @inlinable public 55 | var k:Int 56 | { 57 | 2 58 | } 59 | 60 | enum Cases:Int 61 | { 62 | case a 63 | case b 64 | } 65 | 66 | public static 67 | var a:Self 68 | { 69 | Cases.a.rawValue 70 | } 71 | 72 | public static 73 | var b:Self 74 | { 75 | Cases.b.rawValue 76 | } 77 | } -------------------------------------------------------------------------------- /Examples/ValidExamples/ContainerTypes.spf: -------------------------------------------------------------------------------- 1 | @basis 2 | let primitives:[Never] = 3 | [ 4 | Int, 5 | Int?, 6 | [Int], 7 | [Int: Int], 8 | (Int, Int), 9 | ((Int, Int) throws -> Int), 10 | ] 11 | 12 | enum Variant 13 | { 14 | @matrix(__Primitive__: primitives) 15 | func `as`(_:__Primitive__.Type = __Primitive__.self) -> __Primitive__? 16 | { 17 | nil 18 | } 19 | } -------------------------------------------------------------------------------- /Examples/ValidExamples/ContainerTypes.spf.swift: -------------------------------------------------------------------------------- 1 | 2 | 3 | enum Variant 4 | { 5 | func `as`(_:Int.Type = Int.self) -> Int? 6 | { 7 | nil 8 | } 9 | func `as`(_:Int?.Type = Int?.self) -> Int?? 10 | { 11 | nil 12 | } 13 | func `as`(_:[Int].Type = [Int].self) -> [Int]? 14 | { 15 | nil 16 | } 17 | func `as`(_:[Int: Int].Type = [Int: Int].self) -> [Int: Int]? 18 | { 19 | nil 20 | } 21 | func `as`(_:(Int, Int).Type = (Int, Int).self) -> (Int, Int)? 22 | { 23 | nil 24 | } 25 | func `as`(_:((Int, Int) throws -> Int).Type = ((Int, Int) throws -> Int).self) -> ((Int, Int) throws -> Int)? 26 | { 27 | nil 28 | } 29 | } -------------------------------------------------------------------------------- /Examples/ValidExamples/DocComments.spf: -------------------------------------------------------------------------------- 1 | @basis 2 | let httpCodes:[Never] = 3 | [ 4 | 200, 5 | 404, 6 | 500 7 | ] 8 | @basis 9 | let httpStatuses:[Never] = 10 | [ 11 | ok, 12 | notFound, 13 | serverError 14 | ] 15 | 16 | enum HTTP 17 | { 18 | /// The numeric code for `\(__name__)`, \(__code__). 19 | /// 20 | /// ```swift 21 | /// // prints the number \(__code__) 22 | /// let string:String = 23 | /// """ 24 | /// \(HTTP.\(__name__)) 25 | /// """ 26 | /// print(string) 27 | /// ``` 28 | @matrix(__code__: httpCodes, __name__: httpStatuses) 29 | static 30 | let __name__:Int = __code__ 31 | 32 | /// basis elements render *exactly* as they do in source: 33 | /// \(__tuple__), but they do not include surrounding trivia. 34 | @matrix(__property__: [a, b, c], __tuple__: [("a", 1) , (b, b: 2), (c)]) 35 | var __property__:Never 36 | { 37 | fatalError() 38 | } 39 | } -------------------------------------------------------------------------------- /Examples/ValidExamples/DocComments.spf.swift: -------------------------------------------------------------------------------- 1 | 2 | 3 | enum HTTP 4 | { 5 | /// The numeric code for `ok`, 200. 6 | /// 7 | /// ```swift 8 | /// // prints the number 200 9 | /// let string:String = 10 | /// """ 11 | /// \(HTTP.ok) 12 | /// """ 13 | /// print(string) 14 | /// ``` 15 | static 16 | let ok:Int = 200 17 | /// The numeric code for `notFound`, 404. 18 | /// 19 | /// ```swift 20 | /// // prints the number 404 21 | /// let string:String = 22 | /// """ 23 | /// \(HTTP.notFound) 24 | /// """ 25 | /// print(string) 26 | /// ``` 27 | static 28 | let notFound:Int = 404 29 | /// The numeric code for `serverError`, 500. 30 | /// 31 | /// ```swift 32 | /// // prints the number 500 33 | /// let string:String = 34 | /// """ 35 | /// \(HTTP.serverError) 36 | /// """ 37 | /// print(string) 38 | /// ``` 39 | static 40 | let serverError:Int = 500 41 | 42 | /// basis elements render *exactly* as they do in source: 43 | /// ("a", 1), but they do not include surrounding trivia. 44 | var a:Never 45 | { 46 | fatalError() 47 | } 48 | 49 | /// basis elements render *exactly* as they do in source: 50 | /// (b, b: 2), but they do not include surrounding trivia. 51 | var b:Never 52 | { 53 | fatalError() 54 | } 55 | 56 | /// basis elements render *exactly* as they do in source: 57 | /// (c), but they do not include surrounding trivia. 58 | var c:Never 59 | { 60 | fatalError() 61 | } 62 | } -------------------------------------------------------------------------------- /Examples/ValidExamples/Empty.swift: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tayloraswift/swift-package-factory/babb16e83198e53da6541cb19978d3e3356a3ab8/Examples/ValidExamples/Empty.swift -------------------------------------------------------------------------------- /Examples/ValidExamples/Nested.spf: -------------------------------------------------------------------------------- 1 | import Swift 2 | 3 | // vector arities 4 | @basis 5 | let vectors:[Never] = 6 | [ 7 | Vector2, 8 | Vector3, 9 | Vector4, 10 | ] 11 | // vector scalar constraints 12 | @basis 13 | let scalars:[Never] = 14 | [ 15 | FixedWidthInteger, 16 | BinaryFloatingPoint, 17 | ] 18 | // vector components 19 | @basis 20 | let components:[Never] = 21 | [ 22 | [x, y], 23 | [x, y, z], 24 | [x, y, z, w], 25 | ] 26 | 27 | @matrix(__Type__: vectors, __components__: components) 28 | @frozen public 29 | struct __Type__:Hashable, Sendable where T:Hashable & Sendable 30 | { 31 | /// The *\(__component__)*-component of this vector. 32 | @matrix(__component__: __components__) 33 | public 34 | var __component__:T 35 | } 36 | 37 | @matrix(__Scalar__: scalars) 38 | @matrix(__Type__: vectors) 39 | extension __Type__ where T:__Scalar__ 40 | { 41 | } -------------------------------------------------------------------------------- /Examples/ValidExamples/Nested.spf.swift: -------------------------------------------------------------------------------- 1 | import Swift 2 | 3 | @frozen public 4 | struct Vector2:Hashable, Sendable where T:Hashable & Sendable 5 | { 6 | /// The *x*-component of this vector. 7 | public 8 | var x:T 9 | /// The *y*-component of this vector. 10 | public 11 | var y:T 12 | } 13 | 14 | @frozen public 15 | struct Vector3:Hashable, Sendable where T:Hashable & Sendable 16 | { 17 | /// The *x*-component of this vector. 18 | public 19 | var x:T 20 | /// The *y*-component of this vector. 21 | public 22 | var y:T 23 | /// The *z*-component of this vector. 24 | public 25 | var z:T 26 | } 27 | 28 | @frozen public 29 | struct Vector4:Hashable, Sendable where T:Hashable & Sendable 30 | { 31 | /// The *x*-component of this vector. 32 | public 33 | var x:T 34 | /// The *y*-component of this vector. 35 | public 36 | var y:T 37 | /// The *z*-component of this vector. 38 | public 39 | var z:T 40 | /// The *w*-component of this vector. 41 | public 42 | var w:T 43 | } 44 | 45 | extension Vector2 where T:FixedWidthInteger 46 | { 47 | } 48 | 49 | extension Vector3 where T:FixedWidthInteger 50 | { 51 | } 52 | 53 | extension Vector4 where T:FixedWidthInteger 54 | { 55 | } 56 | 57 | extension Vector2 where T:BinaryFloatingPoint 58 | { 59 | } 60 | 61 | extension Vector3 where T:BinaryFloatingPoint 62 | { 63 | } 64 | 65 | extension Vector4 where T:BinaryFloatingPoint 66 | { 67 | } -------------------------------------------------------------------------------- /Examples/ValidExamples/OtherAttributes.spf: -------------------------------------------------------------------------------- 1 | @basis 2 | let genericTypes:[Never] = 3 | [ 4 | X, 5 | Y, 6 | Z, 7 | ] 8 | @basis 9 | let operators:[Never] = 10 | [ 11 | (+), 12 | (-), 13 | (*), 14 | ] 15 | 16 | // this comment will be kept. 17 | /// This doccomment will also be kept. 18 | @matrix(__Type__: genericTypes, __GenericParameter__: [T, U, V], __operator__: operators) 19 | // if this comment is kept, it will orphan the 20 | // doccomment above it, so it will be discarded. 21 | @resultBuilder 22 | // this comment will stay, because the attribute 23 | // it is attached to was kept, and the attribute 24 | // above it has a doccomment attached 25 | @frozen public 26 | struct __Type__<__GenericParameter__> 27 | { 28 | public static 29 | func buildBlock(_ components:Int...) -> Int 30 | { 31 | components.reduce(0, __operator__) 32 | } 33 | } 34 | 35 | @basis 36 | let types:[Never] = 37 | [ 38 | A, 39 | B, 40 | C, 41 | ] 42 | 43 | // this comment will be kept. 44 | /// This doccomment will also be kept. 45 | @resultBuilder 46 | // this comment will stay, because the attribute 47 | // it is attached to was kept, and the attribute 48 | // above it has a doccomment attached 49 | @frozen 50 | /// this comment will be deleted, even though it is a 51 | /// doccomment, because the @matrix attribute 52 | /// below is not the first attribute. 53 | @matrix(__Type__: types) 54 | public 55 | struct __Type__ 56 | { 57 | public static 58 | func buildBlock(_ components:Int...) -> Int 59 | { 60 | components.reduce(0, +) 61 | } 62 | } -------------------------------------------------------------------------------- /Examples/ValidExamples/OtherAttributes.spf.swift: -------------------------------------------------------------------------------- 1 | 2 | 3 | // this comment will be kept. 4 | /// This doccomment will also be kept. 5 | @resultBuilder 6 | // this comment will stay, because the attribute 7 | // it is attached to was kept, and the attribute 8 | // above it has a doccomment attached 9 | @frozen public 10 | struct X 11 | { 12 | public static 13 | func buildBlock(_ components:Int...) -> Int 14 | { 15 | components.reduce(0, (+)) 16 | } 17 | } 18 | 19 | // this comment will be kept. 20 | /// This doccomment will also be kept. 21 | @resultBuilder 22 | // this comment will stay, because the attribute 23 | // it is attached to was kept, and the attribute 24 | // above it has a doccomment attached 25 | @frozen public 26 | struct Y 27 | { 28 | public static 29 | func buildBlock(_ components:Int...) -> Int 30 | { 31 | components.reduce(0, (-)) 32 | } 33 | } 34 | 35 | // this comment will be kept. 36 | /// This doccomment will also be kept. 37 | @resultBuilder 38 | // this comment will stay, because the attribute 39 | // it is attached to was kept, and the attribute 40 | // above it has a doccomment attached 41 | @frozen public 42 | struct Z 43 | { 44 | public static 45 | func buildBlock(_ components:Int...) -> Int 46 | { 47 | components.reduce(0, (*)) 48 | } 49 | } 50 | 51 | // this comment will be kept. 52 | /// This doccomment will also be kept. 53 | @resultBuilder 54 | // this comment will stay, because the attribute 55 | // it is attached to was kept, and the attribute 56 | // above it has a doccomment attached 57 | @frozen 58 | public 59 | struct A 60 | { 61 | public static 62 | func buildBlock(_ components:Int...) -> Int 63 | { 64 | components.reduce(0, +) 65 | } 66 | } 67 | 68 | // this comment will be kept. 69 | /// This doccomment will also be kept. 70 | @resultBuilder 71 | // this comment will stay, because the attribute 72 | // it is attached to was kept, and the attribute 73 | // above it has a doccomment attached 74 | @frozen 75 | public 76 | struct B 77 | { 78 | public static 79 | func buildBlock(_ components:Int...) -> Int 80 | { 81 | components.reduce(0, +) 82 | } 83 | } 84 | 85 | // this comment will be kept. 86 | /// This doccomment will also be kept. 87 | @resultBuilder 88 | // this comment will stay, because the attribute 89 | // it is attached to was kept, and the attribute 90 | // above it has a doccomment attached 91 | @frozen 92 | public 93 | struct C 94 | { 95 | public static 96 | func buildBlock(_ components:Int...) -> Int 97 | { 98 | components.reduce(0, +) 99 | } 100 | } -------------------------------------------------------------------------------- /Examples/ValidExamples/PrimaryAssociatedtypeDowngrade.spf: -------------------------------------------------------------------------------- 1 | /// This is an evolving protocol with a primary 2 | /// associatedtype. 3 | @matrix(__Protocol__: [EvolvingProtocolA, EvolvingProtocolB]) 4 | @retro protocol __Protocol__ 5 | { 6 | associatedtype Element 7 | associatedtype Index:Strideable 8 | 9 | init() 10 | } 11 | /// Another example. 12 | @retro protocol AnotherProtocol 13 | { 14 | associatedtype Wrapped 15 | associatedtype Projection 16 | } 17 | -------------------------------------------------------------------------------- /Examples/ValidExamples/PrimaryAssociatedtypeDowngrade.spf.swift: -------------------------------------------------------------------------------- 1 | 2 | #if swift(>=5.7) 3 | /// This is an evolving protocol with a primary 4 | /// associatedtype. 5 | protocol EvolvingProtocolA 6 | { 7 | associatedtype Element 8 | associatedtype Index:Strideable 9 | 10 | init() 11 | } 12 | #else 13 | /// This is an evolving protocol with a primary 14 | /// associatedtype. 15 | protocol EvolvingProtocolA 16 | { 17 | associatedtype Element 18 | associatedtype Index:Strideable 19 | 20 | init() 21 | } 22 | #endif 23 | #if swift(>=5.7) 24 | /// This is an evolving protocol with a primary 25 | /// associatedtype. 26 | protocol EvolvingProtocolB 27 | { 28 | associatedtype Element 29 | associatedtype Index:Strideable 30 | 31 | init() 32 | } 33 | #else 34 | /// This is an evolving protocol with a primary 35 | /// associatedtype. 36 | protocol EvolvingProtocolB 37 | { 38 | associatedtype Element 39 | associatedtype Index:Strideable 40 | 41 | init() 42 | } 43 | #endif 44 | #if swift(>=5.7) 45 | /// Another example. 46 | protocol AnotherProtocol 47 | { 48 | associatedtype Wrapped 49 | associatedtype Projection 50 | } 51 | #else 52 | /// Another example. 53 | protocol AnotherProtocol 54 | { 55 | associatedtype Wrapped 56 | associatedtype Projection 57 | } 58 | #endif 59 | -------------------------------------------------------------------------------- /Examples/ValidExamples/Scopes.spf: -------------------------------------------------------------------------------- 1 | @basis 2 | let typenames:[Never] = 3 | [ 4 | OuterA, 5 | OuterB, 6 | OuterC 7 | ] 8 | 9 | @matrix(__Outer__: typenames) 10 | enum __Outer__ 11 | { 12 | @basis 13 | let typenames:[Never] = 14 | [ 15 | InnerA, 16 | InnerB, 17 | InnerC 18 | ] 19 | @matrix(__Inner__: typenames) 20 | enum __Inner__:Sendable 21 | { 22 | } 23 | } 24 | 25 | @matrix(__Outer__: typenames) 26 | extension __Outer__:Sendable 27 | { 28 | } -------------------------------------------------------------------------------- /Examples/ValidExamples/Scopes.spf.swift: -------------------------------------------------------------------------------- 1 | 2 | 3 | enum OuterA 4 | { 5 | enum InnerA:Sendable 6 | { 7 | } 8 | enum InnerB:Sendable 9 | { 10 | } 11 | enum InnerC:Sendable 12 | { 13 | } 14 | } 15 | 16 | enum OuterB 17 | { 18 | enum InnerA:Sendable 19 | { 20 | } 21 | enum InnerB:Sendable 22 | { 23 | } 24 | enum InnerC:Sendable 25 | { 26 | } 27 | } 28 | 29 | enum OuterC 30 | { 31 | enum InnerA:Sendable 32 | { 33 | } 34 | enum InnerB:Sendable 35 | { 36 | } 37 | enum InnerC:Sendable 38 | { 39 | } 40 | } 41 | 42 | extension OuterA:Sendable 43 | { 44 | } 45 | 46 | extension OuterB:Sendable 47 | { 48 | } 49 | 50 | extension OuterC:Sendable 51 | { 52 | } -------------------------------------------------------------------------------- /Examples/ValidExamples/Zip.spf: -------------------------------------------------------------------------------- 1 | @basis 2 | let vectors:[Never] = 3 | [ 4 | SIMD2, 5 | SIMD4, 6 | SIMD8, 7 | SIMD16, 8 | SIMD32, 9 | ] 10 | 11 | @matrix(__SIMDType__: vectors, __Slug__: [UInt16, UInt32, UInt64]) 12 | extension __SIMDType__ where Scalar == UInt8 13 | { 14 | var slug:__Slug__ 15 | { 16 | unsafeBitCast(self, to: __Slug__.self) 17 | } 18 | } -------------------------------------------------------------------------------- /Examples/ValidExamples/Zip.spf.swift: -------------------------------------------------------------------------------- 1 | 2 | 3 | extension SIMD2 where Scalar == UInt8 4 | { 5 | var slug:UInt16 6 | { 7 | unsafeBitCast(self, to: UInt16.self) 8 | } 9 | } 10 | 11 | extension SIMD4 where Scalar == UInt8 12 | { 13 | var slug:UInt32 14 | { 15 | unsafeBitCast(self, to: UInt32.self) 16 | } 17 | } 18 | 19 | extension SIMD8 where Scalar == UInt8 20 | { 21 | var slug:UInt64 22 | { 23 | unsafeBitCast(self, to: UInt64.self) 24 | } 25 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2022 Kelvin Ma (@taylorswift) 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | the `swift-package-factory` plugin and library was created by kelvin ma (@taylorswift). 2 | 3 | you are welcome to contribute to this project at: 4 | 5 | https://github.com/kelvin13/swift-package-factory 6 | 7 | we do not maintain any other mirrors of this repository, and such 8 | forks of this repository may not carry the most up-to-date code. 9 | 10 | contributors: 11 | 12 | 1. kelvin ma (@taylorswift, 2022) -------------------------------------------------------------------------------- /Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "pins" : [ 3 | { 4 | "identity" : "swift-syntax", 5 | "kind" : "remoteSourceControl", 6 | "location" : "https://github.com/apple/swift-syntax.git", 7 | "state" : { 8 | "branch" : "swift-DEVELOPMENT-SNAPSHOT-2022-12-17-a", 9 | "revision" : "e4a3ce84b16d777a3f9da4887140061ae77facfb" 10 | } 11 | }, 12 | { 13 | "identity" : "swift-system", 14 | "kind" : "remoteSourceControl", 15 | "location" : "https://github.com/apple/swift-system.git", 16 | "state" : { 17 | "revision" : "025bcb1165deab2e20d4eaba79967ce73013f496", 18 | "version" : "1.2.1" 19 | } 20 | }, 21 | { 22 | "identity" : "swift-system-extras", 23 | "kind" : "remoteSourceControl", 24 | "location" : "https://github.com/kelvin13/swift-system-extras.git", 25 | "state" : { 26 | "revision" : "42f297a3191e668ed072878d5db3890db8eada50", 27 | "version" : "0.2.0" 28 | } 29 | } 30 | ], 31 | "version" : 2 32 | } 33 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.6 2 | import PackageDescription 3 | 4 | let toolchain:String = "swift-DEVELOPMENT-SNAPSHOT-2022-12-17-a" 5 | 6 | let package:Package = .init( 7 | name: "swift-package-factory", 8 | platforms: 9 | [ 10 | .macOS(.v11) 11 | ], 12 | products: 13 | [ 14 | .executable(name: "swift-package-factory", targets: ["swift-package-factory"]), 15 | .library(name: "Factory", targets: ["Factory"]), 16 | .plugin(name: "FactoryPlugin", targets: ["FactoryPlugin"]), 17 | ], 18 | dependencies: 19 | [ 20 | .package(url: "https://github.com/kelvin13/swift-system-extras.git", from: "0.2.0"), 21 | .package(url: "https://github.com/apple/swift-syntax.git", branch: toolchain), 22 | ], 23 | targets: 24 | [ 25 | .target(name: "Factory", 26 | dependencies: 27 | [ 28 | .product(name: "SystemExtras", package: "swift-system-extras"), 29 | .product(name: "SwiftSyntax", package: "swift-syntax"), 30 | .product(name: "SwiftSyntaxParser", package: "swift-syntax"), 31 | .product(name: "SwiftSyntaxBuilder", package: "swift-syntax"), 32 | ]), 33 | .executableTarget(name: "swift-package-factory", 34 | dependencies: 35 | [ 36 | .target(name: "Factory"), 37 | ]), 38 | .plugin(name: "FactoryPlugin", 39 | capability: .command( 40 | intent: .custom(verb: "factory", 41 | description: "generate swift sources from factory sources"), 42 | permissions: 43 | [ 44 | .writeToPackageDirectory(reason: "factory emits source files") 45 | ]), 46 | dependencies: 47 | [ 48 | .target(name: "swift-package-factory"), 49 | ]), 50 | 51 | .target(name: "ValidExamples", path: "Examples/ValidExamples"), 52 | .target(name: "InvalidExamples", path: "Examples/InvalidExamples"), 53 | ] 54 | ) 55 | -------------------------------------------------------------------------------- /Plugins/FactoryPlugin/Main.swift: -------------------------------------------------------------------------------- 1 | import PackagePlugin 2 | 3 | #if os(Linux) 4 | import Glibc 5 | #elseif os(macOS) 6 | import Darwin 7 | #endif 8 | 9 | @main 10 | struct Main:CommandPlugin 11 | { 12 | private static 13 | func targets(context:PluginContext, filter:[String]) throws -> [SwiftSourceModuleTarget] 14 | { 15 | var targets:[String: [SwiftSourceModuleTarget]] = [:] 16 | for target:any Target in context.package.targets 17 | { 18 | guard let target:SwiftSourceModuleTarget = target as? SwiftSourceModuleTarget 19 | else 20 | { 21 | continue 22 | } 23 | targets[target.name, default: []].append(target) 24 | } 25 | if filter.isEmpty 26 | { 27 | return targets.sorted { $0.key < $1.key } .flatMap(\.value) 28 | } 29 | else 30 | { 31 | return try filter.flatMap 32 | { 33 | (name:String) -> [SwiftSourceModuleTarget] in 34 | if let targets:[SwiftSourceModuleTarget] = targets[name] 35 | { 36 | return targets 37 | } 38 | else 39 | { 40 | throw MissingTargetError.init(name: name) 41 | } 42 | } 43 | } 44 | } 45 | func performCommand(context:PluginContext, arguments:[String]) throws 46 | { 47 | let tool:PluginContext.Tool = try context.tool(named: "swift-package-factory") 48 | for target:SwiftSourceModuleTarget in 49 | try Self.targets(context: context, filter: arguments) 50 | { 51 | for file:File in target.sourceFiles 52 | { 53 | guard case .unknown = file.type 54 | else 55 | { 56 | continue 57 | } 58 | switch file.path.extension 59 | { 60 | case "spf", "swiftpf", "factory": 61 | do 62 | { 63 | try tool.path.string.withCString 64 | { 65 | (ctool:UnsafePointer) in 66 | try file.path.string.withCString 67 | { 68 | (cfile:UnsafePointer) in 69 | // must be null-terminated! 70 | let argv:[UnsafeMutablePointer?] = 71 | [ 72 | .init(mutating: ctool), 73 | .init(mutating: cfile), 74 | nil 75 | ] 76 | var pid:pid_t = 0 77 | switch posix_spawn(&pid, ctool, nil, nil, argv, nil) 78 | { 79 | case 0: 80 | break 81 | case let code: 82 | throw ToolError.init(file: file.path.string, 83 | subtask: .posix_spawn, 84 | status: code) 85 | } 86 | var status:Int32 = 0 87 | switch waitpid(pid, &status, 0) 88 | { 89 | case pid: 90 | break 91 | case let code: 92 | throw ToolError.init(file: file.path.string, 93 | subtask: .waitpid, 94 | status: code) 95 | } 96 | guard status == 0 97 | else 98 | { 99 | throw ToolError.init(file: file.path.string, 100 | subtask: .factory, 101 | status: status) 102 | } 103 | } 104 | } 105 | } 106 | 107 | default: 108 | continue 109 | } 110 | } 111 | } 112 | } 113 | } -------------------------------------------------------------------------------- /Plugins/FactoryPlugin/MissingTargetError.swift: -------------------------------------------------------------------------------- 1 | public 2 | struct MissingTargetError:Error 3 | { 4 | public 5 | let name:String 6 | public 7 | init(name:String) 8 | { 9 | self.name = name 10 | } 11 | } 12 | extension MissingTargetError:CustomStringConvertible 13 | { 14 | public 15 | var description:String 16 | { 17 | "target '\(self.name)' is not a swift source module in this package" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Plugins/FactoryPlugin/ToolError.swift: -------------------------------------------------------------------------------- 1 | public 2 | struct ToolError:Error 3 | { 4 | public 5 | enum Subtask:String 6 | { 7 | case posix_spawn = "posix_spawn" 8 | case waitpid = "waitpid" 9 | case factory = "swift-package-factory" 10 | } 11 | 12 | public 13 | let file:String 14 | public 15 | let subtask:Subtask 16 | public 17 | let status:Int32 18 | } 19 | extension ToolError:CustomStringConvertible 20 | { 21 | public 22 | var description:String 23 | { 24 | "failed to transform file '\(self.file)' (\(self.subtask.rawValue) exited with code \(self.status))" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | ***`factory`***
`2022-12-17-a` 4 | 5 | [![ci build status](https://github.com/kelvin13/swift-package-factory/actions/workflows/build.yml/badge.svg)](https://github.com/kelvin13/swift-package-factory/actions/workflows/build.yml) 6 | 7 |
8 | 9 | **`factory`** is a structured, type-safe source generation tool. It is intended to be a replacement for (and improvement over) the `gyb` tool! 10 | 11 | `factory` is powered by [`swift-syntax`](https://github.com/apple/swift-syntax), so it evolves with the toolchain. **You cannot run it with the 5.6.2 release toolchain**, because the 5.6.2 toolchain is too old and does not support the API `factory` needs to transform your sources safely. 12 | 13 | The current toolchain pin is: 14 | 15 | [**`swift-DEVELOPMENT-SNAPSHOT-2022-12-17-a`**](https://github.com/apple/swift-syntax/tags) 16 | 17 | Swift files *generated* by `factory` are still backwards compatible, in fact one of the main use cases of `factory` is back-deployment. 18 | 19 | ## Platforms 20 | 21 | SPF officially supports Linux and macOS. 22 | 23 | Please note that on macOS, SPM sets the [wrong `@rpath`](https://forums.swift.org/t/5-8-compiler-sets-rpath-to-usr-lib-swift-5-5-macosx-why/59797) by default, so you will need to manually add a symlink to `lib_InternalSwiftSyntaxParser.dylib` inside your build artifacts directory. 24 | 25 | ## Overview 26 | 27 | `factory` was designed with the following goals in mind: 28 | 29 | 1. Template files should look like normal `.swift` files, so highlighters and IDEs don’t freak out. 30 | 31 | 2. Templates should be **safe**, and prohibit arbitrary string splicing or token substitutions. 32 | 33 | 3. Templates should work well with documentation comments. 34 | 35 | 4. Template syntax should be minimal, purely additive, and source generation tooling should accept and return vanilla `.swift` sources unchanged. 36 | 37 | 5. Template users should be able to use as much or as little templating as they like, and using templating on one declaration should not increase the cognitive burden of the rest of the code in the file. 38 | 39 | 6. Templating systems should nudge users towards using **the least amount of templating necessary** for their use-case. 40 | 41 | 7. Template sources should be self-explanatory, and understandable by developers who have never heard of `swift-package-factory`. 42 | 43 | 8. Template users should be able to *stop* using a templating system, and be able to assume responsibility for maintaining generated `.swift` files at any time. 44 | 45 | In a nutshell: 46 | 47 | > [`Basic.spf`](Examples/ValidExamples/Basic.spf) 48 | ```swift 49 | extension Int 50 | { 51 | @matrix(__ordinal__: [i, j, k], __value__: [0, 1, 2]) 52 | @inlinable public 53 | var __ordinal__:Int 54 | { 55 | __value__ 56 | } 57 | 58 | @basis 59 | let cases:[Never] = [a, b] 60 | 61 | enum Cases:Int 62 | { 63 | @matrix(__case__: cases) 64 | case __case__ 65 | } 66 | 67 | @matrix(__case__: cases) 68 | public static 69 | var __case__:Self 70 | { 71 | Cases.__case__.rawValue 72 | } 73 | } 74 | ``` 75 | 76 | > [`Basic.spf.swift`](Examples/ValidExamples/Basic.spf.swift) 77 | ```swift 78 | extension Int 79 | { 80 | @inlinable public 81 | var i:Int 82 | { 83 | 0 84 | } 85 | @inlinable public 86 | var j:Int 87 | { 88 | 1 89 | } 90 | @inlinable public 91 | var k:Int 92 | { 93 | 2 94 | } 95 | 96 | enum Cases:Int 97 | { 98 | case a 99 | case b 100 | } 101 | 102 | public static 103 | var a:Self 104 | { 105 | Cases.a.rawValue 106 | } 107 | 108 | public static 109 | var b:Self 110 | { 111 | Cases.b.rawValue 112 | } 113 | } 114 | ``` 115 | 116 | ## Getting started 117 | 118 | Check out the [`Examples`](Examples/) directory to learn how to use SPF! 119 | 120 | ## Features 121 | 122 | `factory` extends the Swift language with three attributes: 123 | 124 | 1. **`@basis`** 125 | 126 | Defines a sequence of tokens to iterate over when generating declarations from a template. It can be applied to a `let` binding, and it must be initialized with an array literal. 127 | 128 | The declaration it is attached to will be removed from the generated `.swift` code, along with any associated comments and doccomments. 129 | 130 | 2. **`@matrix`** 131 | 132 | Replicates the declaration it is attached to, along with any associated comments and doccomments. It takes `@basis` bindings or and/or inline array literals as arguments, with the name of the argument becoming the name of the loop variable. If more than one basis is given, `@matrix` zips them, and will discard trailing basis elements if their lengths differ. 133 | 134 | `@matrix` can be applied to an `associatedtype`, `actor`, `class`, `case`, `enum`, `extension`, `func`, `import`, `init`, `operator`, precedence group, `protocol`, `struct`, `subscript`, `typealias`, `let`, or `var` declaration. 135 | 136 | 3. **`@retro`** 137 | 138 | Downgrades a protocol with primary associated types to a protocol without any, and gates the two variants by `#if swift(>=5.7)`. It can be applied to a `protocol` with at least one primary `associatedtype`. 139 | 140 | `@retro` copies any comments and doccomments attached to the original `protocol`, and includes them in the generated `#if` blocks. -------------------------------------------------------------------------------- /Sources/Factory/Error.swift: -------------------------------------------------------------------------------- 1 | extension Factory 2 | { 3 | public 4 | enum BasisError:Error 5 | { 6 | case expectedInitializationExpression 7 | case expectedArrayLiteral 8 | 9 | public 10 | var description:String 11 | { 12 | switch self 13 | { 14 | case .expectedInitializationExpression: 15 | return "expected initialization expression" 16 | case .expectedArrayLiteral: 17 | return "expected array literal" 18 | } 19 | } 20 | } 21 | public 22 | enum RetroError:Error 23 | { 24 | case unexpectedArguments 25 | case expectedProtocol 26 | case expectedPrimaryAssociatedTypeClause 27 | 28 | public 29 | var description:String 30 | { 31 | switch self 32 | { 33 | case .unexpectedArguments: 34 | return "@retro takes no arguments" 35 | case .expectedProtocol: 36 | return "@retro can only be applied to a protocol" 37 | case .expectedPrimaryAssociatedTypeClause: 38 | return "@retro can only be applied to a protocol with primary associated types" 39 | } 40 | } 41 | } 42 | public 43 | enum MatrixError:Error 44 | { 45 | case missingArguments 46 | case missingBinding 47 | case undefinedBasis(String) 48 | case invalidBasis(for:String) 49 | 50 | public 51 | var description:String 52 | { 53 | switch self 54 | { 55 | case .missingArguments: 56 | return "@matrix expects at least one loop argument" 57 | case .missingBinding: 58 | return "@matrix loop requires a binding" 59 | case .undefinedBasis(let variable): 60 | return "@matrix basis '\(variable)' is not defined in this lexical scope" 61 | case .invalidBasis(for: let binding): 62 | return "@matrix basis for '\(binding)' must be an array literal or a @basis binding" 63 | } 64 | } 65 | } 66 | public 67 | enum SubstitutionError:Error 68 | { 69 | case notAnIdentifier(String, replacing:String) 70 | 71 | public 72 | var description:String 73 | { 74 | switch self 75 | { 76 | case .notAnIdentifier(let expression, replacing: let name): 77 | return "identifier token '\(name)' cannot be replaced by expression `\(expression)`" 78 | } 79 | } 80 | } 81 | } -------------------------------------------------------------------------------- /Sources/Factory/Factory.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntaxParser 2 | import SwiftSyntax 3 | 4 | public 5 | enum Factory 6 | { 7 | public static 8 | func transform(syntax source:SourceFileSyntax) throws -> SourceFileSyntax 9 | { 10 | let transformer:Transformer = .init() 11 | let output:SourceFileSyntax = transformer.visit(source) 12 | if let error:any Error = transformer.errors.first 13 | { 14 | throw error 15 | } 16 | else 17 | { 18 | return output 19 | } 20 | } 21 | public static 22 | func transform(source:String, filenameForDiagnostics:String = "") throws -> String 23 | { 24 | let source:SourceFileSyntax = try SyntaxParser.parse(source: source, 25 | filenameForDiagnostics: filenameForDiagnostics) 26 | return try Self.transform(syntax: source).description 27 | } 28 | } -------------------------------------------------------------------------------- /Sources/Factory/Instantiator.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | import SwiftSyntaxParser 3 | 4 | extension ExprSyntax 5 | { 6 | func reparsedAsType() -> TypeSyntax? 7 | { 8 | if let reparsed:SourceFileSyntax = 9 | try? SyntaxParser.parse(source: "_ as \(self.description)"), 10 | reparsed.statements.count == 1, 11 | let reparsed:CodeBlockItemSyntax.Item = reparsed.statements.first?.item, 12 | let reparsed:SequenceExprSyntax = reparsed.as(SequenceExprSyntax.self), 13 | reparsed.elements.count == 3, 14 | let reparsed:TypeExprSyntax = reparsed.elements.last?.as(TypeExprSyntax.self) 15 | { 16 | return reparsed.type 17 | } 18 | else 19 | { 20 | return nil 21 | } 22 | } 23 | } 24 | 25 | final 26 | class Instantiator:SyntaxRewriter 27 | { 28 | let substitutions:[[String: ExprSyntax]] 29 | var errors:[any Error] 30 | 31 | private final 32 | func lookup(_ identifier:String) -> ExprSyntax? 33 | { 34 | for substitutions:[String: ExprSyntax] in self.substitutions.reversed() 35 | { 36 | if let expression:ExprSyntax = substitutions[identifier] 37 | { 38 | return expression 39 | } 40 | } 41 | return nil 42 | } 43 | 44 | init(_ substitutions:[[String: ExprSyntax]]) 45 | { 46 | self.substitutions = substitutions 47 | self.errors = [] 48 | super.init() 49 | } 50 | 51 | final override 52 | func visit(_ expression:SimpleTypeIdentifierSyntax) -> TypeSyntax 53 | { 54 | if case .identifier(let identifier) = expression.name.tokenKind, 55 | case nil = expression.genericArgumentClause, 56 | let substitution:TypeSyntax = self.lookup(identifier)?.reparsedAsType() 57 | { 58 | // preserve the original trivia 59 | return substitution 60 | .withLeadingTrivia(expression.name.leadingTrivia) 61 | .withTrailingTrivia(expression.name.trailingTrivia) 62 | } 63 | else 64 | { 65 | return super.visit(expression) 66 | } 67 | } 68 | final override 69 | func visit(_ expression:IdentifierExprSyntax) -> ExprSyntax 70 | { 71 | if case .identifier(let identifier) = expression.identifier.tokenKind, 72 | let substitution:ExprSyntax = self.lookup(identifier) 73 | { 74 | // preserve the original trivia 75 | return substitution 76 | .withLeadingTrivia(expression.identifier.leadingTrivia) 77 | .withTrailingTrivia(expression.identifier.trailingTrivia) 78 | } 79 | else 80 | { 81 | return super.visit(expression) 82 | } 83 | } 84 | final override 85 | func visit(_ token:TokenSyntax) -> TokenSyntax 86 | { 87 | let token:TokenSyntax = token 88 | .withLeadingTrivia(self.visit(trivia: token.leadingTrivia)) 89 | .withTrailingTrivia(self.visit(trivia: token.trailingTrivia)) 90 | if case .identifier(let identifier) = token.tokenKind, 91 | let substitution:ExprSyntax = self.lookup(identifier) 92 | { 93 | guard let substitution:IdentifierExprSyntax = substitution.as(IdentifierExprSyntax.self) 94 | else 95 | { 96 | // API cannot throw... 97 | let error:Factory.SubstitutionError = .notAnIdentifier(substitution.description, 98 | replacing: identifier) 99 | self.errors.append(error) 100 | return token 101 | } 102 | // preserve the original trivia 103 | return token.withKind(substitution.identifier.tokenKind) 104 | } 105 | else 106 | { 107 | return super.visit(token) 108 | } 109 | } 110 | 111 | private final 112 | func visit(trivia:Trivia) -> Trivia 113 | { 114 | .init(pieces: trivia.map 115 | { 116 | switch $0 117 | { 118 | case .docLineComment(let comment): 119 | return .docLineComment(self.visit(docComment: comment)) 120 | case .docBlockComment(let comment): 121 | return .docBlockComment(self.visit(docComment: comment)) 122 | case let piece: 123 | return piece 124 | } 125 | }) 126 | } 127 | private final 128 | func visit(docComment string:String) -> String 129 | { 130 | var substitutions:[(range:Range, substitution:String)] = [] 131 | // look for '\(' and ')' tokens. we are only interested 132 | // in the innermost pairings 133 | var index:String.Index = string.startIndex 134 | var recorded:(exterior:String.Index, interior:String.Index)? = nil 135 | while index < string.endIndex 136 | { 137 | switch (recorded, string[index]) 138 | { 139 | case (_, "\\"): 140 | let start:String.Index = index 141 | string.formIndex(after: &index) 142 | if index < string.endIndex, string[index] == "(" 143 | { 144 | string.formIndex(after: &index) 145 | recorded = (start, index) 146 | } 147 | case (let start?, ")"): 148 | recorded = nil 149 | if let substitution:ExprSyntax = 150 | self.lookup(.init(string[start.interior ..< index])) 151 | { 152 | string.formIndex(after: &index) 153 | substitutions.append((start.exterior ..< index, substitution.description)) 154 | } 155 | else 156 | { 157 | fallthrough 158 | } 159 | default: 160 | string.formIndex(after: &index) 161 | } 162 | } 163 | return string.replacingSubranges(substitutions) 164 | } 165 | } 166 | extension String 167 | { 168 | func replacingSubranges(_ subranges:[(range:Range, substitution:String)]) -> Self 169 | { 170 | // fast path 171 | if subranges.isEmpty 172 | { 173 | return self 174 | } 175 | var spliced:Self = "" 176 | var current:String.Index = self.startIndex 177 | for (range, substitution):(Range, String) in subranges 178 | { 179 | spliced += self[current ..< range.lowerBound] 180 | spliced += substitution 181 | current = range.upperBound 182 | } 183 | if current < self.endIndex 184 | { 185 | spliced += self[current...] 186 | } 187 | return spliced 188 | } 189 | } -------------------------------------------------------------------------------- /Sources/Factory/LexicalScope.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | 3 | protocol LexicalScope:SyntaxCollection, BidirectionalCollection 4 | { 5 | init(_:[Element]) 6 | } 7 | extension CodeBlockItemListSyntax:LexicalScope {} 8 | extension MemberDeclListSyntax:LexicalScope {} 9 | 10 | extension LexicalScope 11 | { 12 | mutating 13 | func remove(where recognize:(Element) throws -> Recognized?) 14 | rethrows -> [Recognized] 15 | { 16 | var removed:[Recognized] = [] 17 | var kept:[Element] = [] 18 | for element:Element in self 19 | { 20 | if let recognized:Recognized = try recognize(element) 21 | { 22 | removed.append(recognized) 23 | } 24 | else 25 | { 26 | kept.append(element) 27 | } 28 | } 29 | if !removed.isEmpty 30 | { 31 | self = .init(kept) 32 | } 33 | return removed 34 | } 35 | } -------------------------------------------------------------------------------- /Sources/Factory/Loop.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | 3 | struct Loop:RandomAccessCollection 4 | { 5 | struct Thread 6 | { 7 | let binding:String 8 | let basis:[ExprSyntax] 9 | } 10 | 11 | let threads:[Thread] 12 | let endIndex:Int 13 | var startIndex:Int { 0 } 14 | 15 | subscript(index:Int) -> [String: ExprSyntax] 16 | { 17 | var element:[String: ExprSyntax] = .init(minimumCapacity: self.threads.count) 18 | for thread:Thread in self.threads 19 | { 20 | element[thread.binding] = thread.basis[index] 21 | } 22 | return element 23 | } 24 | 25 | private 26 | init(_ threads:[Thread]) 27 | { 28 | self.threads = threads 29 | self.endIndex = self.threads.lazy.map(\.basis.count).min() ?? 0 30 | } 31 | 32 | init(parsing arguments:TupleExprElementListSyntax, scope:[[String: [ExprSyntax]]]) throws 33 | { 34 | var zipper:[Loop.Thread] = [] 35 | arguments: 36 | for argument:TupleExprElementSyntax in arguments 37 | { 38 | guard case .identifier(let binding)? = argument.label?.tokenKind 39 | else 40 | { 41 | throw Factory.MatrixError.missingBinding 42 | } 43 | if let literal:ArrayExprSyntax = 44 | argument.expression.as(ArrayExprSyntax.self) 45 | { 46 | zipper.append(.init(binding: binding, 47 | basis: literal.elements.map { $0.expression.withoutTrivia() })) 48 | } 49 | else if let variable:IdentifierExprSyntax = 50 | argument.expression.as(IdentifierExprSyntax.self) 51 | { 52 | let variable:String = variable.identifier.text 53 | for scope:[String: [ExprSyntax]] in scope.reversed() 54 | { 55 | if let basis:[ExprSyntax] = scope[variable] 56 | { 57 | zipper.append(.init(binding: binding, basis: basis)) 58 | continue arguments 59 | } 60 | } 61 | throw Factory.MatrixError.undefinedBasis(variable) 62 | } 63 | else 64 | { 65 | throw Factory.MatrixError.invalidBasis(for: binding) 66 | } 67 | } 68 | self.init(zipper) 69 | } 70 | } -------------------------------------------------------------------------------- /Sources/Factory/MatrixElement.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | import SwiftSyntaxBuilder 3 | 4 | protocol MatrixElement:DeclSyntaxProtocol 5 | { 6 | var attributes:AttributeListSyntax? { get set } 7 | } 8 | extension AssociatedtypeDeclSyntax:MatrixElement {} 9 | extension ClassDeclSyntax:MatrixElement {} 10 | extension EnumCaseDeclSyntax:MatrixElement {} 11 | extension EnumDeclSyntax:MatrixElement {} 12 | extension ExtensionDeclSyntax:MatrixElement {} 13 | extension FunctionDeclSyntax:MatrixElement {} 14 | extension ImportDeclSyntax:MatrixElement {} 15 | extension InitializerDeclSyntax:MatrixElement {} 16 | extension OperatorDeclSyntax:MatrixElement {} 17 | extension PrecedenceGroupDeclSyntax:MatrixElement {} 18 | extension ProtocolDeclSyntax:MatrixElement {} 19 | extension StructDeclSyntax:MatrixElement {} 20 | extension SubscriptDeclSyntax:MatrixElement {} 21 | extension TypealiasDeclSyntax:MatrixElement {} 22 | extension VariableDeclSyntax:MatrixElement {} 23 | 24 | extension MatrixElement 25 | { 26 | private 27 | func matrixExpanded(_ loops:ArraySlice, substitutions:[[String: ExprSyntax]]) 28 | throws -> [DeclSyntax] 29 | { 30 | if let loop:Loop = loops.first 31 | { 32 | var instances:[DeclSyntax] = [] 33 | for iteration:[String: ExprSyntax] in loop 34 | { 35 | instances.append(contentsOf: try self.matrixExpanded(loops.dropFirst(), 36 | substitutions: substitutions + [iteration])) 37 | } 38 | return instances 39 | } 40 | else 41 | { 42 | let instantiator:Instantiator = .init(substitutions) 43 | let declaration:DeclSyntax 44 | switch self 45 | { 46 | case let base as AssociatedtypeDeclSyntax: declaration = instantiator.visit(base) 47 | case let base as ClassDeclSyntax: declaration = instantiator.visit(base) 48 | case let base as EnumCaseDeclSyntax: declaration = instantiator.visit(base) 49 | case let base as EnumDeclSyntax: declaration = instantiator.visit(base) 50 | case let base as ExtensionDeclSyntax: declaration = instantiator.visit(base) 51 | case let base as FunctionDeclSyntax: declaration = instantiator.visit(base) 52 | case let base as ImportDeclSyntax: declaration = instantiator.visit(base) 53 | case let base as InitializerDeclSyntax: declaration = instantiator.visit(base) 54 | case let base as OperatorDeclSyntax: declaration = instantiator.visit(base) 55 | case let base as PrecedenceGroupDeclSyntax: declaration = instantiator.visit(base) 56 | case let base as ProtocolDeclSyntax: declaration = instantiator.visit(base) 57 | case let base as StructDeclSyntax: declaration = instantiator.visit(base) 58 | case let base as SubscriptDeclSyntax: declaration = instantiator.visit(base) 59 | case let base as TypealiasDeclSyntax: declaration = instantiator.visit(base) 60 | case let base as VariableDeclSyntax: declaration = instantiator.visit(base) 61 | default: 62 | fatalError("unreachable") 63 | } 64 | if let error:any Error = instantiator.errors.first 65 | { 66 | throw error 67 | } 68 | return [declaration] 69 | } 70 | } 71 | mutating 72 | func removeAttributes( 73 | where recognize:(AttributeListSyntax.Element) throws -> Recognized?) 74 | rethrows -> [Recognized]? 75 | { 76 | guard let attributes:AttributeListSyntax = self.attributes 77 | else 78 | { 79 | return nil 80 | } 81 | var removed:[Recognized] = [] 82 | // if we delete a node, its leading trivia should coalesce with the 83 | // leading trivia of the next node 84 | var kept:[AttributeListSyntax.Element] = [] 85 | var doccomment:Trivia? = nil 86 | for attribute:AttributeListSyntax.Element in attributes 87 | { 88 | if let recognized:Recognized = try recognize(attribute) 89 | { 90 | // if this would be the first attribute, save the leading trivia, 91 | // as it may contain a doccomment! 92 | if case nil = doccomment, kept.isEmpty, 93 | let trivia:Trivia = attribute.leadingTrivia 94 | { 95 | doccomment = trivia 96 | } 97 | removed.append(recognized) 98 | } 99 | else if let saved:Trivia = doccomment 100 | { 101 | // this *discards* the attribute’s *own* leading trivia! 102 | // if we do not throw it away, the preceding doccomment 103 | // will be orphaned, which is even worse! 104 | kept.append(attribute.withLeadingTrivia(saved)) 105 | doccomment = nil 106 | } 107 | else 108 | { 109 | kept.append(attribute) 110 | } 111 | } 112 | if removed.isEmpty 113 | { 114 | return nil 115 | } 116 | else 117 | { 118 | self.attributes = kept.isEmpty ? nil : .init(kept) 119 | } 120 | // need to check this again, in case there were no other attributes 121 | // around to adopt the doccomment 122 | if let doccomment:Trivia 123 | { 124 | // this *discards* the declaration’s *own* leading trivia! 125 | // if we do not throw it away, the preceding doccomment 126 | // will be orphaned, which is even worse! 127 | self = self.withLeadingTrivia(doccomment) 128 | } 129 | return removed 130 | } 131 | func expanded(scope:[[String: [ExprSyntax]]]) throws -> [DeclSyntax] 132 | { 133 | var template:Self = self 134 | let retro:[Void]? = try template.removeAttributes 135 | { 136 | guard case .customAttribute(let attribute) = $0, 137 | case "retro"? = attribute.simpleName 138 | else 139 | { 140 | return nil 141 | } 142 | if case _? = attribute.argumentList 143 | { 144 | throw Factory.RetroError.unexpectedArguments 145 | } 146 | else 147 | { 148 | return () 149 | } 150 | } 151 | let loops:[Loop]? = try template.removeAttributes 152 | { 153 | guard case .customAttribute(let attribute) = $0, 154 | case "matrix"? = attribute.simpleName 155 | else 156 | { 157 | return nil 158 | } 159 | if let arguments:TupleExprElementListSyntax = attribute.argumentList 160 | { 161 | return try .init(parsing: arguments, scope: scope) 162 | } 163 | else 164 | { 165 | throw Factory.MatrixError.missingArguments 166 | } 167 | } 168 | 169 | var declarations:[DeclSyntax] 170 | if let loops:[Loop] 171 | { 172 | declarations = try template.matrixExpanded(loops[...], substitutions: []) 173 | } 174 | else 175 | { 176 | declarations = [.init(template)] 177 | } 178 | if case _? = retro 179 | { 180 | // ensure that *every* declaration starts with a newline 181 | declarations.prependMissingNewlines() 182 | declarations = try declarations.retroExpanded() 183 | } 184 | else if declarations.count > 1 185 | { 186 | // ensure that *ever* declaration after the first one 187 | // starts with a newline 188 | declarations[1...].prependMissingNewlines() 189 | } 190 | 191 | return declarations 192 | } 193 | } 194 | extension Sequence 195 | { 196 | func retroExpanded() throws -> [DeclSyntax] 197 | { 198 | try self.map 199 | { 200 | (declaration:DeclSyntax) in 201 | 202 | guard let declaration:ProtocolDeclSyntax = declaration.as(ProtocolDeclSyntax.self) 203 | else 204 | { 205 | throw Factory.RetroError.expectedProtocol 206 | } 207 | guard case _? = declaration.primaryAssociatedTypeClause 208 | else 209 | { 210 | throw Factory.RetroError.expectedPrimaryAssociatedTypeClause 211 | } 212 | 213 | let modern:IfConfigClauseSyntax = .init( 214 | poundKeyword: .poundIfKeyword( 215 | leadingTrivia: .newlines(1), 216 | trailingTrivia: .spaces(1)), 217 | condition: .init(FunctionCallExprSyntax.init( 218 | calledExpression: .init(IdentifierExprSyntax.init( 219 | identifier: .identifier("swift"), 220 | declNameArguments: nil)), 221 | leftParen: .leftParenToken(), 222 | argumentList: .init( 223 | [ 224 | .init(label: nil, colon: nil, 225 | expression: .init(PrefixOperatorExprSyntax.init( 226 | operatorToken: .prefixOperator(">="), 227 | postfixExpression: .init(FloatLiteralExprSyntax.init( 228 | floatingDigits: .floatingLiteral("5.7"))))), 229 | trailingComma: nil) 230 | ]), 231 | rightParen: .rightParenToken(), 232 | trailingClosure: nil, 233 | additionalTrailingClosures: nil)), 234 | elements: .decls( 235 | [ 236 | .init(decl: declaration) 237 | ])) 238 | let retro:IfConfigClauseSyntax = .init( 239 | poundKeyword: .poundElseKeyword(leadingTrivia: .newlines(1)), 240 | condition: nil, 241 | elements: .decls( 242 | [ 243 | .init(decl: declaration.withPrimaryAssociatedTypeClause(nil)) 244 | ])) 245 | let block:IfConfigDeclSyntax = .init( 246 | clauses: .init([modern, retro]), 247 | poundEndif: .poundEndifKeyword(leadingTrivia: .newlines(1))) 248 | 249 | return .init(block) 250 | } 251 | } 252 | } 253 | extension MutableCollection 254 | { 255 | mutating 256 | func prependMissingNewlines() 257 | { 258 | for index:Index in self.indices 259 | { 260 | guard let before:Trivia = self[index].leadingTrivia 261 | else 262 | { 263 | self[index] = self[index].withLeadingTrivia(.newlines(1)) 264 | continue 265 | } 266 | guard case true? = before.first?.isLinebreak 267 | else 268 | { 269 | self[index] = self[index].withLeadingTrivia(.init( 270 | pieces: [.newlines(1)] + before)) 271 | continue 272 | } 273 | } 274 | } 275 | } 276 | -------------------------------------------------------------------------------- /Sources/Factory/Transformer.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | 3 | extension CustomAttributeSyntax 4 | { 5 | var simpleName:String? 6 | { 7 | if case .identifier(let name)? = 8 | self.attributeName.as(SimpleTypeIdentifierSyntax.self)?.name.tokenKind 9 | { 10 | return name 11 | } 12 | else 13 | { 14 | return nil 15 | } 16 | } 17 | } 18 | 19 | extension VariableDeclSyntax 20 | { 21 | func bases() -> PatternBindingListSyntax? 22 | { 23 | var scratch:Self = self 24 | let basis:[Void]? = scratch.removeAttributes 25 | { 26 | if case .customAttribute(let attribute) = $0, 27 | case "basis"? = attribute.simpleName 28 | { 29 | return () 30 | } 31 | else 32 | { 33 | return nil 34 | } 35 | } 36 | if case _? = basis 37 | { 38 | return self.bindings 39 | } 40 | else 41 | { 42 | return nil 43 | } 44 | } 45 | } 46 | 47 | extension TriviaPiece 48 | { 49 | var isLinebreak:Bool 50 | { 51 | switch self 52 | { 53 | case .carriageReturnLineFeeds, .carriageReturns, .formfeeds, .newlines: 54 | return true 55 | default: 56 | return false 57 | } 58 | } 59 | } 60 | 61 | final 62 | class Transformer:SyntaxRewriter 63 | { 64 | var scope:[[String: [ExprSyntax]]] 65 | var errors:[any Error] 66 | 67 | override 68 | init() 69 | { 70 | self.scope = [] 71 | self.errors = [] 72 | super.init() 73 | } 74 | 75 | final private 76 | func expand(_ declaration:DeclSyntax) throws -> [DeclSyntax]? 77 | { 78 | if let expandable:any MatrixElement = 79 | declaration.asProtocol(DeclSyntaxProtocol.self) as? MatrixElement 80 | { 81 | return try expandable.expanded(scope: self.scope) 82 | } 83 | else 84 | { 85 | return nil 86 | } 87 | } 88 | 89 | final private 90 | func with(scope bindings:[PatternBindingListSyntax]?, _ body:() throws -> T) throws -> T 91 | { 92 | guard let bindings:[PatternBindingListSyntax], !bindings.isEmpty 93 | else 94 | { 95 | return try body() 96 | } 97 | 98 | var scope:[String: [ExprSyntax]] = [:] 99 | for binding:PatternBindingSyntax in bindings.joined() 100 | { 101 | guard let pattern:IdentifierPatternSyntax = 102 | binding.pattern.as(IdentifierPatternSyntax.self) 103 | else 104 | { 105 | throw Factory.BasisError.expectedInitializationExpression 106 | } 107 | guard let clause:InitializerClauseSyntax = binding.initializer, 108 | let array:ArrayExprSyntax = clause.value.as(ArrayExprSyntax.self) 109 | else 110 | { 111 | throw Factory.BasisError.expectedArrayLiteral 112 | } 113 | 114 | scope[pattern.identifier.text] = array.elements.map { $0.expression.withoutTrivia() } 115 | } 116 | self.scope.append(scope) 117 | defer 118 | { 119 | self.scope.removeLast() 120 | } 121 | return try body() 122 | } 123 | 124 | final override 125 | func visit(_ list:CodeBlockItemListSyntax) -> CodeBlockItemListSyntax 126 | { 127 | var list:CodeBlockItemListSyntax = list 128 | let bindings:[PatternBindingListSyntax] = list.remove 129 | { 130 | $0.item.as(VariableDeclSyntax.self).flatMap { $0.bases() } 131 | } 132 | do 133 | { 134 | return try self.with(scope: bindings) 135 | { 136 | var elements:[CodeBlockItemSyntax] = [] 137 | elements.reserveCapacity(list.count) 138 | for element:CodeBlockItemSyntax in list 139 | { 140 | guard let declaration:DeclSyntax = element.item.as(DeclSyntax.self), 141 | let expanded:[DeclSyntax] = try self.expand(declaration) 142 | else 143 | { 144 | elements.append(element) 145 | continue 146 | } 147 | for element:DeclSyntax in expanded 148 | { 149 | elements.append(.init(item: .init(element))) 150 | } 151 | } 152 | return super.visit(CodeBlockItemListSyntax.init(elements)) 153 | } 154 | } 155 | catch let error 156 | { 157 | self.errors.append(error) 158 | return list 159 | } 160 | } 161 | final override 162 | func visit(_ list:MemberDeclListSyntax) -> MemberDeclListSyntax 163 | { 164 | var list:MemberDeclListSyntax = list 165 | let bindings:[PatternBindingListSyntax]? = list.remove 166 | { 167 | $0.decl.as(VariableDeclSyntax.self).flatMap { $0.bases() } 168 | } 169 | do 170 | { 171 | return try self.with(scope: bindings) 172 | { 173 | var elements:[MemberDeclListItemSyntax] = [] 174 | elements.reserveCapacity(list.count) 175 | for element:MemberDeclListItemSyntax in list 176 | { 177 | guard let expanded:[DeclSyntax] = try self.expand(element.decl) 178 | else 179 | { 180 | elements.append(element) 181 | continue 182 | } 183 | for element:DeclSyntax in expanded 184 | { 185 | elements.append(.init(decl: element, semicolon: nil)) 186 | } 187 | } 188 | return super.visit(MemberDeclListSyntax.init(elements)) 189 | } 190 | } 191 | catch let error 192 | { 193 | self.errors.append(error) 194 | return list 195 | } 196 | } 197 | } -------------------------------------------------------------------------------- /Sources/swift-package-factory/Main.swift: -------------------------------------------------------------------------------- 1 | import SystemExtras 2 | import Factory 3 | 4 | @main 5 | enum Main 6 | { 7 | public static 8 | func main() throws 9 | { 10 | for path:FilePath in CommandLine.arguments.dropFirst().map(FilePath.init(_:)) 11 | { 12 | var output:FilePath = path.lexicallyNormalized() 13 | if let `extension`:String = output.extension 14 | { 15 | output.extension = "\(`extension`).swift" 16 | } 17 | else 18 | { 19 | output.extension = "swift" 20 | } 21 | 22 | let transformed:String = try Factory.transform(source: try path.read(String.self), 23 | filenameForDiagnostics: path.string) 24 | print("generating '\(output)'") 25 | try output.write(transformed) 26 | } 27 | } 28 | } --------------------------------------------------------------------------------