├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ └── swift.yml ├── .gitignore ├── .swiftpm └── xcode │ ├── package.xcworkspace │ └── xcshareddata │ │ └── IDEWorkspaceChecks.plist │ └── xcshareddata │ └── xcschemes │ ├── Injection-Package.xcscheme │ ├── Injection.xcscheme │ └── MacrosTest.xcscheme ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── Package.resolved ├── Package.swift ├── README.md ├── SECURITY.md ├── Sources ├── Injection │ ├── Injected.swift │ ├── InjectedValues.swift │ ├── InjectionKey.swift │ └── MacrosDec.swift └── Macros │ ├── Inject.swift │ ├── InjectedValuesContainer.swift │ ├── MyLibDiagnostic.swift │ ├── MyMacroPlugin.swift │ └── StringExtension.swift └── Tests ├── InjectionTests └── InjectionTests.swift └── MacrosTest └── MacrosTest.swift /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: EngOmarElsayed 4 | 5 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/workflows/swift.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Swift project 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-swift 3 | 4 | name: Swift 5 | 6 | on: 7 | push: 8 | branches: [ "main" ] 9 | pull_request: 10 | branches: [ "main" ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: macos-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Build 20 | run: swift build -v 21 | - name: Run tests 22 | run: swift test -v 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | xcuserdata/ 5 | DerivedData/ 6 | .swiftpm/configuration/registries.json 7 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 8 | .netrc 9 | -------------------------------------------------------------------------------- /.swiftpm/xcode/package.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.swiftpm/xcode/xcshareddata/xcschemes/Injection-Package.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 9 | 10 | 16 | 22 | 23 | 24 | 25 | 26 | 32 | 33 | 43 | 44 | 50 | 51 | 57 | 58 | 59 | 60 | 62 | 63 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /.swiftpm/xcode/xcshareddata/xcschemes/Injection.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 9 | 10 | 16 | 22 | 23 | 24 | 25 | 26 | 32 | 33 | 35 | 41 | 42 | 43 | 45 | 51 | 52 | 53 | 54 | 55 | 65 | 66 | 72 | 73 | 79 | 80 | 81 | 82 | 84 | 85 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /.swiftpm/xcode/xcshareddata/xcschemes/MacrosTest.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 9 | 10 | 16 | 17 | 19 | 25 | 26 | 27 | 28 | 29 | 39 | 40 | 46 | 47 | 49 | 50 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | eng.omar.elsayed@hotmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Injection 2 | 3 | A big welcome and thank you for considering contributing to SwiftUserDefaults open source projects! 4 | 5 | Reading and following these guidelines will help us make the contribution process easy and effective for everyone involved. It also communicates that you agree to respect the time of the developers managing and developing these open source projects. In return, we will reciprocate that respect by addressing your issue, assessing changes, and helping you finalize your pull requests. 6 | 7 | ## Quicklinks 8 | 9 | * [Code of Conduct](#code-of-conduct) 10 | * [Getting Started](#getting-started) 11 | * [Issues](#issues) 12 | * [Pull Requests](#pull-requests) 13 | * [Getting Help](#getting-help) 14 | 15 | ## Code of Conduct 16 | 17 | We take our open source community seriously and hold ourselves and other contributors to high standards of communication. By participating and contributing to this project, you agree to uphold our [Code of Conduct](https://github.com/EngOmarElsayed/SwiftUserDefaults/blob/main/CODE_OF_CONDUCT.md). 18 | 19 | ## Getting Started 20 | 21 | Contributions are made to this repo via Issues and Pull Requests (PRs). A few general guidelines that cover both: 22 | 23 | - To report security vulnerabilities, please use our [Responsible Disclosure Program](https://auth0.com/whitehat) which is monitored by our security team. 24 | - Search for existing Issues and PRs before creating your own. 25 | - We work hard to makes sure issues are handled in a timely manner but, depending on the impact, it could take a while to investigate the root cause. A friendly ping in the comment thread to the submitter or a contributor can help draw attention if your issue is blocking. 26 | 27 | ### Issues 28 | 29 | Issues should be used to report problems with the library, request a new feature, or to discuss potential changes before a PR is created. When you create a new Issue, a template will be loaded that will guide you through collecting and providing the information we need to investigate. 30 | 31 | If you find an Issue that addresses the problem you're having, please add your own reproduction information to the existing issue rather than creating a new one. Adding a [reaction](https://github.blog/2016-03-10-add-reactions-to-pull-requests-issues-and-comments/) can also help be indicating to our maintainers that a particular problem is affecting more than just the reporter. 32 | 33 | ### Pull Requests 34 | 35 | PRs to our libraries are always welcome and can be a quick way to get your fix or improvement slated for the next release. In general, PRs should: 36 | 37 | - Only fix/add the functionality in question **OR** address wide-spread whitespace/style issues, not both. 38 | - Add unit or integration tests for fixed or changed functionality (if a test suite already exists). 39 | - Address a single concern in the least number of changed lines as possible. 40 | - Include documentation in the repo. 41 | - Be accompanied by a complete Pull Request template (loaded automatically when a PR is created). 42 | 43 | For changes that address core functionality or would require breaking changes (e.g. a major release), it's best to open an Issue to discuss your proposal first. This is not required but can save time creating and reviewing changes. 44 | 45 | In general, we follow the ["fork-and-pull" Git workflow](https://github.com/susam/gitpr) 46 | 47 | 1. Fork the repository to your own Github account 48 | 2. Clone the project to your machine 49 | 3. Create a branch locally with a succinct but descriptive name 50 | 4. Commit changes to the branch 51 | 5. Following any formatting and testing guidelines specific to this repo 52 | 6. Push changes to your fork 53 | 7. Open a PR in our repository and follow the PR template so that we can efficiently review the changes. 54 | 55 | ## Getting Help 56 | 57 | Email Me at eng.omar.elsayed@hotmail.com. 58 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Omar Elsayed 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "pins" : [ 3 | { 4 | "identity" : "swift-syntax", 5 | "kind" : "remoteSourceControl", 6 | "location" : "https://github.com/apple/swift-syntax", 7 | "state" : { 8 | "revision" : "303e5c5c36d6a558407d364878df131c3546fad8", 9 | "version" : "510.0.2" 10 | } 11 | } 12 | ], 13 | "version" : 2 14 | } 15 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.9 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | import CompilerPluginSupport 6 | 7 | let package = Package( 8 | name: "Injection", 9 | platforms: [ 10 | .iOS(.v14), 11 | .macOS(.v10_15), 12 | .watchOS(.v5), 13 | .tvOS(.v12) 14 | ], 15 | products: [ 16 | .library( 17 | name: "Injection", 18 | targets: ["Injection"]), 19 | ], 20 | dependencies: [ 21 | .package(url: "https://github.com/apple/swift-syntax", from: "510.0.0") 22 | ], 23 | targets: [ 24 | .macro(name: "Macros", dependencies: [ 25 | .product(name: "SwiftSyntaxMacros", package: "swift-syntax"), 26 | .product(name: "SwiftCompilerPlugin", package: "swift-syntax") 27 | ]), 28 | .target(name: "Injection", dependencies: ["Macros"]), 29 | .testTarget(name: "InjectionTests", dependencies: ["Injection"]), 30 | .testTarget(name: "MacrosTest", dependencies: ["Macros", .product(name: "SwiftSyntaxMacrosTestSupport", package: "swift-syntax")]) 31 | ] 32 | ) 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Injection 2 | ![example workflow](https://github.com/EngOmarElsayed/Injection/actions/workflows/swift.yml/badge.svg) 3 | ![GitHub License](https://img.shields.io/github/license/EngOmarElsayed/Injection) 4 | [![SPM compatible](https://img.shields.io/badge/SPM-compatible-4BC51D.svg?style=flat)](#swift-package-manager) 5 | [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2FEngOmarElsayed%2FInjection%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/EngOmarElsayed/Injection) 6 | [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2FEngOmarElsayed%2FInjection%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/EngOmarElsayed/Injection) 7 | 8 | ## Table of Contents 9 | 1. [Introduction](#introduction) 10 | 2. [How to use](#section-1) 11 | 3. [Testing](#section-2) 12 | 4. [Resources](#resources) 13 | 5. [Author](#conclusion) 14 | 15 | ## Introduction 16 | This package was developed to address one of the most challenging topics in the Swift community: dependency injection. I often found it difficult to grasp this concept and implement it effectively. Through extensive research, I discovered a straightforward method inspired by the `@Environment` property wrapper in SwiftUI. A defining feature of this package is its simplicity, making it easily understandable for anyoney. 17 | 18 | Key issues addressed by this package include: 19 | * Simplifying the process of mocking data for tests. 20 | * Maintaining readability by adhering closely to Swift’s standard APIs. 21 | * Ensuring compile-time safety to prevent hidden crashes, so if the application builds, all dependencies are correctly configured. 22 | * Avoiding large initializers caused by dependency injection. 23 | * Relieving the AppDelegate from being the central point for defining all shared instances. 24 | * Minimizing potential learning curves. 25 | * Eliminating the need for force unwrapping. 26 | * Allowing the definition of standard dependencies without exposing private or internal types within packages. 27 | 28 | first start by adding the pacakge to your code base as follow: 29 | 30 | ```swift 31 | .package(url: "https://github.com/EngOmarElsayed/Injection", from: "1.3"), 32 | ``` 33 | 34 | Alternatively, navigate to the top section labeled 'Files' and click on 'Add Package Dependency': 35 | 36 | Screenshot 2024-03-15 at 3 33 08 AM 37 | 38 | 39 | ## How to use 40 | Let's say we have a protocol called `MotorBike` (why motorBike because I love them 😍😅) that contains a funcation called `move`: 41 | 42 | ```swift 43 | protocol MotorBike { 44 | func move() -> Int 45 | } 46 | ``` 47 | And there is a struct called `Ducati` that conforms to `MotorBike`: 48 | 49 | ```swift 50 | struct Ducati: MotorBike { 51 | func move() -> Int { 52 | return 5 53 | } 54 | } 55 | ``` 56 | 57 | At this point we want to inject this object to another object using dependency injection design pattern to do so, 58 | the first step is to make an extension `InjectedValues` and add the new property that containes the object instance : 59 | 60 | ```swift 61 | @InjecteValues extension InjectedValues { 62 | var ducatiProvider: MotorBike = Ducati() 63 | } 64 | ``` 65 | and that's it...simple right 😉. The `InjecteValues` macro expand the code to this at compile time: 66 | 67 | ```swift 68 | @InjecteValues extension InjectedValues { 69 | var ducatiProvider: MotorBike = Ducati() 70 | 71 | //Expanded Code 72 | private struct DucatiKey: InjectionKey { 73 | static var currentValue: MotorBike = Ducati() 74 | } 75 | var ducatiProvider: MotorBike { 76 | get { Self[DucatiKey.self] } 77 | set { Self[DucatiKey.self] = newValue } 78 | } 79 | } 80 | ``` 81 | 82 | To be able to use it, you will just write this where ever you need it: 83 | 84 | ```swift 85 | struct Garage { 86 | @Injected(\.ducatiProvider) var ducati: MotorBike 87 | } 88 | ``` 89 | 90 | And that's it, simple right 🚀. 91 | 92 | > [!NOTE] 93 | > When ever you call the `@Injected` you will have the same instance throught the life cycle of the app. 94 | > To prevent any side effects and weird outcomes from happening due to inconsistent dependency references. 95 | 96 | > [!NOTE] 97 | > Plus you can easily change the instance by writing: 98 | > 99 | > ```swift 100 | > let garage = Garage() 101 | > garage.ducati = Ducati() 102 | > //OR 103 | > InjectedValues[\.ducatiProvider] = Ducati() 104 | > ``` 105 | > Using the `InjectedValues` static subscript also affects already injected properties. 106 | 107 | 108 | ## Testing 109 | Testing your code is more easier than you think, you will just have to change the injected properties with a mock one using `InjectedValues` static subscript, like so: 110 | 111 | ```swift 112 | final class MotorBikeTests: XCTestCase { 113 | override func setUp() { 114 | InjectedValues[\.ducatiProvider] = DuctiMock() 115 | } 116 | 117 | func test() { 118 | let garge = Garage() 119 | 120 | let result = garge.move() 121 | 122 | XCTAssertEqual(10, result) 123 | } 124 | } 125 | 126 | class DuctiMock: MotorBike { 127 | func move() -> Int { 128 | return 10 129 | } 130 | } 131 | ``` 132 | that's it for how to test your injected properties. Easey right ? 😎 133 | 134 | ## Resources 135 | Some helpful links for you: 136 | * https://developer.apple.com/documentation/swiftui/environment 137 | * https://www.avanderlee.com/swift/dependency-injection/ 138 | * https://www.avanderlee.com/swift/property-wrappers/ 139 | 140 | ## Author 141 | This pacakge was created by [Eng.Omar Elsayed](https://www.linkedin.com/in/engomarelsayed/) to help the iOS comuntity and make there life easir. To contact me email me at eng.omar.elsayed@hotmail.com 142 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Currently our package support security and access control for the code. 6 | 7 | | Version | Supported | 8 | | ------- | ------------------ | 9 | | 1.0.0 | :white_check_mark: | 10 | 11 | ## Reporting a Vulnerability 12 | 13 | if you want to report a Vulnerability please send email to eng.omar.elsayed@hotmail.com 14 | 15 | I will answer your consern as soon as possible, thanks for using my Pacakge. 16 | -------------------------------------------------------------------------------- /Sources/Injection/Injected.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import Foundation 22 | 23 | @propertyWrapper 24 | public struct Injected { 25 | private let keyPath: WritableKeyPath 26 | 27 | public var wrappedValue: T { 28 | get { InjectedValues[keyPath] } 29 | set { InjectedValues[keyPath] = newValue } 30 | } 31 | 32 | public init(_ keyPath: WritableKeyPath) { 33 | self.keyPath = keyPath 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Sources/Injection/InjectedValues.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import Foundation 22 | 23 | /// Gives you access to the injected dependencies. 24 | public struct InjectedValues { 25 | /// This is only used by the subscript to access the computed property's in the ``InjectedValues`` extension. 26 | private static var current = InjectedValues() 27 | 28 | /// This is a static subscript to read and update the currentValue of the ``InjectionKey``. 29 | public static subscript(key: K.Type) -> K.Value where K: InjectionKey { 30 | get { key.currentValue } 31 | set { key.currentValue = newValue } 32 | } 33 | 34 | /// This is a static subscript to reference and update the dependencies directly. 35 | public static subscript(_ keyPath: WritableKeyPath) -> T { 36 | get { current[keyPath: keyPath] } 37 | set { current[keyPath: keyPath] = newValue } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Sources/Injection/InjectionKey.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import Foundation 22 | 23 | public protocol InjectionKey { 24 | /// This represent the type of the dependency injection key/ 25 | associatedtype Value 26 | /// This represent the default value for dependency injection key. 27 | static var currentValue: Self.Value { get set } 28 | } 29 | -------------------------------------------------------------------------------- /Sources/Injection/MacrosDec.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import Foundation 22 | 23 | @attached(memberAttribute) 24 | public macro InjecteValues() = #externalMacro(module: "Macros", type: "InjectedValuesContainer") 25 | 26 | @attached(peer, names: arbitrary) 27 | @attached(accessor, names: named(get), named(set)) 28 | public macro Inject() = #externalMacro(module: "Macros", type: "InjectMacro") 29 | -------------------------------------------------------------------------------- /Sources/Macros/Inject.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import SwiftCompilerPlugin 22 | import SwiftSyntax 23 | import SwiftSyntaxBuilder 24 | import SwiftSyntaxMacros 25 | import SwiftDiagnostics 26 | 27 | //MARK: - Private Methods 28 | public struct InjectMacro { 29 | private static func addError(_ error: MyLibDiagnostic, _ node: AttributeSyntax, context: some MacroExpansionContext) { 30 | let error = Diagnostic(node: node, message: error) 31 | context.diagnose(error) 32 | } 33 | 34 | private static func checkVariable(for varDec: DeclSyntaxProtocol, _ node: AttributeSyntax, context: some MacroExpansionContext) -> (id: TokenSyntax?, bind: PatternBindingSyntax?) { 35 | guard let varDecl = varDec.as(VariableDeclSyntax.self), varDecl.bindingSpecifier.text == "var" else { 36 | addError(.notAVarVariable, node, context: context) 37 | return (nil, nil) 38 | } 39 | 40 | guard let binding = varDecl.bindings.first else { return (nil, nil) } 41 | 42 | guard let _ = binding.initializer else { 43 | addError(.mustContainDefaultValue, node, context: context) 44 | return (nil, nil) 45 | } 46 | 47 | if let isOptionalType = binding.typeAnnotation?.type.is(OptionalTypeSyntax.self), isOptionalType { 48 | addError(.valueIsOptional, node, context: context) 49 | return (nil, nil) 50 | } 51 | 52 | guard var identifier = binding.pattern.as(IdentifierPatternSyntax.self)?.identifier else { 53 | addError(.provideName, node, context: context) 54 | return (nil, nil) 55 | } 56 | 57 | identifier = .identifier(identifier.text.upperCaseFirstLetter()) 58 | return (identifier, binding) 59 | } 60 | } 61 | 62 | //MARK: - AccessorMacro 63 | extension InjectMacro: AccessorMacro { 64 | public static func expansion( 65 | of node: AttributeSyntax, 66 | providingAccessorsOf declaration: some DeclSyntaxProtocol, 67 | in context: some MacroExpansionContext 68 | ) throws -> [AccessorDeclSyntax] { 69 | guard let (identifier,_) = checkVariable(for: declaration, node, context: context) as? (TokenSyntax, PatternBindingSyntax) else { return [] } 70 | 71 | return [""" 72 | get { 73 | Self[\(identifier)InjectionKey.self] 74 | } 75 | set { 76 | Self[\(identifier)InjectionKey.self] = newValue 77 | } 78 | """] 79 | } 80 | } 81 | 82 | //MARK: - PeerMacro 83 | extension InjectMacro: PeerMacro { 84 | public static func expansion( 85 | of node: AttributeSyntax, 86 | providingPeersOf declaration: some DeclSyntaxProtocol, 87 | in context: some MacroExpansionContext 88 | ) throws -> [DeclSyntax] { 89 | guard var (identifier, binding) = checkVariable(for: declaration, node, context: context) as? (TokenSyntax, PatternBindingSyntax) else { return [] } 90 | binding.pattern = PatternSyntax(IdentifierPatternSyntax(identifier: .identifier("currentValue"))) 91 | 92 | return [ 93 | """ 94 | private struct \(identifier)InjectionKey: InjectionKey { 95 | static var \(binding) 96 | } 97 | """ 98 | ] 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /Sources/Macros/InjectedValuesContainer.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import SwiftCompilerPlugin 22 | import SwiftSyntax 23 | import SwiftSyntaxBuilder 24 | import SwiftSyntaxMacros 25 | 26 | public struct InjectedValuesContainer: MemberAttributeMacro { 27 | public static func expansion( 28 | of node: AttributeSyntax, 29 | attachedTo declaration: some DeclGroupSyntax, 30 | providingAttributesFor member: some DeclSyntaxProtocol, 31 | in context: some MacroExpansionContext 32 | ) throws -> [AttributeSyntax] { 33 | guard let varDecl = member.as(VariableDeclSyntax.self) else { return [] } 34 | guard let bind = varDecl.bindings.first else { return [] } 35 | guard bind.pattern.as(IdentifierPatternSyntax.self)?.identifier.text != "current" else { return [] } 36 | 37 | return ["@Inject"] 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Sources/Macros/MyLibDiagnostic.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import Foundation 22 | import SwiftDiagnostics 23 | 24 | enum MyLibDiagnostic: String, DiagnosticMessage { 25 | case notAVarVariable 26 | case mustContainDefaultValue 27 | case provideName 28 | case valueIsOptional 29 | 30 | var message: String { 31 | switch self { 32 | case .notAVarVariable: 33 | "@Inject should be applied to `var` variable" 34 | case .mustContainDefaultValue: 35 | "variable must contain default value" 36 | case .provideName: 37 | "provide a name for the variable" 38 | case .valueIsOptional: 39 | "@Inject can't be applied to Optional" 40 | } 41 | } 42 | 43 | var severity: DiagnosticSeverity { .error } 44 | var diagnosticID: MessageID { .init(domain: "Injection", id: rawValue) } 45 | } 46 | -------------------------------------------------------------------------------- /Sources/Macros/MyMacroPlugin.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import SwiftCompilerPlugin 22 | import SwiftSyntax 23 | import SwiftSyntaxBuilder 24 | import SwiftSyntaxMacros 25 | 26 | @main 27 | struct MyMacroPlugin: CompilerPlugin { 28 | let providingMacros: [Macro.Type] = [ 29 | InjectMacro.self, 30 | InjectedValuesContainer.self 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /Sources/Macros/StringExtension.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import Foundation 22 | 23 | extension String { 24 | func upperCaseFirstLetter() -> String { 25 | return prefix(1).uppercased() + dropFirst() 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Tests/InjectionTests/InjectionTests.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import XCTest 22 | import Injection 23 | 24 | final class InjectionTests: XCTestCase { 25 | @Injected(\.networkProvider) fileprivate var network: Network 26 | 27 | func test_propertyWrapper_getRightInstance() { 28 | let expected = "Succeed" 29 | 30 | let result = network.updateRequest() 31 | 32 | XCTAssertEqual(expected, result) 33 | } 34 | 35 | func test_propertyWrapper_getRightInstance_AfterChangingInjectedValues() { 36 | let expected = "Mock" 37 | 38 | InjectedValues[\.networkProvider] = NetworkProviderMock() 39 | let result = network.updateRequest() 40 | 41 | XCTAssertEqual(expected, result) 42 | } 43 | 44 | func test_propertyWrapper_getRightInstance_AfterChangingPrperty() { 45 | let expected = "Mock" 46 | 47 | network = NetworkProviderMock() 48 | let result = network.updateRequest() 49 | 50 | XCTAssertEqual(expected, result) 51 | } 52 | } 53 | 54 | //MARK: - DependencyExample 55 | 56 | fileprivate protocol Network { 57 | func updateRequest() -> String 58 | } 59 | 60 | fileprivate struct NetworkProvider: Network { 61 | func updateRequest() -> String { 62 | return "Succeed" 63 | } 64 | } 65 | 66 | fileprivate struct NetworkProviderMock: Network { 67 | func updateRequest() -> String { 68 | return "Mock" 69 | } 70 | } 71 | 72 | @InjecteValues extension InjectedValues { 73 | fileprivate var networkProvider: Network = NetworkProvider() 74 | fileprivate var test: String = "Test" 75 | } 76 | -------------------------------------------------------------------------------- /Tests/MacrosTest/MacrosTest.swift: -------------------------------------------------------------------------------- 1 | //Copyright (c) 2024 Eng.Omar Elsayed 2 | // 3 | //Permission is hereby granted, free of charge, to any person obtaining a copy 4 | //of this software and associated documentation files (the "Software"), to deal 5 | //in the Software without restriction, including without limitation the rights 6 | //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | //copies of the Software, and to permit persons to whom the Software is 8 | //furnished to do so, subject to the following conditions: 9 | // 10 | //The above copyright notice and this permission notice shall be included in all 11 | //copies or substantial portions of the Software. 12 | // 13 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | //SOFTWARE. 20 | 21 | import SwiftSyntaxMacros 22 | import SwiftSyntaxMacrosTestSupport 23 | import Macros 24 | import XCTest 25 | 26 | fileprivate let testMacros: [String: Macro.Type] = [ 27 | "Inject" : InjectMacro.self, 28 | "InjectedValuesContainer": InjectedValuesContainer.self 29 | ] 30 | 31 | final class MacrosTest: XCTestCase { 32 | 33 | func test_InjectedValuesContainer_memberAttribute() { 34 | assertMacroExpansion( 35 | """ 36 | @InjectedValuesContainer public struct InjectedValues { 37 | var current = "" 38 | var test: Test = test() 39 | } 40 | """, 41 | expandedSource: """ 42 | public struct InjectedValues { 43 | var current = "" 44 | var test: Test { 45 | get { 46 | Self [TestInjectionKey.self] 47 | } 48 | set { 49 | Self[TestInjectionKey.self] = newValue 50 | } 51 | } 52 | 53 | private struct TestInjectionKey: InjectionKey { 54 | static var currentValue: Test = test() 55 | } 56 | } 57 | """, 58 | macros: testMacros 59 | ) 60 | } 61 | 62 | func test_InjectMacro_Accessor() { 63 | assertMacroExpansion( 64 | """ 65 | @Inject var test: Test = Test() 66 | """, 67 | expandedSource: """ 68 | var test: Test { 69 | get { 70 | Self [TestInjectionKey.self] 71 | } 72 | set { 73 | Self[TestInjectionKey.self] = newValue 74 | } 75 | } 76 | 77 | private struct TestInjectionKey: InjectionKey { 78 | static var currentValue: Test = Test() 79 | } 80 | """, 81 | macros: testMacros 82 | ) 83 | } 84 | } 85 | --------------------------------------------------------------------------------