├── CHANGELOG.md ├── LICENSE ├── README.md ├── bin ├── argv-parser.js └── global.js ├── examples ├── a file you can compile with config.js ├── a file you can compile.js ├── a file you cannot compile.js ├── configuration.json └── included file.js ├── index.js ├── lib ├── README.md ├── compiler.js └── src │ ├── compiler.js │ ├── directives │ ├── condition.js │ ├── define.js │ ├── directives.js │ ├── extra.js │ └── include.js │ ├── main.js │ ├── parse-next-line.js │ ├── processor.js │ ├── string-helper.js │ └── system │ ├── comments.js │ ├── conditions.js │ ├── constants.js │ ├── defines.js │ ├── macros.js │ └── stack.js ├── package.json └── test ├── all.js ├── factory.js ├── ressources ├── file-to-include-once.js └── file-to-include.js ├── tests ├── comments.js ├── define-macro.js ├── define-var.js ├── enum.js ├── error.js ├── if.js ├── ifdef.js ├── include.js ├── pragma.js ├── push-pop-macro.js └── undef.js └── utils.js /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## Version 0.2.13 (15/11/2019) 2 | 3 | - Fix issue: multiple occurrences of a macro on the same line 4 | - Fix issue: macro with no arguments 5 | 6 | 7 | ## Version 0.2.12 (29/01/2017) 8 | 9 | - Add `#pragma push_macro(..)` command (thanks to @zohl) 10 | - Add `#pragma pop_macro(..)` command (thanks to @zohl) 11 | - Fix issue: comment in `#define` directive (thanks to @zohl) 12 | - Add `-v` and `--version` to show the version in the CLI 13 | 14 | 15 | ## Version 0.2.11 (29/01/2017) 16 | 17 | - Add `-c` and `--config` to specify a configuration file in the CLI (thanks to @zohl) 18 | - Add `-h` and `--help` to show the usage in the CLI (thanks to @zohl) 19 | 20 | 21 | ## Version 0.2.10 (05/01/2017) 22 | 23 | - Add `__LINE__` and `__FILE__` 24 | - Rename `options.endLine` to `options.newLine` 25 | - Make optional the second argument of the CLI 26 | - Tidy a bit the source code 27 | - Fix issue: replace line endings from CRLF to LF for macOS 28 | - Fix issue: directives with a whitespace between # and their name 29 | 30 | 31 | ## Version 0.2.9 (17/12/2016) 32 | 33 | - Update README.md 34 | - Add `__TIME__` and `__DATE__` constants 35 | - Add `#error` directive 36 | - Clean unit tests 37 | 38 | 39 | ## Version 0.2.8 (08/12/2016) 40 | 41 | - Make **C-Preprocessor** a bit faster for parsing lines 42 | - Add `options.constants` for adding predefined constants 43 | - Add `options.macros` for adding predefined macros 44 | - Fix issue: macros with another macro with several parameters 45 | 46 | 47 | ## Version 0.2.7 (19/08/2016) 48 | 49 | - Fix issue: multiple calls of success event 50 | - Fix issue: the last line of the file wasn't parsed 51 | - Set `options.includeSpaces` to `0` by default 52 | - Fix CLI command 53 | 54 | 55 | ## Version 0.2.5 (18/08/2016) 56 | 57 | - Complete rewriting of Compile-Js-like-C 58 | - Rename **Compile-Js-like-C** to **C-Preprocessor** 59 | - Add `#if` command 60 | - Add `#pragma once` command 61 | - Add unit tests (run `npm test`) 62 | 63 | 64 | ## Version 0.1.2 (07/01/2016) 65 | 66 | - Fix end of lines 67 | - Fix macros and constants system 68 | 69 | 70 | ## Version 0.1.1 (07/06/2015) 71 | 72 | - Clean a bit the code by separating in several files 73 | 74 | 75 | ## Version 0.0.7 (11/03/2015) 76 | 77 | - Add CLI command 78 | - Add `examples` folder 79 | 80 | 81 | ## Version 0.0.5 (10/03/2015) 82 | 83 | - Update README.md and add usage 84 | 85 | 86 | ## Version 0.0.2 (10/03/2015) 87 | 88 | - Initial release -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | C Preprocessor 2 | =============== 3 | 4 | C Preprocessor is a preprocessor created with Node.js only and 5 | running like a C preprocessor with **#** directives. 6 | It was originally designed for Javascript but you can use it 7 | with any language you want. 8 | See changelog [here](../master/CHANGELOG.md). 9 | 10 | 11 | ## Installation 12 | 13 | For local installation, run the following command: 14 | ``` 15 | npm install c-preprocessor --save 16 | ``` 17 | 18 | For global installation, run the following command: 19 | ``` 20 | npm install -g c-preprocessor 21 | ``` 22 | 23 | 24 | ## Compile a file/text 25 | 26 | #### In command line 27 | If you have installed this package in global, you can run **c-preprocessor** and pass your main file and output file in arguments. 28 | ``` 29 | c-preprocessor mainFile.js outputFile.js 30 | ``` 31 | 32 | Additionally you can specify a configuration file (see below for it's format): 33 | ``` 34 | c-preprocessor --config configFile.js mainFile.js outputFile.js 35 | ``` 36 | 37 | #### With require() 38 | ```js 39 | var compiler = require("c-preprocessor"); 40 | 41 | 42 | // To compile a file 43 | compiler.compileFile(fileName, [ options, ] function(err, result) { 44 | 45 | if (err) 46 | return console.log(err); 47 | 48 | console.log(result); 49 | }); 50 | 51 | 52 | // To compile a text 53 | compiler.compile(code, [ options, ] function(err, result) { 54 | // ... 55 | }); 56 | 57 | 58 | // Or use Compiler class 59 | var c = new compiler.Compiler([options]); 60 | c.on('success', /* ... */) 61 | c.on('error', /* ... */) 62 | 63 | c.compile(code); 64 | // or 65 | c.compileFile(fileName); 66 | ``` 67 | 68 | 69 | 70 | 71 | ## Customize options 72 | This are the defaults options. You can modify them by passing an option object. 73 | ```js 74 | var options = { 75 | 76 | // Predefined constants (ex: { "MY_CONST": "42" }) 77 | constants: {}, 78 | 79 | // Predefined macros (ex: { "MACRO": "(a,b) a+b" }) 80 | macros: {}, 81 | 82 | // End of line character 83 | newLine: '\n', 84 | 85 | // Escape '//#' & '/*#' comments (see extra/comments) 86 | commentEscape: true, 87 | 88 | // Empty lines to add between code and included files 89 | includeSpaces: 0, 90 | 91 | // Limit of empty following lines (0 = no limit) 92 | emptyLinesLimit: 0, 93 | 94 | // Base path for including files 95 | basePath: './', 96 | 97 | // Stop the compiler when an error ocurred ? 98 | stopOnError: true, 99 | 100 | // Must constants in #enum directive be in hexadecimal ? 101 | enumInHex: true 102 | }; 103 | ``` 104 | 105 | 106 | 107 | 108 | ## Usage 109 | 110 | ### Like a C preprocessor 111 | 112 | ##### Include 113 | ```c 114 | #include "file.js" 115 | ``` 116 | Include and parse a file. 117 | 118 | 119 | ##### Define 120 | ```c 121 | // Define a constant 122 | #define MY_CONST 42 123 | 124 | // Define a macro 125 | #define SUM(a,b) a + b 126 | ``` 127 | Create a constant or a macro. 128 | 129 | 130 | ##### Undefine 131 | ```c 132 | #undef MY_CONST 133 | ``` 134 | Delete a constant or a macro. 135 | 136 | 137 | ##### Condition 138 | ```c 139 | #if A + B == 5 && defined(MY_CONST) 140 | // Do stuff 141 | #elif "MY_CONST2" == "House" 142 | // Do other stuff 143 | #else 144 | // Do other stuff 145 | #endif 146 | 147 | #ifndef MY_CONST3 148 | // Do stuff 149 | #endif 150 | ``` 151 | C like conditions. 152 | `#if` condition is evaluated in JS so you must add **"** between string 153 | constants. 154 | Note: `#ifdef C` and `#ifndef C` are faster than `#if defined(C)` and `#if !defined(C)`. 155 | 156 | 157 | ##### Pragma once 158 | ```c 159 | #pragma once 160 | ``` 161 | Include the current file once. 162 | 163 | 164 | ##### Error 165 | ```c 166 | #error This is an error 167 | ``` 168 | Stop the compiler and log the message given after the directive. 169 | 170 | 171 | 172 | ### Extra 173 | 174 | ##### Compiler constants 175 | ```c 176 | __TIME__ // Current time 177 | __DATE__ // Current date 178 | __LINE__ // Current line (where this constant is used). 179 | __FILE__ // Current file (where this constant is used). 180 | ``` 181 | This constants are predefined by the compiler. 182 | 183 | 184 | ##### Comments 185 | ```c 186 | //# One line comment 187 | 188 | /*# 189 | 190 | Multi-lines comment 191 | 192 | #*/ 193 | ``` 194 | This comments will be deleted in the compiled file. 195 | Note: `options.commentEscape` must be `true`. 196 | 197 | 198 | ##### Enumeration 199 | ```c 200 | // Here A=0, ..., D=3 201 | #enum 202 | A, B, C, D 203 | #endenum 204 | 205 | // With options, so Car=5, .., Truck=25 206 | #enum start=5, step=10 207 | Car, Bike, Truck 208 | #endenum 209 | ``` 210 | C like enumeration. 211 | You can use this directive for creating a lot of constants. 212 | -------------------------------------------------------------------------------- /bin/argv-parser.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | A simple argv parser 4 | 5 | 6 | © 2017 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | 14 | // List of short/long name commands 15 | var short = {}; 16 | var long = {}; 17 | 18 | 19 | // Remaning parameters 20 | exports.argv = []; 21 | 22 | 23 | 24 | // On error callback 25 | exports.error = null; 26 | 27 | // Emit an error 28 | function error(msg) { 29 | if (exports.error) 30 | exports.error(msg); 31 | else 32 | console.log('Error: ' + msg); 33 | } 34 | 35 | 36 | 37 | 38 | // Current length & position 39 | var count = 0; 40 | var n = 0; 41 | 42 | // Get the next argument 43 | function next() { 44 | return process.argv[n++]; 45 | } 46 | 47 | 48 | 49 | 50 | // Add a new commands 51 | exports.add = function add(name, longName, length, callback) { 52 | 53 | var obj = { 54 | length: length, 55 | callback: callback 56 | }; 57 | 58 | short[name] = obj; 59 | long[longName] = obj; 60 | }; 61 | 62 | 63 | 64 | 65 | // Call a command 66 | function call(name, isLong) { 67 | 68 | var obj = isLong ? long[name] : short[name]; 69 | if (!obj) 70 | return error(`Unknown argument '${name}'`); 71 | 72 | if (n + obj.length > count) 73 | return error(`Too few arguments after '${name}'`); 74 | 75 | var arr = process.argv.slice(n, n + obj.length); 76 | n += obj.length; 77 | 78 | obj.callback(arr); 79 | }; 80 | 81 | 82 | 83 | 84 | 85 | // Start parsing argv 86 | exports.parse = function() { 87 | 88 | count = process.argv.length; 89 | n = 2; 90 | 91 | var s; 92 | while ((s = next()) != undefined) { 93 | 94 | if (s.startsWith('--')) 95 | call(s.substr(2), true); 96 | 97 | else if (s.startsWith('-')) 98 | call(s.substr(1), false); 99 | 100 | else 101 | exports.argv.push(s); 102 | } 103 | }; 104 | -------------------------------------------------------------------------------- /bin/global.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /* 4 | 5 | C Preprocessor, CLI 6 | 7 | 8 | © 2017 - 9 | Guillaume Gonnet 10 | Al Zohali 11 | 12 | License GPLv2 13 | 14 | Sources at https://github.com/ParksProjets/C-Preprocessor 15 | 16 | */ 17 | 18 | 19 | // Libraries 20 | var fs = require('fs'), 21 | path = require('path'), 22 | compiler = require('../index.js'), 23 | argv = require('./argv-parser.js'); 24 | 25 | 26 | 27 | // Start time 28 | var startTime = Date.now(); 29 | 30 | 31 | // Local options 32 | var options; 33 | var inputFile; 34 | var outputFile; 35 | 36 | 37 | 38 | // Show an error 39 | function error(msg, addHint) { 40 | console.log('\x1b[31m'); 41 | console.log('The compiler has stopped on an error') 42 | console.log(`\x1b[1;31mError: ${msg}\x1b[0m`); 43 | 44 | if (addHint) 45 | console.log(`\nPlease use -h to show the usage`); 46 | 47 | process.exit(1); 48 | } 49 | 50 | 51 | // Argv parser error 52 | argv.error = function(msg) { 53 | error(msg, true); 54 | }; 55 | 56 | 57 | 58 | 59 | // Help argument 60 | argv.add('h', 'help', 0, function help() { 61 | console.log('\n Usage: c-preprocessor [options] input-file [output-file]'); 62 | console.log('\n Options:'); 63 | console.log('\n -c, --config configuration file'); 64 | 65 | process.exit(1); 66 | }); 67 | 68 | 69 | 70 | // Version argument 71 | argv.add('v', 'version', 0, function version() { 72 | var json = require('../package.json'); 73 | console.log('\n C-Preprocessor version: ' + json.version); 74 | process.exit(1); 75 | }); 76 | 77 | 78 | 79 | 80 | // Configuration file 81 | argv.add('c', 'config', 1, function(arr) { 82 | try { 83 | options = JSON.parse(fs.readFileSync(arr[0], 'utf8')); 84 | } catch(e) { 85 | error("Can't read configuration file"); 86 | } 87 | }); 88 | 89 | 90 | 91 | 92 | // Start parsing argv 93 | argv.parse(); 94 | 95 | // Input & output files 96 | inputFile = argv.argv[0]; 97 | outputFile = argv.argv[1]; 98 | 99 | 100 | // If the input file is not specified 101 | if (inputFile === undefined) 102 | error("input file are required", true); 103 | 104 | 105 | // If the output file is not specified 106 | if (outputFile === undefined) { 107 | var parsed = path.parse(inputFile), 108 | dir = parsed.dir ? parsed.dir+'/' : '', 109 | name = parsed.name, 110 | ext = parsed.ext; 111 | 112 | outputFile = dir + name + '-built' + ext; 113 | } 114 | 115 | 116 | 117 | 118 | 119 | 120 | // Preprocess input file 121 | var c = new compiler.Compiler(options); 122 | 123 | c.on('error', function(err) { 124 | return error(err); 125 | }); 126 | 127 | c.on('success', function(code) { 128 | fs.writeFile(outputFile, code, function(err) { 129 | 130 | if (err) 131 | return error(`Unable to write the output file "${outputFile}"`); 132 | 133 | 134 | // Display the time spent 135 | console.log('\x1b[1;32m'); 136 | console.log(`Done in ${(Date.now() - startTime) / 1000}s\x1b[0m`); 137 | }); 138 | }); 139 | 140 | c.compileFile(inputFile); 141 | -------------------------------------------------------------------------------- /examples/a file you can compile with config.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | This file works only when compiled with the config file (./configuration.json) 4 | 5 | 6 | Sources at https://github.com/ParksProjets/C-Preprocessor 7 | License GPLv2 8 | 9 | */ 10 | 11 | 12 | #include "included file.js" 13 | 14 | 15 | var x = SUM(MY_CONST, 8); 16 | 17 | #ifdef OK 18 | 19 | if (x === 50) { 20 | console.log('It works !'); 21 | } 22 | 23 | #endif 24 | 25 | 26 | console.log(x); 27 | -------------------------------------------------------------------------------- /examples/a file you can compile.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | This file can be compiled without errors 4 | 5 | 6 | Sources at https://github.com/ParksProjets/C-Preprocessor 7 | License GPLv2 8 | 9 | */ 10 | 11 | 12 | #include "included file.js" 13 | 14 | #define ADD_2(v) v+2 15 | 16 | 17 | #ifdef OK 18 | 19 | console.log('It works !'); 20 | 21 | #endif 22 | 23 | 24 | console.log(ADD_2(PI)); 25 | -------------------------------------------------------------------------------- /examples/a file you cannot compile.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | This file cannot be compiled and produces an error 4 | 5 | 6 | Sources at https://github.com/ParksProjets/C-Preprocessor 7 | License GPLv2 8 | 9 | */ 10 | 11 | 12 | #include "no file.js" 13 | 14 | #define ADD_2(v) v+2 15 | 16 | 17 | #ifdef OK 18 | 19 | console.log('It doesn\'t work !'); 20 | 21 | #endif 22 | 23 | 24 | console.log(ADD_2(PI, 3)); 25 | 26 | 27 | console.log(':('); 28 | -------------------------------------------------------------------------------- /examples/configuration.json: -------------------------------------------------------------------------------- 1 | { 2 | "constants": { 3 | "MY_CONST": "42" 4 | }, 5 | "macros": { 6 | "SUM": "(a,b) a+b" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /examples/included file.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | File included 4 | 5 | 6 | Sources at https://github.com/ParksProjets/C-Preprocessor 7 | License GPLv2 8 | 9 | #*/ 10 | 11 | 12 | #define PI 3.1415926 13 | 14 | #define OK 15 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | C Preprocessor 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/Compile-JS-like-C 10 | 11 | */ 12 | 13 | 14 | // Get the lib object 15 | var lib = require('./lib/compiler.js'); 16 | 17 | 18 | // Export Compiler class 19 | exports.Compiler = lib.Compiler; 20 | 21 | 22 | 23 | // Quick access: compile a code 24 | exports.compile = function(code, options, callback) { 25 | 26 | // If there isn't an option but a callback 27 | if (typeof options == "function") { 28 | callback = options; 29 | options = null; 30 | } 31 | 32 | 33 | // Create the compiler and attach it the callback 34 | var compiler = new lib.Compiler(options); 35 | 36 | compiler.once('error', function(msg) { 37 | callback && callback(msg, null); 38 | }); 39 | 40 | compiler.once('success', function(result) { 41 | callback && callback(null, result); 42 | }); 43 | 44 | compiler.compile(code); 45 | }; 46 | 47 | 48 | 49 | 50 | 51 | // Quick access: compile a file 52 | exports.compileFile = function(file, options, callback) { 53 | 54 | // If there isn't an option but a callback 55 | if (typeof options == "function") { 56 | callback = options; 57 | options = null; 58 | } 59 | 60 | 61 | // Create the compiler and attach it the callback 62 | var compiler = new lib.Compiler(options); 63 | 64 | compiler.once('error', function(msg) { 65 | callback && callback(msg, null); 66 | }); 67 | 68 | compiler.once('success', function(result) { 69 | callback && callback(null, result); 70 | }); 71 | 72 | compiler.compileFile(file); 73 | }; 74 | -------------------------------------------------------------------------------- /lib/README.md: -------------------------------------------------------------------------------- 1 | ## Sources 2 | 3 | Compile the sources with this command: 4 | ``` 5 | c-preprocessor "src/main.js" "compiler.js" 6 | ``` -------------------------------------------------------------------------------- /lib/compiler.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | C Preprocessor 4 | 5 | 6 | © 2017 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | 14 | // Libraries 15 | var EventEmitter = require('events'), 16 | fs = require("fs"), 17 | path = require("path"); 18 | 19 | 20 | 21 | // Return the last character of the string 22 | String.prototype.last = function() { 23 | return this.slice(-1); 24 | }; 25 | 26 | 27 | 28 | // Remove and add some text in the same time 29 | String.prototype.splice = function(idx, rem, s) { 30 | return (this.slice(0,idx) + s + this.slice(idx + rem)); 31 | }; 32 | 33 | 34 | 35 | // Get the next "..." string 36 | String.prototype.getNextString = function() { 37 | var str = this.match(/^"([A-Za-z0-9\-_\. \/\\]+)"/); 38 | return (!str || !str[1]) ? '' : str[1]; 39 | }; 40 | 41 | 42 | 43 | 44 | // Test if a character is alpha numeric or _ 45 | var StringArray = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"; 46 | 47 | String.prototype.isAlpha = function(i) { 48 | return StringArray.indexOf(this[i]) != -1; 49 | }; 50 | var Compiler = function(opt) { 51 | 52 | // Inherit of EventEmitter 53 | EventEmitter.call(this); 54 | 55 | 56 | // Options object 57 | this.options = {}; 58 | this.options.newLine = '\n'; 59 | this.options.commentEscape = true; 60 | this.options.includeSpaces = 0; 61 | this.options.emptyLinesLimit = 0; 62 | this.options.basePath = './'; 63 | this.options.stopOnError = true; 64 | this.options.enumInHex = true; 65 | 66 | // Apply options 67 | opt = opt || {}; 68 | for (var i in opt) 69 | this.options[i] = opt[i]; 70 | 71 | 72 | // List of defined macros/constants 73 | this.defines = {}; 74 | 75 | // Stack for macros/constants 76 | this.stack = {}; 77 | 78 | // List of #pragma once 79 | this.includeOnce = {}; 80 | 81 | 82 | // Global constants 83 | var date = new Date(); 84 | this._compConst('TIME', date.toLocaleTimeString()); 85 | this._compConst('DATE', date.toLocaleDateString()); 86 | this._compConst('LINE', '0'); 87 | this._compConst('FILE', 'main'); 88 | 89 | 90 | // User defined constants 91 | var c = opt.constants || {}; 92 | for (var i in c) 93 | this.createConstant(i, c[i].toString(), false); 94 | 95 | // User defined macros 96 | var m = opt.macros || {}; 97 | for (var i in m) 98 | this.createMacro(i, m[i]); 99 | }; 100 | 101 | 102 | 103 | // Inherit of EventEmitter, constructor and exports 104 | Compiler.prototype = Object.create(EventEmitter.prototype); 105 | Compiler.prototype.constructor = Compiler; 106 | exports.Compiler = Compiler; 107 | 108 | 109 | 110 | 111 | // Compile a text code 112 | Compiler.prototype.compile = function(code, filename) { 113 | if (filename) 114 | this.options.filename = filename; 115 | 116 | var processor = new Processor(this, code); 117 | processor.run(); 118 | }; 119 | 120 | 121 | 122 | 123 | 124 | // Compile a file 125 | Compiler.prototype.compileFile = function(file) { 126 | var _this = this; 127 | 128 | fs.readFile(_this.options.basePath + file, 'utf8', function(err, code) { 129 | 130 | if (err) 131 | return _this._error(`can't read file "${file}"`); 132 | 133 | _this.options.filename = file; 134 | 135 | var processor = new Processor(_this, code); 136 | processor.run(); 137 | }); 138 | }; 139 | 140 | 141 | 142 | 143 | 144 | // Emit an error 145 | Compiler.prototype._error = function(text) { 146 | this.emit('error', text); 147 | }; 148 | 149 | 150 | // Emit a success 151 | Compiler.prototype._success = function(code) { 152 | this.emit('success', code); 153 | }; 154 | var Processor = function(parent, code) { 155 | 156 | // Parent compiler 157 | this.parent = parent; 158 | this.options = parent.options; 159 | 160 | 161 | // List of defined macros/constants & stack 162 | this.defines = parent.defines; 163 | this.stack = parent.stack; 164 | 165 | // Is the processor running ? 166 | this.running = false; 167 | 168 | 169 | // Code & result text 170 | this.code = code; 171 | this.result = ''; 172 | 173 | // Number of empty lines 174 | this.emptyLines = 0; 175 | 176 | // Current line & file 177 | this.currentLine = 0; 178 | this.currentFile = this.options.filename || 'main'; 179 | this._compConst('FILE', this.currentFile); 180 | 181 | // Current path 182 | var p = path.dirname(this.currentFile); 183 | this.path = (p == '.') ? '' : p + '/'; 184 | 185 | 186 | // Bind some functions 187 | this.parseNext = this.parseNext.bind(this); 188 | this.next = this.next.bind(this); 189 | }; 190 | 191 | 192 | 193 | // Constructor 194 | Processor.prototype.constructor = Processor; 195 | 196 | 197 | 198 | 199 | // Run the processor 200 | Processor.prototype.run = function() { 201 | var _this = this; 202 | 203 | // Set the processor as running 204 | this.running = true; 205 | 206 | 207 | // Get an array of all lines 208 | var lines = this.code.split(/\r?\n/); 209 | this.linesCount = lines.length; 210 | 211 | // Return the next line 212 | function nextLine() { 213 | _this._compConst('LINE', _this.currentLine+1); 214 | return lines[_this.currentLine++]; 215 | } 216 | 217 | this.nextLine = nextLine; 218 | 219 | 220 | // Parse the first line 221 | this.next(); 222 | }; 223 | 224 | 225 | 226 | 227 | // Parse the next lines (doing it synchronously until an asynchronous command) 228 | Processor.prototype.next = function() { 229 | 230 | var running = true; 231 | while (this.running && running && this.currentLine < this.linesCount) 232 | running = (this.parseNext() !== false); 233 | 234 | if (this.running && running && this.currentLine >= this.linesCount) 235 | this.success(); 236 | }; 237 | 238 | 239 | 240 | 241 | // Append a line to the result 242 | Processor.prototype.addLine = function(line) { 243 | this.result += line + this.options.newLine; 244 | this.emptyLines = 0; 245 | }; 246 | 247 | 248 | 249 | 250 | 251 | 252 | // Emit an error 253 | Processor.prototype.error = function(msg) { 254 | if (this.options.stopOnError) 255 | this.running = false; 256 | 257 | msg = `(line ${this.currentLine} in "${this.currentFile}") ${msg}`; 258 | this.parent._error(msg); 259 | 260 | return !this.options.stopOnError; 261 | }; 262 | 263 | 264 | 265 | // Emit the success 266 | Processor.prototype.success = function() { 267 | this.running = false; 268 | 269 | if (this.onsuccess) 270 | this.onsuccess(); 271 | else 272 | this.parent._success(this.result); 273 | }; 274 | Processor.prototype.parseNext = function() { 275 | 276 | // No more line to parse: stop this function 277 | if (this.currentLine >= this.linesCount) 278 | return; 279 | 280 | 281 | // Get the next line text 282 | var line = this.nextLine(), 283 | text = line.trimLeft(); 284 | 285 | 286 | // If the line is empty: apply empty lines limit option 287 | if (text.length == 0) { 288 | if (this.options.emptyLinesLimit && this.emptyLines >= this.options.emptyLinesLimit) 289 | return; 290 | 291 | this.emptyLines++; 292 | return this.addLine(line); 293 | } 294 | 295 | 296 | // If the line starts with a # comment: delete it 297 | if (this.options.commentEscape && text.startsWith("//#")) 298 | return; 299 | 300 | if (this.options.commentEscape && text.startsWith("/*#")) 301 | return this.commentEnd(); 302 | 303 | 304 | 305 | // If the line doesn't start with # 306 | if (text[0] != '#') 307 | return this.addLine(this.addDefines(line)); 308 | 309 | 310 | // Get the # directive and the remaing text 311 | var i = text.indexOf(' '), name; 312 | 313 | if (i != -1) { 314 | name = text.substr(1, i - 1); 315 | text = text.substr(i + 1); 316 | } else { 317 | name = text.substr(1); 318 | } 319 | 320 | 321 | 322 | // Get the # directive 323 | var cmd = Directives[name.trimLeft()]; 324 | 325 | // If the command exists: call the corresponding function 326 | if (cmd) 327 | return cmd.call(this, text); 328 | 329 | 330 | // Else: remove the line if 'commentEscape' is enabled 331 | if (!this.options.commentEscape) 332 | this.addLine(this.addDefines(line)); 333 | }; 334 | // Add defined objects to a line 335 | Processor.prototype.addDefines = 336 | Compiler.prototype.addDefines = function(line, withConst, withMacros) { 337 | 338 | // Local variables 339 | var i1 = -1, i2; 340 | var d, r; 341 | 342 | 343 | // Check if the constant is present in the line 344 | for (var i in this.defines) { 345 | 346 | d = this.defines[i]; 347 | 348 | if (d.count !== undefined && withMacros === false) 349 | continue; 350 | if (d.count == undefined && withConst === false) 351 | continue; 352 | 353 | i2 = i.length; 354 | i1 = -1; 355 | 356 | // It can have the same constant more than one time 357 | for (;;) { 358 | 359 | // Get the position of the constant (-1 if not present) 360 | i1 = line.indexOf(i, i1 + 1); 361 | if (i1 == -1) 362 | break; 363 | 364 | // Check that the constant isn't in a middle of a word and add the constant if not 365 | if (line.isAlpha(i1 - 1) || line.isAlpha(i1 + i2)) 366 | continue; 367 | 368 | // Add the macro or the constant 369 | if (d.count !== undefined) 370 | r = this.addMacro(line, i1, d); 371 | else 372 | r = this.addConstant(line, i1, d); 373 | 374 | line = r.line; 375 | i1 = r.index; 376 | } 377 | } 378 | 379 | return line; 380 | }; 381 | 382 | 383 | 384 | 385 | 386 | // Create a constant 387 | Processor.prototype.createConstant = 388 | Compiler.prototype.createConstant = function(name, value, addDefines) { 389 | 390 | // Add constants value to the constant value 391 | if (addDefines !== false) 392 | value = this.addDefines(value); 393 | 394 | // Store the constant 395 | this.defines[name] = { 396 | name: name, 397 | value: value 398 | }; 399 | }; 400 | 401 | 402 | 403 | 404 | 405 | // Set a compiler constant 406 | Processor.prototype._compConst = 407 | Compiler.prototype._compConst = function(name, value) { 408 | this.createConstant('__' + name + '__', value, false); 409 | }; 410 | 411 | 412 | 413 | 414 | 415 | // Add a constant in a line 416 | Processor.prototype.addConstant = 417 | Compiler.prototype.addConstant = function(line, i, constant) { 418 | 419 | line = line.splice(i, constant.name.length, constant.value); 420 | i += constant.value.length; 421 | 422 | return { line: line, index: i }; 423 | }; 424 | // Create a macro (text must have the macro arguments, like this: '(a,b) a+b') 425 | Processor.prototype.createMacro = 426 | Compiler.prototype.createMacro = function(name, text) { 427 | 428 | // First, get macro arguments 429 | var args = []; 430 | 431 | var end = text.indexOf(")"), 432 | i1 = 1, 433 | i2 = 0; 434 | 435 | 436 | // If there is no closing parenthesis 437 | if (end == -1) 438 | return this.error(`no closing parenthesis in the #define of marcro ${name}`); 439 | 440 | 441 | // Get arguments 442 | while( (i2 = text.indexOf(",", i2 + 1)) != -1 && i2 < end) { 443 | args.push(text.substring(i1, i2).trim()); 444 | i1 = i2 + 1; 445 | } 446 | 447 | if (end > i1) // If there is at least one argument. 448 | args.push(text.substring(i1, end)); 449 | 450 | 451 | // Remove arguments in the text 452 | text = text.substr(end + 1).trimLeft(); 453 | 454 | // Execute defined macros 455 | text = this.addDefines(text, false, true); 456 | 457 | 458 | // Secondly, makes breaks and store variables positions 459 | var breaks = []; 460 | 461 | for (var i = 0, l = args.length, p; i < l; i++) { 462 | 463 | i1 = -1; 464 | p = args[i]; 465 | i2 = p.length; 466 | 467 | for(;;) { 468 | i1 = text.indexOf(p, i1+1); 469 | if (i1 == -1) 470 | break; 471 | 472 | if (text.isAlpha(i1-1) || text.isAlpha(i1+i2)) 473 | continue; 474 | 475 | breaks.push([ i1, i, i2 ]); 476 | } 477 | } 478 | 479 | 480 | // Sort variables in order of their positions in the macro text 481 | breaks.sort(function(a, b) { 482 | return a[0] - b[0] 483 | }); 484 | 485 | 486 | 487 | // Thirdly, cut the text into parts without variable and add defined constants 488 | var offset = 0, 489 | content = [], 490 | pos = []; 491 | i = 0; 492 | 493 | for (; i < breaks.length; i++) { 494 | content[i] = this.addDefines(text.slice(offset, breaks[i][0]), true, false); 495 | offset = breaks[i][0] + breaks[i][2]; 496 | pos[i] = breaks[i][1]; 497 | } 498 | 499 | content[i] = this.addDefines(text.slice(offset)); 500 | 501 | 502 | 503 | // Fourthly, store the macro 504 | this.defines[name] = { 505 | content: content, 506 | count: args.length, 507 | pos: pos, 508 | name: name 509 | }; 510 | }; 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | // Read a line and transform macro by adding their value 520 | Processor.prototype.addMacro = 521 | Compiler.prototype.addMacro = function(line, i, macro) { 522 | 523 | // Local variables 524 | var m = 0, 525 | e = i + macro.name.length, 526 | s = e, 527 | l = 0, 528 | args = []; 529 | 530 | 531 | // Get arguments between parenthesis (by counting parenthesis) 532 | for (var v, l = line.length; e < l; e++) { 533 | 534 | v = line[e]; 535 | 536 | if (v == "(") { 537 | m++; 538 | if (m == 1) 539 | s = e + 1; 540 | } 541 | 542 | else if (v == "," && m == 1) { 543 | args.push(line.slice(s, e)); 544 | s = e + 1; 545 | } 546 | 547 | else if (v == ")") { 548 | if (m == 1) 549 | break; 550 | m--; 551 | } 552 | 553 | else if (v != ' ' && m == 0) { 554 | return this.error(`there is no openning parenthesis for macro ${macro.name}`); 555 | } 556 | } 557 | 558 | 559 | // If the closing parenthesis is missing 560 | if (m != 1) 561 | return this.error(`the closing parenthesis is missing for macro ${macro.name}`); 562 | 563 | // Add the last argument. 564 | var lastarg = line.slice(s, e); 565 | if (lastarg.trim()) 566 | args.push(lastarg); 567 | 568 | 569 | // Check if there is the right number of arguments 570 | if (args.length > macro.count) 571 | return this.error(`too many arguments for macro ${macro.name}`); 572 | 573 | if (args.length < macro.count) 574 | return this.error(`too few arguments for macro ${macro.name}`); 575 | 576 | 577 | // Execute 'addDefines' on each argument 578 | for (var j = 0; j < macro.count; j++) 579 | args[j] = this.addDefines(args[j]); 580 | 581 | 582 | // Replace macro variables with the given arguments 583 | var str = macro.content[0]; 584 | 585 | for (s = 0, l = macro.pos.length; s < l; s++) 586 | str += args[ macro.pos[s] ] + macro.content[s+1]; 587 | 588 | 589 | // Add the result into the line 590 | line = line.splice(i, e - i + 1, str); 591 | i += str.length; 592 | 593 | return { line: line, index: i }; 594 | }; 595 | // Save the current value of a macro on top of the stack 596 | Processor.prototype.pushMacro = function(name) { 597 | 598 | if (this.defines[name] === undefined) 599 | return this.error(`macro ${name} is not defined, cannot push it`); 600 | 601 | 602 | if (this.stack[name] === undefined) 603 | this.stack[name] = []; 604 | 605 | this.stack[name].push(this.defines[name]); 606 | }; 607 | 608 | 609 | 610 | 611 | // Set current value of the specified macro to previously saved value 612 | Processor.prototype.popMacro = function(name) { 613 | 614 | if (this.stack[name] === undefined || this.stack[name].length == 0) 615 | return this.error(`stack for macro ${name} is empty, cannot pop from it`); 616 | 617 | 618 | this.defines[name] = this.stack[name].pop(); 619 | }; 620 | // Go to the next #elif, #else or #endif 621 | Processor.prototype.conditionNext = function(end) { 622 | 623 | // #if directives to start a condition 624 | var ifCmd = ['if', 'ifdef', 'ifndef']; 625 | 626 | // #else directives 627 | var elseCmd = ['elif', 'else']; 628 | 629 | 630 | // Local variables 631 | var line, s, n = 1; 632 | 633 | 634 | // Count unexploited conditions 635 | while (this.currentLine < this.linesCount) { 636 | 637 | line = this.nextLine().trimLeft(); 638 | if (line[0] != '#') 639 | continue; 640 | 641 | s = line.substr(1).trimLeft().split(' ')[0]; 642 | 643 | if (ifCmd.indexOf(s) != -1) 644 | n++; 645 | 646 | else if (!end && n == 1 && elseCmd.indexOf(s) != -1) 647 | return this.callCondition(line); 648 | 649 | else if (s == "endif") { 650 | n--; 651 | if (n == 0) 652 | return; 653 | } 654 | } 655 | }; 656 | 657 | 658 | 659 | 660 | 661 | // Call a #else or #elif condition 662 | Processor.prototype.callCondition = function(text) { 663 | 664 | // Get the directive name 665 | var split = text.substr(1).trimLeft().split(' '), 666 | name = split[0]; 667 | 668 | // Get the remaining text (without the # directive) 669 | split.shift(); 670 | text = split.join(' ').trimLeft(); 671 | 672 | 673 | // Call the corresponding directive 674 | Directives[name].call(this, text, true); 675 | }; 676 | 677 | 678 | 679 | 680 | 681 | // Go to the end of the condtion (#endif) 682 | Processor.prototype.conditionEnd = function() { 683 | this.conditionNext(true); 684 | }; 685 | // Go to the end of a multilines comment 686 | Processor.prototype.commentEnd = function() { 687 | 688 | this.currentLine--; 689 | var line, i; 690 | 691 | // Find the end of the comment 692 | while (this.currentLine < this.linesCount) { 693 | line = this.nextLine(); 694 | 695 | if (line.indexOf("*/") != -1) 696 | break; 697 | } 698 | }; 699 | // List of all directives 700 | var Directives = {}; 701 | 702 | 703 | 704 | // Create a directive 705 | function createDirective(name, fn) { 706 | Directives[name] = fn; 707 | } 708 | 709 | 710 | 711 | createDirective("include", function(text) { 712 | var _this = this; 713 | 714 | // Get the name of the file to include 715 | var name = text.getNextString(); 716 | if (!name) 717 | return this.error('invalid include'); 718 | 719 | 720 | // File to read 721 | var file = this.path + name; 722 | 723 | // If the file is already included and #pragma once 724 | if (this.parent.includeOnce[file]) 725 | return; 726 | 727 | 728 | // Read the file asynchronously and parse it 729 | fs.readFile(this.options.basePath + file, 'utf8', function(err, code) { 730 | 731 | if (err) 732 | return _this.error(`can't read file "${file}"`); 733 | 734 | _this.options.filename = file; 735 | var processor = new Processor(_this.parent, code); 736 | 737 | // On success: add the file content to the result 738 | processor.onsuccess = function() { 739 | processor.onsuccess = null; 740 | 741 | var e = ''; 742 | for (var i = 0, l = _this.options.includeSpaces; i < l; i++) 743 | e += _this.options.newLine; 744 | 745 | _this.addLine(e + processor.result.trim() + e); 746 | 747 | _this._compConst('FILE', _this.currentFile); 748 | _this.next(); 749 | }; 750 | 751 | processor.run(); 752 | }); 753 | 754 | 755 | // Block the synchronous loop 756 | return false; 757 | }); 758 | // #define directive 759 | createDirective("define", function(text) { 760 | 761 | // Get the constant/macro name 762 | var i = 0; 763 | while (text.isAlpha(i)) 764 | i++; 765 | 766 | var name = text.substr(0, i), 767 | isMacro = text[i] == '('; 768 | 769 | text = text.substr(name.length).trimLeft(); 770 | 771 | 772 | // Read a multilines constants/macro if there is an '\' at the end of the line 773 | var str = text.trimRight(); 774 | text = ''; 775 | 776 | while (str.last() == "\\") { 777 | text += str.substr(0, str.length - 1) + this.options.newLine; 778 | str = this.nextLine().trimRight(); 779 | } 780 | 781 | text += str; 782 | 783 | 784 | // Strip comments from the definition 785 | var posBegin; 786 | var posEnd; 787 | 788 | while ((posBegin = text.indexOf('/*')) != -1) { 789 | posEnd = text.indexOf('*/', 1 + posBegin); 790 | if (posEnd == -1) 791 | posEnd = text.length; 792 | 793 | text = text.substring(0, posBegin) + ' ' + text.substring(2 + posEnd); 794 | } 795 | 796 | if ((posBegin = text.indexOf('//')) != -1) 797 | text = text.substring(0, posBegin) + ' '; 798 | 799 | text.trimRight(); 800 | 801 | 802 | // If there is an '(' after the name: define a macro 803 | if (isMacro) 804 | this.createMacro(name, text); 805 | 806 | // Else: create a constant 807 | else 808 | this.createConstant(name, text); 809 | }); 810 | 811 | 812 | 813 | 814 | 815 | // #undef directive 816 | createDirective("undef", function(text) { 817 | 818 | // Get the constant/macro name 819 | var i = 0; 820 | while (text.isAlpha(i)) 821 | i++; 822 | 823 | var name = text.substr(0, i); 824 | 825 | 826 | // Delete the constant/macro 827 | delete this.defines[name]; 828 | }); 829 | // #if directive 830 | // See README to know how to use this directive 831 | createDirective("if", function(expr) { 832 | // Exectute 'defined' function 833 | var i, i2, name; 834 | var _this = this; 835 | 836 | expr = expr.replace(/defined\s*\(\s*([\s\S]+?)\s*\)/g, function(match, p1){ 837 | return _this.defines[p1] === undefined ? 'false' : 'true'; 838 | }); 839 | 840 | // Replace constants by their values 841 | expr = this.addDefines(expr); 842 | 843 | 844 | // Evaluate the expression 845 | try { 846 | var r = eval(expr); 847 | } catch(e) { 848 | return this.error('error when evaluating #if expression'); 849 | } 850 | 851 | 852 | // If the expr is 'false', go to the next #elif, #else or #endif 853 | if (!r) 854 | this.conditionNext(); 855 | }); 856 | 857 | 858 | 859 | 860 | 861 | // #ifdef directive (note: '#ifdef VARIABLE' is faster than '#if defined(VARIABLE)') 862 | createDirective("ifdef", function(text) { 863 | 864 | // Get the constant/macro name 865 | var name = text.split(' ')[0]; 866 | 867 | // Check if the constant/macro exists 868 | if (this.defines[name] === undefined) 869 | this.conditionNext(); 870 | }); 871 | 872 | 873 | 874 | 875 | 876 | // #ifndef directive (note: '#ifndef VARIABLE' is faster than '#if !defined(VARIABLE)') 877 | createDirective("ifndef", function(text) { 878 | 879 | // Get the constant/macro name 880 | var name = text.split(' ')[0]; 881 | 882 | // Check if the constant/macro doesn't exist 883 | if (this.defines[name] !== undefined) 884 | this.conditionNext(); 885 | }); 886 | 887 | 888 | 889 | 890 | 891 | 892 | 893 | 894 | // #elif directive 895 | createDirective("elif", function(expr, called) { 896 | 897 | // If this directive wasn't callaed by 'this.callCondition' 898 | if (!called) 899 | return this.conditionEnd(); 900 | 901 | // Else: execute this directive as an #if directive 902 | Directives.if.call(this, expr); 903 | }); 904 | 905 | 906 | 907 | 908 | // #else directive 909 | createDirective("else", function(expr, called) { 910 | 911 | // If this directive wasn't called by 'this.callCondition' 912 | if (!called) 913 | return this.conditionEnd(); 914 | 915 | // Else: nothing to compute, parse the next line 916 | }); 917 | 918 | 919 | 920 | 921 | 922 | 923 | 924 | // #endif directive 925 | createDirective("endif", function(expr, called) { 926 | // Do nothing beacause this directive is already evaluated by 'this.conditionNext' 927 | }); 928 | // #pragma directive 929 | createDirective("pragma", function(text) { 930 | 931 | text = text.trim(); 932 | 933 | 934 | // #pragma once: include a file once 935 | if (text == 'once') 936 | this.parent.includeOnce[this.currentFile] = true; 937 | 938 | 939 | // #pragma push_macro(...): save value of a macro on top of the stack 940 | else if (text.startsWith('push_macro')) { 941 | 942 | var match = text.match(/push_macro\("([^"]+)"\)/); 943 | 944 | if (match === null || match[1].length == 0) 945 | this.error(`wrong pragma format`); 946 | else 947 | this.pushMacro(match[1]); 948 | } 949 | 950 | 951 | // #pragma pop_macro(...): set value of the a macro to saved value 952 | else if (text.startsWith('pop_macro')) { 953 | 954 | var match = text.match(/pop_macro\("([^"]+)"\)/); 955 | 956 | if (match === null || match[1].length == 0) 957 | this.error(`wrong pragma format`); 958 | else 959 | this.popMacro(match[1]); 960 | } 961 | 962 | 963 | // Else: error 964 | else 965 | this.error(`unknown pragma "${text}"`); 966 | }); 967 | 968 | 969 | 970 | 971 | 972 | // #error directive 973 | createDirective("error", function(text) { 974 | this.error(text.trim()); 975 | }); 976 | 977 | 978 | 979 | 980 | 981 | 982 | // #enum directive: c like enumeration 983 | createDirective("enum", function(text) { 984 | 985 | // Get the enum options 986 | text = text.replace(/=/g, ':'); 987 | 988 | try { 989 | eval(`var opt = { ${text} }`); 990 | } catch(e) { 991 | var opt = {}; 992 | } 993 | 994 | 995 | // Default options 996 | opt.start = opt.start || 0; 997 | opt.step = opt.step || 1; 998 | 999 | 1000 | // Get all names of constants to create 1001 | var line, str = ''; 1002 | 1003 | while (this.currentLine < this.linesCount) { 1004 | line = this.nextLine(); 1005 | if (line.trimLeft().startsWith("#endenum")) 1006 | break; 1007 | 1008 | str += line; 1009 | } 1010 | 1011 | 1012 | // Create an array of constant names 1013 | var split = str.split(','), 1014 | name, v; 1015 | 1016 | // Create the constants and add their value 1017 | for (var i = 0, l = split.length; i < l; i++) { 1018 | 1019 | name = split[i].trim(); 1020 | v = opt.start + i * opt.step; 1021 | 1022 | this.defines[name] = { 1023 | value: this.options.enumInHex ? '0x'+v.toString(16) : v.toString(), 1024 | name: name 1025 | }; 1026 | } 1027 | }); 1028 | 1029 | 1030 | 1031 | // #endenum directive 1032 | createDirective("endenum", function() { 1033 | // Do nothing beacause this directive is already evaluated by #enum 1034 | }); 1035 | 1036 | -------------------------------------------------------------------------------- /lib/src/compiler.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | Compiler class 4 | 5 | 6 | © 2017 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | #*/ 12 | 13 | 14 | var Compiler = function(opt) { 15 | 16 | // Inherit of EventEmitter 17 | EventEmitter.call(this); 18 | 19 | 20 | // Options object 21 | this.options = {}; 22 | this.options.newLine = '\n'; 23 | this.options.commentEscape = true; 24 | this.options.includeSpaces = 0; 25 | this.options.emptyLinesLimit = 0; 26 | this.options.basePath = './'; 27 | this.options.stopOnError = true; 28 | this.options.enumInHex = true; 29 | 30 | // Apply options 31 | opt = opt || {}; 32 | for (var i in opt) 33 | this.options[i] = opt[i]; 34 | 35 | 36 | // List of defined macros/constants 37 | this.defines = {}; 38 | 39 | // Stack for macros/constants 40 | this.stack = {}; 41 | 42 | // List of #pragma once 43 | this.includeOnce = {}; 44 | 45 | 46 | // Global constants 47 | var date = new Date(); 48 | this._compConst('TIME', date.toLocaleTimeString()); 49 | this._compConst('DATE', date.toLocaleDateString()); 50 | this._compConst('LINE', '0'); 51 | this._compConst('FILE', 'main'); 52 | 53 | 54 | // User defined constants 55 | var c = opt.constants || {}; 56 | for (var i in c) 57 | this.createConstant(i, c[i].toString(), false); 58 | 59 | // User defined macros 60 | var m = opt.macros || {}; 61 | for (var i in m) 62 | this.createMacro(i, m[i]); 63 | }; 64 | 65 | 66 | 67 | // Inherit of EventEmitter, constructor and exports 68 | Compiler.prototype = Object.create(EventEmitter.prototype); 69 | Compiler.prototype.constructor = Compiler; 70 | exports.Compiler = Compiler; 71 | 72 | 73 | 74 | 75 | // Compile a text code 76 | Compiler.prototype.compile = function(code, filename) { 77 | if (filename) 78 | this.options.filename = filename; 79 | 80 | var processor = new Processor(this, code); 81 | processor.run(); 82 | }; 83 | 84 | 85 | 86 | 87 | 88 | // Compile a file 89 | Compiler.prototype.compileFile = function(file) { 90 | var _this = this; 91 | 92 | fs.readFile(_this.options.basePath + file, 'utf8', function(err, code) { 93 | 94 | if (err) 95 | return _this._error(`can't read file "${file}"`); 96 | 97 | _this.options.filename = file; 98 | 99 | var processor = new Processor(_this, code); 100 | processor.run(); 101 | }); 102 | }; 103 | 104 | 105 | 106 | 107 | 108 | // Emit an error 109 | Compiler.prototype._error = function(text) { 110 | this.emit('error', text); 111 | }; 112 | 113 | 114 | // Emit a success 115 | Compiler.prototype._success = function(code) { 116 | this.emit('success', code); 117 | }; 118 | -------------------------------------------------------------------------------- /lib/src/directives/condition.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | #if, #ifdef, #ifndef, #elif, #else, #endif directives 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | #*/ 12 | 13 | 14 | // #if directive 15 | // See README to know how to use this directive 16 | createDirective("if", function(expr) { 17 | // Exectute 'defined' function 18 | var i, i2, name; 19 | var _this = this; 20 | 21 | expr = expr.replace(/defined\s*\(\s*([\s\S]+?)\s*\)/g, function(match, p1){ 22 | return _this.defines[p1] === undefined ? 'false' : 'true'; 23 | }); 24 | 25 | // Replace constants by their values 26 | expr = this.addDefines(expr); 27 | 28 | 29 | // Evaluate the expression 30 | try { 31 | var r = eval(expr); 32 | } catch(e) { 33 | return this.error('error when evaluating #if expression'); 34 | } 35 | 36 | 37 | // If the expr is 'false', go to the next #elif, #else or #endif 38 | if (!r) 39 | this.conditionNext(); 40 | }); 41 | 42 | 43 | 44 | 45 | 46 | // #ifdef directive (note: '#ifdef VARIABLE' is faster than '#if defined(VARIABLE)') 47 | createDirective("ifdef", function(text) { 48 | 49 | // Get the constant/macro name 50 | var name = text.split(' ')[0]; 51 | 52 | // Check if the constant/macro exists 53 | if (this.defines[name] === undefined) 54 | this.conditionNext(); 55 | }); 56 | 57 | 58 | 59 | 60 | 61 | // #ifndef directive (note: '#ifndef VARIABLE' is faster than '#if !defined(VARIABLE)') 62 | createDirective("ifndef", function(text) { 63 | 64 | // Get the constant/macro name 65 | var name = text.split(' ')[0]; 66 | 67 | // Check if the constant/macro doesn't exist 68 | if (this.defines[name] !== undefined) 69 | this.conditionNext(); 70 | }); 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | // #elif directive 80 | createDirective("elif", function(expr, called) { 81 | 82 | // If this directive wasn't callaed by 'this.callCondition' 83 | if (!called) 84 | return this.conditionEnd(); 85 | 86 | // Else: execute this directive as an #if directive 87 | Directives.if.call(this, expr); 88 | }); 89 | 90 | 91 | 92 | 93 | // #else directive 94 | createDirective("else", function(expr, called) { 95 | 96 | // If this directive wasn't called by 'this.callCondition' 97 | if (!called) 98 | return this.conditionEnd(); 99 | 100 | // Else: nothing to compute, parse the next line 101 | }); 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | // #endif directive 110 | createDirective("endif", function(expr, called) { 111 | // Do nothing beacause this directive is already evaluated by 'this.conditionNext' 112 | }); 113 | -------------------------------------------------------------------------------- /lib/src/directives/define.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | #define and #undef directives 4 | 5 | 6 | © 2017 - 7 | Guillaume Gonnet 8 | Al Zohali 9 | 10 | License GPLv2 11 | 12 | Sources at https://github.com/ParksProjets/C-Preprocessor 13 | 14 | #*/ 15 | 16 | 17 | // #define directive 18 | createDirective("define", function(text) { 19 | 20 | // Get the constant/macro name 21 | var i = 0; 22 | while (text.isAlpha(i)) 23 | i++; 24 | 25 | var name = text.substr(0, i), 26 | isMacro = text[i] == '('; 27 | 28 | text = text.substr(name.length).trimLeft(); 29 | 30 | 31 | // Read a multilines constants/macro if there is an '\' at the end of the line 32 | var str = text.trimRight(); 33 | text = ''; 34 | 35 | while (str.last() == "\\") { 36 | text += str.substr(0, str.length - 1) + this.options.newLine; 37 | str = this.nextLine().trimRight(); 38 | } 39 | 40 | text += str; 41 | 42 | 43 | // Strip comments from the definition 44 | var posBegin; 45 | var posEnd; 46 | 47 | while ((posBegin = text.indexOf('/*')) != -1) { 48 | posEnd = text.indexOf('*/', 1 + posBegin); 49 | if (posEnd == -1) 50 | posEnd = text.length; 51 | 52 | text = text.substring(0, posBegin) + ' ' + text.substring(2 + posEnd); 53 | } 54 | 55 | if ((posBegin = text.indexOf('//')) != -1) 56 | text = text.substring(0, posBegin) + ' '; 57 | 58 | text.trimRight(); 59 | 60 | 61 | // If there is an '(' after the name: define a macro 62 | if (isMacro) 63 | this.createMacro(name, text); 64 | 65 | // Else: create a constant 66 | else 67 | this.createConstant(name, text); 68 | }); 69 | 70 | 71 | 72 | 73 | 74 | // #undef directive 75 | createDirective("undef", function(text) { 76 | 77 | // Get the constant/macro name 78 | var i = 0; 79 | while (text.isAlpha(i)) 80 | i++; 81 | 82 | var name = text.substr(0, i); 83 | 84 | 85 | // Delete the constant/macro 86 | delete this.defines[name]; 87 | }); 88 | -------------------------------------------------------------------------------- /lib/src/directives/directives.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | Manage the # directives 4 | 5 | 6 | © 2017 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | #*/ 12 | 13 | 14 | // List of all directives 15 | var Directives = {}; 16 | 17 | 18 | 19 | // Create a directive 20 | function createDirective(name, fn) { 21 | Directives[name] = fn; 22 | } 23 | 24 | 25 | 26 | //# Include all directives 27 | #include "include.js" 28 | #include "define.js" 29 | #include "condition.js" 30 | #include "extra.js" 31 | -------------------------------------------------------------------------------- /lib/src/directives/extra.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | #pragma, #error and #enum directives 4 | 5 | 6 | © 2017 - 7 | Guillaume Gonnet 8 | Al Zohali 9 | 10 | License GPLv2 11 | 12 | Sources at https://github.com/ParksProjets/C-Preprocessor 13 | 14 | #*/ 15 | 16 | 17 | // #pragma directive 18 | createDirective("pragma", function(text) { 19 | 20 | text = text.trim(); 21 | 22 | 23 | // #pragma once: include a file once 24 | if (text == 'once') 25 | this.parent.includeOnce[this.currentFile] = true; 26 | 27 | 28 | // #pragma push_macro(...): save value of a macro on top of the stack 29 | else if (text.startsWith('push_macro')) { 30 | 31 | var match = text.match(/push_macro\("([^"]+)"\)/); 32 | 33 | if (match === null || match[1].length == 0) 34 | this.error(`wrong pragma format`); 35 | else 36 | this.pushMacro(match[1]); 37 | } 38 | 39 | 40 | // #pragma pop_macro(...): set value of the a macro to saved value 41 | else if (text.startsWith('pop_macro')) { 42 | 43 | var match = text.match(/pop_macro\("([^"]+)"\)/); 44 | 45 | if (match === null || match[1].length == 0) 46 | this.error(`wrong pragma format`); 47 | else 48 | this.popMacro(match[1]); 49 | } 50 | 51 | 52 | // Else: error 53 | else 54 | this.error(`unknown pragma "${text}"`); 55 | }); 56 | 57 | 58 | 59 | 60 | 61 | // #error directive 62 | createDirective("error", function(text) { 63 | this.error(text.trim()); 64 | }); 65 | 66 | 67 | 68 | 69 | 70 | 71 | // #enum directive: c like enumeration 72 | createDirective("enum", function(text) { 73 | 74 | // Get the enum options 75 | text = text.replace(/=/g, ':'); 76 | 77 | try { 78 | eval(`var opt = { ${text} }`); 79 | } catch(e) { 80 | var opt = {}; 81 | } 82 | 83 | 84 | // Default options 85 | opt.start = opt.start || 0; 86 | opt.step = opt.step || 1; 87 | 88 | 89 | // Get all names of constants to create 90 | var line, str = ''; 91 | 92 | while (this.currentLine < this.linesCount) { 93 | line = this.nextLine(); 94 | if (line.trimLeft().startsWith("#endenum")) 95 | break; 96 | 97 | str += line; 98 | } 99 | 100 | 101 | // Create an array of constant names 102 | var split = str.split(','), 103 | name, v; 104 | 105 | // Create the constants and add their value 106 | for (var i = 0, l = split.length; i < l; i++) { 107 | 108 | name = split[i].trim(); 109 | v = opt.start + i * opt.step; 110 | 111 | this.defines[name] = { 112 | value: this.options.enumInHex ? '0x'+v.toString(16) : v.toString(), 113 | name: name 114 | }; 115 | } 116 | }); 117 | 118 | 119 | 120 | // #endenum directive 121 | createDirective("endenum", function() { 122 | // Do nothing beacause this directive is already evaluated by #enum 123 | }); 124 | -------------------------------------------------------------------------------- /lib/src/directives/include.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | #include directive 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | #*/ 12 | 13 | 14 | createDirective("include", function(text) { 15 | var _this = this; 16 | 17 | // Get the name of the file to include 18 | var name = text.getNextString(); 19 | if (!name) 20 | return this.error('invalid include'); 21 | 22 | 23 | // File to read 24 | var file = this.path + name; 25 | 26 | // If the file is already included and #pragma once 27 | if (this.parent.includeOnce[file]) 28 | return; 29 | 30 | 31 | // Read the file asynchronously and parse it 32 | fs.readFile(this.options.basePath + file, 'utf8', function(err, code) { 33 | 34 | if (err) 35 | return _this.error(`can't read file "${file}"`); 36 | 37 | _this.options.filename = file; 38 | var processor = new Processor(_this.parent, code); 39 | 40 | // On success: add the file content to the result 41 | processor.onsuccess = function() { 42 | processor.onsuccess = null; 43 | 44 | var e = ''; 45 | for (var i = 0, l = _this.options.includeSpaces; i < l; i++) 46 | e += _this.options.newLine; 47 | 48 | _this.addLine(e + processor.result.trim() + e); 49 | 50 | _this._compConst('FILE', _this.currentFile); 51 | _this.next(); 52 | }; 53 | 54 | processor.run(); 55 | }); 56 | 57 | 58 | // Block the synchronous loop 59 | return false; 60 | }); 61 | -------------------------------------------------------------------------------- /lib/src/main.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | C Preprocessor 4 | 5 | 6 | © 2017 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | 14 | // Libraries 15 | var EventEmitter = require('events'), 16 | fs = require("fs"), 17 | path = require("path"); 18 | 19 | 20 | 21 | //# Includes all js files 22 | #include "string-helper.js" 23 | #include "compiler.js" 24 | #include "processor.js" 25 | #include "parse-next-line.js" 26 | #include "system/defines.js" 27 | #include "system/stack.js" 28 | #include "system/conditions.js" 29 | #include "system/comments.js" 30 | #include "directives/directives.js" 31 | -------------------------------------------------------------------------------- /lib/src/parse-next-line.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | Parse the next line 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | #*/ 12 | 13 | 14 | Processor.prototype.parseNext = function() { 15 | 16 | // No more line to parse: stop this function 17 | if (this.currentLine >= this.linesCount) 18 | return; 19 | 20 | 21 | // Get the next line text 22 | var line = this.nextLine(), 23 | text = line.trimLeft(); 24 | 25 | 26 | // If the line is empty: apply empty lines limit option 27 | if (text.length == 0) { 28 | if (this.options.emptyLinesLimit && this.emptyLines >= this.options.emptyLinesLimit) 29 | return; 30 | 31 | this.emptyLines++; 32 | return this.addLine(line); 33 | } 34 | 35 | 36 | // If the line starts with a # comment: delete it 37 | if (this.options.commentEscape && text.startsWith("//#")) 38 | return; 39 | 40 | if (this.options.commentEscape && text.startsWith("/*#")) 41 | return this.commentEnd(); 42 | 43 | 44 | 45 | // If the line doesn't start with # 46 | if (text[0] != '#') 47 | return this.addLine(this.addDefines(line)); 48 | 49 | 50 | // Get the # directive and the remaing text 51 | var i = text.indexOf(' '), name; 52 | 53 | if (i != -1) { 54 | name = text.substr(1, i - 1); 55 | text = text.substr(i + 1); 56 | } else { 57 | name = text.substr(1); 58 | } 59 | 60 | 61 | 62 | // Get the # directive 63 | var cmd = Directives[name.trimLeft()]; 64 | 65 | // If the command exists: call the corresponding function 66 | if (cmd) 67 | return cmd.call(this, text); 68 | 69 | 70 | // Else: remove the line if 'commentEscape' is enabled 71 | if (!this.options.commentEscape) 72 | this.addLine(this.addDefines(line)); 73 | }; 74 | -------------------------------------------------------------------------------- /lib/src/processor.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | Processor class 4 | 5 | 6 | © 2017 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | #*/ 12 | 13 | 14 | var Processor = function(parent, code) { 15 | 16 | // Parent compiler 17 | this.parent = parent; 18 | this.options = parent.options; 19 | 20 | 21 | // List of defined macros/constants & stack 22 | this.defines = parent.defines; 23 | this.stack = parent.stack; 24 | 25 | // Is the processor running ? 26 | this.running = false; 27 | 28 | 29 | // Code & result text 30 | this.code = code; 31 | this.result = ''; 32 | 33 | // Number of empty lines 34 | this.emptyLines = 0; 35 | 36 | // Current line & file 37 | this.currentLine = 0; 38 | this.currentFile = this.options.filename || 'main'; 39 | this._compConst('FILE', this.currentFile); 40 | 41 | // Current path 42 | var p = path.dirname(this.currentFile); 43 | this.path = (p == '.') ? '' : p + '/'; 44 | 45 | 46 | // Bind some functions 47 | this.parseNext = this.parseNext.bind(this); 48 | this.next = this.next.bind(this); 49 | }; 50 | 51 | 52 | 53 | // Constructor 54 | Processor.prototype.constructor = Processor; 55 | 56 | 57 | 58 | 59 | // Run the processor 60 | Processor.prototype.run = function() { 61 | var _this = this; 62 | 63 | // Set the processor as running 64 | this.running = true; 65 | 66 | 67 | // Get an array of all lines 68 | var lines = this.code.split(/\r?\n/); 69 | this.linesCount = lines.length; 70 | 71 | // Return the next line 72 | function nextLine() { 73 | _this._compConst('LINE', _this.currentLine+1); 74 | return lines[_this.currentLine++]; 75 | } 76 | 77 | this.nextLine = nextLine; 78 | 79 | 80 | // Parse the first line 81 | this.next(); 82 | }; 83 | 84 | 85 | 86 | 87 | // Parse the next lines (doing it synchronously until an asynchronous command) 88 | Processor.prototype.next = function() { 89 | 90 | var running = true; 91 | while (this.running && running && this.currentLine < this.linesCount) 92 | running = (this.parseNext() !== false); 93 | 94 | if (this.running && running && this.currentLine >= this.linesCount) 95 | this.success(); 96 | }; 97 | 98 | 99 | 100 | 101 | // Append a line to the result 102 | Processor.prototype.addLine = function(line) { 103 | this.result += line + this.options.newLine; 104 | this.emptyLines = 0; 105 | }; 106 | 107 | 108 | 109 | 110 | 111 | 112 | // Emit an error 113 | Processor.prototype.error = function(msg) { 114 | if (this.options.stopOnError) 115 | this.running = false; 116 | 117 | msg = `(line ${this.currentLine} in "${this.currentFile}") ${msg}`; 118 | this.parent._error(msg); 119 | 120 | return !this.options.stopOnError; 121 | }; 122 | 123 | 124 | 125 | // Emit the success 126 | Processor.prototype.success = function() { 127 | this.running = false; 128 | 129 | if (this.onsuccess) 130 | this.onsuccess(); 131 | else 132 | this.parent._success(this.result); 133 | }; 134 | -------------------------------------------------------------------------------- /lib/src/string-helper.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | Some functions for using strings more easily 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | #*/ 12 | 13 | 14 | 15 | // Return the last character of the string 16 | String.prototype.last = function() { 17 | return this.slice(-1); 18 | }; 19 | 20 | 21 | 22 | // Remove and add some text in the same time 23 | String.prototype.splice = function(idx, rem, s) { 24 | return (this.slice(0,idx) + s + this.slice(idx + rem)); 25 | }; 26 | 27 | 28 | 29 | // Get the next "..." string 30 | String.prototype.getNextString = function() { 31 | var str = this.match(/^"([A-Za-z0-9\-_\. \/\\]+)"/); 32 | return (!str || !str[1]) ? '' : str[1]; 33 | }; 34 | 35 | 36 | 37 | 38 | // Test if a character is alpha numeric or _ 39 | var StringArray = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"; 40 | 41 | String.prototype.isAlpha = function(i) { 42 | return StringArray.indexOf(this[i]) != -1; 43 | }; 44 | -------------------------------------------------------------------------------- /lib/src/system/comments.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | Manage the # comments 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | #*/ 12 | 13 | 14 | // Go to the end of a multilines comment 15 | Processor.prototype.commentEnd = function() { 16 | 17 | this.currentLine--; 18 | var line, i; 19 | 20 | // Find the end of the comment 21 | while (this.currentLine < this.linesCount) { 22 | line = this.nextLine(); 23 | 24 | if (line.indexOf("*/") != -1) 25 | break; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /lib/src/system/conditions.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | Manage the conditions 4 | 5 | 6 | © 2017 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | #*/ 12 | 13 | 14 | // Go to the next #elif, #else or #endif 15 | Processor.prototype.conditionNext = function(end) { 16 | 17 | // #if directives to start a condition 18 | var ifCmd = ['if', 'ifdef', 'ifndef']; 19 | 20 | // #else directives 21 | var elseCmd = ['elif', 'else']; 22 | 23 | 24 | // Local variables 25 | var line, s, n = 1; 26 | 27 | 28 | // Count unexploited conditions 29 | while (this.currentLine < this.linesCount) { 30 | 31 | line = this.nextLine().trimLeft(); 32 | if (line[0] != '#') 33 | continue; 34 | 35 | s = line.substr(1).trimLeft().split(' ')[0]; 36 | 37 | if (ifCmd.indexOf(s) != -1) 38 | n++; 39 | 40 | else if (!end && n == 1 && elseCmd.indexOf(s) != -1) 41 | return this.callCondition(line); 42 | 43 | else if (s == "endif") { 44 | n--; 45 | if (n == 0) 46 | return; 47 | } 48 | } 49 | }; 50 | 51 | 52 | 53 | 54 | 55 | // Call a #else or #elif condition 56 | Processor.prototype.callCondition = function(text) { 57 | 58 | // Get the directive name 59 | var split = text.substr(1).trimLeft().split(' '), 60 | name = split[0]; 61 | 62 | // Get the remaining text (without the # directive) 63 | split.shift(); 64 | text = split.join(' ').trimLeft(); 65 | 66 | 67 | // Call the corresponding directive 68 | Directives[name].call(this, text, true); 69 | }; 70 | 71 | 72 | 73 | 74 | 75 | // Go to the end of the condtion (#endif) 76 | Processor.prototype.conditionEnd = function() { 77 | this.conditionNext(true); 78 | }; 79 | -------------------------------------------------------------------------------- /lib/src/system/constants.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | #define a constant 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | #*/ 12 | 13 | 14 | // Create a constant 15 | Processor.prototype.createConstant = 16 | Compiler.prototype.createConstant = function(name, value, addDefines) { 17 | 18 | // Add constants value to the constant value 19 | if (addDefines !== false) 20 | value = this.addDefines(value); 21 | 22 | // Store the constant 23 | this.defines[name] = { 24 | name: name, 25 | value: value 26 | }; 27 | }; 28 | 29 | 30 | 31 | 32 | 33 | // Set a compiler constant 34 | Processor.prototype._compConst = 35 | Compiler.prototype._compConst = function(name, value) { 36 | this.createConstant('__' + name + '__', value, false); 37 | }; 38 | 39 | 40 | 41 | 42 | 43 | // Add a constant in a line 44 | Processor.prototype.addConstant = 45 | Compiler.prototype.addConstant = function(line, i, constant) { 46 | 47 | line = line.splice(i, constant.name.length, constant.value); 48 | i += constant.value.length; 49 | 50 | return { line: line, index: i }; 51 | }; 52 | -------------------------------------------------------------------------------- /lib/src/system/defines.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | Manage defined objects like macros and constants 4 | 5 | 6 | © 2017 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | #*/ 12 | 13 | 14 | 15 | // Add defined objects to a line 16 | Processor.prototype.addDefines = 17 | Compiler.prototype.addDefines = function(line, withConst, withMacros) { 18 | 19 | // Local variables 20 | var i1 = -1, i2; 21 | var d, r; 22 | 23 | 24 | // Check if the constant is present in the line 25 | for (var i in this.defines) { 26 | 27 | d = this.defines[i]; 28 | 29 | if (d.count !== undefined && withMacros === false) 30 | continue; 31 | if (d.count == undefined && withConst === false) 32 | continue; 33 | 34 | i2 = i.length; 35 | i1 = -1; 36 | 37 | // It can have the same constant more than one time 38 | for (;;) { 39 | 40 | // Get the position of the constant (-1 if not present) 41 | i1 = line.indexOf(i, i1 + 1); 42 | if (i1 == -1) 43 | break; 44 | 45 | // Check that the constant isn't in a middle of a word and add the constant if not 46 | if (line.isAlpha(i1 - 1) || line.isAlpha(i1 + i2)) 47 | continue; 48 | 49 | // Add the macro or the constant 50 | if (d.count !== undefined) 51 | r = this.addMacro(line, i1, d); 52 | else 53 | r = this.addConstant(line, i1, d); 54 | 55 | line = r.line; 56 | i1 = r.index; 57 | } 58 | } 59 | 60 | return line; 61 | }; 62 | 63 | 64 | 65 | 66 | 67 | //# Include js files 68 | #include "constants.js" 69 | #include "macros.js" 70 | -------------------------------------------------------------------------------- /lib/src/system/macros.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | #define a macro 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | #*/ 12 | 13 | 14 | // Create a macro (text must have the macro arguments, like this: '(a,b) a+b') 15 | Processor.prototype.createMacro = 16 | Compiler.prototype.createMacro = function(name, text) { 17 | 18 | // First, get macro arguments 19 | var args = []; 20 | 21 | var end = text.indexOf(")"), 22 | i1 = 1, 23 | i2 = 0; 24 | 25 | 26 | // If there is no closing parenthesis 27 | if (end == -1) 28 | return this.error(`no closing parenthesis in the #define of marcro ${name}`); 29 | 30 | 31 | // Get arguments 32 | while( (i2 = text.indexOf(",", i2 + 1)) != -1 && i2 < end) { 33 | args.push(text.substring(i1, i2).trim()); 34 | i1 = i2 + 1; 35 | } 36 | 37 | if (end > i1) // If there is at least one argument. 38 | args.push(text.substring(i1, end)); 39 | 40 | 41 | // Remove arguments in the text 42 | text = text.substr(end + 1).trimLeft(); 43 | 44 | // Execute defined macros 45 | text = this.addDefines(text, false, true); 46 | 47 | 48 | // Secondly, makes breaks and store variables positions 49 | var breaks = []; 50 | 51 | for (var i = 0, l = args.length, p; i < l; i++) { 52 | 53 | i1 = -1; 54 | p = args[i]; 55 | i2 = p.length; 56 | 57 | for(;;) { 58 | i1 = text.indexOf(p, i1+1); 59 | if (i1 == -1) 60 | break; 61 | 62 | if (text.isAlpha(i1-1) || text.isAlpha(i1+i2)) 63 | continue; 64 | 65 | breaks.push([ i1, i, i2 ]); 66 | } 67 | } 68 | 69 | 70 | // Sort variables in order of their positions in the macro text 71 | breaks.sort(function(a, b) { 72 | return a[0] - b[0] 73 | }); 74 | 75 | 76 | 77 | // Thirdly, cut the text into parts without variable and add defined constants 78 | var offset = 0, 79 | content = [], 80 | pos = []; 81 | i = 0; 82 | 83 | for (; i < breaks.length; i++) { 84 | content[i] = this.addDefines(text.slice(offset, breaks[i][0]), true, false); 85 | offset = breaks[i][0] + breaks[i][2]; 86 | pos[i] = breaks[i][1]; 87 | } 88 | 89 | content[i] = this.addDefines(text.slice(offset)); 90 | 91 | 92 | 93 | // Fourthly, store the macro 94 | this.defines[name] = { 95 | content: content, 96 | count: args.length, 97 | pos: pos, 98 | name: name 99 | }; 100 | }; 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | // Read a line and transform macro by adding their value 110 | Processor.prototype.addMacro = 111 | Compiler.prototype.addMacro = function(line, i, macro) { 112 | 113 | // Local variables 114 | var m = 0, 115 | e = i + macro.name.length, 116 | s = e, 117 | l = 0, 118 | args = []; 119 | 120 | 121 | // Get arguments between parenthesis (by counting parenthesis) 122 | for (var v, l = line.length; e < l; e++) { 123 | 124 | v = line[e]; 125 | 126 | if (v == "(") { 127 | m++; 128 | if (m == 1) 129 | s = e + 1; 130 | } 131 | 132 | else if (v == "," && m == 1) { 133 | args.push(line.slice(s, e)); 134 | s = e + 1; 135 | } 136 | 137 | else if (v == ")") { 138 | if (m == 1) 139 | break; 140 | m--; 141 | } 142 | 143 | else if (v != ' ' && m == 0) { 144 | return this.error(`there is no openning parenthesis for macro ${macro.name}`); 145 | } 146 | } 147 | 148 | 149 | // If the closing parenthesis is missing 150 | if (m != 1) 151 | return this.error(`the closing parenthesis is missing for macro ${macro.name}`); 152 | 153 | // Add the last argument. 154 | var lastarg = line.slice(s, e); 155 | if (lastarg.trim()) 156 | args.push(lastarg); 157 | 158 | 159 | // Check if there is the right number of arguments 160 | if (args.length > macro.count) 161 | return this.error(`too many arguments for macro ${macro.name}`); 162 | 163 | if (args.length < macro.count) 164 | return this.error(`too few arguments for macro ${macro.name}`); 165 | 166 | 167 | // Execute 'addDefines' on each argument 168 | for (var j = 0; j < macro.count; j++) 169 | args[j] = this.addDefines(args[j]); 170 | 171 | 172 | // Replace macro variables with the given arguments 173 | var str = macro.content[0]; 174 | 175 | for (s = 0, l = macro.pos.length; s < l; s++) 176 | str += args[ macro.pos[s] ] + macro.content[s+1]; 177 | 178 | 179 | // Add the result into the line 180 | line = line.splice(i, e - i + 1, str); 181 | i += str.length; 182 | 183 | return { line: line, index: i }; 184 | }; 185 | -------------------------------------------------------------------------------- /lib/src/system/stack.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | Stack system 4 | 5 | 6 | © 2017 - 7 | Guillaume Gonnet 8 | Al Zohali 9 | 10 | License GPLv2 11 | 12 | Sources at https://github.com/ParksProjets/C-Preprocessor 13 | 14 | #*/ 15 | 16 | 17 | // Save the current value of a macro on top of the stack 18 | Processor.prototype.pushMacro = function(name) { 19 | 20 | if (this.defines[name] === undefined) 21 | return this.error(`macro ${name} is not defined, cannot push it`); 22 | 23 | 24 | if (this.stack[name] === undefined) 25 | this.stack[name] = []; 26 | 27 | this.stack[name].push(this.defines[name]); 28 | }; 29 | 30 | 31 | 32 | 33 | // Set current value of the specified macro to previously saved value 34 | Processor.prototype.popMacro = function(name) { 35 | 36 | if (this.stack[name] === undefined || this.stack[name].length == 0) 37 | return this.error(`stack for macro ${name} is empty, cannot pop from it`); 38 | 39 | 40 | this.defines[name] = this.stack[name].pop(); 41 | }; 42 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "c-preprocessor", 3 | "description": "Preprocess JS files like C files.", 4 | "version": "0.2.13", 5 | 6 | "author": { 7 | "name": "Guillaume Gonnet", 8 | "url": "https://github.com/ParksProjets" 9 | }, 10 | "repository": "ParksProjets/C-Preprocessor", 11 | "license": "GPLv2", 12 | 13 | "main": "index.js", 14 | "scripts": { 15 | "test": "node test/all.js" 16 | }, 17 | 18 | "keywords": [ 19 | "preprocessor", 20 | "compile", 21 | "compiler", 22 | "c" 23 | ], 24 | "files": [ 25 | "index.js", 26 | "lib", 27 | "test", 28 | "bin" 29 | ], 30 | 31 | "bin": { 32 | "c-preprocessor": "./bin/global.js" 33 | }, 34 | 35 | "dependencies": { 36 | } 37 | } -------------------------------------------------------------------------------- /test/all.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /* 4 | 5 | Start all tests 6 | 7 | 8 | © 2016 - Guillaume Gonnet 9 | License GPLv2 10 | 11 | Sources at https://github.com/ParksProjets/C-Preprocessor 12 | 13 | */ 14 | 15 | 16 | var fs = require('fs'); 17 | 18 | 19 | // Run all js files in the 'tests' folder 20 | fs.readdir('test/tests', function(err, files) { 21 | 22 | if (err) 23 | return console.error("Can't read 'test/tests' folder"); 24 | 25 | for (var i = 0, l = files.length; i < l; i++) 26 | require('./tests/' + files[i]) 27 | }); 28 | -------------------------------------------------------------------------------- /test/factory.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Test factory 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | 14 | // Libraries 15 | var compiler = require('../index.js'), 16 | vm = require('vm'); 17 | 18 | 19 | 20 | // Test class 21 | var Test = function(name) { 22 | this.name = name; 23 | this.results = {}; 24 | this.settings = {}; 25 | }; 26 | 27 | 28 | // Constructor & export 29 | Test.prototype.constructor = Test; 30 | exports.Test = Test; 31 | 32 | 33 | 34 | // Log a success 35 | Test.prototype.success = function() { 36 | console.log(`\x1b[1;32m${this.name} test passed\x1b[0m\n`); 37 | }; 38 | 39 | 40 | 41 | // Log an error 42 | Test.prototype.error = function(error) { 43 | console.log(`\x1b[1;31m${this.name} test error`); 44 | 45 | if (error) 46 | console.log(`\x1b[1;31m Error: ${error}`); 47 | 48 | console.log('\x1b[0m'); 49 | }; 50 | 51 | 52 | 53 | 54 | // Add a result 55 | Test.prototype.result = function(name, value) { 56 | this.results[name] = value; 57 | }; 58 | 59 | 60 | 61 | // Set a setting 62 | Test.prototype.setting = function(name, value) { 63 | this.settings[name] = value; 64 | }; 65 | 66 | 67 | 68 | 69 | 70 | // Run the test 71 | Test.prototype.run = function(code) { 72 | var _this = this; 73 | 74 | 75 | // Run the code and check the results 76 | function run(err, code) { 77 | 78 | // If there is a compiler error 79 | if (err) 80 | return _this.error(`compiler error -> ${err}`); 81 | 82 | 83 | // Run the code 84 | try { 85 | var sandbox = {}; 86 | vm.runInNewContext(code, sandbox); 87 | } catch(e) { 88 | return _this.error(`code execution failed -> ${e.message}`); 89 | } 90 | 91 | 92 | // Check the results 93 | for (var n in _this.results) { 94 | var e = _this.results[n], 95 | r = sandbox[n]; 96 | 97 | if (e !== r) 98 | return _this.error(`the expected value of variable ${n} was '${e}' but we got '${r}'`); 99 | } 100 | 101 | 102 | // All is OK: log the success 103 | _this.success(); 104 | } 105 | 106 | 107 | // Compile the code 108 | try { 109 | compiler.compile(code, this.settings, run); 110 | } catch(e) { 111 | this.error(`compiler execution failed -> ${e.message}`); 112 | console.log(e); 113 | } 114 | }; 115 | -------------------------------------------------------------------------------- /test/ressources/file-to-include-once.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | File to include once for the #include & #pragma tests 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Source at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | #pragma once 14 | 15 | 16 | #define NUMBER_2 56 17 | 18 | 19 | var file = "__FILE__"; 20 | 21 | -------------------------------------------------------------------------------- /test/ressources/file-to-include.js: -------------------------------------------------------------------------------- 1 | /*# 2 | 3 | File to include for the #include test 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Source at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | #*/ 12 | 13 | 14 | r = true; 15 | 16 | #define NUMBER 42 17 | 18 | -------------------------------------------------------------------------------- /test/tests/comments.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Test the //# and /*# comments 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | 14 | // Create the test 15 | var utils = require('../utils.js'), 16 | test1 = utils.test('comments (enabled)'), 17 | test2 = utils.test('comments (disabled)'); 18 | 19 | 20 | 21 | // Expected results 22 | test1.result('result', 0); 23 | test2.result('result', 25); 24 | 25 | 26 | // Disable comment espace 27 | test2.setting('commentEscape', false); 28 | 29 | 30 | 31 | // Code to run 32 | var code = ` 33 | 34 | var r1 = \` 35 | 36 | /*# 37 | This is a comment 38 | #*/ 39 | 40 | \`; 41 | 42 | 43 | var result = r1.trim().length; 44 | 45 | `; 46 | 47 | 48 | // Run the tests 49 | test1.run(code); 50 | test2.run(code); 51 | -------------------------------------------------------------------------------- /test/tests/define-macro.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Test the #define directive for defining a macro 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | 14 | // Create the test 15 | var utils = require('../utils.js'), 16 | test = utils.test('#define macro'); 17 | 18 | 19 | 20 | // Random numbers 21 | var a = utils.randint(0, 100), 22 | b = utils.randint(0, 100); 23 | 24 | 25 | // Expected results 26 | test.result('r1', a * 5 * 7); 27 | test.result('r2', a*(b+12)*5*5 - 74); 28 | test.result('same', 74 + 42 + 74 + 42); 29 | test.result('str', 'Name -> This is (a) label'); 30 | test.result('f8', 21); 31 | 32 | 33 | // Predefined macros 34 | test.setting('macros', { 35 | "SUM": "(var1, var2) (var1 + var2)" 36 | }); 37 | 38 | 39 | 40 | // Run the test 41 | test.run(` 42 | 43 | #define NUM 74 44 | 45 | #define EMPTY() 42 46 | 47 | #define MACRO1(a,b) a*5*b 48 | #define MACRO2(a,b2,c) MACRO1(a,b2)-c 49 | 50 | #define STR(name, label) name + " -> " + label 51 | 52 | #define MAT2(a,b,c,d) [a, b, c, d] // A 2x2 matrix 53 | 54 | #define MUL(m1,m2) [ /* Multiplication of matrices */ \ 55 | (m1)[0]*(m2)[0] + (m1)[1]*(m2)[2], /* (0, 0)-element */ \ 56 | (m1)[0]*(m2)[1] + (m1)[2]*(m2)[3], /* (0, 1)-element */ \ 57 | (m1)[2]*(m2)[0] + (m1)[3]*(m2)[2], /* (1, 0)-element */ \ 58 | (m1)[2]*(m2)[1] + (m1)[3]*(m2)[3]] /* (1, 1)-element */ 59 | 60 | 61 | var r1 = MACRO1(${a}, 7), 62 | r2 = MACRO2(${a}, MACRO1(SUM(${b}, 12), 1), NUM); 63 | 64 | var same = NUM + EMPTY() + NUM + EMPTY( ); 65 | 66 | var str = STR('Name', 'This is (a) label') 67 | 68 | var m = MAT2(1,1,1,0); 69 | for (let i = 0; i < 3; ++i) { 70 | m = MUL(m,m); 71 | } 72 | var f8 = m[1]; 73 | 74 | `); 75 | -------------------------------------------------------------------------------- /test/tests/define-var.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Test the #define directive for defining a variable 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | 14 | // Create the test 15 | var utils = require('../utils.js'), 16 | test = utils.test('#define variable'); 17 | 18 | 19 | 20 | // Random numbers 21 | var a = utils.randint(1, 100), 22 | b = utils.randint(1, 100), 23 | c = utils.randint(200, 300); 24 | 25 | 26 | // Expected results 27 | test.result('r1', a + b); 28 | test.result('r2', c); 29 | test.result('r3', a * a + a); 30 | test.result('today', new Date().toLocaleDateString()); 31 | 32 | 33 | // Predefined constants 34 | test.setting('constants', { 35 | "VARIABLE_3": c 36 | }); 37 | 38 | 39 | 40 | // Run the test 41 | test.run(` 42 | 43 | #define VARIABLE ${a} // This is a comment 44 | #define VARIABLE_2 ${b} 45 | 46 | var r1 = VARIABLE + VARIABLE_2, 47 | r2 = VARIABLE_3, 48 | r3 = VARIABLE * VARIABLE + VARIABLE; 49 | 50 | var today = "__DATE__"; 51 | 52 | `); 53 | -------------------------------------------------------------------------------- /test/tests/enum.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Test the #enum directive 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | 14 | // Create the test 15 | var utils = require('../utils.js'), 16 | test = utils.test('#enum'); 17 | 18 | 19 | 20 | // Random numbers 21 | var step = utils.randint(5, 20), 22 | start = utils.randint(0, 100); 23 | 24 | 25 | // Expected results 26 | test.result('r1', 6); 27 | test.result('r2', start + 2*step); 28 | 29 | 30 | 31 | // Run the test 32 | test.run(` 33 | 34 | #enum 35 | A, B, C, D 36 | #endenum 37 | 38 | #enum start=${start}, step=${step} 39 | Car, Bike, Truck, Plane 40 | #endenum 41 | 42 | var r1 = A + B + C + D; 43 | var r2 = Truck; 44 | 45 | `); 46 | -------------------------------------------------------------------------------- /test/tests/error.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Test the #error directive 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | 14 | // Create the test 15 | var utils = require('../utils.js'), 16 | test = utils.test('#error'); 17 | 18 | 19 | 20 | // Expected the rsult 21 | var text = 'Math is the life !'; 22 | 23 | 24 | // Store error and success functions 25 | var error = test.error, 26 | success = test.success; 27 | 28 | 29 | // Override error function for checking if the right error is called 30 | test.error = function(err) { 31 | var msg = 'compiler error -> (line 3 in "main") ' + text; 32 | 33 | if (err == msg) 34 | success.call(test); 35 | else 36 | error.call(test, "we didn't get the right message"); 37 | }; 38 | 39 | 40 | // Override success function 41 | test.success = function(err) { 42 | error.call(test, 'no error raised'); 43 | }; 44 | 45 | 46 | 47 | // Run the test 48 | test.run(` 49 | 50 | #error ${text} 51 | 52 | `); 53 | -------------------------------------------------------------------------------- /test/tests/if.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Test the #if directive 4 | 5 | 6 | © 2017 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | 14 | // Create the test 15 | var utils = require('../utils.js'), 16 | test = utils.test('#if'); 17 | 18 | 19 | 20 | // Random numbers 21 | var a = utils.randint(0, 100), 22 | b = utils.randint(0, 100); 23 | 24 | 25 | // Expected results 26 | test.result('r1', true); 27 | test.result('r2', true); 28 | test.result('r3', true); 29 | 30 | // Set the file name 31 | test.setting('filename', 'if-condition.js'); 32 | 33 | 34 | 35 | // Run the test 36 | test.run(` 37 | 38 | var r3 = true; 39 | 40 | #define A ${a} 41 | #define B ${b} 42 | #define C ${a+b} 43 | 44 | 45 | #if defined(A) && !defined(D) 46 | # if "__FILE__" == "if-condition.js" 47 | var r1 = true; 48 | # else 49 | var r1 = false; 50 | # endif 51 | #else 52 | var r1 = false; 53 | #endif 54 | 55 | #if A + B != C 56 | 57 | #if A == 2 58 | r3 = false; 59 | #elif A == 4 60 | r3 = false; 61 | #else 62 | r3 = false; 63 | #endif 64 | 65 | var r2 = false; 66 | #elif A + B == C + 1 67 | var r2 = false; 68 | #else 69 | var r2 = true; 70 | #endif 71 | 72 | `); 73 | -------------------------------------------------------------------------------- /test/tests/ifdef.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Test the #ifdef directive 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | 14 | // Create the test 15 | var utils = require('../utils.js'), 16 | test = utils.test('#ifdef'); 17 | 18 | 19 | 20 | // Create a random constant name 21 | var name = utils.randstr(); 22 | 23 | 24 | // Expected results 25 | test.result('r1', true); 26 | test.result('r2', true); 27 | 28 | 29 | 30 | // Code to parse 31 | test.run(` 32 | 33 | #define ${name} 42 34 | 35 | #ifdef ${name} 36 | var r1 = true; 37 | #else 38 | var r1 = false; 39 | #endif 40 | 41 | #ifndef VARIABLE_2 42 | var r2 = true; 43 | #else 44 | var r2 = false; 45 | #endif 46 | 47 | `); 48 | -------------------------------------------------------------------------------- /test/tests/include.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Test the #include directive 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | 14 | // Create the test 15 | var utils = require('../utils.js'), 16 | test = utils.test('#include'); 17 | 18 | 19 | 20 | // Expected results 21 | test.result('n2', 56); 22 | test.result('r', true); 23 | test.result('file', 'test/ressources/file-to-include-once.js'); 24 | test.result('file2', 'main'); 25 | 26 | 27 | 28 | // Code to parse 29 | test.run(` 30 | 31 | var r = false; 32 | 33 | // This test is running in the base folder 34 | #include "test/ressources/file-to-include-once.js" 35 | 36 | var n2 = NUMBER_2; 37 | var file2 = "__FILE__"; 38 | 39 | // Include another file 40 | #include "test/ressources/file-to-include.js"`); 41 | -------------------------------------------------------------------------------- /test/tests/pragma.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Test the #pragma directive 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Source at https://github.com/ParksProjets/Compile-JS-like-C 10 | 11 | */ 12 | 13 | 14 | // Create the test 15 | var utils = require('../utils.js'), 16 | test = utils.test('#pragma'); 17 | 18 | 19 | 20 | // Expected results 21 | test.result('n1', "number"); 22 | test.result('n2', "undefined"); 23 | 24 | 25 | 26 | // Run the test 27 | test.run(` 28 | 29 | // This test is running in the base folder 30 | #include "test/ressources/file-to-include-once.js" 31 | 32 | var n1 = typeof(NUMBER_2); 33 | 34 | #undef NUMBER_2 35 | 36 | // Re-include the file 37 | #include "test/ressources/file-to-include-once.js" 38 | 39 | var n2 = typeof(NUMBER_2) 40 | 41 | `); 42 | -------------------------------------------------------------------------------- /test/tests/push-pop-macro.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Test the #pragma push_macro(...) and #pragma pop_macro(...) directives 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | 14 | // Create the test 15 | var utils = require('../utils.js'), 16 | test = utils.test('#pragma push_macro/pop_macro'); 17 | 18 | 19 | 20 | // Expected results 21 | test.result('r1', 52); 22 | test.result('r2', 42); 23 | 24 | 25 | 26 | // Code to run 27 | test.run(` 28 | 29 | #define VARIABLE 42 30 | 31 | #pragma push_macro("VARIABLE") 32 | #define VARIABLE 52 33 | 34 | var r1 = VARIABLE; 35 | 36 | #pragma pop_macro("VARIABLE") 37 | 38 | var r2 = VARIABLE; 39 | 40 | `); 41 | -------------------------------------------------------------------------------- /test/tests/undef.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Test the #undef directive 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Source at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | 14 | // Create the test 15 | var utils = require('../utils.js'), 16 | test = utils.test('#undef'); 17 | 18 | 19 | 20 | // Random numbers 21 | var a = utils.randint(0, 100), 22 | b = utils.randint(0, 100); 23 | 24 | 25 | // Expected results 26 | test.result('r1', b); 27 | test.result('r2', a); 28 | 29 | 30 | 31 | // Run the test 32 | test.run(` 33 | 34 | var VARIABLE = ${a}; 35 | 36 | #define VARIABLE ${b} 37 | var r1 = VARIABLE; 38 | 39 | #undef VARIABLE 40 | var r2 = VARIABLE; 41 | 42 | `); 43 | -------------------------------------------------------------------------------- /test/utils.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Some useful functions 4 | 5 | 6 | © 2016 - Guillaume Gonnet 7 | License GPLv2 8 | 9 | Sources at https://github.com/ParksProjets/C-Preprocessor 10 | 11 | */ 12 | 13 | 14 | // Test factory 15 | var factory = require('./factory.js'); 16 | 17 | 18 | // Create a test 19 | exports.test = function(name) { 20 | return new factory.Test(name); 21 | }; 22 | 23 | 24 | 25 | // Random number in {a,..,b} 26 | exports.randint = function(a, b) { 27 | return Math.round(a + Math.random() * (b - a)); 28 | }; 29 | 30 | 31 | // Random string 32 | exports.randstr = function(length) { 33 | var str = Math.random().toString(36).replace(/[^a-z]+/g, ''); 34 | return str.substr(0, length || exports.randint(5, 15)); 35 | }; 36 | --------------------------------------------------------------------------------