├── .clang-format ├── .gitignore ├── .tm_properties ├── CMakeLists.txt ├── LICENSE ├── README.md ├── cmake ├── colors.cmake ├── coverage.cmake └── pedantic.cmake ├── examples ├── CMakeLists.txt ├── test-single-header.cpp └── test.cpp ├── shorty.cpp ├── single-header ├── CMakeLists.txt ├── generate.cmake ├── shorty.hpp └── shorty.hpp.in └── source ├── CMakeLists.txt └── shorty ├── compatibility ├── concepts.cppm ├── concepts.hpp ├── pack-indexing.cppm └── pack-indexing.hpp ├── leaves.cppm ├── leaves.hpp ├── literals.cppm ├── literals.hpp ├── ops.cppm ├── ops.hpp ├── shorty.cppm └── shorty.hpp /.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Cpp 3 | # BasedOnStyle: WebKit 4 | AccessModifierOffset: -4 5 | AlignAfterOpenBracket: DontAlign 6 | AlignConsecutiveMacros: None 7 | AlignConsecutiveAssignments: None 8 | AlignConsecutiveBitFields: None 9 | AlignConsecutiveDeclarations: None 10 | AlignEscapedNewlines: Right 11 | AlignOperands: DontAlign 12 | AlignTrailingComments: true 13 | AllowAllArgumentsOnNextLine: true 14 | AllowAllConstructorInitializersOnNextLine: true 15 | AllowAllParametersOfDeclarationOnNextLine: true 16 | AllowShortEnumsOnASingleLine: true 17 | AllowShortBlocksOnASingleLine: Always 18 | AllowShortCaseLabelsOnASingleLine: false 19 | AllowShortFunctionsOnASingleLine: All 20 | AllowShortLambdasOnASingleLine: All 21 | AllowShortIfStatementsOnASingleLine: Always 22 | AllowShortLoopsOnASingleLine: true 23 | AlwaysBreakAfterDefinitionReturnType: None 24 | AlwaysBreakAfterReturnType: None 25 | AlwaysBreakBeforeMultilineStrings: true 26 | AlwaysBreakTemplateDeclarations: No 27 | AttributeMacros: 28 | - __capability 29 | BinPackArguments: true 30 | BinPackParameters: true 31 | BraceWrapping: 32 | AfterCaseLabel: false 33 | AfterClass: false 34 | AfterControlStatement: Never 35 | AfterEnum: false 36 | AfterFunction: false 37 | AfterNamespace: false 38 | AfterObjCDeclaration: false 39 | AfterStruct: false 40 | AfterUnion: false 41 | AfterExternBlock: false 42 | BeforeCatch: false 43 | BeforeElse: false 44 | BeforeLambdaBody: false 45 | BeforeWhile: false 46 | IndentBraces: false 47 | SplitEmptyFunction: false 48 | SplitEmptyRecord: false 49 | SplitEmptyNamespace: false 50 | BreakBeforeBinaryOperators: All 51 | BreakBeforeConceptDeclarations: false 52 | BreakBeforeBraces: Attach 53 | BreakBeforeInheritanceComma: false 54 | BreakInheritanceList: BeforeColon 55 | BreakBeforeTernaryOperators: true 56 | BreakConstructorInitializersBeforeComma: false 57 | BreakAfterJavaFieldAnnotations: false 58 | BreakStringLiterals: true 59 | ColumnLimit: 0 60 | CommentPragmas: '^ IWYU pragma:' 61 | CompactNamespaces: false 62 | ConstructorInitializerAllOnOneLineOrOnePerLine: false 63 | ConstructorInitializerIndentWidth: 4 64 | ContinuationIndentWidth: 4 65 | Cpp11BracedListStyle: true 66 | DeriveLineEnding: true 67 | DerivePointerAlignment: false 68 | DisableFormat: false 69 | EmptyLineBeforeAccessModifier: LogicalBlock 70 | ExperimentalAutoDetectBinPacking: false 71 | FixNamespaceComments: true 72 | ForEachMacros: 73 | - foreach 74 | - Q_FOREACH 75 | - BOOST_FOREACH 76 | StatementAttributeLikeMacros: 77 | - Q_EMIT 78 | IncludeBlocks: Merge 79 | IncludeCategories: 80 | - Regex: '^$' 81 | Priority: 3 82 | SortPriority: 0 83 | CaseSensitive: false 84 | - Regex: '^$' 85 | Priority: 0 86 | SortPriority: 0 87 | CaseSensitive: false 88 | - Regex: '^$' 89 | Priority: 1 90 | SortPriority: 0 91 | CaseSensitive: false 92 | - Regex: '^".+/.+"$' 93 | Priority: 2 94 | SortPriority: 0 95 | CaseSensitive: false 96 | - Regex: '^".+"$' 97 | Priority: 1 98 | SortPriority: 0 99 | CaseSensitive: false 100 | - Regex: '^$' 101 | Priority: 4 102 | SortPriority: 0 103 | CaseSensitive: false 104 | - Regex: '^<(c[^.]+|.+\.h)>$' 105 | Priority: 8 106 | SortPriority: 0 107 | CaseSensitive: false 108 | - Regex: '^<.+>$' 109 | Priority: 7 110 | SortPriority: 0 111 | CaseSensitive: false 112 | IncludeIsMainRegex: '(Test)?$' 113 | IncludeIsMainSourceRegex: '' 114 | IndentCaseLabels: false 115 | IndentCaseBlocks: false 116 | IndentGotoLabels: true 117 | IndentPPDirectives: None 118 | IndentExternBlock: AfterExternBlock 119 | IndentRequires: false 120 | IndentWidth: 4 121 | IndentWrappedFunctionNames: false 122 | InsertTrailingCommas: None 123 | JavaScriptQuotes: Leave 124 | JavaScriptWrapImports: true 125 | KeepEmptyLinesAtTheStartOfBlocks: false 126 | LambdaBodyIndentation: OuterScope 127 | MacroBlockBegin: '' 128 | MacroBlockEnd: '' 129 | MaxEmptyLinesToKeep: 1 130 | NamespaceIndentation: Inner 131 | PenaltyBreakAssignment: 2 132 | PenaltyBreakBeforeFirstCallParameter: 19 133 | PenaltyBreakComment: 300 134 | PenaltyBreakFirstLessLess: 120 135 | PenaltyBreakString: 1000 136 | PenaltyBreakTemplateDeclaration: 10 137 | PenaltyExcessCharacter: 1000000 138 | PenaltyReturnTypeOnItsOwnLine: 60 139 | PenaltyIndentedWhitespace: 0 140 | PointerAlignment: Middle 141 | ReflowComments: true 142 | RequiresClausePosition: SingleLine 143 | SortIncludes: true 144 | SortJavaStaticImport: Before 145 | SortUsingDeclarations: true 146 | SpaceAfterCStyleCast: false 147 | SpaceAfterLogicalNot: false 148 | SpaceAfterTemplateKeyword: true 149 | SpaceBeforeAssignmentOperators: true 150 | SpaceBeforeCaseColon: false 151 | SpaceBeforeCpp11BracedList: false 152 | SpaceBeforeCtorInitializerColon: false 153 | SpaceBeforeInheritanceColon: false 154 | SpaceBeforeParens: ControlStatements 155 | SpaceAroundPointerQualifiers: Both 156 | SpaceBeforeRangeBasedForLoopColon: false 157 | SpaceInEmptyBlock: true 158 | SpaceInEmptyParentheses: false 159 | SpacesBeforeTrailingComments: 1 160 | SpacesInAngles: false 161 | SpacesInConditionalStatement: false 162 | SpacesInContainerLiterals: false 163 | SpacesInCStyleCastParentheses: false 164 | SpacesInParentheses: false 165 | SpacesInSquareBrackets: false 166 | SpaceBeforeSquareBrackets: false 167 | BitFieldColonSpacing: After 168 | Standard: c++20 169 | TabWidth: 4 170 | UseCRLF: false 171 | UseTab: Always 172 | WhitespaceSensitiveMacros: [] 173 | 174 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build* -------------------------------------------------------------------------------- /.tm_properties: -------------------------------------------------------------------------------- 1 | CLANG_FORMAT_ON_SAVE = true 2 | 3 | excludeDirectories = "{$excludeDirectories,build}" 4 | includeDirectories = "{$includeDirectories}" 5 | include = "{$include,.gitignore,.gitattributes,.clang-format,.github}" 6 | excludeInFolderSearch = "{$excludeInFolderSearch,build,external,*-single-header.hpp}" 7 | includeInFolderSearch = "{$includeInFolderSearch}" 8 | excludeInFileChooser = "{$excludeInFileChooser}" 9 | softTabs = false 10 | tabSize = 2 11 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 4.0) 2 | 3 | list(PREPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") 4 | 5 | option(SHORTY_IS_IN_MODULE "build shorty library as a c++ module" ON) 6 | 7 | if (SHORTY_IS_IN_MODULE) 8 | set(CMAKE_CXX_STANDARD 23) 9 | set(CMAKE_EXPERIMENTAL_CXX_IMPORT_STD "a9e1cf81-9932-4810-974b-6eccaf14e457") 10 | set(CMAKE_COLOR_DIAGNOSTICS ON) 11 | 12 | set(CMAKE_CXX_STANDARD_REQUIRED OFF) 13 | set(CMAKE_CXX_MODULE_STD 1) 14 | endif() 15 | 16 | include(colors) 17 | include(pedantic) 18 | 19 | project(shorty VERSION 1.0 LANGUAGES CXX) 20 | 21 | add_subdirectory(source) 22 | add_subdirectory(single-header EXCLUDE_FROM_ALL) 23 | add_subdirectory(examples EXCLUDE_FROM_ALL) 24 | 25 | 26 | -------------------------------------------------------------------------------- /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 | 203 | 204 | --- LLVM Exceptions to the Apache 2.0 License ---- 205 | 206 | As an exception, if, as a result of your compiling your source code, portions 207 | of this Software are embedded into an Object form of such source code, you 208 | may redistribute such embedded portions in such Object form without complying 209 | with the conditions of Sections 4(a), 4(b) and 4(d) of the License. 210 | 211 | In addition, if you combine or link compiled forms of this Software with 212 | software that is licensed under the GPLv2 ("Combined Software") and if a 213 | court of competent jurisdiction determines that the patent provision (Section 214 | 3), the indemnity provision (Section 9) or other Section of the License 215 | conflicts with the conditions of the GPLv2, you may retroactively and 216 | prospectively choose to deem waived or otherwise exclude such Section(s) of 217 | the License, but only in their entirety and only with respect to the Combined 218 | Software. 219 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # terser (shorter) lambda == SHORTY 2 | 3 | This library is intended to give terser syntax than C++'s lambdas, not replace C++ with lazy DSL. 4 | 5 | ```c++ 6 | import shorty; 7 | using namespace shorty::literals; 8 | 9 | // you no longer need to remember if it's `std::less` or `std::greater` 10 | std::ranges::sort(subject, $lhs > $rhs); 11 | 12 | // filter only even 13 | subject | std::views::filter(($i % 2) == 0); 14 | 15 | // zip together and transform 16 | std::views::zip(A,B,C,D) | std::views::transform($a * $b + $c * $d); 17 | 18 | // call external function 19 | auto pythagorean = $($a * $a + $b * $b); // or $call; 20 | pythagorean(3.0, 4.0) == 5.0; 21 | 22 | // casting 23 | auto to_int = $($0); // or $cast; 24 | to_int(4.3) == 4; 25 | 26 | // remap by index 27 | auto indices = std::vector{...}; 28 | auto mapping = indices | $(data)[$i]; 29 | ``` 30 | 31 | ## accessing arguments 32 | 33 | If shorty callable gets only one argument and the argument is `tuple_like` then it's automatically unwrapped. Same applies to any lazy calls. 34 | 35 | By default arguments are accessible using `$0`...`$9` syntax (for first 10) or `$arg`. But also you can use following special arguments: 36 | 37 | - `$lhs` and `$rhs` for binary callables (it limits them to two arguments) 38 | - `$it` for first and only argument, which is also compatible with `std::input_or_output_iterator` 39 | - `$a` ... `$f` for first 6 arguments but names instead of numbers (can't be mixed with other types of arguments) 40 | - `$x`, `$y`, `$z` for first 3 arguments (again can't be mixed with other types of arguments) 41 | - `$i`, `$n`, `$k`, `$in` ... for first and only argument (can't be mixed too) 42 | 43 | ## querying arguments 44 | 45 | - `$argc` for getting number of arguments as `size_t` 46 | - `$args` to get all arguments as a tuple 47 | 48 | ## capturing 49 | 50 | - `$(v)` or `$ref(v)` capture by reference (or const reference, depending on const qualifier of `v`) 51 | - `$value(v)`, `$val(v)`, or `$copy(v)` capture by copy 52 | - `$fixed` or `$const` capture by CNTTP (only for structural types) 53 | 54 | ## calling functions 55 | 56 | - `$(args...)` or `$call(args...)` call `callable` with arguments `args` 57 | - `$(args...)` or `$call(args...)` call new instance of type `CallableType` with arguments `args` 58 | 59 | ## casting 60 | 61 | - `$(expr)` or `$cast(expr)` will `static_cast` expression result into `T` 62 | 63 | ## making a tuple 64 | 65 | - `($a, $b, $c)` - will make `tuple` 66 | - `($0, $1)` - will make `tuple` 67 | 68 | ## assigning 69 | 70 | - `$a += 2` will add 2 to `$a` and return result 71 | - `-=`, `*=`, `/=`, `%=` all works too 72 | 73 | ---- 74 | 75 | Special thanks (and a bit of hate) to an [anonymous Argentinian](https://bsky.app/profile/kaballo86.bsky.social) for nerd-sniping into this. 76 | -------------------------------------------------------------------------------- /cmake/colors.cmake: -------------------------------------------------------------------------------- 1 | option (FORCE_COLORED_OUTPUT "Always produce ANSI-colored output (GNU/Clang only)." ON) 2 | if (${FORCE_COLORED_OUTPUT}) 3 | if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") 4 | add_compile_options ($<$:-fdiagnostics-color=always>) 5 | add_compile_options ($<$:-fdiagnostics-color=always>) 6 | elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") 7 | add_compile_options ($<$:-fcolor-diagnostics>) 8 | add_compile_options ($<$:-fcolor-diagnostics>) 9 | endif () 10 | endif () -------------------------------------------------------------------------------- /cmake/coverage.cmake: -------------------------------------------------------------------------------- 1 | SET(test_source "int main() { }") 2 | 3 | try_compile(COVERAGE_WORKS SOURCE_FROM_VAR test.cpp test_source LINK_OPTIONS -fprofile-instr-generate -fcoverage-mapping OUTPUT_VARIABLE COVERAGE_WORKS_OUTPUT) 4 | 5 | if (NOT COVERAGE_WORKS) 6 | #message(STATUS "test coverage is not compatible with current compiler") 7 | #message(STATUS "${COVERAGE_WORKS_OUTPUT}") 8 | function(enable_coverage) 9 | endfunction() 10 | 11 | function(coverage_report_after EVENT TARGET) 12 | add_custom_target(coverage DEPENDS ${EVENT}) 13 | endfunction() 14 | 15 | unset(LLVM_COV) 16 | return() 17 | endif() 18 | 19 | cmake_path(GET CMAKE_CXX_COMPILER PARENT_PATH COMPILER_HINT_PATH) 20 | 21 | if (NOT LLVM_PROFDATA) 22 | find_program(LLVM_PROFDATA llvm-profdata HINTS ${COMPILER_HINT_PATH}) 23 | endif() 24 | 25 | if (NOT LLVM_COV) 26 | find_program(LLVM_COV llvm-cov HINTS ${COMPILER_HINT_PATH}) 27 | endif() 28 | 29 | if (LLVM_PROFDATA AND LLVM_COV) 30 | set(LLVM_PROFDATA "${LLVM_PROFDATA}" CACHE INTERNAL "path to llvm-profdata") 31 | set(LLVM_COV "${LLVM_COV}" CACHE INTERNAL "path to llvm-cov") 32 | else() 33 | find_program(XCRUN xcrun) 34 | if (XCRUN) 35 | set(LLVM_PROFDATA "${XCRUN} llvm-profdata" CACHE INTERNAL "path to llvm-profdata") 36 | set(LLVM_COV "${XCRUN} llvm-cov" CACHE INTERNAL "path to llvm-cov") 37 | endif() 38 | endif() 39 | 40 | find_program(OPEN_UTILITY open) 41 | set(OPEN_UTILITY "${OPEN_UTILITY}" CACHE INTERNAL "path to open utility") 42 | 43 | function(enable_coverage) 44 | 45 | if (NOT COVERAGE_WORKS) 46 | message(FATAL_ERROR "Source level code coverage is not supporter!") 47 | endif() 48 | 49 | if (NOT LLVM_COV) 50 | message(FATAL_ERROR "Source level code coverage is supported only for Clang compiler! (CMAKE_CXX_COMPILER_ID = ${CMAKE_CXX_COMPILER_ID})") 51 | endif() 52 | 53 | message(STATUS "Enabling Clang source code-coverage (llvm-cov=${LLVM_COV})") 54 | 55 | # add flags to emit coverage 56 | add_compile_options("-fprofile-instr-generate" "-fcoverage-mapping" "-g") 57 | add_link_options("-fprofile-instr-generate" "-fcoverage-mapping") 58 | add_compile_options("-ffile-prefix-map=${CMAKE_SOURCE_DIR}/=/") 59 | endfunction() 60 | 61 | function(coverage_report_after EVENT TARGET) 62 | if (NOT LLVM_COV) 63 | add_custom_target(coverage DEPENDS ${EVENT}) 64 | return() 65 | endif() 66 | 67 | SET(coverage_data_name "default.profraw") 68 | add_custom_command(TARGET ${EVENT} POST_BUILD 69 | COMMAND ${LLVM_PROFDATA} merge -sparse ${coverage_data_name} -o coverage.profdata 70 | COMMAND ${LLVM_COV} show $ -format html -instr-profile=coverage.profdata "-ignore-filename-regex=\"(external/.*|tests/.*|cthash/internal/assert[.]hpp)\"" -output-dir ${CMAKE_BINARY_DIR}/report -show-instantiations=false -show-directory-coverage -show-expansions=false -show-line-counts --show-line-counts-or-regions -Xdemangler c++filt -Xdemangler -n -show-branches=percent -tab-size=4 -path-equivalence=/,${CMAKE_SOURCE_DIR} 71 | COMMAND cd ${CMAKE_BINARY_DIR} && zip -q -r -9 report.zip report BYPRODUCTS ${CMAKE_BINARY_DIR}/report.zip COMMENT "Generating Code-Coverage report" 72 | ) 73 | 74 | add_custom_target(coverage DEPENDS ${CMAKE_BINARY_DIR}/report.zip) 75 | 76 | if (OPEN_UTILITY) 77 | add_custom_command(TARGET coverage POST_BUILD COMMAND ${OPEN_UTILITY} ${CMAKE_BINARY_DIR}/report/index.html DEPENDS ${CMAKE_BINARY_DIR}/report.zip) 78 | endif() 79 | endfunction() 80 | -------------------------------------------------------------------------------- /cmake/pedantic.cmake: -------------------------------------------------------------------------------- 1 | macro(add_c_and_cxx_compile_options NAME) 2 | add_compile_options("$<$:${NAME}>") 3 | add_compile_options("$<$:${NAME}>") 4 | endmacro() 5 | 6 | macro(add_c_and_cxx_compile_definitions NAME) 7 | add_compile_definitions("$<$:${NAME}>") 8 | add_compile_definitions("$<$:${NAME}>") 9 | endmacro() 10 | 11 | if (MSVC) 12 | add_c_and_cxx_compile_options("/W4") 13 | add_c_and_cxx_compile_options("/WX") 14 | else() 15 | add_c_and_cxx_compile_options("-Wall") 16 | add_c_and_cxx_compile_options("-Wextra") 17 | add_c_and_cxx_compile_options("-pedantic") 18 | add_c_and_cxx_compile_options("-Wshadow") 19 | add_c_and_cxx_compile_options("-Wconversion") 20 | add_c_and_cxx_compile_options("-Werror") 21 | add_c_and_cxx_compile_options("-Wno-dollar-in-identifier-extension") 22 | 23 | if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") 24 | add_c_and_cxx_compile_definitions("_LIBCPP_ENABLE_NODISCARD") 25 | 26 | if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 13.0) 27 | add_c_and_cxx_compile_options("-Wno-missing-braces") 28 | endif() 29 | elseif(CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang") 30 | add_c_and_cxx_compile_definitions("_LIBCPP_ENABLE_NODISCARD") 31 | add_c_and_cxx_compile_options("-Wno-missing-braces") 32 | endif() 33 | endif() 34 | -------------------------------------------------------------------------------- /examples/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_executable(test test.cpp) 2 | target_link_libraries(test PRIVATE shorty) 3 | 4 | add_executable(test-single-header test-single-header.cpp) 5 | target_link_libraries(test-single-header PRIVATE shorty-single-header) 6 | 7 | add_custom_target(examples DEPENDS test test-single-header) 8 | -------------------------------------------------------------------------------- /examples/test-single-header.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | using namespace shorty::literals; 8 | 9 | auto data = std::array{1, 2, 3, 4, 5}; 10 | auto indices = std::array{0, 0, 4, 4, 1}; 11 | 12 | std::ranges::sort(indices, $lhs < $rhs); 13 | 14 | for (auto v: indices | std::views::transform($(data)[$($0)])) { 15 | std::println("{}", v); 16 | } 17 | 18 | std::println("zip:"); 19 | auto a = std::array{1, 2, 3, 4, 5}; 20 | auto b = std::array{2, 0, 1, 1, 3}; 21 | for (auto v: std::views::zip(a, b) | std::views::transform($0 + $1)) { 22 | std::println("{}", v); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /examples/test.cpp: -------------------------------------------------------------------------------- 1 | #ifdef SHORTY_IS_IN_MODULE 2 | import shorty; 3 | import std; 4 | #else 5 | #include 6 | #include 7 | #include 8 | #include 9 | #endif 10 | 11 | #include 12 | 13 | int main() { 14 | using namespace shorty::literals; 15 | 16 | auto data = std::array{1, 2, 3, 4, 5}; 17 | std::ranges::sort(data, $lhs < $rhs); 18 | 19 | auto indices = std::array{0, 0, 4, 4, 1}; 20 | for (auto v: indices | std::views::transform($(data)[$0])) { 21 | std::println("{}", v); 22 | } 23 | 24 | std::println("zip:"); 25 | auto a = std::array{1, 2, 3, 4, 5}; 26 | auto b = std::array{2, 0, 1, 1, 3}; 27 | auto c = std::array{1, 1, 1, 0, 1}; 28 | for (auto v: std::views::zip(a, b, c) | std::views::transform(($a + $b) * $c)) { 29 | std::println("{}", v); 30 | } 31 | 32 | std::println("squares:"); 33 | constexpr auto sqrt = [](std::floating_point auto v) { 34 | return std::sqrt(v); 35 | }; 36 | 37 | auto values = std::array{1.0, 2.0, 3.0, 4.0, 5.0, 6.0}; 38 | for (auto v: values | std::views::transform($($0))) { 39 | std::println("{}", v); 40 | } 41 | 42 | [[maybe_unused]] auto cast_to_int = $($0); 43 | assert(cast_to_int(42.3) == 42); 44 | 45 | // auto wrong_expr = $x + $a; 46 | auto expr = $0 + $1; 47 | assert(expr(1, 4) == 5); 48 | 49 | auto make_tuple = ($0, $1, $2); 50 | std::tuple r = make_tuple(1, 2, 3); 51 | auto [t0, t1, t2] = r; 52 | assert(t0 == 1); 53 | assert(t1 == 2); 54 | assert(t2 == 3); 55 | 56 | constexpr auto sum = [](shorty::tuple_like auto && tpl) { 57 | return [&](std::index_sequence) { 58 | return (std::get(tpl) + ... + 0); 59 | }(std::make_index_sequence>>()); 60 | }; 61 | 62 | auto test = $(($0, $1, $2, $3)); // double paranthesis are explicit, so we get tuple 63 | auto r2 = test(1, 2, 3, 4); 64 | std::println("{} == 10", r2); 65 | 66 | // identify i; 67 | // expr(1, 2); 68 | // expr(std::tuple{1}); 69 | 70 | // auto expr2 = $lhs + $x; 71 | } -------------------------------------------------------------------------------- /shorty.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | namespace shorty { 8 | 9 | struct ast_node { }; 10 | 11 | #if __cpp_pack_indexing < 202311L 12 | template constexpr auto extract_nth(First && first, Args &&... args) noexcept { 13 | if constexpr (N == 0u) { 14 | return first; 15 | } else { 16 | return extract_nth(std::forward(args)...); 17 | } 18 | } 19 | #endif 20 | 21 | template struct nth_argument { 22 | template constexpr auto operator()(Args &&... args) const { 23 | static_assert(N < sizeof...(Args)); 24 | #if __cpp_pack_indexing >= 202311L 25 | return args...[N]; 26 | #else 27 | return extract_nth(std::forward(args)...); 28 | #endif 29 | } 30 | constexpr operator ast_node() const { return {}; } 31 | }; 32 | 33 | template struct nth_argument_of_k { 34 | template constexpr auto operator()(Args &&... args) const { 35 | static_assert(Count == sizeof...(Args)); 36 | static_assert(N < sizeof...(Args)); 37 | #if __cpp_pack_indexing >= 202311L 38 | return args...[N]; 39 | #else 40 | return extract_nth(std::forward(args)...); 41 | #endif 42 | } 43 | constexpr operator ast_node() const { return {}; } 44 | }; 45 | 46 | template struct nth_argument_with_query { 47 | template constexpr auto operator()(Args &&... args) const { 48 | static_assert(N < sizeof...(Args)); 49 | #if __cpp_pack_indexing >= 202311L 50 | static_assert(Query(std::type_identity { })); 51 | return args...[N]; 52 | #else 53 | static_assert(Query(std::type_identity(std::forward(args)...))>{})); 54 | return extract_nth(std::forward(args)...); 55 | #endif 56 | } 57 | constexpr operator ast_node() const { return {}; } 58 | }; 59 | 60 | struct argument_count { 61 | template constexpr auto operator()(Args &&...) const { 62 | return sizeof...(Args); 63 | } 64 | constexpr operator ast_node() const { return {}; } 65 | }; 66 | 67 | struct pack_arguments { 68 | template constexpr auto operator()(Args &&... args) const { 69 | return std::tuple(std::forward(args)...); 70 | } 71 | constexpr operator ast_node() const { return {}; } 72 | }; 73 | 74 | template struct constant { 75 | template constexpr auto operator()(Args &&...) const { 76 | return V; 77 | } 78 | constexpr operator ast_node() const { return {}; } 79 | }; 80 | 81 | template struct value { 82 | T & data; 83 | template constexpr auto operator()(Args &&...) const { 84 | return data; 85 | } 86 | constexpr operator ast_node() const { return {}; } 87 | }; 88 | 89 | template struct static_string { 90 | using type = const CharT (&)[N]; 91 | type data; 92 | consteval static_string(const CharT (&_data)[N]) noexcept: data{_data} { } 93 | template constexpr type operator()(Args &&...) const { 94 | return data; 95 | } 96 | constexpr operator ast_node() const { return {}; } 97 | }; 98 | 99 | template struct reference { 100 | T & value; 101 | template constexpr auto operator()(Args &&...) const { 102 | return value; 103 | } 104 | constexpr operator ast_node() const { return {}; } 105 | }; 106 | 107 | template constexpr decltype(auto) evaluate(T && obj, [[maybe_unused]] Args &&... args) { 108 | if constexpr (requires { 109 | obj(std::forward(args)...); 110 | }) { 111 | return obj(std::forward(args)...); 112 | } else { 113 | return obj; 114 | } 115 | } 116 | 117 | template struct node { 118 | using base_node = node; 119 | 120 | static constexpr auto op = Op{}; 121 | [[no_unique_address]] std::tuple ast_operands; 122 | 123 | node(node &&) = default; 124 | node(const node &) = default; 125 | constexpr node(std::convertible_to auto &&... _ast_operands): ast_operands{std::forward(_ast_operands)...} { } 126 | 127 | template constexpr auto operator()(Args &&... args) const { 128 | #if __cpp_structured_bindings >= 202411L 129 | auto && [... operands] = ast_operands; 130 | return op(evaluate(std::forward(operands), std::forward(args)...)...); 131 | #else 132 | return [&](std::index_sequence) { 133 | return op(evaluate(std::get(ast_operands), std::forward(args)...)...); 134 | }(std::make_index_sequence::value>()); 135 | #endif 136 | } 137 | 138 | constexpr operator ast_node() const { return {}; } 139 | }; 140 | 141 | template concept is_node = requires(const T & maybe_node) { 142 | typename T::base_node; 143 | { node{std::declval()} } -> std::same_as; 144 | { node{maybe_node} } -> std::same_as; 145 | }; 146 | 147 | // just to make sure nodes and arguments are not references 148 | // template auto fix_type(std::remove_cvref_t *) -> std::remove_cvref_t; 149 | 150 | // everything else can be 151 | // template auto fix_type(...) -> value>; 152 | 153 | template auto wrap(Y *) -> std::remove_cvref_t requires std::convertible_to, ast_node>; 154 | 155 | template struct wrapper { 156 | using result = value>; 157 | }; 158 | 159 | template struct wrapper { 160 | using result = static_string; 161 | }; 162 | 163 | template T> struct wrapper { 164 | using result = std::remove_cvref_t; 165 | }; 166 | 167 | // template using select = decltype(fix_type(nullptr)); 168 | template using select = wrapper::result; 169 | 170 | // SUPPORT FOR UNARY and BINARY OPS 171 | template struct unary_op: node { }; 172 | template struct binary_op: node { }; 173 | 174 | template struct node_builder { 175 | template constexpr auto operator()(Args &&... args) { 176 | if constexpr (sizeof...(Args) == 1) { 177 | return unary_op...>(std::forward(args)...); 178 | } else if constexpr (sizeof...(Args) == 2) { 179 | return binary_op...>(std::forward(args)...); 180 | } else { 181 | return node...>(std::forward(args)...); 182 | } 183 | } 184 | }; 185 | 186 | template constexpr auto build = node_builder{}; 187 | 188 | // I wish I have the universal template arguments 189 | template