├── .github └── workflows │ ├── ci.yml │ └── clean.yml ├── .gitignore ├── .scalafmt.conf ├── LICENSE ├── README.md ├── build.sbt ├── core └── shared │ └── src │ └── main │ ├── scala-2 │ └── org │ │ └── typelevel │ │ └── literally │ │ └── Literally.scala │ └── scala-3 │ └── org │ └── typelevel │ └── literally │ └── Literally.scala ├── project ├── build.properties └── plugins.sbt └── tests └── shared └── src ├── main ├── scala-2 │ └── org │ │ └── typelevel │ │ └── literally │ │ └── examples │ │ ├── ShortString.scala │ │ └── literals.scala ├── scala-3 │ └── org │ │ └── typelevel │ │ └── literally │ │ └── examples │ │ ├── ShortString.scala │ │ └── literals.scala └── scala │ └── org │ └── typelevel │ └── literally │ └── examples │ └── Port.scala └── test └── scala └── org └── typelevel └── literally └── LiterallySuite.scala /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # This file was automatically generated by sbt-github-actions using the 2 | # githubWorkflowGenerate task. You should add and commit this file to 3 | # your git repository. It goes without saying that you shouldn't edit 4 | # this file by hand! Instead, if you wish to make changes, you should 5 | # change your sbt build configuration to revise the workflow description 6 | # to meet your needs, then regenerate this file. 7 | 8 | name: Continuous Integration 9 | 10 | on: 11 | pull_request: 12 | branches: ['**', '!update/**', '!pr/**'] 13 | push: 14 | branches: ['**', '!update/**', '!pr/**'] 15 | tags: [v*] 16 | 17 | env: 18 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 19 | 20 | 21 | concurrency: 22 | group: ${{ github.workflow }} @ ${{ github.ref }} 23 | cancel-in-progress: true 24 | 25 | jobs: 26 | build: 27 | name: Test 28 | strategy: 29 | matrix: 30 | os: [ubuntu-22.04] 31 | scala: [2.12, 2.13, 3] 32 | java: [temurin@8] 33 | project: [rootJS, rootJVM, rootNative] 34 | runs-on: ${{ matrix.os }} 35 | timeout-minutes: 60 36 | steps: 37 | - name: Checkout current branch (full) 38 | uses: actions/checkout@v4 39 | with: 40 | fetch-depth: 0 41 | 42 | - name: Setup sbt 43 | uses: sbt/setup-sbt@v1 44 | 45 | - name: Setup Java (temurin@8) 46 | id: setup-java-temurin-8 47 | if: matrix.java == 'temurin@8' 48 | uses: actions/setup-java@v4 49 | with: 50 | distribution: temurin 51 | java-version: 8 52 | cache: sbt 53 | 54 | - name: sbt update 55 | if: matrix.java == 'temurin@8' && steps.setup-java-temurin-8.outputs.cache-hit == 'false' 56 | run: sbt +update 57 | 58 | - name: Check that workflows are up to date 59 | run: sbt githubWorkflowCheck 60 | 61 | - name: Check headers and formatting 62 | if: matrix.java == 'temurin@8' && matrix.os == 'ubuntu-22.04' 63 | run: sbt 'project ${{ matrix.project }}' '++ ${{ matrix.scala }}' headerCheckAll scalafmtCheckAll 'project /' scalafmtSbtCheck 64 | 65 | - name: scalaJSLink 66 | if: matrix.project == 'rootJS' 67 | run: sbt 'project ${{ matrix.project }}' '++ ${{ matrix.scala }}' Test/scalaJSLinkerResult 68 | 69 | - name: nativeLink 70 | if: matrix.project == 'rootNative' 71 | run: sbt 'project ${{ matrix.project }}' '++ ${{ matrix.scala }}' Test/nativeLink 72 | 73 | - name: Test 74 | run: sbt 'project ${{ matrix.project }}' '++ ${{ matrix.scala }}' test 75 | 76 | - name: Check binary compatibility 77 | if: matrix.java == 'temurin@8' && matrix.os == 'ubuntu-22.04' 78 | run: sbt 'project ${{ matrix.project }}' '++ ${{ matrix.scala }}' mimaReportBinaryIssues 79 | 80 | - name: Generate API documentation 81 | if: matrix.java == 'temurin@8' && matrix.os == 'ubuntu-22.04' 82 | run: sbt 'project ${{ matrix.project }}' '++ ${{ matrix.scala }}' doc 83 | 84 | - name: Make target directories 85 | if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main') 86 | run: mkdir -p core/native/target core/js/target core/jvm/target project/target 87 | 88 | - name: Compress target directories 89 | if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main') 90 | run: tar cf targets.tar core/native/target core/js/target core/jvm/target project/target 91 | 92 | - name: Upload target directories 93 | if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main') 94 | uses: actions/upload-artifact@v4 95 | with: 96 | name: target-${{ matrix.os }}-${{ matrix.java }}-${{ matrix.scala }}-${{ matrix.project }} 97 | path: targets.tar 98 | 99 | publish: 100 | name: Publish Artifacts 101 | needs: [build] 102 | if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main') 103 | strategy: 104 | matrix: 105 | os: [ubuntu-22.04] 106 | java: [temurin@8] 107 | runs-on: ${{ matrix.os }} 108 | steps: 109 | - name: Checkout current branch (full) 110 | uses: actions/checkout@v4 111 | with: 112 | fetch-depth: 0 113 | 114 | - name: Setup sbt 115 | uses: sbt/setup-sbt@v1 116 | 117 | - name: Setup Java (temurin@8) 118 | id: setup-java-temurin-8 119 | if: matrix.java == 'temurin@8' 120 | uses: actions/setup-java@v4 121 | with: 122 | distribution: temurin 123 | java-version: 8 124 | cache: sbt 125 | 126 | - name: sbt update 127 | if: matrix.java == 'temurin@8' && steps.setup-java-temurin-8.outputs.cache-hit == 'false' 128 | run: sbt +update 129 | 130 | - name: Download target directories (2.12, rootJS) 131 | uses: actions/download-artifact@v4 132 | with: 133 | name: target-${{ matrix.os }}-${{ matrix.java }}-2.12-rootJS 134 | 135 | - name: Inflate target directories (2.12, rootJS) 136 | run: | 137 | tar xf targets.tar 138 | rm targets.tar 139 | 140 | - name: Download target directories (2.12, rootJVM) 141 | uses: actions/download-artifact@v4 142 | with: 143 | name: target-${{ matrix.os }}-${{ matrix.java }}-2.12-rootJVM 144 | 145 | - name: Inflate target directories (2.12, rootJVM) 146 | run: | 147 | tar xf targets.tar 148 | rm targets.tar 149 | 150 | - name: Download target directories (2.12, rootNative) 151 | uses: actions/download-artifact@v4 152 | with: 153 | name: target-${{ matrix.os }}-${{ matrix.java }}-2.12-rootNative 154 | 155 | - name: Inflate target directories (2.12, rootNative) 156 | run: | 157 | tar xf targets.tar 158 | rm targets.tar 159 | 160 | - name: Download target directories (2.13, rootJS) 161 | uses: actions/download-artifact@v4 162 | with: 163 | name: target-${{ matrix.os }}-${{ matrix.java }}-2.13-rootJS 164 | 165 | - name: Inflate target directories (2.13, rootJS) 166 | run: | 167 | tar xf targets.tar 168 | rm targets.tar 169 | 170 | - name: Download target directories (2.13, rootJVM) 171 | uses: actions/download-artifact@v4 172 | with: 173 | name: target-${{ matrix.os }}-${{ matrix.java }}-2.13-rootJVM 174 | 175 | - name: Inflate target directories (2.13, rootJVM) 176 | run: | 177 | tar xf targets.tar 178 | rm targets.tar 179 | 180 | - name: Download target directories (2.13, rootNative) 181 | uses: actions/download-artifact@v4 182 | with: 183 | name: target-${{ matrix.os }}-${{ matrix.java }}-2.13-rootNative 184 | 185 | - name: Inflate target directories (2.13, rootNative) 186 | run: | 187 | tar xf targets.tar 188 | rm targets.tar 189 | 190 | - name: Download target directories (3, rootJS) 191 | uses: actions/download-artifact@v4 192 | with: 193 | name: target-${{ matrix.os }}-${{ matrix.java }}-3-rootJS 194 | 195 | - name: Inflate target directories (3, rootJS) 196 | run: | 197 | tar xf targets.tar 198 | rm targets.tar 199 | 200 | - name: Download target directories (3, rootJVM) 201 | uses: actions/download-artifact@v4 202 | with: 203 | name: target-${{ matrix.os }}-${{ matrix.java }}-3-rootJVM 204 | 205 | - name: Inflate target directories (3, rootJVM) 206 | run: | 207 | tar xf targets.tar 208 | rm targets.tar 209 | 210 | - name: Download target directories (3, rootNative) 211 | uses: actions/download-artifact@v4 212 | with: 213 | name: target-${{ matrix.os }}-${{ matrix.java }}-3-rootNative 214 | 215 | - name: Inflate target directories (3, rootNative) 216 | run: | 217 | tar xf targets.tar 218 | rm targets.tar 219 | 220 | - name: Import signing key 221 | if: env.PGP_SECRET != '' && env.PGP_PASSPHRASE == '' 222 | env: 223 | PGP_SECRET: ${{ secrets.PGP_SECRET }} 224 | PGP_PASSPHRASE: ${{ secrets.PGP_PASSPHRASE }} 225 | run: echo $PGP_SECRET | base64 -d -i - | gpg --import 226 | 227 | - name: Import signing key and strip passphrase 228 | if: env.PGP_SECRET != '' && env.PGP_PASSPHRASE != '' 229 | env: 230 | PGP_SECRET: ${{ secrets.PGP_SECRET }} 231 | PGP_PASSPHRASE: ${{ secrets.PGP_PASSPHRASE }} 232 | run: | 233 | echo "$PGP_SECRET" | base64 -d -i - > /tmp/signing-key.gpg 234 | echo "$PGP_PASSPHRASE" | gpg --pinentry-mode loopback --passphrase-fd 0 --import /tmp/signing-key.gpg 235 | (echo "$PGP_PASSPHRASE"; echo; echo) | gpg --command-fd 0 --pinentry-mode loopback --change-passphrase $(gpg --list-secret-keys --with-colons 2> /dev/null | grep '^sec:' | cut --delimiter ':' --fields 5 | tail -n 1) 236 | 237 | - name: Publish 238 | env: 239 | SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} 240 | SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }} 241 | SONATYPE_CREDENTIAL_HOST: ${{ secrets.SONATYPE_CREDENTIAL_HOST }} 242 | run: sbt tlCiRelease 243 | 244 | dependency-submission: 245 | name: Submit Dependencies 246 | if: github.event.repository.fork == false && github.event_name != 'pull_request' 247 | strategy: 248 | matrix: 249 | os: [ubuntu-22.04] 250 | java: [temurin@8] 251 | runs-on: ${{ matrix.os }} 252 | steps: 253 | - name: Checkout current branch (full) 254 | uses: actions/checkout@v4 255 | with: 256 | fetch-depth: 0 257 | 258 | - name: Setup sbt 259 | uses: sbt/setup-sbt@v1 260 | 261 | - name: Setup Java (temurin@8) 262 | id: setup-java-temurin-8 263 | if: matrix.java == 'temurin@8' 264 | uses: actions/setup-java@v4 265 | with: 266 | distribution: temurin 267 | java-version: 8 268 | cache: sbt 269 | 270 | - name: sbt update 271 | if: matrix.java == 'temurin@8' && steps.setup-java-temurin-8.outputs.cache-hit == 'false' 272 | run: sbt +update 273 | 274 | - name: Submit Dependencies 275 | uses: scalacenter/sbt-dependency-submission@v2 276 | with: 277 | modules-ignore: rootjs_2.12 rootjs_2.13 rootjs_3 tests_sjs1_2.12 tests_sjs1_2.13 tests_sjs1_3 rootjvm_2.12 rootjvm_2.13 rootjvm_3 rootnative_2.12 rootnative_2.13 rootnative_3 tests_2.12 tests_2.13 tests_3 tests_native0.5_2.12 tests_native0.5_2.13 tests_native0.5_3 278 | configs-ignore: test scala-tool scala-doc-tool test-internal 279 | -------------------------------------------------------------------------------- /.github/workflows/clean.yml: -------------------------------------------------------------------------------- 1 | # This file was automatically generated by sbt-github-actions using the 2 | # githubWorkflowGenerate task. You should add and commit this file to 3 | # your git repository. It goes without saying that you shouldn't edit 4 | # this file by hand! Instead, if you wish to make changes, you should 5 | # change your sbt build configuration to revise the workflow description 6 | # to meet your needs, then regenerate this file. 7 | 8 | name: Clean 9 | 10 | on: push 11 | 12 | jobs: 13 | delete-artifacts: 14 | name: Delete Artifacts 15 | runs-on: ubuntu-latest 16 | env: 17 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 18 | steps: 19 | - name: Delete artifacts 20 | run: | 21 | # Customize those three lines with your repository and credentials: 22 | REPO=${GITHUB_API_URL}/repos/${{ github.repository }} 23 | 24 | # A shortcut to call GitHub API. 25 | ghapi() { curl --silent --location --user _:$GITHUB_TOKEN "$@"; } 26 | 27 | # A temporary file which receives HTTP response headers. 28 | TMPFILE=/tmp/tmp.$$ 29 | 30 | # An associative array, key: artifact name, value: number of artifacts of that name. 31 | declare -A ARTCOUNT 32 | 33 | # Process all artifacts on this repository, loop on returned "pages". 34 | URL=$REPO/actions/artifacts 35 | while [[ -n "$URL" ]]; do 36 | 37 | # Get current page, get response headers in a temporary file. 38 | JSON=$(ghapi --dump-header $TMPFILE "$URL") 39 | 40 | # Get URL of next page. Will be empty if we are at the last page. 41 | URL=$(grep '^Link:' "$TMPFILE" | tr ',' '\n' | grep 'rel="next"' | head -1 | sed -e 's/.*.*//') 42 | rm -f $TMPFILE 43 | 44 | # Number of artifacts on this page: 45 | COUNT=$(( $(jq <<<$JSON -r '.artifacts | length') )) 46 | 47 | # Loop on all artifacts on this page. 48 | for ((i=0; $i < $COUNT; i++)); do 49 | 50 | # Get name of artifact and count instances of this name. 51 | name=$(jq <<<$JSON -r ".artifacts[$i].name?") 52 | ARTCOUNT[$name]=$(( $(( ${ARTCOUNT[$name]} )) + 1)) 53 | 54 | id=$(jq <<<$JSON -r ".artifacts[$i].id?") 55 | size=$(( $(jq <<<$JSON -r ".artifacts[$i].size_in_bytes?") )) 56 | printf "Deleting '%s' #%d, %'d bytes\n" $name ${ARTCOUNT[$name]} $size 57 | ghapi -X DELETE $REPO/actions/artifacts/$id 58 | done 59 | done 60 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.log 3 | target 4 | .metals 5 | .bloop 6 | .bsp 7 | metals.sbt 8 | .vscode 9 | -------------------------------------------------------------------------------- /.scalafmt.conf: -------------------------------------------------------------------------------- 1 | version = "3.9.4" 2 | runner.dialect = scala213Source3 3 | project.includePaths = [] # disables formatting 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Literally 2 | 3 | Compile time validation of literal values built from strings. 4 | 5 | ### Rationale 6 | 7 | Consider a type like `Port`: 8 | 9 | ```scala 10 | case class Port private (value: Int) 11 | 12 | object Port { 13 | val MinValue = 0 14 | val MaxValue = 65535 15 | 16 | def fromInt(i: Int): Option[Port] = 17 | if (i < MinValue || i > MaxValue) None else Some(new Port(i)) 18 | } 19 | ``` 20 | 21 | This library simplifies the definition of literal values which are validated at compilation time: 22 | 23 | ```scala 24 | val p: Port = port"8080" 25 | // p: Port = Port(8080) 26 | 27 | val q: Port = port"100000" 28 | // :17: error: invalid port - must be integer between 0 and 65535 29 | ``` 30 | 31 | Validation is performed at compile time. This library provides the macro implementations for both Scala 2 and Scala 3 which powers custom string literals. 32 | 33 | ### Quick Start 34 | 35 | To get started with **literally** in an SBT project add the following dependency to your **build.sbt**: 36 | ``` 37 | libraryDependencies += "org.typelevel" %% "literally" % "" 38 | ``` 39 | where `` is the most recent version of **literally**. 40 | 41 | ### Usage 42 | 43 | Defining a custom string literal for a type `A` involves: 44 | - Implementing an `org.typelevel.literally.Literally[A]` instance 45 | - Defining an extension method on a `StringContext` which uses the defined `Literally[A]` instance 46 | 47 | ```scala 48 | import org.typelevel.literally.Literally 49 | 50 | object literals: 51 | extension (inline ctx: StringContext) 52 | inline def port(inline args: Any*): Port = 53 | ${PortLiteral('ctx, 'args)} 54 | 55 | object PortLiteral extends Literally[Port]: 56 | def validate(s: String)(using Quotes) = 57 | s.toIntOption.flatMap(Port.fromInt) match 58 | case None => Left(s"invalid port - must be integer between ${Port.MinValue} and ${Port.MaxValue}") 59 | case Some(_) => Right('{Port.fromInt(${Expr(s)}.toInt).get}) 60 | ``` 61 | 62 | The same pattern is used for Scala 2, though the syntax for extension methods and macros are a bit different: 63 | 64 | ```scala 65 | import scala.util.Try 66 | import org.typelevel.literally.Literally 67 | 68 | object literals { 69 | implicit class short(val sc: StringContext) extends AnyVal { 70 | def port(args: Any*): Port = macro PortLiteral.make 71 | } 72 | 73 | object PortLiteral extends Literally[Port] { 74 | def validate(c: Context)(s: String): Either[String, c.Expr[Port]] = { 75 | import c.universe.{Try => _, _} 76 | Try(s.toInt).toOption.flatMap(Port.fromInt) match { 77 | case None => Left(s"invalid port - must be integer between ${Port.MinValue} and ${Port.MaxValue}") 78 | case Some(_) => Right(c.Expr(q"Port.fromInt($s.toInt).get")) 79 | } 80 | } 81 | 82 | def make(c: Context)(args: c.Expr[Any]*): c.Expr[Port] = apply(c)(args: _*) 83 | } 84 | } 85 | ``` 86 | 87 | The `tests` directory in this project has more examples. 88 | 89 | 90 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | ThisBuild / tlBaseVersion := "1.2" 2 | 3 | ThisBuild / developers += tlGitHubDev("mpilquist", "Michael Pilquist") 4 | ThisBuild / startYear := Some(2021) 5 | 6 | ThisBuild / crossScalaVersions := List("2.12.20", "2.13.16", "3.3.6") 7 | ThisBuild / tlVersionIntroduced := Map("3" -> "1.0.2") 8 | 9 | lazy val root = tlCrossRootProject.aggregate(core, tests) 10 | 11 | lazy val core = crossProject(JSPlatform, JVMPlatform, NativePlatform) 12 | .settings( 13 | name := "literally", 14 | scalacOptions := scalacOptions.value.filterNot(_ == "-source:3.0-migration"), 15 | libraryDependencies ++= { 16 | if (tlIsScala3.value) Nil else List("org.scala-lang" % "scala-reflect" % scalaVersion.value % Provided) 17 | }, 18 | tlMimaPreviousVersions := tlMimaPreviousVersions.value - "1.0.3" 19 | ) 20 | .nativeSettings( 21 | tlVersionIntroduced := List("2.12", "2.13", "3").map(_ -> "1.2.0").toMap 22 | ) 23 | 24 | lazy val tests = crossProject(JSPlatform, JVMPlatform, NativePlatform) 25 | .enablePlugins(NoPublishPlugin) 26 | .dependsOn(core) 27 | .settings( 28 | name := "tests", 29 | scalacOptions := scalacOptions.value.filterNot(_ == "-source:3.0-migration"), 30 | libraryDependencies += "org.scalameta" %%% "munit" % "1.1.1" % Test, 31 | libraryDependencies ++= { 32 | if (tlIsScala3.value) Nil else List("org.scala-lang" % "scala-reflect" % scalaVersion.value % Provided) 33 | } 34 | ) 35 | -------------------------------------------------------------------------------- /core/shared/src/main/scala-2/org/typelevel/literally/Literally.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.typelevel.literally 18 | 19 | trait Literally[A] { 20 | type Context = scala.reflect.macros.blackbox.Context 21 | 22 | def validate(c: Context)(s: String): Either[String, c.Expr[A]] 23 | 24 | def apply(c: Context)(args: c.Expr[Any]*): c.Expr[A] = { 25 | import c.universe._ 26 | identity(args) 27 | c.prefix.tree match { 28 | case Apply(_, List(Apply(_, (Literal(Constant(p: String))) :: Nil))) => 29 | validate(c)(p) match { 30 | case Left(msg) => c.abort(c.enclosingPosition, msg) 31 | case Right(a) => a 32 | } 33 | case other => c.abort(c.enclosingPosition, "unsupported prefix: " + other) 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /core/shared/src/main/scala-3/org/typelevel/literally/Literally.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.typelevel.literally 18 | 19 | import scala.quoted._ 20 | 21 | trait Literally[A]: 22 | type Quotes = scala.quoted.Quotes 23 | type Expr[A] = scala.quoted.Expr[A] 24 | val Expr = scala.quoted.Expr 25 | 26 | def validate(s: String)(using Quotes): Either[String, Expr[A]] 27 | 28 | def apply(strCtxExpr: Expr[StringContext], argsExpr: Expr[Seq[Any]])(using Quotes): Expr[A] = 29 | apply(strCtxExpr.valueOrAbort.parts, argsExpr) 30 | 31 | private def apply(parts: Seq[String], argsExpr: Expr[Seq[Any]])(using Quotes): Expr[A] = 32 | if parts.size == 1 then 33 | val literal = parts.head 34 | validate(literal) match 35 | case Left(err) => 36 | quotes.reflect.report.error(err) 37 | ??? 38 | case Right(a) => 39 | a 40 | else 41 | quotes.reflect.report.error("interpolation not supported", argsExpr) 42 | ??? 43 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.11.1 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.18.2") 2 | addSbtPlugin("org.typelevel" % "sbt-typelevel" % "0.8.0") 3 | addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.5.7") 4 | addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.3.2") 5 | -------------------------------------------------------------------------------- /tests/shared/src/main/scala-2/org/typelevel/literally/examples/ShortString.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.typelevel.literally.examples 18 | 19 | case class ShortString private (value: String) 20 | 21 | object ShortString { 22 | val MaxLength = 10 23 | 24 | def fromString(value: String): Option[ShortString] = 25 | if (value.length > MaxLength) None else Some(new ShortString(value)) 26 | 27 | def unsafeFromString(value: String): ShortString = 28 | new ShortString(value) 29 | } 30 | -------------------------------------------------------------------------------- /tests/shared/src/main/scala-2/org/typelevel/literally/examples/literals.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.typelevel.literally.examples 18 | 19 | import scala.util.Try 20 | import org.typelevel.literally.Literally 21 | 22 | object literals { 23 | implicit class short(val sc: StringContext) extends AnyVal { 24 | def short(args: Any*): ShortString = macro ShortStringLiteral.make 25 | def port(args: Any*): Port = macro PortLiteral.make 26 | } 27 | 28 | object ShortStringLiteral extends Literally[ShortString] { 29 | def validate(c: Context)(s: String): Either[String, c.Expr[ShortString]] = { 30 | import c.universe._ 31 | if (s.length <= ShortString.MaxLength) Right(c.Expr(q"ShortString.unsafeFromString($s)")) 32 | else Left(s"ShortString must be <= ${ShortString.MaxLength} characters") 33 | } 34 | 35 | def make(c: Context)(args: c.Expr[Any]*): c.Expr[ShortString] = apply(c)(args: _*) 36 | } 37 | 38 | object PortLiteral extends Literally[Port] { 39 | def validate(c: Context)(s: String): Either[String, c.Expr[Port]] = { 40 | import c.universe.{Try => _, _} 41 | Try(s.toInt).toOption.flatMap(Port.fromInt) match { 42 | case None => Left(s"invalid port - must be integer between ${Port.MinValue} and ${Port.MaxValue}") 43 | case Some(_) => Right(c.Expr(q"Port.fromInt($s.toInt).get")) 44 | } 45 | } 46 | 47 | def make(c: Context)(args: c.Expr[Any]*): c.Expr[Port] = apply(c)(args: _*) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /tests/shared/src/main/scala-3/org/typelevel/literally/examples/ShortString.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.typelevel.literally.examples 18 | 19 | opaque type ShortString = String 20 | 21 | object ShortString: 22 | val MaxLength = 10 23 | 24 | def fromString(value: String): Option[ShortString] = 25 | if value.length > MaxLength then None else Some(value) 26 | 27 | def unsafeFromString(value: String): ShortString = value -------------------------------------------------------------------------------- /tests/shared/src/main/scala-3/org/typelevel/literally/examples/literals.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.typelevel.literally.examples 18 | 19 | import org.typelevel.literally.Literally 20 | 21 | object literals: 22 | extension (inline ctx: StringContext) 23 | inline def short(inline args: Any*): ShortString = 24 | ${ShortStringLiteral('ctx, 'args)} 25 | 26 | inline def port(inline args: Any*): Port = 27 | ${PortLiteral('ctx, 'args)} 28 | 29 | object ShortStringLiteral extends Literally[ShortString]: 30 | def validate(s: String)(using Quotes) = 31 | if s.length <= ShortString.MaxLength then Right('{ShortString.unsafeFromString(${Expr(s)})}) 32 | else Left(s"ShortString must be <= ${ShortString.MaxLength} characters") 33 | 34 | object PortLiteral extends Literally[Port]: 35 | def validate(s: String)(using Quotes) = 36 | s.toIntOption.flatMap(Port.fromInt) match 37 | case None => Left(s"invalid port - must be integer between ${Port.MinValue} and ${Port.MaxValue}") 38 | case Some(_) => Right('{Port.fromInt(${Expr(s)}.toInt).get}) -------------------------------------------------------------------------------- /tests/shared/src/main/scala/org/typelevel/literally/examples/Port.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.typelevel.literally.examples 18 | 19 | case class Port private (value: Int) 20 | object Port { 21 | val MinValue = 0 22 | val MaxValue = 65535 23 | 24 | def fromInt(i: Int): Option[Port] = 25 | if (i < MinValue || i > MaxValue) None else Some(new Port(i)) 26 | } -------------------------------------------------------------------------------- /tests/shared/src/test/scala/org/typelevel/literally/LiterallySuite.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.typelevel.literally 18 | 19 | import munit.FunSuite 20 | 21 | class LiterallySuite extends FunSuite { 22 | 23 | import org.typelevel.literally.examples.{ShortString, Port} 24 | import org.typelevel.literally.examples.literals._ 25 | 26 | test("short string construction") { 27 | assertEquals(short"asdf", ShortString.fromString("asdf").get) 28 | } 29 | 30 | test("short string literal prevents invalid construction") { 31 | compileErrors("""short"asdfasdfasdf"""") 32 | } 33 | 34 | test("port construction") { 35 | assertEquals(port"8080", Port.fromInt(8080).get) 36 | } 37 | 38 | test("port literal prevents invalid construction") { 39 | assert(compileErrors("""port"asdf"""").nonEmpty) 40 | assert(compileErrors("""port"-1"""").nonEmpty) 41 | assert(compileErrors("""port"100000"""").nonEmpty) 42 | } 43 | } 44 | --------------------------------------------------------------------------------