├── .gitignore ├── CMakeLists.txt ├── CPP2C.cpp ├── LICENSE ├── README.md └── output ├── cwrapper.cpp └── cwrapper.h /.gitignore: -------------------------------------------------------------------------------- 1 | build/** 2 | .cproject 3 | .project -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.8) 2 | project(CPP2C) 3 | 4 | # Allow the user to override the install prefix. 5 | if(NOT DEFINED CMAKE_INSTALL_PREFIX) 6 | set(CMAKE_INSTALL_PREFIX "/usr/local") 7 | endif() 8 | string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") 9 | 10 | find_package(LLVM REQUIRED CONFIG) 11 | 12 | message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}") 13 | message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}") 14 | 15 | # Set your project compile flags. 16 | # E.g. if using the C++ header files 17 | # you will need to enable C++11 support 18 | # for your compiler. 19 | SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") 20 | 21 | include_directories(${LLVM_INCLUDE_DIRS}) 22 | link_directories(${LLVM_LIBRARY_DIRS}) 23 | add_definitions(${LLVM_DEFINITIONS}) 24 | 25 | # Now build our tools 26 | add_executable(cpp2c CPP2C.cpp) 27 | 28 | # Find the libraries that correspond to the LLVM components 29 | # that we wish to use 30 | llvm_map_components_to_libnames(llvm_libs x86asmparser bitreader support mc option profiledata) 31 | message(STATUS "LLVM_LIBS: ${llvm_libs}") 32 | 33 | target_link_libraries(cpp2c 34 | clangFrontend 35 | clangSerialization 36 | clangDriver 37 | clangTooling 38 | clangParse 39 | clangSema 40 | clangAnalysis 41 | clangRewriteFrontend 42 | clangRewrite 43 | clangEdit 44 | clangAST 45 | clangLex 46 | clangBasic 47 | clangASTMatchers 48 | ) 49 | 50 | target_link_libraries(cpp2c ${llvm_libs}) 51 | 52 | execute_process(COMMAND bash "-c" "llvm-config --cxxflags" OUTPUT_VARIABLE compile_flags OUTPUT_STRIP_TRAILING_WHITESPACE) 53 | set_property(TARGET cpp2c APPEND PROPERTY COMPILE_FLAGS "${compile_flags} -Wno-strict-aliasing") 54 | 55 | install(TARGETS cpp2c DESTINATION bin) 56 | -------------------------------------------------------------------------------- /CPP2C.cpp: -------------------------------------------------------------------------------- 1 | #include "clang/Driver/Options.h" 2 | #include "clang/AST/AST.h" 3 | #include "clang/AST/ASTContext.h" 4 | #include "clang/AST/ASTConsumer.h" 5 | #include "clang/AST/RecursiveASTVisitor.h" 6 | #include "clang/Frontend/ASTConsumers.h" 7 | #include "clang/Frontend/FrontendActions.h" 8 | #include "clang/Frontend/CompilerInstance.h" 9 | #include "clang/Tooling/CommonOptionsParser.h" 10 | #include "clang/Tooling/Tooling.h" 11 | #include "clang/Rewrite/Core/Rewriter.h" 12 | #include "clang/ASTMatchers/ASTMatchers.h" 13 | #include "clang/ASTMatchers/ASTMatchFinder.h" 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | using namespace std; 21 | using namespace clang; 22 | using namespace clang::driver; 23 | using namespace clang::tooling; 24 | using namespace clang::ast_matchers; 25 | using namespace llvm; 26 | 27 | /** Options **/ 28 | static cl::OptionCategory CPP2CCategory("CPP2C options"); 29 | static std::unique_ptr Options(createDriverOptTable()); 30 | static cl::opt OutputFilename("o", cl::desc(Options->getOptionHelpText((options::OPT_o)))); 31 | 32 | /** Classes to be mapped to C **/ 33 | struct OutputStreams{ 34 | string headerString; 35 | string bodyString; 36 | 37 | llvm::raw_string_ostream HeaderOS; 38 | llvm::raw_string_ostream BodyOS; 39 | 40 | OutputStreams() : headerString(""), bodyString(""), HeaderOS(headerString), BodyOS(bodyString){}; 41 | }; 42 | 43 | 44 | vector ClassList = {"uThread", "kThread", "Cluster", "Connection", "Mutex", "OwnerLock", "ConditionVariable", "Semaphore", "uThreadPool"}; 45 | 46 | map funcList; 47 | 48 | /** Matchers **/ 49 | 50 | /** Handlers **/ 51 | class classMatchHandler: public MatchFinder::MatchCallback{ 52 | public: 53 | classMatchHandler(OutputStreams& os): OS(os){} 54 | 55 | tuple determineCType(const QualType& qt){ 56 | 57 | string CType = ""; 58 | string CastType = ""; //whether this should be casted or not 59 | bool isPointer = false; 60 | bool shoulReturn = true; 61 | 62 | //if it is builtint type use it as is 63 | if(qt->isBuiltinType() || (qt->isPointerType() && qt->getPointeeType()->isBuiltinType())){ 64 | CType = qt.getAsString(); 65 | if(qt->isVoidType()) 66 | shoulReturn = false; 67 | //if it is a CXXrecordDecl then return a pointer to WName* 68 | }else if(qt->isRecordType()){ 69 | const CXXRecordDecl* crd = qt->getAsCXXRecordDecl(); 70 | string recordName = crd->getNameAsString(); 71 | CType = "W" + recordName + "*"; 72 | CastType = recordName+ "*"; 73 | 74 | }else if( (qt->isReferenceType() || qt->isPointerType()) && qt->getPointeeType()->isRecordType()){ 75 | isPointer = true; //to properly differentiate among cast types 76 | const CXXRecordDecl* crd = qt->getPointeeType()->getAsCXXRecordDecl(); 77 | string recordName = crd->getNameAsString(); 78 | if ( std::find(ClassList.begin(), ClassList.end(), recordName) != ClassList.end() ){ 79 | CType = "W" + recordName + "*"; 80 | CastType = recordName + "*"; 81 | }else{ 82 | CType = recordName+"*"; 83 | } 84 | 85 | } 86 | return make_tuple(CType, CastType, isPointer, shoulReturn); 87 | 88 | } 89 | 90 | virtual void run(const MatchFinder::MatchResult &Result){ 91 | if (const CXXMethodDecl *cmd = Result.Nodes.getNodeAs("publicMethodDecl")){ 92 | string methodName = ""; 93 | string className = cmd->getParent()->getDeclName().getAsString(); 94 | string returnType = ""; 95 | string returnCast = ""; 96 | bool shouldReturn, isPointer; 97 | string self = "W" + className + "* self"; 98 | string separator = ", "; 99 | string bodyEnd = ""; 100 | 101 | std::stringstream functionBody; 102 | 103 | //ignore operator overloadings 104 | if(cmd->isOverloadedOperator()) 105 | return; 106 | 107 | //constructor 108 | if (const CXXConstructorDecl* ccd = dyn_cast(cmd)) { 109 | if(ccd->isCopyConstructor() || ccd->isMoveConstructor()) return; 110 | methodName = "_create"; 111 | returnType = "W" + className + "*"; 112 | self = ""; 113 | separator = ""; 114 | functionBody << "return reinterpret_cast<"<< returnType << ">( new " << className << "("; 115 | bodyEnd += "))"; 116 | }else if (isa(cmd)) { 117 | methodName = "_destroy"; 118 | returnType = "void"; 119 | functionBody << " delete reinterpret_cast<"<(self)"; 120 | }else{ 121 | methodName = "_" + cmd->getNameAsString(); 122 | const QualType qt = cmd->getReturnType(); 123 | std::tie(returnType, returnCast, isPointer, shouldReturn) = determineCType(qt); 124 | 125 | //should this function return? 126 | if(shouldReturn) 127 | functionBody << "return "; 128 | 129 | if(returnCast != ""){ 130 | //if not pointer and it needs to be casted, then return the pointer 131 | if(!isPointer) 132 | functionBody << "&"; 133 | functionBody << "reinterpret_cast<"<< returnType << ">("; 134 | bodyEnd += ")"; 135 | } 136 | 137 | //if Static call it properly 138 | if(cmd->isStatic()) 139 | functionBody <getNameAsString() << "("; 140 | //if not use the passed object to call the method 141 | else 142 | functionBody << "reinterpret_cast<"<(self)->" << cmd->getNameAsString() << "("; 143 | 144 | bodyEnd += ")"; 145 | } 146 | 147 | 148 | std::stringstream funcname; 149 | funcname << returnType << " " << className << methodName; 150 | 151 | auto it = funcList.find(funcname.str()); 152 | 153 | if(it != funcList.end()){ 154 | it->second++; 155 | funcname << "_" << it->second ; 156 | }else{ 157 | funcList[funcname.str()] = 0; 158 | } 159 | 160 | funcname << "(" << self; 161 | 162 | for(unsigned int i=0; igetNumParams(); i++) 163 | { 164 | const QualType qt = cmd->parameters()[i]->getType(); 165 | std::tie(returnType, returnCast, isPointer, shouldReturn) = determineCType(qt); 166 | funcname << separator << returnType << " "; 167 | funcname << cmd->parameters()[i]->getQualifiedNameAsString() << ""; 168 | 169 | if(i !=0 ) 170 | functionBody << separator; 171 | if(returnCast == "") 172 | functionBody << cmd->parameters()[i]->getQualifiedNameAsString(); 173 | else{ 174 | if(!isPointer) 175 | functionBody << "*"; 176 | functionBody << "reinterpret_cast<" << returnCast << ">("<< cmd->parameters()[i]->getQualifiedNameAsString() << ")"; 177 | 178 | } 179 | 180 | string separator = ", "; 181 | 182 | } 183 | funcname << ")"; 184 | 185 | OS.HeaderOS << funcname.str() << ";\n"; 186 | 187 | OS.BodyOS << funcname.str() << "{\n "; 188 | OS.BodyOS << functionBody.str(); 189 | OS.BodyOS << bodyEnd << "; \n}\n" ; 190 | } 191 | } 192 | virtual void onEndOfTranslationUnit(){} 193 | private: 194 | OutputStreams& OS; 195 | 196 | }; 197 | 198 | 199 | /****************** /Member Functions *******************************/ 200 | // Implementation of the ASTConsumer interface for reading an AST produced 201 | // by the Clang parser. It registers a couple of matchers and runs them on 202 | // the AST. 203 | class MyASTConsumer: public ASTConsumer { 204 | public: 205 | MyASTConsumer(OutputStreams& os) : OS(os), 206 | HandlerForClassMatcher(os){ 207 | // Add a simple matcher for finding 'if' statements. 208 | 209 | for(string& className : ClassList){ 210 | OS.HeaderOS << "struct W"<< className << "; \n" 211 | "typedef struct W"<< className << " W"<< className << ";\n"; 212 | //oss.push_back(std::move(os)) 213 | 214 | DeclarationMatcher classMatcher = cxxMethodDecl(isPublic(), ofClass(hasName(className))).bind("publicMethodDecl"); 215 | Matcher.addMatcher(classMatcher, &HandlerForClassMatcher); 216 | } 217 | 218 | } 219 | 220 | void HandleTranslationUnit(ASTContext &Context) override { 221 | // Run the matchers when we have the whole TU parsed. 222 | Matcher.matchAST(Context); 223 | } 224 | 225 | private: 226 | OutputStreams& OS; 227 | classMatchHandler HandlerForClassMatcher; 228 | 229 | MatchFinder Matcher; 230 | }; 231 | 232 | // For each source file provided to the tool, a new FrontendAction is created. 233 | class MyFrontendAction: public ASTFrontendAction { 234 | public: 235 | MyFrontendAction() { 236 | OS.HeaderOS << "#ifndef UTHREADS_CWRAPPER_H\n" 237 | "#define UTHREADS_CWRAPPER_H_\n" 238 | "#include \n" 239 | "#include \n" 240 | "#include \n" 241 | "#include \n\n" 242 | 243 | "#ifdef __cplusplus\n" 244 | "extern \"C\"{\n" 245 | "#endif\n" 246 | "#include \n"; 247 | OS.BodyOS << "#include \"generic/basics.h\"\n" 248 | "#include \"cwrapper.h\"\n" 249 | "#include \"runtime/uThread.h\"\n" 250 | "#include \"runtime/uThreadPool.h\"\n" 251 | "#include \"runtime/kThread.h\"\n" 252 | "#include \"io/Network.h\"\n" 253 | "#ifdef __cplusplus\n" 254 | "extern \"C\"{\n" 255 | "#endif\n"; 256 | 257 | } 258 | 259 | void EndSourceFileAction() override { 260 | 261 | StringRef headerFile("cwrapper.h"); 262 | StringRef bodyFile("cwrapper.cpp"); 263 | 264 | // Open the output file 265 | std::error_code EC; 266 | llvm::raw_fd_ostream HOS(headerFile, EC, llvm::sys::fs::F_None); 267 | if (EC) { 268 | llvm::errs() << "while opening '" << headerFile<< "': " 269 | << EC.message() << '\n'; 270 | exit(1); 271 | } 272 | llvm::raw_fd_ostream BOS(bodyFile, EC, llvm::sys::fs::F_None); 273 | if (EC) { 274 | llvm::errs() << "while opening '" << bodyFile<< "': " 275 | << EC.message() << '\n'; 276 | exit(1); 277 | } 278 | 279 | 280 | OS.HeaderOS << "#ifdef __cplusplus\n" 281 | "}\n" 282 | "#endif\n" 283 | "#endif /* UTHREADS_CWRAPPER_H_ */\n"; 284 | 285 | OS.BodyOS<< "#ifdef __cplusplus\n" 286 | "}\n" 287 | "#endif\n"; 288 | 289 | OS.HeaderOS.flush(); 290 | OS.BodyOS.flush(); 291 | HOS<< OS.headerString << "\n"; 292 | BOS<< OS.bodyString << "\n"; 293 | 294 | } 295 | 296 | std::unique_ptr CreateASTConsumer(CompilerInstance &CI, 297 | StringRef file) override { 298 | 299 | return llvm::make_unique(OS); 300 | } 301 | 302 | private: 303 | OutputStreams OS; 304 | }; 305 | 306 | int main(int argc, const char **argv) { 307 | // parse the command-line args passed to your code 308 | CommonOptionsParser op(argc, argv, CPP2CCategory); 309 | // create a new Clang Tool instance (a LibTooling environment) 310 | ClangTool Tool(op.getCompilations(), op.getSourcePathList()); 311 | 312 | 313 | // run the Clang Tool, creating a new FrontendAction 314 | return Tool.run(newFrontendActionFactory().get()); 315 | } 316 | -------------------------------------------------------------------------------- /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 | # CPP2C 2 | This is simple tool to generate a C interface from C++ source code using clang libtooling. CPP2C currently is a proof of concept, 3 | and only applies to [https://github.com/samanbarghi/uThreads](https://github.com/samanbarghi/uThreads), to generate the C interface. The code is explained in details in [this blog post](http://samanbarghi.com/blog/2016/12/06/generate-c-interface-from-c-source-code-using-clang-libtooling/). 4 | 5 | ## Building and Installation 6 | ``` 7 | git clone https://github.com/samanbarghi/CPP2C 8 | cd CPP2C 9 | mkdir build 10 | cmake .. 11 | make 12 | sudo make install 13 | ``` 14 | 15 | ## Run it over uThreads source code 16 | ``` 17 | git clone https://github.com/samanbarghi/uThreads 18 | cd uThreads 19 | cpp2c include/uThreads.h -- -I./src -I/usr/include/x86_64-linux-gnu/c++/5/ -I/usr/include/c++/5.4.0 -std=c++11 20 | ``` 21 | 22 | ## Output 23 | You can find the output in _outpu_ folder: _cwrapper.h_ is the header that should be included in C files, and _cwrapper.cpp_ is in C++ and is responsible to convert C++ pointers to C and vice versa. 24 | -------------------------------------------------------------------------------- /output/cwrapper.cpp: -------------------------------------------------------------------------------- 1 | #include "generic/basics.h" 2 | #include "cwrapper.h" 3 | #include "runtime/uThread.h" 4 | #include "runtime/uThreadPool.h" 5 | #include "runtime/kThread.h" 6 | #include "io/Network.h" 7 | #ifdef __cplusplus 8 | extern "C"{ 9 | #endif 10 | WMutex* Mutex_create(){ 11 | return reinterpret_cast( new Mutex()); 12 | } 13 | _Bool Mutex_acquire(WMutex* self){ 14 | return reinterpret_cast(self)->acquire(); 15 | } 16 | _Bool Mutex_acquire_1(WMutex* self){ 17 | return reinterpret_cast(self)->acquire(); 18 | } 19 | void Mutex_release(WMutex* self){ 20 | reinterpret_cast(self)->release(); 21 | } 22 | void Mutex_unlock(WMutex* self){ 23 | reinterpret_cast(self)->unlock(); 24 | } 25 | void Mutex_destroy(WMutex* self){ 26 | delete reinterpret_cast(self); 27 | } 28 | WOwnerLock* OwnerLock_create(){ 29 | return reinterpret_cast( new OwnerLock()); 30 | } 31 | mword OwnerLock_acquire(WOwnerLock* self){ 32 | return reinterpret_cast(self)->acquire(); 33 | } 34 | mword OwnerLock_release(WOwnerLock* self){ 35 | return reinterpret_cast(self)->release(); 36 | } 37 | void ConditionVariable_wait(WConditionVariable* self, WMutex* mutex){ 38 | reinterpret_cast(self)->wait(reinterpret_cast(mutex)); 39 | } 40 | void ConditionVariable_signal(WConditionVariable* self, WMutex* mutex){ 41 | reinterpret_cast(self)->signal(reinterpret_cast(mutex)); 42 | } 43 | void ConditionVariable_signalAll(WConditionVariable* self, WMutex* mutex){ 44 | reinterpret_cast(self)->signalAll(reinterpret_cast(mutex)); 45 | } 46 | _Bool ConditionVariable_empty(WConditionVariable* self){ 47 | return reinterpret_cast(self)->empty(); 48 | } 49 | void ConditionVariable_destroy(WConditionVariable* self){ 50 | delete reinterpret_cast(self); 51 | } 52 | WConditionVariable* ConditionVariable_create(){ 53 | return reinterpret_cast( new ConditionVariable()); 54 | } 55 | WSemaphore* Semaphore_create(mword c){ 56 | return reinterpret_cast( new Semaphore(c)); 57 | } 58 | _Bool Semaphore_P(WSemaphore* self){ 59 | return reinterpret_cast(self)->P(); 60 | } 61 | void Semaphore_V(WSemaphore* self){ 62 | reinterpret_cast(self)->V(); 63 | } 64 | void Semaphore_destroy(WSemaphore* self){ 65 | delete reinterpret_cast(self); 66 | } 67 | WuThread* uThread_create(WuThread* self, size_t ss, _Bool joinable){ 68 | return reinterpret_cast(uThread::create(ss, joinable)); 69 | } 70 | WuThread* uThread_create_1(WuThread* self, _Bool joinable){ 71 | return reinterpret_cast(uThread::create(joinable)); 72 | } 73 | void uThread_start(WuThread* self, WCluster* cluster, ptr_t func, ptr_t arg1, ptr_t arg2, ptr_t arg3){ 74 | reinterpret_cast(self)->start(reinterpret_cast(cluster), func, arg1, arg2, arg3); 75 | } 76 | void uThread_yield(WuThread* self){ 77 | uThread::yield(); 78 | } 79 | void uThread_terminate(WuThread* self){ 80 | uThread::terminate(); 81 | } 82 | void uThread_migrate(WuThread* self, WCluster* ){ 83 | uThread::migrate(reinterpret_cast()); 84 | } 85 | void uThread_resume(WuThread* self){ 86 | reinterpret_cast(self)->resume(); 87 | } 88 | _Bool uThread_join(WuThread* self){ 89 | return reinterpret_cast(self)->join(); 90 | } 91 | void uThread_detach(WuThread* self){ 92 | reinterpret_cast(self)->detach(); 93 | } 94 | WCluster* uThread_getCurrentCluster(WuThread* self){ 95 | return reinterpret_cast(reinterpret_cast(self)->getCurrentCluster()); 96 | } 97 | uint64_t uThread_getTotalNumberofUTs(WuThread* self){ 98 | return uThread::getTotalNumberofUTs(); 99 | } 100 | uint64_t uThread_getID(WuThread* self){ 101 | return reinterpret_cast(self)->getID(); 102 | } 103 | WuThread* uThread_currentUThread(WuThread* self){ 104 | return reinterpret_cast(uThread::currentUThread()); 105 | } 106 | void uThread_destroy(WuThread* self){ 107 | delete reinterpret_cast(self); 108 | } 109 | WCluster* Cluster_create(){ 110 | return reinterpret_cast( new Cluster()); 111 | } 112 | void Cluster_destroy(WCluster* self){ 113 | delete reinterpret_cast(self); 114 | } 115 | WCluster* Cluster_getDefaultCluster(WCluster* self){ 116 | return reinterpret_cast(Cluster::getDefaultCluster()); 117 | } 118 | uint64_t Cluster_getID(WCluster* self){ 119 | return reinterpret_cast(self)->getID(); 120 | } 121 | size_t Cluster_getNumberOfkThreads(WCluster* self){ 122 | return reinterpret_cast(self)->getNumberOfkThreads(); 123 | } 124 | WkThread* kThread_create(WCluster* ){ 125 | return reinterpret_cast( new kThread(reinterpret_cast())); 126 | } 127 | void kThread_destroy(WkThread* self){ 128 | delete reinterpret_cast(self); 129 | } 130 | std::class thread::native_handle_type kThread_getThreadNativeHandle(WkThread* self){ 131 | return reinterpret_cast(self)->getThreadNativeHandle(); 132 | } 133 | Wid* kThread_getID(WkThread* self){ 134 | return &reinterpret_cast(reinterpret_cast(self)->getID()); 135 | } 136 | WkThread* kThread_currentkThread(WkThread* self){ 137 | return reinterpret_cast(kThread::currentkThread()); 138 | } 139 | uint kThread_getTotalNumberOfkThreads(WkThread* self){ 140 | return kThread::getTotalNumberOfkThreads(); 141 | } 142 | WConnection* Connection_create(){ 143 | return reinterpret_cast( new Connection()); 144 | } 145 | WConnection* Connection_create_1(int fd){ 146 | return reinterpret_cast( new Connection(fd)); 147 | } 148 | WConnection* Connection_create_2(int domainint typeint protocol){ 149 | return reinterpret_cast( new Connection(domaintypeprotocol)); 150 | } 151 | void Connection_destroy(WConnection* self){ 152 | delete reinterpret_cast(self); 153 | } 154 | int Connection_accept(WConnection* self, WConnection* conn, sockaddr* addr, socklen_t * addrlen){ 155 | return reinterpret_cast(self)->accept(reinterpret_cast(conn), addr, addrlen); 156 | } 157 | WConnection* Connection_accept(WConnection* self, sockaddr* addr, socklen_t * addrlen){ 158 | return reinterpret_cast(reinterpret_cast(self)->accept(addr, addrlen)); 159 | } 160 | int Connection_socket(WConnection* self, int domain, int type, int protocol){ 161 | return reinterpret_cast(self)->socket(domain, type, protocol); 162 | } 163 | int Connection_listen(WConnection* self, int backlog){ 164 | return reinterpret_cast(self)->listen(backlog); 165 | } 166 | int Connection_bind(WConnection* self, sockaddr* addr, socklen_t addrlen){ 167 | return reinterpret_cast(self)->bind(addr, addrlen); 168 | } 169 | int Connection_connect(WConnection* self, sockaddr* addr, socklen_t addrlen){ 170 | return reinterpret_cast(self)->connect(addr, addrlen); 171 | } 172 | ssize_t Connection_recv(WConnection* self, void * buf, size_t len, int flags){ 173 | return reinterpret_cast(self)->recv(buf, len, flags); 174 | } 175 | ssize_t Connection_recvfrom(WConnection* self, void * buf, size_t len, int flags, sockaddr* src_addr, socklen_t * addrlen){ 176 | return reinterpret_cast(self)->recvfrom(buf, len, flags, src_addr, addrlen); 177 | } 178 | ssize_t Connection_recvmsg(WConnection* self, int sockfd, msghdr* msg, int flags){ 179 | return reinterpret_cast(self)->recvmsg(sockfd, msg, flags); 180 | } 181 | int Connection_recvmmsg(WConnection* self, int sockfd, mmsghdr* msgvec, unsigned int vlen, unsigned int flags, timespec* timeout){ 182 | return reinterpret_cast(self)->recvmmsg(sockfd, msgvec, vlen, flags, timeout); 183 | } 184 | ssize_t Connection_send(WConnection* self, const void * buf, size_t len, int flags){ 185 | return reinterpret_cast(self)->send(buf, len, flags); 186 | } 187 | ssize_t Connection_sendto(WConnection* self, int sockfd, const void * buf, size_t len, int flags, sockaddr* dest_addr, socklen_t addrlen){ 188 | return reinterpret_cast(self)->sendto(sockfd, buf, len, flags, dest_addr, addrlen); 189 | } 190 | ssize_t Connection_sendmsg(WConnection* self, msghdr* msg, int flags){ 191 | return reinterpret_cast(self)->sendmsg(msg, flags); 192 | } 193 | int Connection_sendmmsg(WConnection* self, int sockfd, mmsghdr* msgvec, unsigned int vlen, unsigned int flags){ 194 | return reinterpret_cast(self)->sendmmsg(sockfd, msgvec, vlen, flags); 195 | } 196 | ssize_t Connection_read(WConnection* self, void * buf, size_t count){ 197 | return reinterpret_cast(self)->read(buf, count); 198 | } 199 | ssize_t Connection_write(WConnection* self, const void * buf, size_t count){ 200 | return reinterpret_cast(self)->write(buf, count); 201 | } 202 | void Connection_blockOnRead(WConnection* self){ 203 | reinterpret_cast(self)->blockOnRead(); 204 | } 205 | void Connection_blockOnWrite(WConnection* self){ 206 | reinterpret_cast(self)->blockOnWrite(); 207 | } 208 | int Connection_close(WConnection* self){ 209 | return reinterpret_cast(self)->close(); 210 | } 211 | int Connection_getFd(WConnection* self){ 212 | return reinterpret_cast(self)->getFd(); 213 | } 214 | #ifdef __cplusplus 215 | } 216 | #endif 217 | 218 | -------------------------------------------------------------------------------- /output/cwrapper.h: -------------------------------------------------------------------------------- 1 | #ifndef UTHREADS_CWRAPPER_H 2 | #define UTHREADS_CWRAPPER_H_ 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #ifdef __cplusplus 9 | extern "C"{ 10 | #endif 11 | #include 12 | struct WuThread; 13 | typedef struct WuThread WuThread; 14 | struct WkThread; 15 | typedef struct WkThread WkThread; 16 | struct WCluster; 17 | typedef struct WCluster WCluster; 18 | struct WConnection; 19 | typedef struct WConnection WConnection; 20 | struct WMutex; 21 | typedef struct WMutex WMutex; 22 | struct WOwnerLock; 23 | typedef struct WOwnerLock WOwnerLock; 24 | struct WConditionVariable; 25 | typedef struct WConditionVariable WConditionVariable; 26 | struct WSemaphore; 27 | typedef struct WSemaphore WSemaphore; 28 | struct WuThreadPool; 29 | typedef struct WuThreadPool WuThreadPool; 30 | WMutex* Mutex_create(); 31 | _Bool Mutex_acquire(WMutex* self); 32 | _Bool Mutex_acquire_1(WMutex* self); 33 | void Mutex_release(WMutex* self); 34 | void Mutex_unlock(WMutex* self); 35 | void Mutex_destroy(WMutex* self); 36 | WOwnerLock* OwnerLock_create(); 37 | mword OwnerLock_acquire(WOwnerLock* self); 38 | mword OwnerLock_release(WOwnerLock* self); 39 | void ConditionVariable_wait(WConditionVariable* self, WMutex* mutex); 40 | void ConditionVariable_signal(WConditionVariable* self, WMutex* mutex); 41 | void ConditionVariable_signalAll(WConditionVariable* self, WMutex* mutex); 42 | _Bool ConditionVariable_empty(WConditionVariable* self); 43 | void ConditionVariable_destroy(WConditionVariable* self); 44 | WConditionVariable* ConditionVariable_create(); 45 | WSemaphore* Semaphore_create(mword c); 46 | _Bool Semaphore_P(WSemaphore* self); 47 | void Semaphore_V(WSemaphore* self); 48 | void Semaphore_destroy(WSemaphore* self); 49 | WuThread* uThread_create(WuThread* self, size_t ss, _Bool joinable); 50 | WuThread* uThread_create_1(WuThread* self, _Bool joinable); 51 | void uThread_start(WuThread* self, WCluster* cluster, ptr_t func, ptr_t arg1, ptr_t arg2, ptr_t arg3); 52 | void uThread_yield(WuThread* self); 53 | void uThread_terminate(WuThread* self); 54 | void uThread_migrate(WuThread* self, WCluster* ); 55 | void uThread_resume(WuThread* self); 56 | _Bool uThread_join(WuThread* self); 57 | void uThread_detach(WuThread* self); 58 | WCluster* uThread_getCurrentCluster(WuThread* self); 59 | uint64_t uThread_getTotalNumberofUTs(WuThread* self); 60 | uint64_t uThread_getID(WuThread* self); 61 | WuThread* uThread_currentUThread(WuThread* self); 62 | void uThread_destroy(WuThread* self); 63 | WCluster* Cluster_create(); 64 | void Cluster_destroy(WCluster* self); 65 | WCluster* Cluster_getDefaultCluster(WCluster* self); 66 | uint64_t Cluster_getID(WCluster* self); 67 | size_t Cluster_getNumberOfkThreads(WCluster* self); 68 | WkThread* kThread_create(WCluster* ); 69 | void kThread_destroy(WkThread* self); 70 | std::class thread::native_handle_type kThread_getThreadNativeHandle(WkThread* self); 71 | Wid* kThread_getID(WkThread* self); 72 | WkThread* kThread_currentkThread(WkThread* self); 73 | uint kThread_getTotalNumberOfkThreads(WkThread* self); 74 | WConnection* Connection_create(); 75 | WConnection* Connection_create_1(int fd); 76 | WConnection* Connection_create_2(int domainint typeint protocol); 77 | void Connection_destroy(WConnection* self); 78 | int Connection_accept(WConnection* self, WConnection* conn, sockaddr* addr, socklen_t * addrlen); 79 | WConnection* Connection_accept(WConnection* self, sockaddr* addr, socklen_t * addrlen); 80 | int Connection_socket(WConnection* self, int domain, int type, int protocol); 81 | int Connection_listen(WConnection* self, int backlog); 82 | int Connection_bind(WConnection* self, sockaddr* addr, socklen_t addrlen); 83 | int Connection_connect(WConnection* self, sockaddr* addr, socklen_t addrlen); 84 | ssize_t Connection_recv(WConnection* self, void * buf, size_t len, int flags); 85 | ssize_t Connection_recvfrom(WConnection* self, void * buf, size_t len, int flags, sockaddr* src_addr, socklen_t * addrlen); 86 | ssize_t Connection_recvmsg(WConnection* self, int sockfd, msghdr* msg, int flags); 87 | int Connection_recvmmsg(WConnection* self, int sockfd, mmsghdr* msgvec, unsigned int vlen, unsigned int flags, timespec* timeout); 88 | ssize_t Connection_send(WConnection* self, const void * buf, size_t len, int flags); 89 | ssize_t Connection_sendto(WConnection* self, int sockfd, const void * buf, size_t len, int flags, sockaddr* dest_addr, socklen_t addrlen); 90 | ssize_t Connection_sendmsg(WConnection* self, msghdr* msg, int flags); 91 | int Connection_sendmmsg(WConnection* self, int sockfd, mmsghdr* msgvec, unsigned int vlen, unsigned int flags); 92 | ssize_t Connection_read(WConnection* self, void * buf, size_t count); 93 | ssize_t Connection_write(WConnection* self, const void * buf, size_t count); 94 | void Connection_blockOnRead(WConnection* self); 95 | void Connection_blockOnWrite(WConnection* self); 96 | int Connection_close(WConnection* self); 97 | int Connection_getFd(WConnection* self); 98 | #ifdef __cplusplus 99 | } 100 | #endif 101 | #endif /* UTHREADS_CWRAPPER_H_ */ 102 | 103 | --------------------------------------------------------------------------------