├── .gitattributes ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── LICENSE.md ├── Makefile ├── README.md ├── examples ├── book.doge ├── doge.c ├── fib.smallc ├── foobar.c ├── line_reader.c ├── lispy.c ├── maths.c ├── minimal.smallc ├── prelude.lspy ├── readme.maths ├── simple.maths ├── smallc.c ├── so_c.doge └── tree_traversal.c ├── mpc.c ├── mpc.h ├── mpc.pc ├── package.json └── tests ├── combinators.c ├── core.c ├── digits.txt ├── grammar.c ├── maths.grammar ├── ptest.c ├── ptest.h ├── regex.c └── test.c /.gitattributes: -------------------------------------------------------------------------------- 1 | "* text=auto" 2 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | 3 | name: CI 4 | 5 | jobs: 6 | check: 7 | name: Build and test 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v3 11 | - run: make 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.exe 3 | *.dSYM 4 | test 5 | examples/doge 6 | examples/lispy 7 | examples/maths 8 | examples/smallc 9 | examples/foobar 10 | examples/tree_traversal 11 | build/* 12 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Licensed Under BSD 2 | 3 | Copyright (c) 2013, Daniel Holden 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 2. Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 16 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 17 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 19 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 20 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 21 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 22 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 24 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | 26 | The views and conclusions contained in the software and documentation are those 27 | of the authors and should not be interpreted as representing official policies, 28 | either expressed or implied, of the FreeBSD Project. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PROJ = mpc 2 | CC ?= gcc 3 | STD ?= -ansi 4 | DIST = build 5 | MKDIR ?= mkdir -p 6 | PREFIX ?= /usr/local 7 | CFLAGS ?= $(STD) -pedantic -O3 -g -Wall -Werror -Wextra -Wformat=2 -Wshadow \ 8 | -Wno-long-long -Wno-overlength-strings -Wno-format-nonliteral -Wcast-align \ 9 | -Wwrite-strings -Wstrict-prototypes -Wold-style-definition -Wredundant-decls \ 10 | -Wnested-externs -Wmissing-include-dirs -Wswitch-default 11 | 12 | TESTS = $(wildcard tests/*.c) 13 | EXAMPLES = $(wildcard examples/*.c) 14 | EXAMPLESEXE = $(EXAMPLES:.c=) 15 | 16 | .PHONY: all check clean libs $(DIST)/$(PROJ).pc 17 | 18 | all: $(EXAMPLESEXE) check libs $(DIST)/$(PROJ).pc 19 | 20 | $(DIST)/.dirstamp: 21 | $(MKDIR) $(DIST) 22 | $(MKDIR) $(DIST)/examples 23 | touch $@ 24 | 25 | check: $(DIST)/.dirstamp $(DIST)/test-file $(DIST)/test-static $(DIST)/test-dynamic 26 | ./$(DIST)/test-file 27 | ./$(DIST)/test-static 28 | LD_LIBRARY_PATH=$(DIST) ./$(DIST)/test-dynamic 29 | 30 | $(DIST)/test-file: $(TESTS) $(PROJ).c $(PROJ).h tests/ptest.h 31 | $(CC) $(filter-out -Werror, $(CFLAGS)) $(TESTS) $(PROJ).c -lm -o $(DIST)/test-file 32 | 33 | $(DIST)/test-dynamic: $(TESTS) $(DIST)/lib$(PROJ).so $(PROJ).h tests/ptest.h 34 | $(CC) $(filter-out -Werror, $(CFLAGS)) $(TESTS) -lm -L$(DIST) -l$(PROJ) -o $(DIST)/test-dynamic 35 | 36 | $(DIST)/test-static: $(TESTS) $(DIST)/lib$(PROJ).a $(PROJ).h tests/ptest.h 37 | $(CC) $(filter-out -Werror, $(CFLAGS)) $(TESTS) -lm -L$(DIST) -l$(PROJ) -static -o $(DIST)/test-static 38 | 39 | examples/%: $(DIST)/.dirstamp examples/%.c $(PROJ).c $(PROJ).h 40 | $(CC) $(CFLAGS) $(filter-out $(DIST)/.dirstamp $(PROJ).h, $^) -lm -o $(DIST)/$@ 41 | 42 | $(DIST)/lib$(PROJ).so: $(DIST)/.dirstamp $(PROJ).c $(PROJ).h 43 | ifneq ($(OS),Windows_NT) 44 | $(CC) $(CFLAGS) -fPIC -shared $(PROJ).c -o $(DIST)/lib$(PROJ).so 45 | else 46 | $(CC) $(CFLAGS) -shared $(PROJ).c -o $(DIST)/lib$(PROJ).so 47 | endif 48 | 49 | $(DIST)/lib$(PROJ).a: $(DIST)/.dirstamp $(PROJ).c $(PROJ).h 50 | $(CC) $(CFLAGS) -c $(PROJ).c -o $(DIST)/$(PROJ).o 51 | $(AR) rcs $(DIST)/lib$(PROJ).a $(DIST)/$(PROJ).o 52 | 53 | libs: $(DIST)/lib$(PROJ).so $(DIST)/lib$(PROJ).a 54 | 55 | $(DIST)/$(PROJ).pc: $(DIST)/.dirstamp $(PROJ).pc 56 | cp $(PROJ).pc $(DIST)/$(PROJ).pc 57 | sed -i '1i\prefix=$(PREFIX)/' $(DIST)/$(PROJ).pc 58 | 59 | clean: 60 | rm -rf -- $(DIST) 61 | 62 | install: all 63 | install -d -m645 $(DESTDIR)$(PREFIX)/include 64 | install -d -m645 $(DESTDIR)$(PREFIX)/lib/pkgconfig 65 | install -d -m645 $(DESTDIR)$(PREFIX)/share/$(PROJ) 66 | install -m755 -t $(DESTDIR)$(PREFIX)/lib $(DIST)/lib* 67 | install -m644 -t $(DESTDIR)$(PREFIX)/share/$(PROJ) $(PROJ).c $(PROJ).h 68 | install -m644 $(PROJ).h $(DESTDIR)$(PREFIX)/include/$(PROJ).h 69 | install -m644 $(DIST)/$(PROJ).pc \ 70 | $(DESTDIR)$(PREFIX)/lib/pkgconfig/$(PROJ).pc 71 | 72 | uninstall: 73 | rm -rf -- \ 74 | $(DESTDIR)$(PREFIX)/include/$(PROJ).h \ 75 | $(DESTDIR)$(PREFIX)/share/$(PROJ)/$(PROJ).{c,h} \ 76 | $(DESTDIR)$(PREFIX)/lib/lib$(PROJ).{so,a} 77 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Micro Parser Combinators 2 | ======================== 3 | 4 | Version 0.9.0 5 | 6 | 7 | About 8 | ----- 9 | 10 | _mpc_ is a lightweight and powerful Parser Combinator library for C. 11 | 12 | Using _mpc_ might be of interest to you if you are... 13 | 14 | * Building a new programming language 15 | * Building a new data format 16 | * Parsing an existing programming language 17 | * Parsing an existing data format 18 | * Embedding a Domain Specific Language 19 | * Implementing [Greenspun's Tenth Rule](http://en.wikipedia.org/wiki/Greenspun%27s_tenth_rule) 20 | 21 | 22 | Features 23 | -------- 24 | 25 | * Type-Generic 26 | * Predictive, Recursive Descent 27 | * Easy to Integrate (One Source File in ANSI C) 28 | * Automatic Error Message Generation 29 | * Regular Expression Parser Generator 30 | * Language/Grammar Parser Generator 31 | 32 | 33 | Alternatives 34 | ------------ 35 | 36 | The current main alternative for a C based parser combinator library is a branch of [Cesium3](https://github.com/wbhart/Cesium3/tree/combinators). 37 | 38 | _mpc_ provides a number of features that this project does not offer, and also overcomes a number of potential downsides: 39 | 40 | * _mpc_ Works for Generic Types 41 | * _mpc_ Doesn't rely on Boehm-Demers-Weiser Garbage Collection 42 | * _mpc_ Doesn't use `setjmp` and `longjmp` for errors 43 | * _mpc_ Doesn't pollute the namespace 44 | 45 | 46 | Quickstart 47 | ========== 48 | 49 | Here is how one would use _mpc_ to create a parser for a basic mathematical expression language. 50 | 51 | ```c 52 | mpc_parser_t *Expr = mpc_new("expression"); 53 | mpc_parser_t *Prod = mpc_new("product"); 54 | mpc_parser_t *Value = mpc_new("value"); 55 | mpc_parser_t *Maths = mpc_new("maths"); 56 | 57 | mpca_lang(MPCA_LANG_DEFAULT, 58 | " expression : (('+' | '-') )*; " 59 | " product : (('*' | '/') )*; " 60 | " value : /[0-9]+/ | '(' ')'; " 61 | " maths : /^/ /$/; ", 62 | Expr, Prod, Value, Maths, NULL); 63 | 64 | mpc_result_t r; 65 | 66 | if (mpc_parse("input", input, Maths, &r)) { 67 | mpc_ast_print(r.output); 68 | mpc_ast_delete(r.output); 69 | } else { 70 | mpc_err_print(r.error); 71 | mpc_err_delete(r.error); 72 | } 73 | 74 | mpc_cleanup(4, Expr, Prod, Value, Maths); 75 | ``` 76 | 77 | If you were to set `input` to the string `(4 * 2 * 11 + 2) - 5`, the printed output would look like this. 78 | 79 | ``` 80 | > 81 | regex 82 | expression|> 83 | value|> 84 | char:1:1 '(' 85 | expression|> 86 | product|> 87 | value|regex:1:2 '4' 88 | char:1:4 '*' 89 | value|regex:1:6 '2' 90 | char:1:8 '*' 91 | value|regex:1:10 '11' 92 | char:1:13 '+' 93 | product|value|regex:1:15 '2' 94 | char:1:16 ')' 95 | char:1:18 '-' 96 | product|value|regex:1:20 '5' 97 | regex 98 | ``` 99 | 100 | Getting Started 101 | =============== 102 | 103 | Introduction 104 | ------------ 105 | 106 | Parser Combinators are structures that encode how to parse particular languages. They can be combined using intuitive operators to create new parsers of increasing complexity. Using these operators detailed grammars and languages can be parsed and processed in a quick, efficient, and easy way. 107 | 108 | The trick behind Parser Combinators is the observation that by structuring the library in a particular way, one can make building parser combinators look like writing a grammar itself. Therefore instead of describing _how to parse a language_, a user must only specify _the language itself_, and the library will work out how to parse it ... as if by magic! 109 | 110 | _mpc_ can be used in this mode, or, as shown in the above example, you can specify the grammar directly as a string or in a file. 111 | 112 | Basic Parsers 113 | ------------- 114 | 115 | ### String Parsers 116 | 117 | All the following functions construct new basic parsers of the type `mpc_parser_t *`. All of those parsers return a newly allocated `char *` with the character(s) they manage to match. If unsuccessful they will return an error. They have the following functionality. 118 | 119 | * * * 120 | 121 | ```c 122 | mpc_parser_t *mpc_any(void); 123 | ``` 124 | 125 | Matches any individual character 126 | 127 | * * * 128 | 129 | ```c 130 | mpc_parser_t *mpc_char(char c); 131 | ``` 132 | 133 | Matches a single given character `c` 134 | 135 | * * * 136 | 137 | ```c 138 | mpc_parser_t *mpc_range(char s, char e); 139 | ``` 140 | 141 | Matches any single given character in the range `s` to `e` (inclusive) 142 | 143 | * * * 144 | 145 | ```c 146 | mpc_parser_t *mpc_oneof(const char *s); 147 | ``` 148 | 149 | Matches any single given character in the string `s` 150 | 151 | * * * 152 | 153 | ```c 154 | mpc_parser_t *mpc_noneof(const char *s); 155 | ``` 156 | 157 | Matches any single given character not in the string `s` 158 | 159 | * * * 160 | 161 | ```c 162 | mpc_parser_t *mpc_satisfy(int(*f)(char)); 163 | ``` 164 | 165 | Matches any single given character satisfying function `f` 166 | 167 | * * * 168 | 169 | ```c 170 | mpc_parser_t *mpc_string(const char *s); 171 | ``` 172 | 173 | Matches exactly the string `s` 174 | 175 | 176 | ### Other Parsers 177 | 178 | Several other functions exist that construct parsers with some other special functionality. 179 | 180 | * * * 181 | 182 | ```c 183 | mpc_parser_t *mpc_pass(void); 184 | ``` 185 | 186 | Consumes no input, always successful, returns `NULL` 187 | 188 | * * * 189 | 190 | ```c 191 | mpc_parser_t *mpc_fail(const char *m); 192 | mpc_parser_t *mpc_failf(const char *fmt, ...); 193 | ``` 194 | 195 | Consumes no input, always fails with message `m` or formatted string `fmt`. 196 | 197 | * * * 198 | 199 | ```c 200 | mpc_parser_t *mpc_lift(mpc_ctor_t f); 201 | ``` 202 | 203 | Consumes no input, always successful, returns the result of function `f` 204 | 205 | * * * 206 | 207 | ```c 208 | mpc_parser_t *mpc_lift_val(mpc_val_t *x); 209 | ``` 210 | 211 | Consumes no input, always successful, returns `x` 212 | 213 | * * * 214 | 215 | ```c 216 | mpc_parser_t *mpc_state(void); 217 | ``` 218 | 219 | Consumes no input, always successful, returns a copy of the parser state as a `mpc_state_t *`. This state is newly allocated and so needs to be released with `free` when finished with. 220 | 221 | * * * 222 | 223 | ```c 224 | mpc_parser_t *mpc_anchor(int(*f)(char,char)); 225 | ``` 226 | 227 | Consumes no input. Successful when function `f` returns true. Always returns `NULL`. 228 | 229 | Function `f` is a _anchor_ function. It takes as input the last character parsed, and the next character in the input, and returns success or failure. This function can be set by the user to ensure some condition is met. For example to test that the input is at a boundary between words and non-words. 230 | 231 | At the start of the input the first argument is set to `'\0'`. At the end of the input the second argument is set to `'\0'`. 232 | 233 | 234 | 235 | Parsing 236 | ------- 237 | 238 | Once you've build a parser, you can run it on some input using one of the following functions. These functions return `1` on success and `0` on failure. They output either the result, or an error to a `mpc_result_t` variable. This type is defined as follows. 239 | 240 | ```c 241 | typedef union { 242 | mpc_err_t *error; 243 | mpc_val_t *output; 244 | } mpc_result_t; 245 | ``` 246 | 247 | where `mpc_val_t *` is synonymous with `void *` and simply represents some pointer to data - the exact type of which is dependant on the parser. 248 | 249 | 250 | * * * 251 | 252 | ```c 253 | int mpc_parse(const char *filename, const char *string, mpc_parser_t *p, mpc_result_t *r); 254 | ``` 255 | 256 | Run a parser on some string. 257 | 258 | * * * 259 | 260 | ```c 261 | int mpc_parse_file(const char *filename, FILE *file, mpc_parser_t *p, mpc_result_t *r); 262 | ``` 263 | 264 | Run a parser on some file. 265 | 266 | * * * 267 | 268 | ```c 269 | int mpc_parse_pipe(const char *filename, FILE *pipe, mpc_parser_t *p, mpc_result_t *r); 270 | ``` 271 | 272 | Run a parser on some pipe (such as `stdin`). 273 | 274 | * * * 275 | 276 | ```c 277 | int mpc_parse_contents(const char *filename, mpc_parser_t *p, mpc_result_t *r); 278 | ``` 279 | 280 | Run a parser on the contents of some file. 281 | 282 | 283 | Combinators 284 | ----------- 285 | 286 | Combinators are functions that take one or more parsers and return a new parser of some given functionality. 287 | 288 | These combinators work independently of exactly what data type the parser(s) supplied as input return. In languages such as Haskell ensuring you don't input one type of data into a parser requiring a different type is done by the compiler. But in C we don't have that luxury. So it is at the discretion of the programmer to ensure that he or she deals correctly with the outputs of different parser types. 289 | 290 | A second annoyance in C is that of manual memory management. Some parsers might get half-way and then fail. This means they need to clean up any partial result that has been collected in the parse. In Haskell this is handled by the Garbage Collector, but in C these combinators will need to take _destructor_ functions as input, which say how clean up any partial data that has been collected. 291 | 292 | Here are the main combinators and how to use then. 293 | 294 | * * * 295 | 296 | ```c 297 | mpc_parser_t *mpc_expect(mpc_parser_t *a, const char *e); 298 | mpc_parser_t *mpc_expectf(mpc_parser_t *a, const char *fmt, ...); 299 | ``` 300 | 301 | Returns a parser that runs `a`, and on success returns the result of `a`, while on failure reports that `e` was expected. 302 | 303 | * * * 304 | 305 | ```c 306 | mpc_parser_t *mpc_apply(mpc_parser_t *a, mpc_apply_t f); 307 | mpc_parser_t *mpc_apply_to(mpc_parser_t *a, mpc_apply_to_t f, void *x); 308 | ``` 309 | 310 | Returns a parser that applies function `f` (optionality taking extra input `x`) to the result of parser `a`. 311 | 312 | * * * 313 | 314 | ```c 315 | mpc_parser_t *mpc_check(mpc_parser_t *a, mpc_dtor_t da, mpc_check_t f, const char *e); 316 | mpc_parser_t *mpc_check_with(mpc_parser_t *a, mpc_dtor_t da, mpc_check_with_t f, void *x, const char *e); 317 | mpc_parser_t *mpc_checkf(mpc_parser_t *a, mpc_dtor_t da, mpc_check_t f, const char *fmt, ...); 318 | mpc_parser_t *mpc_check_withf(mpc_parser_t *a, mpc_dtor_t da, mpc_check_with_t f, void *x, const char *fmt, ...); 319 | ``` 320 | 321 | Returns a parser that applies function `f` (optionally taking extra input `x`) to the result of parser `a`. If `f` returns non-zero, then the parser succeeds and returns the value of `a` (possibly modified by `f`). If `f` returns zero, then the parser fails with message `e`, and the result of `a` is destroyed with the destructor `da`. 322 | 323 | * * * 324 | 325 | ```c 326 | mpc_parser_t *mpc_not(mpc_parser_t *a, mpc_dtor_t da); 327 | mpc_parser_t *mpc_not_lift(mpc_parser_t *a, mpc_dtor_t da, mpc_ctor_t lf); 328 | ``` 329 | 330 | Returns a parser with the following behaviour. If parser `a` succeeds, then it fails and consumes no input. If parser `a` fails, then it succeeds, consumes no input and returns `NULL` (or the result of lift function `lf`). Destructor `da` is used to destroy the result of `a` on success. 331 | 332 | * * * 333 | 334 | ```c 335 | mpc_parser_t *mpc_maybe(mpc_parser_t *a); 336 | mpc_parser_t *mpc_maybe_lift(mpc_parser_t *a, mpc_ctor_t lf); 337 | ``` 338 | 339 | Returns a parser that runs `a`. If `a` is successful then it returns the result of `a`. If `a` is unsuccessful then it succeeds, but returns `NULL` (or the result of `lf`). 340 | 341 | * * * 342 | 343 | ```c 344 | mpc_parser_t *mpc_many(mpc_fold_t f, mpc_parser_t *a); 345 | ``` 346 | 347 | Runs `a` zero or more times until it fails. Results are combined using fold function `f`. See the _Function Types_ section for more details. 348 | 349 | * * * 350 | 351 | ```c 352 | mpc_parser_t *mpc_many1(mpc_fold_t f, mpc_parser_t *a); 353 | ``` 354 | 355 | Runs `a` one or more times until it fails. Results are combined with fold function `f`. 356 | 357 | * * * 358 | 359 | ```c 360 | mpc_parser_t *mpc_sepby1(mpc_fold_t f, mpc_parser_t *sep, mpc_parser_t *a); 361 | ``` 362 | 363 | Runs `a` one or more times, separated by `sep`. Results are combined with fold function `f`. 364 | 365 | * * * 366 | 367 | ```c 368 | mpc_parser_t *mpc_count(int n, mpc_fold_t f, mpc_parser_t *a, mpc_dtor_t da); 369 | ``` 370 | 371 | Runs `a` exactly `n` times. If this fails, any partial results are destructed with `da`. If successful results of `a` are combined using fold function `f`. 372 | 373 | * * * 374 | 375 | ```c 376 | mpc_parser_t *mpc_or(int n, ...); 377 | ``` 378 | 379 | Attempts to run `n` parsers in sequence, returning the first one that succeeds. If all fail, returns an error. 380 | 381 | * * * 382 | 383 | ```c 384 | mpc_parser_t *mpc_and(int n, mpc_fold_t f, ...); 385 | ``` 386 | 387 | Attempts to run `n` parsers in sequence, returning the fold of the results using fold function `f`. First parsers must be specified, followed by destructors for each parser, excluding the final parser. These are used in case of partial success. For example: `mpc_and(3, mpcf_strfold, mpc_char('a'), mpc_char('b'), mpc_char('c'), free, free);` would attempt to match `'a'` followed by `'b'` followed by `'c'`, and if successful would concatenate them using `mpcf_strfold`. Otherwise would use `free` on the partial results. 388 | 389 | * * * 390 | 391 | ```c 392 | mpc_parser_t *mpc_predictive(mpc_parser_t *a); 393 | ``` 394 | 395 | Returns a parser that runs `a` with backtracking disabled. This means if `a` consumes more than one character, it will not be reverted, even on failure. Turning backtracking off has good performance benefits for grammars which are `LL(1)`. These are grammars where the first character completely determines the parse result - such as the decision of parsing either a C identifier, number, or string literal. This option should not be used for non `LL(1)` grammars or it will produce incorrect results or crash the parser. 396 | 397 | Another way to think of `mpc_predictive` is that it can be applied to a parser (for a performance improvement) if either successfully parsing the first character will result in a completely successful parse, or all of the referenced sub-parsers are also `LL(1)`. 398 | 399 | 400 | Function Types 401 | -------------- 402 | 403 | The combinator functions take a number of special function types as function pointers. Here is a short explanation of those types are how they are expected to behave. It is important that these behave correctly otherwise it is easy to introduce memory leaks or crashes into the system. 404 | 405 | * * * 406 | 407 | ```c 408 | typedef void(*mpc_dtor_t)(mpc_val_t*); 409 | ``` 410 | 411 | Given some pointer to a data value it will ensure the memory it points to is freed correctly. 412 | 413 | * * * 414 | 415 | ```c 416 | typedef mpc_val_t*(*mpc_ctor_t)(void); 417 | ``` 418 | 419 | Returns some data value when called. It can be used to create _empty_ versions of data types when certain combinators have no known default value to return. For example it may be used to return a newly allocated empty string. 420 | 421 | * * * 422 | 423 | ```c 424 | typedef mpc_val_t*(*mpc_apply_t)(mpc_val_t*); 425 | typedef mpc_val_t*(*mpc_apply_to_t)(mpc_val_t*,void*); 426 | ``` 427 | 428 | This takes in some pointer to data and outputs some new or modified pointer to data, ensuring to free the input data if it is no longer used. The `apply_to` variation takes in an extra pointer to some data such as global state. 429 | 430 | * * * 431 | 432 | ```c 433 | typedef int(*mpc_check_t)(mpc_val_t**); 434 | typedef int(*mpc_check_with_t)(mpc_val_t**,void*); 435 | ``` 436 | 437 | This takes in some pointer to data and outputs 0 if parsing should stop with an error. Additionally, this may change or free the input data. The `check_with` variation takes in an extra pointer to some data such as global state. 438 | 439 | * * * 440 | 441 | ```c 442 | typedef mpc_val_t*(*mpc_fold_t)(int,mpc_val_t**); 443 | ``` 444 | 445 | This takes a list of pointers to data values and must return some combined or folded version of these data values. It must ensure to free any input data that is no longer used once the combination has taken place. 446 | 447 | 448 | Case Study - Identifier 449 | ======================= 450 | 451 | Combinator Method 452 | ----------------- 453 | 454 | Using the above combinators we can create a parser that matches a C identifier. 455 | 456 | When using the combinators we need to supply a function that says how to combine two `char *`. 457 | 458 | For this we build a fold function that will concatenate zero or more strings together. For this sake of this tutorial we will write it by hand, but this (as well as many other useful fold functions), are actually included in _mpc_ under the `mpcf_*` namespace, such as `mpcf_strfold`. 459 | 460 | ```c 461 | mpc_val_t *strfold(int n, mpc_val_t **xs) { 462 | char *x = calloc(1, 1); 463 | int i; 464 | for (i = 0; i < n; i++) { 465 | x = realloc(x, strlen(x) + strlen(xs[i]) + 1); 466 | strcat(x, xs[i]); 467 | free(xs[i]); 468 | } 469 | return x; 470 | } 471 | ``` 472 | 473 | We can use this to specify a C identifier, making use of some combinators to say how the basic parsers are combined. 474 | 475 | ```c 476 | mpc_parser_t *alpha = mpc_or(2, mpc_range('a', 'z'), mpc_range('A', 'Z')); 477 | mpc_parser_t *digit = mpc_range('0', '9'); 478 | mpc_parser_t *underscore = mpc_char('_'); 479 | 480 | mpc_parser_t *ident = mpc_and(2, strfold, 481 | mpc_or(2, alpha, underscore), 482 | mpc_many(strfold, mpc_or(3, alpha, digit, underscore)), 483 | free); 484 | 485 | /* Do Some Parsing... */ 486 | 487 | mpc_delete(ident); 488 | ``` 489 | 490 | Notice that previous parsers are used as input to new parsers we construct from the combinators. Note that only the final parser `ident` must be deleted. When we input a parser into a combinator we should consider it to be part of the output of that combinator. 491 | 492 | Because of this we shouldn't create a parser and input it into multiple places, or it will be doubly freed. 493 | 494 | 495 | Regex Method 496 | ------------ 497 | 498 | There is an easier way to do this than the above method. _mpc_ comes with a handy regex function for constructing parsers using regex syntax. We can specify an identifier using a regex pattern as shown below. 499 | 500 | ```c 501 | mpc_parser_t *ident = mpc_re("[a-zA-Z_][a-zA-Z_0-9]*"); 502 | 503 | /* Do Some Parsing... */ 504 | 505 | mpc_delete(ident); 506 | ``` 507 | 508 | 509 | Library Method 510 | -------------- 511 | 512 | Although if we really wanted to create a parser for C identifiers, a function for creating this parser comes included in _mpc_ along with many other common parsers. 513 | 514 | ```c 515 | mpc_parser_t *ident = mpc_ident(); 516 | 517 | /* Do Some Parsing... */ 518 | 519 | mpc_delete(ident); 520 | ``` 521 | 522 | Parser References 523 | ================= 524 | 525 | Building parsers in the above way can have issues with self-reference or cyclic-reference. To overcome this we can separate the construction of parsers into two different steps. Construction and Definition. 526 | 527 | * * * 528 | 529 | ```c 530 | mpc_parser_t *mpc_new(const char *name); 531 | ``` 532 | 533 | This will construct a parser called `name` which can then be used as input to others, including itself, without fear of being deleted. Any parser created using `mpc_new` is said to be _retained_. This means it will behave differently to a normal parser when referenced. When deleting a parser that includes a _retained_ parser, the _retained_ parser will not be deleted along with it. To delete a retained parser `mpc_delete` must be used on it directly. 534 | 535 | A _retained_ parser can then be _defined_ using... 536 | 537 | * * * 538 | 539 | ```c 540 | mpc_parser_t *mpc_define(mpc_parser_t *p, mpc_parser_t *a); 541 | ``` 542 | 543 | This assigns the contents of parser `a` to `p`, and deletes `a`. With this technique parsers can now reference each other, as well as themselves, without trouble. 544 | 545 | * * * 546 | 547 | ```c 548 | mpc_parser_t *mpc_undefine(mpc_parser_t *p); 549 | ``` 550 | 551 | A final step is required. Parsers that reference each other must all be undefined before they are deleted. It is important to do any undefining before deletion. The reason for this is that to delete a parser it must look at each sub-parser that is used by it. If any of these have already been deleted a segfault is unavoidable - even if they were retained beforehand. 552 | 553 | * * * 554 | 555 | ```c 556 | void mpc_cleanup(int n, ...); 557 | ``` 558 | 559 | To ease the task of undefining and then deleting parsers `mpc_cleanup` can be used. It takes `n` parsers as input, and undefines them all, before deleting them all. 560 | 561 | * * * 562 | 563 | ```c 564 | mpc_parser_t *mpc_copy(mpc_parser_t *a); 565 | ``` 566 | 567 | This function makes a copy of a parser `a`. This can be useful when you want to 568 | use a parser as input for some other parsers multiple times without retaining 569 | it. 570 | 571 | * * * 572 | 573 | ```c 574 | mpc_parser_t *mpc_re(const char *re); 575 | mpc_parser_t *mpc_re_mode(const char *re, int mode); 576 | ``` 577 | 578 | This function takes as input the regular expression `re` and builds a parser 579 | for it. With the `mpc_re_mode` function optional mode flags can also be given. 580 | Available flags are `MPC_RE_MULTILINE` / `MPC_RE_M` where the start of input 581 | character `^` also matches the beginning of new lines and the end of input `$` 582 | character also matches new lines, and `MPC_RE_DOTALL` / `MPC_RE_S` where the 583 | any character token `.` also matches newlines (by default it doesn't). 584 | 585 | 586 | Library Reference 587 | ================= 588 | 589 | Common Parsers 590 | -------------- 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | 605 | 606 | 607 | 608 | 609 | 610 | 611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 623 | 624 | 625 | 626 | 627 |
mpc_soiMatches only the start of input, returns NULL
mpc_eoiMatches only the end of input, returns NULL
mpc_boundaryMatches only the boundary between words, returns NULL
mpc_boundary_newlineMatches the start of a new line, returns NULL
mpc_whitespaceMatches any whitespace character " \f\n\r\t\v"
mpc_whitespacesMatches zero or more whitespace characters
mpc_blankMatches whitespaces and frees the result, returns NULL
mpc_newlineMatches '\n'
mpc_tabMatches '\t'
mpc_escapeMatches a backslash followed by any character
mpc_digitMatches any character in the range '0' - '9'
mpc_hexdigitMatches any character in the range '0 - '9' as well as 'A' - 'F' and 'a' - 'f'
mpc_octdigitMatches any character in the range '0' - '7'
mpc_digitsMatches one or more digit
mpc_hexdigitsMatches one or more hexdigit
mpc_octdigitsMatches one or more octdigit
mpc_lowerMatches any lower case character
mpc_upperMatches any upper case character
mpc_alphaMatches any alphabet character
mpc_underscoreMatches '_'
mpc_alphanumMatches any alphabet character, underscore or digit
mpc_intMatches digits and returns an int*
mpc_hexMatches hexdigits and returns an int*
mpc_octMatches octdigits and returns an int*
mpc_numberMatches mpc_int, mpc_hex or mpc_oct
mpc_realMatches some floating point number as a string
mpc_floatMatches some floating point number and returns a float*
mpc_char_litMatches some character literal surrounded by '
mpc_string_litMatches some string literal surrounded by "
mpc_regex_litMatches some regex literal surrounded by /
mpc_identMatches a C style identifier
628 | 629 | 630 | Useful Parsers 631 | -------------- 632 | 633 | 634 | 635 | 636 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 | 652 | 653 | 654 | 655 |
mpc_startswith(mpc_parser_t *a);Matches the start of input followed by a
mpc_endswith(mpc_parser_t *a, mpc_dtor_t da);Matches a followed by the end of input
mpc_whole(mpc_parser_t *a, mpc_dtor_t da);Matches the start of input, a, and the end of input
mpc_stripl(mpc_parser_t *a);Matches a first consuming any whitespace to the left
mpc_stripr(mpc_parser_t *a);Matches a then consumes any whitespace to the right
mpc_strip(mpc_parser_t *a);Matches a consuming any surrounding whitespace
mpc_tok(mpc_parser_t *a);Matches a and consumes any trailing whitespace
mpc_sym(const char *s);Matches string s and consumes any trailing whitespace
mpc_total(mpc_parser_t *a, mpc_dtor_t da);Matches the whitespace consumed a, enclosed in the start and end of input
mpc_between(mpc_parser_t *a, mpc_dtor_t ad,
const char *o, const char *c);
Matches a between strings o and c
mpc_parens(mpc_parser_t *a, mpc_dtor_t ad);Matches a between "(" and ")"
mpc_braces(mpc_parser_t *a, mpc_dtor_t ad);Matches a between "<" and ">"
mpc_brackets(mpc_parser_t *a, mpc_dtor_t ad);Matches a between "{" and "}"
mpc_squares(mpc_parser_t *a, mpc_dtor_t ad);Matches a between "[" and "]"
mpc_tok_between(mpc_parser_t *a, mpc_dtor_t ad,
const char *o, const char *c);
Matches a between o and c, where o and c have their trailing whitespace striped.
mpc_tok_parens(mpc_parser_t *a, mpc_dtor_t ad);Matches a between trailing whitespace consumed "(" and ")"
mpc_tok_braces(mpc_parser_t *a, mpc_dtor_t ad);Matches a between trailing whitespace consumed "<" and ">"
mpc_tok_brackets(mpc_parser_t *a, mpc_dtor_t ad);Matches a between trailing whitespace consumed "{" and "}"
mpc_tok_squares(mpc_parser_t *a, mpc_dtor_t ad);Matches a between trailing whitespace consumed "[" and "]"
656 | 657 | 658 | Apply Functions 659 | --------------- 660 | 661 | 662 | 663 | 664 | 665 | 666 | 667 | 668 | 669 | 670 | 671 | 672 | 673 | 674 | 675 | 676 | 677 | 678 | 679 | 680 | 681 | 682 |
void mpcf_dtor_null(mpc_val_t *x);Empty destructor. Does nothing
mpc_val_t *mpcf_ctor_null(void);Returns NULL
mpc_val_t *mpcf_ctor_str(void);Returns ""
mpc_val_t *mpcf_free(mpc_val_t *x);Frees x and returns NULL
mpc_val_t *mpcf_int(mpc_val_t *x);Converts a decimal string x to an int*
mpc_val_t *mpcf_hex(mpc_val_t *x);Converts a hex string x to an int*
mpc_val_t *mpcf_oct(mpc_val_t *x);Converts a oct string x to an int*
mpc_val_t *mpcf_float(mpc_val_t *x);Converts a string x to a float*
mpc_val_t *mpcf_escape(mpc_val_t *x);Converts a string x to an escaped version
mpc_val_t *mpcf_escape_regex(mpc_val_t *x);Converts a regex x to an escaped version
mpc_val_t *mpcf_escape_string_raw(mpc_val_t *x);Converts a raw string x to an escaped version
mpc_val_t *mpcf_escape_char_raw(mpc_val_t *x);Converts a raw character x to an escaped version
mpc_val_t *mpcf_unescape(mpc_val_t *x);Converts a string x to an unescaped version
mpc_val_t *mpcf_unescape_regex(mpc_val_t *x);Converts a regex x to an unescaped version
mpc_val_t *mpcf_unescape_string_raw(mpc_val_t *x);Converts a raw string x to an unescaped version
mpc_val_t *mpcf_unescape_char_raw(mpc_val_t *x);Converts a raw character x to an unescaped version
mpc_val_t *mpcf_strtriml(mpc_val_t *x);Trims whitespace from the left of string x
mpc_val_t *mpcf_strtrimr(mpc_val_t *x);Trims whitespace from the right of string x
mpc_val_t *mpcf_strtrim(mpc_val_t *x);Trims whitespace from either side of string x
683 | 684 | 685 | Fold Functions 686 | -------------- 687 | 688 | 689 | 690 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 | 700 | 701 |
mpc_val_t *mpcf_null(int n, mpc_val_t** xs);Returns NULL
mpc_val_t *mpcf_fst(int n, mpc_val_t** xs);Returns first element of xs
mpc_val_t *mpcf_snd(int n, mpc_val_t** xs);Returns second element of xs
mpc_val_t *mpcf_trd(int n, mpc_val_t** xs);Returns third element of xs
mpc_val_t *mpcf_fst_free(int n, mpc_val_t** xs);Returns first element of xs and calls free on others
mpc_val_t *mpcf_snd_free(int n, mpc_val_t** xs);Returns second element of xs and calls free on others
mpc_val_t *mpcf_trd_free(int n, mpc_val_t** xs);Returns third element of xs and calls free on others
mpc_val_t *mpcf_all_free(int n, mpc_val_t** xs);Calls free on all elements of xs and returns NULL
mpc_val_t *mpcf_strfold(int n, mpc_val_t** xs);Concatenates all xs together as strings and returns result
702 | 703 | 704 | Case Study - Maths Language 705 | =========================== 706 | 707 | Combinator Approach 708 | ------------------- 709 | 710 | Passing around all these function pointers might seem clumsy, but having parsers be type-generic is important as it lets users define their own output types for parsers. For example we could design our own syntax tree type to use. We can also use this method to do some specific house-keeping or data processing in the parsing phase. 711 | 712 | As an example of this power, we can specify a simple maths grammar, that outputs `int *`, and computes the result of the expression as it goes along. 713 | 714 | We start with a fold function that will fold two `int *` into a new `int *` based on some `char *` operator. 715 | 716 | ```c 717 | mpc_val_t *fold_maths(int n, mpc_val_t **xs) { 718 | 719 | int **vs = (int**)xs; 720 | 721 | if (strcmp(xs[1], "*") == 0) { *vs[0] *= *vs[2]; } 722 | if (strcmp(xs[1], "/") == 0) { *vs[0] /= *vs[2]; } 723 | if (strcmp(xs[1], "%") == 0) { *vs[0] %= *vs[2]; } 724 | if (strcmp(xs[1], "+") == 0) { *vs[0] += *vs[2]; } 725 | if (strcmp(xs[1], "-") == 0) { *vs[0] -= *vs[2]; } 726 | 727 | free(xs[1]); free(xs[2]); 728 | 729 | return xs[0]; 730 | } 731 | ``` 732 | 733 | And then we use this to specify a basic grammar, which folds together any results. 734 | 735 | ```c 736 | mpc_parser_t *Expr = mpc_new("expr"); 737 | mpc_parser_t *Factor = mpc_new("factor"); 738 | mpc_parser_t *Term = mpc_new("term"); 739 | mpc_parser_t *Maths = mpc_new("maths"); 740 | 741 | mpc_define(Expr, mpc_or(2, 742 | mpc_and(3, fold_maths, 743 | Factor, mpc_oneof("+-"), Factor, 744 | free, free), 745 | Factor 746 | )); 747 | 748 | mpc_define(Factor, mpc_or(2, 749 | mpc_and(3, fold_maths, 750 | Term, mpc_oneof("*/"), Term, 751 | free, free), 752 | Term 753 | )); 754 | 755 | mpc_define(Term, mpc_or(2, mpc_int(), mpc_parens(Expr, free))); 756 | mpc_define(Maths, mpc_whole(Expr, free)); 757 | 758 | /* Do Some Parsing... */ 759 | 760 | mpc_delete(Maths); 761 | ``` 762 | 763 | If we supply this function with something like `(4*2)+5`, we can expect it to output `13`. 764 | 765 | 766 | Language Approach 767 | ----------------- 768 | 769 | It is possible to avoid passing in and around all those function pointers, if you don't care what type is output by _mpc_. For this, a generic Abstract Syntax Tree type `mpc_ast_t` is included in _mpc_. The combinator functions which act on this don't need information on how to destruct or fold instances of the result as they know it will be a `mpc_ast_t`. So there are a number of combinator functions which work specifically (and only) on parsers that return this type. They reside under `mpca_*`. 770 | 771 | Doing things via this method means that all the data processing must take place after the parsing. In many instances this is not an issue, or even preferable. 772 | 773 | It also allows for one more trick. As all the fold and destructor functions are implicit, the user can simply specify the grammar of the language in some nice way and the system can try to build a parser for the AST type from this alone. For this there are a few functions supplied which take in a string, and output a parser. The format for these grammars is simple and familiar to those who have used parser generators before. It looks something like this. 774 | 775 | ``` 776 | number "number" : /[0-9]+/ ; 777 | expression : (('+' | '-') )* ; 778 | product : (('*' | '/') )* ; 779 | value : | '(' ')' ; 780 | maths : /^/ /$/ ; 781 | ``` 782 | 783 | The syntax for this is defined as follows. 784 | 785 | 786 | 787 | 788 | 789 | 790 | 791 | 792 | 793 | 794 | 795 |
"ab"The string ab is required.
'a'The character a is required.
'a' 'b'First 'a' is required, then 'b' is required..
'a' | 'b'Either 'a' is required, or 'b' is required.
'a'*Zero or more 'a' are required.
'a'+One or more 'a' are required.
'a'?Zero or one 'a' is required.
'a'{x}Exactly x (integer) copies of 'a' are required.
<abba>The rule called abba is required.
796 | 797 | Rules are specified by rule name, optionally followed by an _expected_ string, followed by a colon `:`, followed by the definition, and ending in a semicolon `;`. Multiple rules can be specified. The _rule names_ must match the names given to any parsers created by `mpc_new`, otherwise the function will crash. 798 | 799 | The flags variable is a set of flags `MPCA_LANG_DEFAULT`, `MPCA_LANG_PREDICTIVE`, or `MPCA_LANG_WHITESPACE_SENSITIVE`. For specifying if the language is predictive or whitespace sensitive. 800 | 801 | Like with the regular expressions, this user input is parsed by existing parts of the _mpc_ library. It provides one of the more powerful features of the library. 802 | 803 | * * * 804 | 805 | ```c 806 | mpc_parser_t *mpca_grammar(int flags, const char *grammar, ...); 807 | ``` 808 | 809 | This takes in some single right hand side of a rule, as well as a list of any of the parsers referenced, and outputs a parser that does what is specified by the rule. The list of parsers referenced can be terminated with `NULL` to get an error instead of a crash when a parser required is not supplied. 810 | 811 | * * * 812 | 813 | ```c 814 | mpc_err_t *mpca_lang(int flags, const char *lang, ...); 815 | ``` 816 | 817 | This takes in a full language (zero or more rules) as well as any parsers referred to by either the right or left hand sides. Any parsers specified on the left hand side of any rule will be assigned a parser equivalent to what is specified on the right. On valid user input this returns `NULL`, while if there are any errors in the user input it will return an instance of `mpc_err_t` describing the issues. The list of parsers referenced can be terminated with `NULL` to get an error instead of a crash when a parser required is not supplied. 818 | 819 | * * * 820 | 821 | ```c 822 | mpc_err_t *mpca_lang_file(int flags, FILE* f, ...); 823 | ``` 824 | 825 | This reads in the contents of file `f` and inputs it into `mpca_lang`. 826 | 827 | * * * 828 | 829 | ```c 830 | mpc_err_t *mpca_lang_contents(int flags, const char *filename, ...); 831 | ``` 832 | 833 | This opens and reads in the contents of the file given by `filename` and passes it to `mpca_lang`. 834 | 835 | Case Study - Tokenizer 836 | ====================== 837 | 838 | Another common task we might be interested in doing is tokenizing some block of 839 | text (splitting the text into individual elements) and performing some function 840 | on each one of these elements as it is read. We can do this with `mpc` too. 841 | 842 | First, we can build a regular expression which parses an individual token. For 843 | example if our tokens are identifiers, integers, commas, periods and colons we 844 | could build something like this `mpc_re("\\s*([a-zA-Z_]+|[0-9]+|,|\\.|:)")`. 845 | Next we can strip any whitespace, and add a callback function using `mpc_apply` 846 | which gets called every time this regex is parsed successfully 847 | `mpc_apply(mpc_strip(mpc_re("\\s*([a-zA-Z_]+|[0-9]+|,|\\.|:)")), print_token)`. 848 | Finally we can surround all of this in `mpc_many` to parse it zero or more 849 | times. The final code might look something like this: 850 | 851 | ```c 852 | static mpc_val_t *print_token(mpc_val_t *x) { 853 | printf("Token: '%s'\n", (char*)x); 854 | return x; 855 | } 856 | 857 | int main(int argc, char **argv) { 858 | 859 | const char *input = " hello 4352 , \n foo.bar \n\n test:ing "; 860 | 861 | mpc_parser_t* Tokens = mpc_many( 862 | mpcf_all_free, 863 | mpc_apply(mpc_strip(mpc_re("\\s*([a-zA-Z_]+|[0-9]+|,|\\.|:)")), print_token)); 864 | 865 | mpc_result_t r; 866 | mpc_parse("input", input, Tokens, &r); 867 | 868 | mpc_delete(Tokens); 869 | 870 | return 0; 871 | } 872 | ``` 873 | 874 | Running this program will produce an output something like this: 875 | 876 | ``` 877 | Token: 'hello' 878 | Token: '4352' 879 | Token: ',' 880 | Token: 'foo' 881 | Token: '.' 882 | Token: 'bar' 883 | Token: 'test' 884 | Token: ':' 885 | Token: 'ing' 886 | ``` 887 | 888 | By extending the regex we can easily extend this to parse many more types of 889 | tokens and quickly and easily build a tokenizer for whatever language we are 890 | interested in. 891 | 892 | 893 | Error Reporting 894 | =============== 895 | 896 | _mpc_ provides some automatic generation of error messages. These can be enhanced by the user, with use of `mpc_expect`, but many of the defaults should provide both useful and readable. An example of an error message might look something like this: 897 | 898 | ``` 899 | :0:3: error: expected one or more of 'a' or 'd' at 'k' 900 | ``` 901 | 902 | Misc 903 | ==== 904 | 905 | Here are some other misc functions that mpc provides. These functions are susceptible to change between versions so use them with some care. 906 | 907 | * * * 908 | 909 | ```c 910 | void mpc_print(mpc_parser_t *p); 911 | ``` 912 | 913 | Prints out a parser in some weird format. This is generally used for debugging so don't expect to be able to understand the output right away without looking at the source code a little bit. 914 | 915 | * * * 916 | 917 | ```c 918 | void mpc_stats(mpc_parser_t *p); 919 | ``` 920 | 921 | Prints out some basic stats about a parser. Again used for debugging and optimisation. 922 | 923 | * * * 924 | 925 | ```c 926 | void mpc_optimise(mpc_parser_t *p); 927 | ``` 928 | 929 | Performs some basic optimisations on a parser to reduce it's size and increase its running speed. 930 | 931 | 932 | Limitations & FAQ 933 | ================= 934 | 935 | ### I'm getting namespace issues due to `libmpc`, what can I do? 936 | 937 | There is a re-naming of this project to `pcq` hosted on the [pcq branch](https://github.com/orangeduck/mpc/tree/pcq) which should be usable without namespace issues. 938 | 939 | ### Does _mpc_ support Unicode? 940 | 941 | _mpc_ Only supports ASCII. Sorry! Writing a parser library that supports Unicode is pretty difficult. I welcome contributions! 942 | 943 | 944 | ### Is _mpc_ binary safe? 945 | 946 | No. Sorry! Including NULL characters in a string or a file will probably break it. Avoid this if possible. 947 | 948 | 949 | ### The Parser is going into an infinite loop! 950 | 951 | While it is certainly possible there is an issue with _mpc_, it is probably the case that your grammar contains _left recursion_. This is something _mpc_ cannot deal with. _Left recursion_ is when a rule directly or indirectly references itself on the left hand side of a derivation. For example consider this left recursive grammar intended to parse an expression. 952 | 953 | ``` 954 | expr : '+' ( | | ); 955 | ``` 956 | 957 | When the rule `expr` is called, it looks the first rule on the left. This happens to be the rule `expr` again. So again it looks for the first rule on the left. Which is `expr` again. And so on. To avoid left recursion this can be rewritten (for example) as the following. Note that rewriting as follows also changes the operator associativity. 958 | 959 | ``` 960 | value : | ; 961 | expr : ('+' )* ; 962 | ``` 963 | 964 | Avoiding left recursion can be tricky, but is easy once you get a feel for it. For more information you can look on [wikipedia](http://en.wikipedia.org/wiki/Left_recursion) which covers some common techniques and more examples. Possibly in the future _mpc_ will support functionality to warn the user or re-write grammars which contain left recursion, but it wont for now. 965 | 966 | 967 | ### Backtracking isn't working! 968 | 969 | _mpc_ supports backtracking, but it may not work as you expect. It isn't a silver bullet, and you still must structure your grammar to be unambiguous. To demonstrate this behaviour examine the following erroneous grammar, intended to parse either a C style identifier, or a C style function call. 970 | 971 | ``` 972 | factor : 973 | | '(' ? (',' )* ')' ; 974 | ``` 975 | 976 | This grammar will never correctly parse a function call because it will always first succeed parsing the initial identifier and return a factor. At this point it will encounter the parenthesis of the function call, give up, and throw an error. Even if it were to try and parse a factor again on this failure it would never reach the correct function call option because it always tries the other options first, and always succeeds with the identifier. 977 | 978 | The solution to this is to always structure grammars with the most specific clause first, and more general clauses afterwards. This is the natural technique used for avoiding left-recursive grammars and unambiguity, so is a good habit to get into anyway. 979 | 980 | Now the parser will try to match a function first, and if this fails backtrack and try to match just an identifier. 981 | 982 | ``` 983 | factor : '(' ? (',' )* ')' 984 | | ; 985 | ``` 986 | 987 | An alternative, and better option is to remove the ambiguity completely by factoring out the first identifier. This is better because it removes any need for backtracking at all! Now the grammar is predictive! 988 | 989 | ``` 990 | factor : ('(' ? (',' )* ')')? ; 991 | ``` 992 | 993 | 994 | ### How can I avoid the maximum string literal length? 995 | 996 | Some compilers limit the maximum length of string literals. If you have a huge language string in the source file to be passed into `mpca_lang` you might encounter this. The ANSI standard says that 509 is the maximum length allowed for a string literal. Most compilers support greater than this. Visual Studio supports up to 2048 characters, while gcc allocates memory dynamically and so has no real limit. 997 | 998 | There are a couple of ways to overcome this issue if it arises. You could instead use `mpca_lang_contents` and load the language from file or you could use a string literal for each line and let the preprocessor automatically concatenate them together, avoiding the limit. The final option is to upgrade your compiler. In C99 this limit has been increased to 4095. 999 | 1000 | 1001 | ### The automatic tags in the AST are annoying! 1002 | 1003 | When parsing from a grammar, the abstract syntax tree is tagged with different tags for each primitive type it encounters. For example a regular expression will be automatically tagged as `regex`. Character literals as `char` and strings as `string`. This is to help people wondering exactly how they might need to convert the node contents. 1004 | 1005 | If you have a rule in your grammar called `string`, `char` or `regex`, you may encounter some confusion. This is because nodes will be tagged with (for example) `string` _either_ if they are a string primitive, _or_ if they were parsed via your `string` rule. If you are detecting node type using something like `strstr`, in this situation it might break. One solution to this is to always check that `string` is the innermost tag to test for string primitives, or to rename your rule called `string` to something that doesn't conflict. 1006 | 1007 | Yes it is annoying but its probably not going to change! 1008 | -------------------------------------------------------------------------------- /examples/book.doge: -------------------------------------------------------------------------------- 1 | wow c so language such book -------------------------------------------------------------------------------- /examples/doge.c: -------------------------------------------------------------------------------- 1 | #include "../mpc.h" 2 | 3 | int main(int argc, char **argv) { 4 | 5 | mpc_result_t r; 6 | 7 | mpc_parser_t* Adjective = mpc_new("adjective"); 8 | mpc_parser_t* Noun = mpc_new("noun"); 9 | mpc_parser_t* Phrase = mpc_new("phrase"); 10 | mpc_parser_t* Doge = mpc_new("doge"); 11 | 12 | mpca_lang(MPCA_LANG_DEFAULT, 13 | " adjective : \"wow\" | \"many\" | \"so\" | \"such\"; " 14 | " noun : \"lisp\" | \"language\" | \"c\" | \"book\" | \"build\"; " 15 | " phrase : ; " 16 | " doge : /^/ * /$/; ", 17 | Adjective, Noun, Phrase, Doge, NULL); 18 | 19 | if (argc > 1) { 20 | 21 | if (mpc_parse_contents(argv[1], Doge, &r)) { 22 | mpc_ast_print(r.output); 23 | mpc_ast_delete(r.output); 24 | } else { 25 | mpc_err_print(r.error); 26 | mpc_err_delete(r.error); 27 | } 28 | 29 | } else { 30 | 31 | if (mpc_parse_pipe("", stdin, Doge, &r)) { 32 | mpc_ast_print(r.output); 33 | mpc_ast_delete(r.output); 34 | } else { 35 | mpc_err_print(r.error); 36 | mpc_err_delete(r.error); 37 | } 38 | 39 | } 40 | 41 | mpc_cleanup(4, Adjective, Noun, Phrase, Doge); 42 | 43 | return 0; 44 | 45 | } 46 | 47 | -------------------------------------------------------------------------------- /examples/fib.smallc: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | 3 | int fib(int n) { 4 | if (n == 0) { return 0; } 5 | if (n == 1) { return 1; } 6 | return fib(n - 1) + fib(n - 2); 7 | } 8 | 9 | main() { 10 | 11 | int n; 12 | int i; 13 | 14 | while (i < 10) { 15 | n = fib(10); 16 | print(n); 17 | i = i + 1; 18 | } 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /examples/foobar.c: -------------------------------------------------------------------------------- 1 | #include "../mpc.h" 2 | 3 | int main(int argc, char** argv) { 4 | 5 | mpc_result_t r; 6 | mpc_parser_t* Foobar; 7 | 8 | if (argc != 2) { 9 | printf("Usage: ./foobar \n"); 10 | exit(0); 11 | } 12 | 13 | Foobar = mpc_new("foobar"); 14 | mpca_lang(MPCA_LANG_DEFAULT, "foobar : \"foo\" | \"bar\";", Foobar); 15 | 16 | if (mpc_parse("", argv[1], Foobar, &r)) { 17 | mpc_ast_print(r.output); 18 | mpc_ast_delete(r.output); 19 | } else { 20 | mpc_err_print(r.error); 21 | mpc_err_delete(r.error); 22 | } 23 | 24 | mpc_cleanup(1, Foobar); 25 | 26 | return 0; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /examples/line_reader.c: -------------------------------------------------------------------------------- 1 | #include "../mpc.h" 2 | 3 | static void* read_line(void* line) { 4 | printf("Reading Line: %s", (char*)line); 5 | return line; 6 | } 7 | 8 | int main(int argc, char **argv) { 9 | 10 | const char *input = 11 | "abcHVwufvyuevuy3y436782\n" 12 | "\n" 13 | "\n" 14 | "rehre\n" 15 | "rew\n" 16 | "-ql.;qa\n" 17 | "eg"; 18 | 19 | mpc_parser_t* Line = mpc_many( 20 | mpcf_strfold, 21 | mpc_apply(mpc_re("[^\\n]*(\\n|$)"), read_line)); 22 | 23 | mpc_result_t r; 24 | 25 | (void)argc; (void)argv; 26 | 27 | mpc_parse("input", input, Line, &r); 28 | printf("\nParsed String: %s", (char*)r.output); 29 | free(r.output); 30 | 31 | mpc_delete(Line); 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /examples/lispy.c: -------------------------------------------------------------------------------- 1 | #include "../mpc.h" 2 | 3 | int main(int argc, char **argv) { 4 | 5 | mpc_result_t r; 6 | 7 | mpc_parser_t* Number = mpc_new("number"); 8 | mpc_parser_t* Symbol = mpc_new("symbol"); 9 | mpc_parser_t* String = mpc_new("string"); 10 | mpc_parser_t* Comment = mpc_new("comment"); 11 | mpc_parser_t* Sexpr = mpc_new("sexpr"); 12 | mpc_parser_t* Qexpr = mpc_new("qexpr"); 13 | mpc_parser_t* Expr = mpc_new("expr"); 14 | mpc_parser_t* Lispy = mpc_new("lispy"); 15 | 16 | mpca_lang(MPCA_LANG_PREDICTIVE, 17 | " number \"number\" : /[0-9]+/ ; " 18 | " symbol \"symbol\" : /[a-zA-Z0-9_+\\-*\\/\\\\=<>!&]+/ ; " 19 | " string \"string\" : /\"(\\\\.|[^\"])*\"/ ; " 20 | " comment : /;[^\\r\\n]*/ ; " 21 | " sexpr : '(' * ')' ; " 22 | " qexpr : '{' * '}' ; " 23 | " expr : | | " 24 | " | | | ; " 25 | " lispy : /^/ * /$/ ; ", 26 | Number, Symbol, String, Comment, Sexpr, Qexpr, Expr, Lispy, NULL); 27 | 28 | if (argc > 1) { 29 | 30 | if (mpc_parse_contents(argv[1], Lispy, &r)) { 31 | mpc_ast_print(r.output); 32 | mpc_ast_delete(r.output); 33 | } else { 34 | mpc_err_print(r.error); 35 | mpc_err_delete(r.error); 36 | } 37 | 38 | } else { 39 | 40 | if (mpc_parse_pipe("", stdin, Lispy, &r)) { 41 | mpc_ast_print(r.output); 42 | mpc_ast_delete(r.output); 43 | } else { 44 | mpc_err_print(r.error); 45 | mpc_err_delete(r.error); 46 | } 47 | 48 | } 49 | 50 | mpc_cleanup(8, Number, Symbol, String, Comment, Sexpr, Qexpr, Expr, Lispy); 51 | 52 | return 0; 53 | 54 | } 55 | 56 | -------------------------------------------------------------------------------- /examples/maths.c: -------------------------------------------------------------------------------- 1 | #include "../mpc.h" 2 | 3 | int main(int argc, char **argv) { 4 | 5 | mpc_parser_t *Expr = mpc_new("expression"); 6 | mpc_parser_t *Prod = mpc_new("product"); 7 | mpc_parser_t *Value = mpc_new("value"); 8 | mpc_parser_t *Maths = mpc_new("maths"); 9 | 10 | mpca_lang(MPCA_LANG_PREDICTIVE, 11 | " expression : (('+' | '-') )*; " 12 | " product : (('*' | '/') )*; " 13 | " value : /[0-9]+/ | '(' ')'; " 14 | " maths : /^/ /$/; ", 15 | Expr, Prod, Value, Maths, NULL); 16 | 17 | mpc_print(Expr); 18 | mpc_print(Prod); 19 | mpc_print(Value); 20 | mpc_print(Maths); 21 | 22 | if (argc > 1) { 23 | 24 | mpc_result_t r; 25 | if (mpc_parse_contents(argv[1], Maths, &r)) { 26 | mpc_ast_print(r.output); 27 | mpc_ast_delete(r.output); 28 | } else { 29 | mpc_err_print(r.error); 30 | mpc_err_delete(r.error); 31 | } 32 | 33 | } else { 34 | 35 | mpc_result_t r; 36 | if (mpc_parse_pipe("", stdin, Maths, &r)) { 37 | mpc_ast_print(r.output); 38 | mpc_ast_delete(r.output); 39 | } else { 40 | mpc_err_print(r.error); 41 | mpc_err_delete(r.error); 42 | } 43 | 44 | } 45 | 46 | mpc_cleanup(4, Expr, Prod, Value, Maths); 47 | 48 | return 0; 49 | 50 | } 51 | 52 | -------------------------------------------------------------------------------- /examples/minimal.smallc: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | 3 | main() { 4 | 5 | int i; 6 | int j; 7 | 8 | j = 10; 9 | 10 | return 0; 11 | } -------------------------------------------------------------------------------- /examples/prelude.lspy: -------------------------------------------------------------------------------- 1 | ;;; 2 | ;;; Lispy Standard Prelude 3 | ;;; 4 | 5 | ;;; Atoms 6 | (def {nil} {}) 7 | (def {true} 1) 8 | (def {false} 0) 9 | 10 | ;;; Functional Functions 11 | 12 | ; Function Definitions 13 | (def {fun} (\ {f b} { 14 | def (head f) (\ (tail f) b) 15 | })) 16 | 17 | ; Open new scope 18 | (fun {let b} { 19 | ((\ {_} b) ()) 20 | }) 21 | 22 | ; Unpack List to Function 23 | (fun {unpack f l} { 24 | eval (join (list f) l) 25 | }) 26 | 27 | ; Unapply List to Function 28 | (fun {pack f & xs} {f xs}) 29 | 30 | ; Curried and Uncurried calling 31 | (def {curry} {unpack}) 32 | (def {uncurry} {pack}) 33 | 34 | ; Perform Several things in Sequence 35 | (fun {do & l} { 36 | if (== l {}) 37 | {{}} 38 | {last l} 39 | }) 40 | 41 | ;;; Logical Functions 42 | 43 | ; Logical Functions 44 | (fun {not x} {- 1 x}) 45 | (fun {or x y} {+ x y}) 46 | (fun {and x y} {* x y}) 47 | 48 | 49 | ;;; Numeric Functions 50 | 51 | ; Minimum of Arguments 52 | (fun {min & xs} { 53 | if (== (tail xs) {}) {fst xs} 54 | {do 55 | (= {rest} (unpack min (tail xs))) 56 | (= {item} (fst xs)) 57 | (if (< item rest) {item} {rest}) 58 | } 59 | }) 60 | 61 | ; Minimum of Arguments 62 | (fun {max & xs} { 63 | if (== (tail xs) {}) {fst xs} 64 | {do 65 | (= {rest} (unpack max (tail xs))) 66 | (= {item} (fst xs)) 67 | (if (> item rest) {item} {rest}) 68 | } 69 | }) 70 | 71 | ;;; Conditional Functions 72 | 73 | (fun {select & cs} { 74 | if (== cs {}) 75 | {error "No Selection Found"} 76 | {if (fst (fst cs)) {snd (fst cs)} {unpack select (tail cs)}} 77 | }) 78 | 79 | (fun {case x & cs} { 80 | if (== cs {}) 81 | {error "No Case Found"} 82 | {if (== x (fst (fst cs))) {snd (fst cs)} {unpack case (join (list x) (tail cs))}} 83 | }) 84 | 85 | (def {otherwise} true) 86 | 87 | 88 | ;;; Misc Functions 89 | 90 | (fun {flip f a b} {f b a}) 91 | (fun {ghost & xs} {eval xs}) 92 | (fun {comp f g x} {f (g x)}) 93 | 94 | ;;; List Functions 95 | 96 | ; First, Second, or Third Item in List 97 | (fun {fst l} { eval (head l) }) 98 | (fun {snd l} { eval (head (tail l)) }) 99 | (fun {trd l} { eval (head (tail (tail l))) }) 100 | 101 | ; List Length 102 | (fun {len l} { 103 | if (== l {}) 104 | {0} 105 | {+ 1 (len (tail l))} 106 | }) 107 | 108 | ; Nth item in List 109 | (fun {nth n l} { 110 | if (== n 0) 111 | {fst l} 112 | {nth (- n 1) (tail l)} 113 | }) 114 | 115 | ; Last item in List 116 | (fun {last l} {nth (- (len l) 1) l}) 117 | 118 | ; Apply Function to List 119 | (fun {map f l} { 120 | if (== l {}) 121 | {{}} 122 | {join (list (f (fst l))) (map f (tail l))} 123 | }) 124 | 125 | ; Apply Filter to List 126 | (fun {filter f l} { 127 | if (== l {}) 128 | {{}} 129 | {join (if (f (fst l)) {head l} {{}}) (filter f (tail l))} 130 | }) 131 | 132 | ; Return all of list but last element 133 | (fun {init l} { 134 | if (== (tail l) {}) 135 | {{}} 136 | {join (head l) (init (tail l))} 137 | }) 138 | 139 | ; Reverse List 140 | (fun {reverse l} { 141 | if (== l {}) 142 | {{}} 143 | {join (reverse (tail l)) (head l)} 144 | }) 145 | 146 | ; Fold Left 147 | (fun {foldl f z l} { 148 | if (== l {}) 149 | {z} 150 | {foldl f (f z (fst l)) (tail l)} 151 | }) 152 | 153 | ; Fold Right 154 | (fun {foldr f z l} { 155 | if (== l {}) 156 | {z} 157 | {f (fst l) (foldr f z (tail l))} 158 | }) 159 | 160 | (fun {sum l} {foldl + 0 l}) 161 | (fun {product l} {foldl * 1 l}) 162 | 163 | ; Take N items 164 | (fun {take n l} { 165 | if (== n 0) 166 | {{}} 167 | {join (head l) (take (- n 1) (tail l))} 168 | }) 169 | 170 | ; Drop N items 171 | (fun {drop n l} { 172 | if (== n 0) 173 | {l} 174 | {drop (- n 1) (tail l)} 175 | }) 176 | 177 | ; Split at N 178 | (fun {split n l} {list (take n l) (drop n l)}) 179 | 180 | ; Take While 181 | (fun {take-while f l} { 182 | if (not (unpack f (head l))) 183 | {{}} 184 | {join (head l) (take-while f (tail l))} 185 | }) 186 | 187 | ; Drop While 188 | (fun {drop-while f l} { 189 | if (not (unpack f (head l))) 190 | {l} 191 | {drop-while f (tail l)} 192 | }) 193 | 194 | ; Element of List 195 | (fun {elem x l} { 196 | if (== l {}) 197 | {false} 198 | {if (== x (fst l)) {true} {elem x (tail l)}} 199 | }) 200 | 201 | ; Find element in list of pairs 202 | (fun {lookup x l} { 203 | if (== l {}) 204 | {error "No Element Found"} 205 | {do 206 | (= {key} (fst (fst l))) 207 | (= {val} (snd (fst l))) 208 | (if (== key x) {val} {lookup x (tail l)}) 209 | } 210 | }) 211 | 212 | ; Zip two lists together into a list of pairs 213 | (fun {zip x y} { 214 | if (or (== x {}) (== y {})) 215 | {{}} 216 | {join (list (join (head x) (head y))) (zip (tail x) (tail y))} 217 | }) 218 | 219 | ; Unzip a list of pairs into two lists 220 | (fun {unzip l} { 221 | if (== l {}) 222 | {{{} {}}} 223 | {do 224 | (= {x} (fst l)) 225 | (= {xs} (unzip (tail l))) 226 | (list (join (head x) (fst xs)) (join (tail x) (snd xs))) 227 | } 228 | }) 229 | 230 | ;;; Other Fun 231 | 232 | ; Fibonacci 233 | (fun {fib n} { 234 | select 235 | { (== n 0) 0 } 236 | { (== n 1) 1 } 237 | { otherwise (+ (fib (- n 1)) (fib (- n 2))) } 238 | }) 239 | 240 | -------------------------------------------------------------------------------- /examples/readme.maths: -------------------------------------------------------------------------------- 1 | (4 * 2 * 11 + 2) - 5 -------------------------------------------------------------------------------- /examples/simple.maths: -------------------------------------------------------------------------------- 1 | 29 + 2 * 3 - 99 - (5 + 5 + 2) / 100 -------------------------------------------------------------------------------- /examples/smallc.c: -------------------------------------------------------------------------------- 1 | #include "../mpc.h" 2 | 3 | int main(int argc, char **argv) { 4 | 5 | mpc_parser_t* Ident = mpc_new("ident"); 6 | mpc_parser_t* Number = mpc_new("number"); 7 | mpc_parser_t* Character = mpc_new("character"); 8 | mpc_parser_t* String = mpc_new("string"); 9 | mpc_parser_t* Factor = mpc_new("factor"); 10 | mpc_parser_t* Term = mpc_new("term"); 11 | mpc_parser_t* Lexp = mpc_new("lexp"); 12 | mpc_parser_t* Stmt = mpc_new("stmt"); 13 | mpc_parser_t* Exp = mpc_new("exp"); 14 | mpc_parser_t* Typeident = mpc_new("typeident"); 15 | mpc_parser_t* Decls = mpc_new("decls"); 16 | mpc_parser_t* Args = mpc_new("args"); 17 | mpc_parser_t* Body = mpc_new("body"); 18 | mpc_parser_t* Procedure = mpc_new("procedure"); 19 | mpc_parser_t* Main = mpc_new("main"); 20 | mpc_parser_t* Includes = mpc_new("includes"); 21 | mpc_parser_t* Smallc = mpc_new("smallc"); 22 | 23 | mpc_err_t* err = mpca_lang(MPCA_LANG_DEFAULT, 24 | " ident : /[a-zA-Z_][a-zA-Z0-9_]*/ ; \n" 25 | " number : /[0-9]+/ ; \n" 26 | " character : /'.'/ ; \n" 27 | " string : /\"(\\\\.|[^\"])*\"/ ; \n" 28 | " \n" 29 | " factor : '(' ')' \n" 30 | " | \n" 31 | " | \n" 32 | " | \n" 33 | " | '(' ? (',' )* ')' \n" 34 | " | ; \n" 35 | " \n" 36 | " term : (('*' | '/' | '%') )* ; \n" 37 | " lexp : (('+' | '-') )* ; \n" 38 | " \n" 39 | " stmt : '{' * '}' \n" 40 | " | \"while\" '(' ')' \n" 41 | " | \"if\" '(' ')' \n" 42 | " | '=' ';' \n" 43 | " | \"print\" '(' ? ')' ';' \n" 44 | " | \"return\" ? ';' \n" 45 | " | '(' ? (',' )* ')' ';' ; \n" 46 | " \n" 47 | " exp : '>' \n" 48 | " | '<' \n" 49 | " | \">=\" \n" 50 | " | \"<=\" \n" 51 | " | \"!=\" \n" 52 | " | \"==\" ; \n" 53 | " \n" 54 | " typeident : (\"int\" | \"char\") ; \n" 55 | " decls : ( ';')* ; \n" 56 | " args : ? (',' )* ; \n" 57 | " body : '{' * '}' ; \n" 58 | " procedure : (\"int\" | \"char\") '(' ')' ; \n" 59 | " main : \"main\" '(' ')' ; \n" 60 | " includes : (\"#include\" )* ; \n" 61 | " smallc : /^/ *
/$/ ; \n", 62 | Ident, Number, Character, String, Factor, Term, Lexp, Stmt, Exp, 63 | Typeident, Decls, Args, Body, Procedure, Main, Includes, Smallc, NULL); 64 | 65 | if (err != NULL) { 66 | mpc_err_print(err); 67 | mpc_err_delete(err); 68 | exit(1); 69 | } 70 | 71 | if (argc > 1) { 72 | 73 | mpc_result_t r; 74 | if (mpc_parse_contents(argv[1], Smallc, &r)) { 75 | mpc_ast_print(r.output); 76 | mpc_ast_delete(r.output); 77 | } else { 78 | mpc_err_print(r.error); 79 | mpc_err_delete(r.error); 80 | } 81 | 82 | } else { 83 | 84 | mpc_result_t r; 85 | if (mpc_parse_pipe("", stdin, Smallc, &r)) { 86 | mpc_ast_print(r.output); 87 | mpc_ast_delete(r.output); 88 | } else { 89 | mpc_err_print(r.error); 90 | mpc_err_delete(r.error); 91 | } 92 | 93 | } 94 | 95 | mpc_cleanup(17, Ident, Number, Character, String, Factor, Term, Lexp, Stmt, Exp, 96 | Typeident, Decls, Args, Body, Procedure, Main, Includes, Smallc); 97 | 98 | return 0; 99 | 100 | } 101 | 102 | -------------------------------------------------------------------------------- /examples/tree_traversal.c: -------------------------------------------------------------------------------- 1 | #include "../mpc.h" 2 | 3 | int main(int argc, char *argv[]) { 4 | 5 | mpc_parser_t *Input = mpc_new("input"); 6 | mpc_parser_t *Node = mpc_new("node"); 7 | mpc_parser_t *Leaf = mpc_new("leaf"); 8 | mpc_ast_t *ast, *tree, *child, *child_sub, *ast_next; 9 | mpc_ast_trav_t *trav; 10 | mpc_result_t r; 11 | int index, lb, i; 12 | 13 | mpca_lang(MPCA_LANG_PREDICTIVE, 14 | " node : '(' ',' /foo/ ',' ')' | ;" 15 | " leaf : /bar/;" 16 | " input : /^/ /$/;", 17 | Node, Leaf, Input, NULL); 18 | 19 | if (argc > 1) { 20 | 21 | if (mpc_parse_contents(argv[1], Input, &r)) { 22 | ast = r.output; 23 | } else { 24 | mpc_err_print(r.error); 25 | mpc_err_delete(r.error); 26 | mpc_cleanup(3, Node, Leaf, Input); 27 | return EXIT_FAILURE; 28 | } 29 | 30 | } else { 31 | 32 | if (mpc_parse_pipe("", stdin, Input, &r)) { 33 | ast = r.output; 34 | } else { 35 | mpc_err_print(r.error); 36 | mpc_err_delete(r.error); 37 | mpc_cleanup(3, Node, Leaf, Input); 38 | return EXIT_FAILURE; 39 | } 40 | 41 | } 42 | 43 | /* Get index or child of tree */ 44 | tree = ast->children[1]; 45 | 46 | index = mpc_ast_get_index(tree, "node|>"); 47 | child = mpc_ast_get_child(tree, "node|>"); 48 | 49 | if(child == NULL) { 50 | mpc_cleanup(3, Node, Leaf, Input); 51 | mpc_ast_delete(ast); 52 | return EXIT_FAILURE; 53 | } 54 | 55 | printf("Index: %d; Child: \"%s\"\n", index, child->tag); 56 | 57 | /* Get multiple indexes or children of trees */ 58 | index = mpc_ast_get_index_lb(child, "node|leaf|regex", 0); 59 | child_sub = mpc_ast_get_child_lb(child, "node|leaf|regex", 0); 60 | 61 | while(index != -1) { 62 | printf("-- Index: %d; Child: \"%s\"\n", index, child_sub->tag); 63 | 64 | lb = index + 1; 65 | index = mpc_ast_get_index_lb(child, "node|leaf|regex", lb); 66 | child_sub = mpc_ast_get_child_lb(child, "node|leaf|regex", lb); 67 | } 68 | 69 | /* Traversal */ 70 | printf("Pre order tree traversal.\n"); 71 | trav = mpc_ast_traverse_start(ast, mpc_ast_trav_order_pre); 72 | 73 | ast_next = mpc_ast_traverse_next(&trav); 74 | 75 | while(ast_next != NULL) { 76 | printf("Tag: %s; Contents: %s\n", 77 | ast_next->tag, 78 | ast_next->contents); 79 | ast_next = mpc_ast_traverse_next(&trav); 80 | } 81 | 82 | mpc_ast_traverse_free(&trav); 83 | 84 | printf("Post order tree traversal.\n"); 85 | 86 | trav = mpc_ast_traverse_start(ast, mpc_ast_trav_order_post); 87 | 88 | ast_next = mpc_ast_traverse_next(&trav); 89 | 90 | while(ast_next != NULL) { 91 | printf("Tag: %s; Contents: %s\n", 92 | ast_next->tag, 93 | ast_next->contents); 94 | ast_next = mpc_ast_traverse_next(&trav); 95 | } 96 | 97 | mpc_ast_traverse_free(&trav); 98 | 99 | printf("Partial traversal.\n"); 100 | 101 | trav = mpc_ast_traverse_start(ast, mpc_ast_trav_order_post); 102 | 103 | ast_next = mpc_ast_traverse_next(&trav); 104 | 105 | for(i=0; i<2 && ast_next != NULL; i++) { 106 | printf("Tag: %s; Contents: %s\n", 107 | ast_next->tag, 108 | ast_next->contents); 109 | ast_next = mpc_ast_traverse_next(&trav); 110 | } 111 | 112 | mpc_ast_traverse_free(&trav); 113 | 114 | /* Clean up and return */ 115 | mpc_cleanup(3, Node, Leaf, Input); 116 | mpc_ast_delete(ast); 117 | 118 | return EXIT_SUCCESS; 119 | } 120 | -------------------------------------------------------------------------------- /mpc.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** mpc - Micro Parser Combinator library for C 3 | ** 4 | ** https://github.com/orangeduck/mpc 5 | ** 6 | ** Daniel Holden - contact@daniel-holden.com 7 | ** Licensed under BSD3 8 | */ 9 | 10 | #ifndef mpc_h 11 | #define mpc_h 12 | 13 | #ifdef __cplusplus 14 | extern "C" { 15 | #endif 16 | 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | /* 26 | ** State Type 27 | */ 28 | 29 | typedef struct { 30 | long pos; 31 | long row; 32 | long col; 33 | int term; 34 | } mpc_state_t; 35 | 36 | /* 37 | ** Error Type 38 | */ 39 | 40 | typedef struct { 41 | mpc_state_t state; 42 | int expected_num; 43 | char *filename; 44 | char *failure; 45 | char **expected; 46 | char received; 47 | } mpc_err_t; 48 | 49 | void mpc_err_delete(mpc_err_t *e); 50 | char *mpc_err_string(mpc_err_t *e); 51 | void mpc_err_print(mpc_err_t *e); 52 | void mpc_err_print_to(mpc_err_t *e, FILE *f); 53 | 54 | /* 55 | ** Parsing 56 | */ 57 | 58 | typedef void mpc_val_t; 59 | 60 | typedef union { 61 | mpc_err_t *error; 62 | mpc_val_t *output; 63 | } mpc_result_t; 64 | 65 | struct mpc_parser_t; 66 | typedef struct mpc_parser_t mpc_parser_t; 67 | 68 | int mpc_parse(const char *filename, const char *string, mpc_parser_t *p, mpc_result_t *r); 69 | int mpc_nparse(const char *filename, const char *string, size_t length, mpc_parser_t *p, mpc_result_t *r); 70 | int mpc_parse_file(const char *filename, FILE *file, mpc_parser_t *p, mpc_result_t *r); 71 | int mpc_parse_pipe(const char *filename, FILE *pipe, mpc_parser_t *p, mpc_result_t *r); 72 | int mpc_parse_contents(const char *filename, mpc_parser_t *p, mpc_result_t *r); 73 | 74 | /* 75 | ** Function Types 76 | */ 77 | 78 | typedef void(*mpc_dtor_t)(mpc_val_t*); 79 | typedef mpc_val_t*(*mpc_ctor_t)(void); 80 | 81 | typedef mpc_val_t*(*mpc_apply_t)(mpc_val_t*); 82 | typedef mpc_val_t*(*mpc_apply_to_t)(mpc_val_t*,void*); 83 | typedef mpc_val_t*(*mpc_fold_t)(int,mpc_val_t**); 84 | 85 | typedef int(*mpc_check_t)(mpc_val_t**); 86 | typedef int(*mpc_check_with_t)(mpc_val_t**,void*); 87 | 88 | /* 89 | ** Building a Parser 90 | */ 91 | 92 | mpc_parser_t *mpc_new(const char *name); 93 | mpc_parser_t *mpc_copy(mpc_parser_t *a); 94 | mpc_parser_t *mpc_define(mpc_parser_t *p, mpc_parser_t *a); 95 | mpc_parser_t *mpc_undefine(mpc_parser_t *p); 96 | 97 | void mpc_delete(mpc_parser_t *p); 98 | void mpc_cleanup(int n, ...); 99 | 100 | /* 101 | ** Basic Parsers 102 | */ 103 | 104 | mpc_parser_t *mpc_any(void); 105 | mpc_parser_t *mpc_char(char c); 106 | mpc_parser_t *mpc_range(char s, char e); 107 | mpc_parser_t *mpc_oneof(const char *s); 108 | mpc_parser_t *mpc_noneof(const char *s); 109 | mpc_parser_t *mpc_satisfy(int(*f)(char)); 110 | mpc_parser_t *mpc_string(const char *s); 111 | 112 | /* 113 | ** Other Parsers 114 | */ 115 | 116 | mpc_parser_t *mpc_pass(void); 117 | mpc_parser_t *mpc_fail(const char *m); 118 | mpc_parser_t *mpc_failf(const char *fmt, ...); 119 | mpc_parser_t *mpc_lift(mpc_ctor_t f); 120 | mpc_parser_t *mpc_lift_val(mpc_val_t *x); 121 | mpc_parser_t *mpc_anchor(int(*f)(char,char)); 122 | mpc_parser_t *mpc_state(void); 123 | 124 | /* 125 | ** Combinator Parsers 126 | */ 127 | 128 | mpc_parser_t *mpc_expect(mpc_parser_t *a, const char *e); 129 | mpc_parser_t *mpc_expectf(mpc_parser_t *a, const char *fmt, ...); 130 | mpc_parser_t *mpc_apply(mpc_parser_t *a, mpc_apply_t f); 131 | mpc_parser_t *mpc_apply_to(mpc_parser_t *a, mpc_apply_to_t f, void *x); 132 | mpc_parser_t *mpc_check(mpc_parser_t *a, mpc_dtor_t da, mpc_check_t f, const char *e); 133 | mpc_parser_t *mpc_check_with(mpc_parser_t *a, mpc_dtor_t da, mpc_check_with_t f, void *x, const char *e); 134 | mpc_parser_t *mpc_checkf(mpc_parser_t *a, mpc_dtor_t da, mpc_check_t f, const char *fmt, ...); 135 | mpc_parser_t *mpc_check_withf(mpc_parser_t *a, mpc_dtor_t da, mpc_check_with_t f, void *x, const char *fmt, ...); 136 | 137 | mpc_parser_t *mpc_not(mpc_parser_t *a, mpc_dtor_t da); 138 | mpc_parser_t *mpc_not_lift(mpc_parser_t *a, mpc_dtor_t da, mpc_ctor_t lf); 139 | mpc_parser_t *mpc_maybe(mpc_parser_t *a); 140 | mpc_parser_t *mpc_maybe_lift(mpc_parser_t *a, mpc_ctor_t lf); 141 | 142 | mpc_parser_t *mpc_many(mpc_fold_t f, mpc_parser_t *a); 143 | mpc_parser_t *mpc_many1(mpc_fold_t f, mpc_parser_t *a); 144 | mpc_parser_t *mpc_count(int n, mpc_fold_t f, mpc_parser_t *a, mpc_dtor_t da); 145 | 146 | mpc_parser_t *mpc_or(int n, ...); 147 | mpc_parser_t *mpc_and(int n, mpc_fold_t f, ...); 148 | 149 | mpc_parser_t *mpc_predictive(mpc_parser_t *a); 150 | 151 | /* 152 | ** Common Parsers 153 | */ 154 | 155 | mpc_parser_t *mpc_eoi(void); 156 | mpc_parser_t *mpc_soi(void); 157 | 158 | mpc_parser_t *mpc_boundary(void); 159 | mpc_parser_t *mpc_boundary_newline(void); 160 | 161 | mpc_parser_t *mpc_whitespace(void); 162 | mpc_parser_t *mpc_whitespaces(void); 163 | mpc_parser_t *mpc_blank(void); 164 | 165 | mpc_parser_t *mpc_newline(void); 166 | mpc_parser_t *mpc_tab(void); 167 | mpc_parser_t *mpc_escape(void); 168 | 169 | mpc_parser_t *mpc_digit(void); 170 | mpc_parser_t *mpc_hexdigit(void); 171 | mpc_parser_t *mpc_octdigit(void); 172 | mpc_parser_t *mpc_digits(void); 173 | mpc_parser_t *mpc_hexdigits(void); 174 | mpc_parser_t *mpc_octdigits(void); 175 | 176 | mpc_parser_t *mpc_lower(void); 177 | mpc_parser_t *mpc_upper(void); 178 | mpc_parser_t *mpc_alpha(void); 179 | mpc_parser_t *mpc_underscore(void); 180 | mpc_parser_t *mpc_alphanum(void); 181 | 182 | mpc_parser_t *mpc_int(void); 183 | mpc_parser_t *mpc_hex(void); 184 | mpc_parser_t *mpc_oct(void); 185 | mpc_parser_t *mpc_number(void); 186 | 187 | mpc_parser_t *mpc_real(void); 188 | mpc_parser_t *mpc_float(void); 189 | 190 | mpc_parser_t *mpc_char_lit(void); 191 | mpc_parser_t *mpc_string_lit(void); 192 | mpc_parser_t *mpc_regex_lit(void); 193 | 194 | mpc_parser_t *mpc_ident(void); 195 | 196 | /* 197 | ** Useful Parsers 198 | */ 199 | 200 | mpc_parser_t *mpc_startwith(mpc_parser_t *a); 201 | mpc_parser_t *mpc_endwith(mpc_parser_t *a, mpc_dtor_t da); 202 | mpc_parser_t *mpc_whole(mpc_parser_t *a, mpc_dtor_t da); 203 | 204 | mpc_parser_t *mpc_stripl(mpc_parser_t *a); 205 | mpc_parser_t *mpc_stripr(mpc_parser_t *a); 206 | mpc_parser_t *mpc_strip(mpc_parser_t *a); 207 | mpc_parser_t *mpc_tok(mpc_parser_t *a); 208 | mpc_parser_t *mpc_sym(const char *s); 209 | mpc_parser_t *mpc_total(mpc_parser_t *a, mpc_dtor_t da); 210 | 211 | mpc_parser_t *mpc_between(mpc_parser_t *a, mpc_dtor_t ad, const char *o, const char *c); 212 | mpc_parser_t *mpc_parens(mpc_parser_t *a, mpc_dtor_t ad); 213 | mpc_parser_t *mpc_braces(mpc_parser_t *a, mpc_dtor_t ad); 214 | mpc_parser_t *mpc_brackets(mpc_parser_t *a, mpc_dtor_t ad); 215 | mpc_parser_t *mpc_squares(mpc_parser_t *a, mpc_dtor_t ad); 216 | 217 | mpc_parser_t *mpc_tok_between(mpc_parser_t *a, mpc_dtor_t ad, const char *o, const char *c); 218 | mpc_parser_t *mpc_tok_parens(mpc_parser_t *a, mpc_dtor_t ad); 219 | mpc_parser_t *mpc_tok_braces(mpc_parser_t *a, mpc_dtor_t ad); 220 | mpc_parser_t *mpc_tok_brackets(mpc_parser_t *a, mpc_dtor_t ad); 221 | mpc_parser_t *mpc_tok_squares(mpc_parser_t *a, mpc_dtor_t ad); 222 | 223 | mpc_parser_t *mpc_sepby1(mpc_fold_t f, mpc_parser_t *sep, mpc_parser_t *a); 224 | 225 | /* 226 | ** Common Function Parameters 227 | */ 228 | 229 | void mpcf_dtor_null(mpc_val_t *x); 230 | 231 | mpc_val_t *mpcf_ctor_null(void); 232 | mpc_val_t *mpcf_ctor_str(void); 233 | 234 | mpc_val_t *mpcf_free(mpc_val_t *x); 235 | mpc_val_t *mpcf_int(mpc_val_t *x); 236 | mpc_val_t *mpcf_hex(mpc_val_t *x); 237 | mpc_val_t *mpcf_oct(mpc_val_t *x); 238 | mpc_val_t *mpcf_float(mpc_val_t *x); 239 | mpc_val_t *mpcf_strtriml(mpc_val_t *x); 240 | mpc_val_t *mpcf_strtrimr(mpc_val_t *x); 241 | mpc_val_t *mpcf_strtrim(mpc_val_t *x); 242 | 243 | mpc_val_t *mpcf_escape(mpc_val_t *x); 244 | mpc_val_t *mpcf_escape_regex(mpc_val_t *x); 245 | mpc_val_t *mpcf_escape_string_raw(mpc_val_t *x); 246 | mpc_val_t *mpcf_escape_char_raw(mpc_val_t *x); 247 | 248 | mpc_val_t *mpcf_unescape(mpc_val_t *x); 249 | mpc_val_t *mpcf_unescape_regex(mpc_val_t *x); 250 | mpc_val_t *mpcf_unescape_string_raw(mpc_val_t *x); 251 | mpc_val_t *mpcf_unescape_char_raw(mpc_val_t *x); 252 | 253 | mpc_val_t *mpcf_null(int n, mpc_val_t** xs); 254 | mpc_val_t *mpcf_fst(int n, mpc_val_t** xs); 255 | mpc_val_t *mpcf_snd(int n, mpc_val_t** xs); 256 | mpc_val_t *mpcf_trd(int n, mpc_val_t** xs); 257 | 258 | mpc_val_t *mpcf_fst_free(int n, mpc_val_t** xs); 259 | mpc_val_t *mpcf_snd_free(int n, mpc_val_t** xs); 260 | mpc_val_t *mpcf_trd_free(int n, mpc_val_t** xs); 261 | mpc_val_t *mpcf_all_free(int n, mpc_val_t** xs); 262 | 263 | mpc_val_t *mpcf_freefold(int n, mpc_val_t** xs); 264 | mpc_val_t *mpcf_strfold(int n, mpc_val_t** xs); 265 | 266 | /* 267 | ** Regular Expression Parsers 268 | */ 269 | 270 | enum { 271 | MPC_RE_DEFAULT = 0, 272 | MPC_RE_M = 1, 273 | MPC_RE_S = 2, 274 | MPC_RE_MULTILINE = 1, 275 | MPC_RE_DOTALL = 2 276 | }; 277 | 278 | mpc_parser_t *mpc_re(const char *re); 279 | mpc_parser_t *mpc_re_mode(const char *re, int mode); 280 | 281 | /* 282 | ** AST 283 | */ 284 | 285 | typedef struct mpc_ast_t { 286 | char *tag; 287 | char *contents; 288 | mpc_state_t state; 289 | int children_num; 290 | struct mpc_ast_t** children; 291 | } mpc_ast_t; 292 | 293 | mpc_ast_t *mpc_ast_new(const char *tag, const char *contents); 294 | mpc_ast_t *mpc_ast_build(int n, const char *tag, ...); 295 | mpc_ast_t *mpc_ast_add_root(mpc_ast_t *a); 296 | mpc_ast_t *mpc_ast_add_child(mpc_ast_t *r, mpc_ast_t *a); 297 | mpc_ast_t *mpc_ast_add_tag(mpc_ast_t *a, const char *t); 298 | mpc_ast_t *mpc_ast_add_root_tag(mpc_ast_t *a, const char *t); 299 | mpc_ast_t *mpc_ast_tag(mpc_ast_t *a, const char *t); 300 | mpc_ast_t *mpc_ast_state(mpc_ast_t *a, mpc_state_t s); 301 | 302 | void mpc_ast_delete(mpc_ast_t *a); 303 | void mpc_ast_print(mpc_ast_t *a); 304 | void mpc_ast_print_to(mpc_ast_t *a, FILE *fp); 305 | 306 | int mpc_ast_get_index(mpc_ast_t *ast, const char *tag); 307 | int mpc_ast_get_index_lb(mpc_ast_t *ast, const char *tag, int lb); 308 | mpc_ast_t *mpc_ast_get_child(mpc_ast_t *ast, const char *tag); 309 | mpc_ast_t *mpc_ast_get_child_lb(mpc_ast_t *ast, const char *tag, int lb); 310 | 311 | typedef enum { 312 | mpc_ast_trav_order_pre, 313 | mpc_ast_trav_order_post 314 | } mpc_ast_trav_order_t; 315 | 316 | typedef struct mpc_ast_trav_t { 317 | mpc_ast_t *curr_node; 318 | struct mpc_ast_trav_t *parent; 319 | int curr_child; 320 | mpc_ast_trav_order_t order; 321 | } mpc_ast_trav_t; 322 | 323 | mpc_ast_trav_t *mpc_ast_traverse_start(mpc_ast_t *ast, 324 | mpc_ast_trav_order_t order); 325 | 326 | mpc_ast_t *mpc_ast_traverse_next(mpc_ast_trav_t **trav); 327 | 328 | void mpc_ast_traverse_free(mpc_ast_trav_t **trav); 329 | 330 | /* 331 | ** Warning: This function currently doesn't test for equality of the `state` member! 332 | */ 333 | int mpc_ast_eq(mpc_ast_t *a, mpc_ast_t *b); 334 | 335 | mpc_val_t *mpcf_fold_ast(int n, mpc_val_t **as); 336 | mpc_val_t *mpcf_str_ast(mpc_val_t *c); 337 | mpc_val_t *mpcf_state_ast(int n, mpc_val_t **xs); 338 | 339 | mpc_parser_t *mpca_tag(mpc_parser_t *a, const char *t); 340 | mpc_parser_t *mpca_add_tag(mpc_parser_t *a, const char *t); 341 | mpc_parser_t *mpca_root(mpc_parser_t *a); 342 | mpc_parser_t *mpca_state(mpc_parser_t *a); 343 | mpc_parser_t *mpca_total(mpc_parser_t *a); 344 | 345 | mpc_parser_t *mpca_not(mpc_parser_t *a); 346 | mpc_parser_t *mpca_maybe(mpc_parser_t *a); 347 | 348 | mpc_parser_t *mpca_many(mpc_parser_t *a); 349 | mpc_parser_t *mpca_many1(mpc_parser_t *a); 350 | mpc_parser_t *mpca_count(int n, mpc_parser_t *a); 351 | 352 | mpc_parser_t *mpca_or(int n, ...); 353 | mpc_parser_t *mpca_and(int n, ...); 354 | 355 | enum { 356 | MPCA_LANG_DEFAULT = 0, 357 | MPCA_LANG_PREDICTIVE = 1, 358 | MPCA_LANG_WHITESPACE_SENSITIVE = 2 359 | }; 360 | 361 | mpc_parser_t *mpca_grammar(int flags, const char *grammar, ...); 362 | 363 | mpc_err_t *mpca_lang(int flags, const char *language, ...); 364 | mpc_err_t *mpca_lang_file(int flags, FILE *f, ...); 365 | mpc_err_t *mpca_lang_pipe(int flags, FILE *f, ...); 366 | mpc_err_t *mpca_lang_contents(int flags, const char *filename, ...); 367 | 368 | /* 369 | ** Misc 370 | */ 371 | 372 | 373 | void mpc_print(mpc_parser_t *p); 374 | void mpc_optimise(mpc_parser_t *p); 375 | void mpc_stats(mpc_parser_t *p); 376 | 377 | int mpc_test_pass(mpc_parser_t *p, const char *s, const void *d, 378 | int(*tester)(const void*, const void*), 379 | mpc_dtor_t destructor, 380 | void(*printer)(const void*)); 381 | 382 | int mpc_test_fail(mpc_parser_t *p, const char *s, const void *d, 383 | int(*tester)(const void*, const void*), 384 | mpc_dtor_t destructor, 385 | void(*printer)(const void*)); 386 | 387 | #ifdef __cplusplus 388 | } 389 | #endif 390 | 391 | #endif 392 | -------------------------------------------------------------------------------- /mpc.pc: -------------------------------------------------------------------------------- 1 | libdir=${prefix}/lib 2 | includedir=${prefix}/include 3 | 4 | Name: mpc 5 | Description: Library for creating parser combinators 6 | Version: 0.9.0 7 | Libs: -L${libdir} -lmpc 8 | Cflags: -I${includedir} 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mpc", 3 | "version": "0.9.8", 4 | "repo": "orangeduck/mpc", 5 | "description": "A Parser Combinator library for C", 6 | "keywords": ["parser", "combinator", "library", "c", "mpc"], 7 | "license": "BSD", 8 | "src": ["mpc.c", "mpc.h"] 9 | } 10 | -------------------------------------------------------------------------------- /tests/combinators.c: -------------------------------------------------------------------------------- 1 | #include "ptest.h" 2 | #include "../mpc.h" 3 | 4 | static int check_is_a(mpc_val_t** x) { 5 | return strcmp(*x, "a") == 0; 6 | } 7 | 8 | static int check_is(mpc_val_t** x, void* t) { 9 | return strcmp(*x, t) == 0; 10 | } 11 | 12 | void test_check(void) { 13 | int success; 14 | mpc_result_t r; 15 | mpc_parser_t* p = mpc_check(mpc_or(2, mpc_char('a'), mpc_char('b')), free, check_is_a, "Expected 'a'"); 16 | 17 | success = mpc_parse("test", "a", p, &r); 18 | PT_ASSERT(success); 19 | PT_ASSERT_STR_EQ(r.output, "a"); 20 | if (success) free(r.output); else mpc_err_delete(r.error); 21 | 22 | success = mpc_parse("test", "b", p, &r); 23 | PT_ASSERT(!success); 24 | PT_ASSERT_STR_EQ(r.error->failure, "Expected 'a'"); 25 | if (success) free(r.output); else mpc_err_delete(r.error); 26 | 27 | mpc_delete(p); 28 | } 29 | 30 | void test_check_with(void) { 31 | int success; 32 | mpc_result_t r; 33 | mpc_parser_t* p = mpc_check_with(mpc_or(2, mpc_char('a'), mpc_char('b')), free, check_is, (void*)"a", "Expected 'a'"); 34 | 35 | success = mpc_parse("test", "a", p, &r); 36 | PT_ASSERT(success); 37 | if (success) PT_ASSERT_STR_EQ(r.output, "a"); 38 | if (success) free(r.output); else mpc_err_delete(r.error); 39 | 40 | success = mpc_parse("test", "b", p, &r); 41 | PT_ASSERT(!success); 42 | if (!success) PT_ASSERT_STR_EQ(r.error->failure, "Expected 'a'"); 43 | if (success) free(r.output); else mpc_err_delete(r.error); 44 | 45 | mpc_delete(p); 46 | } 47 | 48 | void test_checkf(void) { 49 | int success; 50 | mpc_result_t r; 51 | mpc_parser_t* p = mpc_checkf(mpc_or(2, mpc_char('a'), mpc_char('b')), free, check_is_a, "Expected '%s'", "a"); 52 | 53 | success = mpc_parse("test", "a", p, &r); 54 | PT_ASSERT(success); 55 | PT_ASSERT_STR_EQ(r.output, "a"); 56 | if (success) free(r.output); else mpc_err_delete(r.error); 57 | 58 | success = mpc_parse("test", "b", p, &r); 59 | PT_ASSERT(!success); 60 | PT_ASSERT_STR_EQ(r.error->failure, "Expected 'a'"); 61 | if (success) free(r.output); else mpc_err_delete(r.error); 62 | 63 | mpc_delete(p); 64 | } 65 | 66 | void test_check_withf(void) { 67 | int success; 68 | mpc_result_t r; 69 | mpc_parser_t* p = mpc_check_withf(mpc_or(2, mpc_char('a'), mpc_char('b')), free, check_is, (void*)"a", "Expected '%s'", "a"); 70 | 71 | success = mpc_parse("test", "a", p, &r); 72 | PT_ASSERT(success); 73 | if (success) PT_ASSERT_STR_EQ(r.output, "a"); 74 | if (success) free(r.output); else mpc_err_delete(r.error); 75 | 76 | success = mpc_parse("test", "b", p, &r); 77 | PT_ASSERT(!success); 78 | if (!success) PT_ASSERT_STR_EQ(r.error->failure, "Expected 'a'"); 79 | if (success) free(r.output); else mpc_err_delete(r.error); 80 | 81 | mpc_delete(p); 82 | } 83 | 84 | void suite_combinators(void) { 85 | pt_add_test(test_check, "Test Check", "Suite Combinators"); 86 | pt_add_test(test_check_with, "Test Check with", "Suite Combinators"); 87 | pt_add_test(test_checkf, "Test Check F", "Suite Combinators"); 88 | pt_add_test(test_check_withf, "Test Check with F", "Suite Combinators"); 89 | } 90 | -------------------------------------------------------------------------------- /tests/core.c: -------------------------------------------------------------------------------- 1 | #include "ptest.h" 2 | #include "../mpc.h" 3 | 4 | #include 5 | #include 6 | 7 | static int int_eq(const void* x, const void* y) { return (*(int*)x == *(int*)y); } 8 | static void int_print(const void* x) { printf("'%i'", *((int*)x)); } 9 | static int streq(const void* x, const void* y) { return (strcmp(x, y) == 0); } 10 | static void strprint(const void* x) { printf("'%s'", (char*)x); } 11 | static mpc_val_t *fold_vals(int n, mpc_val_t **xs) { 12 | char** vals = malloc(sizeof(char*) * n); 13 | memcpy(vals, xs, sizeof(char*) * n); 14 | return vals; 15 | } 16 | 17 | void test_ident(void) { 18 | 19 | /* ^[a-zA-Z_][a-zA-Z0-9_]*$ */ 20 | 21 | mpc_parser_t* Ident = mpc_whole( 22 | mpc_and(2, mpcf_strfold, 23 | mpc_or(2, mpc_alpha(), mpc_underscore()), 24 | mpc_many1(mpcf_strfold, mpc_or(3, mpc_alpha(), mpc_underscore(), mpc_digit())), 25 | free), 26 | free 27 | ); 28 | 29 | PT_ASSERT(mpc_test_pass(Ident, "test", "test", streq, free, strprint)); 30 | PT_ASSERT(mpc_test_fail(Ident, " blah", "", streq, free, strprint)); 31 | PT_ASSERT(mpc_test_pass(Ident, "anoth21er", "anoth21er", streq, free, strprint)); 32 | PT_ASSERT(mpc_test_pass(Ident, "du__de", "du__de", streq, free, strprint)); 33 | PT_ASSERT(mpc_test_fail(Ident, "some spaces", "", streq, free, strprint)); 34 | PT_ASSERT(mpc_test_fail(Ident, "", "", streq, free, strprint)); 35 | PT_ASSERT(mpc_test_fail(Ident, "18nums", "", streq, free, strprint)); 36 | 37 | mpc_delete(Ident); 38 | 39 | } 40 | 41 | static mpc_val_t *mpcf_maths(int n, mpc_val_t **xs) { 42 | int **vs = (int**)xs; 43 | (void) n; 44 | 45 | switch(((char*)xs[1])[0]) 46 | { 47 | case '*': { *vs[0] *= *vs[2]; }; break; 48 | case '/': { *vs[0] /= *vs[2]; }; break; 49 | case '%': { *vs[0] %= *vs[2]; }; break; 50 | case '+': { *vs[0] += *vs[2]; }; break; 51 | case '-': { *vs[0] -= *vs[2]; }; break; 52 | default: break; 53 | } 54 | 55 | free(xs[1]); free(xs[2]); 56 | 57 | return xs[0]; 58 | } 59 | 60 | void test_maths(void) { 61 | 62 | mpc_parser_t *Expr, *Factor, *Term, *Maths; 63 | int r0 = 1, r1 = 5, r2 = 13, r3 = 0, r4 = 2; 64 | 65 | Expr = mpc_new("expr"); 66 | Factor = mpc_new("factor"); 67 | Term = mpc_new("term"); 68 | Maths = mpc_new("maths"); 69 | 70 | mpc_define(Expr, mpc_or(2, 71 | mpc_and(3, mpcf_maths, Factor, mpc_oneof("+-"), Factor, free, free), 72 | Factor 73 | )); 74 | 75 | mpc_define(Factor, mpc_or(2, 76 | mpc_and(3, mpcf_maths, Term, mpc_oneof("*/"), Term, free, free), 77 | Term 78 | )); 79 | 80 | mpc_define(Term, mpc_or(2, 81 | mpc_int(), 82 | mpc_parens(Expr, free) 83 | )); 84 | 85 | mpc_define(Maths, mpc_whole(Expr, free)); 86 | 87 | PT_ASSERT(mpc_test_pass(Maths, "1", &r0, int_eq, free, int_print)); 88 | PT_ASSERT(mpc_test_pass(Maths, "(5)", &r1, int_eq, free, int_print)); 89 | PT_ASSERT(mpc_test_pass(Maths, "(4*2)+5", &r2, int_eq, free, int_print)); 90 | PT_ASSERT(mpc_test_pass(Maths, "4*2+5", &r2, int_eq, free, int_print)); 91 | PT_ASSERT(mpc_test_fail(Maths, "a", &r3, int_eq, free, int_print)); 92 | PT_ASSERT(mpc_test_fail(Maths, "2b+4", &r4, int_eq, free, int_print)); 93 | 94 | mpc_cleanup(4, Expr, Factor, Term, Maths); 95 | } 96 | 97 | void test_strip(void) { 98 | 99 | mpc_parser_t *Stripperl = mpc_apply(mpc_many(mpcf_strfold, mpc_any()), mpcf_strtriml); 100 | mpc_parser_t *Stripperr = mpc_apply(mpc_many(mpcf_strfold, mpc_any()), mpcf_strtrimr); 101 | mpc_parser_t *Stripper = mpc_apply(mpc_many(mpcf_strfold, mpc_any()), mpcf_strtrim); 102 | 103 | PT_ASSERT(mpc_test_pass(Stripperl, " asdmlm dasd ", "asdmlm dasd ", streq, free, strprint)); 104 | PT_ASSERT(mpc_test_pass(Stripperr, " asdmlm dasd ", " asdmlm dasd", streq, free, strprint)); 105 | PT_ASSERT(mpc_test_pass(Stripper, " asdmlm dasd ", "asdmlm dasd", streq, free, strprint)); 106 | 107 | mpc_delete(Stripperl); 108 | mpc_delete(Stripperr); 109 | mpc_delete(Stripper); 110 | 111 | } 112 | 113 | void test_repeat(void) { 114 | 115 | int success; 116 | mpc_result_t r; 117 | mpc_parser_t *p = mpc_count(3, mpcf_strfold, mpc_digit(), free); 118 | 119 | success = mpc_parse("test", "046", p, &r); 120 | PT_ASSERT(success); 121 | PT_ASSERT_STR_EQ(r.output, "046"); 122 | free(r.output); 123 | 124 | success = mpc_parse("test", "046aa", p, &r); 125 | PT_ASSERT(success); 126 | PT_ASSERT_STR_EQ(r.output, "046"); 127 | free(r.output); 128 | 129 | success = mpc_parse("test", "04632", p, &r); 130 | PT_ASSERT(success); 131 | PT_ASSERT_STR_EQ(r.output, "046"); 132 | free(r.output); 133 | 134 | success = mpc_parse("test", "04", p, &r); 135 | PT_ASSERT(!success); 136 | mpc_err_delete(r.error); 137 | 138 | mpc_delete(p); 139 | 140 | } 141 | 142 | void test_copy(void) { 143 | 144 | int success; 145 | mpc_result_t r; 146 | mpc_parser_t* p = mpc_or(2, mpc_char('a'), mpc_char('b')); 147 | mpc_parser_t* q = mpc_and(2, mpcf_strfold, p, mpc_copy(p), free); 148 | 149 | success = mpc_parse("test", "aa", q, &r); 150 | PT_ASSERT(success); 151 | PT_ASSERT_STR_EQ(r.output, "aa"); 152 | free(r.output); 153 | 154 | success = mpc_parse("test", "bb", q, &r); 155 | PT_ASSERT(success); 156 | PT_ASSERT_STR_EQ(r.output, "bb"); 157 | free(r.output); 158 | 159 | success = mpc_parse("test", "ab", q, &r); 160 | PT_ASSERT(success); 161 | PT_ASSERT_STR_EQ(r.output, "ab"); 162 | free(r.output); 163 | 164 | success = mpc_parse("test", "ba", q, &r); 165 | PT_ASSERT(success); 166 | PT_ASSERT_STR_EQ(r.output, "ba"); 167 | free(r.output); 168 | 169 | success = mpc_parse("test", "c", p, &r); 170 | PT_ASSERT(!success); 171 | mpc_err_delete(r.error); 172 | 173 | mpc_delete(mpc_copy(p)); 174 | mpc_delete(mpc_copy(q)); 175 | 176 | mpc_delete(q); 177 | 178 | } 179 | 180 | static int line_count = 0; 181 | 182 | static mpc_val_t* read_line(mpc_val_t* line) { 183 | line_count++; 184 | return line; 185 | } 186 | 187 | void test_reader(void) { 188 | 189 | mpc_parser_t* Line = mpc_many( 190 | mpcf_strfold, 191 | mpc_apply(mpc_re("[^\\n]*(\\n|$)"), read_line)); 192 | 193 | line_count = 0; 194 | 195 | PT_ASSERT(mpc_test_pass(Line, 196 | "hello\nworld\n\nthis\nis\ndan", 197 | "hello\nworld\n\nthis\nis\ndan", streq, free, strprint)); 198 | 199 | PT_ASSERT(line_count == 6); 200 | 201 | line_count = 0; 202 | 203 | PT_ASSERT(mpc_test_pass(Line, 204 | "abcHVwufvyuevuy3y436782\n\n\nrehre\nrew\n-ql.;qa\neg", 205 | "abcHVwufvyuevuy3y436782\n\n\nrehre\nrew\n-ql.;qa\neg", streq, free, strprint)); 206 | 207 | PT_ASSERT(line_count == 7); 208 | 209 | mpc_delete(Line); 210 | 211 | } 212 | 213 | static int token_count = 0; 214 | 215 | static mpc_val_t *print_token(mpc_val_t *x) { 216 | /*printf("Token: '%s'\n", (char*)x);*/ 217 | token_count++; 218 | return x; 219 | } 220 | 221 | void test_tokens(void) { 222 | 223 | mpc_parser_t* Tokens = mpc_many( 224 | mpcf_strfold, 225 | mpc_apply(mpc_strip(mpc_re("\\s*([a-zA-Z_]+|[0-9]+|,|\\.|:)")), print_token)); 226 | 227 | token_count = 0; 228 | 229 | PT_ASSERT(mpc_test_pass(Tokens, 230 | " hello 4352 , \n foo.bar \n\n test:ing ", 231 | "hello4352,foo.bartest:ing", streq, free, strprint)); 232 | 233 | PT_ASSERT(token_count == 9); 234 | 235 | mpc_delete(Tokens); 236 | 237 | } 238 | 239 | void test_eoi(void) { 240 | 241 | mpc_parser_t* Line = mpc_re("[^\\n]*$"); 242 | 243 | PT_ASSERT(mpc_test_pass(Line, "blah", "blah", streq, free, strprint)); 244 | PT_ASSERT(mpc_test_pass(Line, "blah\n", "blah\n", streq, free, strprint)); 245 | 246 | mpc_delete(Line); 247 | 248 | } 249 | 250 | void test_sepby(void) { 251 | mpc_parser_t* CommaSepIdent = mpc_sepby1(mpcf_strfold, mpc_char(','), mpc_ident()); 252 | 253 | PT_ASSERT(mpc_test_fail(CommaSepIdent, "", "", streq, free, strprint)); 254 | PT_ASSERT(mpc_test_pass(CommaSepIdent, "one", "one", streq, free, strprint)); 255 | PT_ASSERT(mpc_test_pass(CommaSepIdent, "one,", "one", streq, free, strprint)); 256 | PT_ASSERT(mpc_test_pass(CommaSepIdent, "one,two,", "onetwo", streq, free, strprint)); 257 | PT_ASSERT(mpc_test_pass(CommaSepIdent, "one,two,three", "onetwothree", streq, free, strprint)); 258 | 259 | mpc_delete(CommaSepIdent); 260 | 261 | mpc_parser_t* CommaSepIdent1 = mpc_sepby1(fold_vals, mpc_char(','), mpc_ident()); 262 | mpc_result_t r; 263 | 264 | mpc_parse("", "uno,dos,tres,cuatro", CommaSepIdent1, &r); 265 | char **vals = r.output; 266 | PT_ASSERT(strcmp("uno", vals[0]) == 0); 267 | PT_ASSERT(strcmp("dos", vals[1]) == 0); 268 | PT_ASSERT(strcmp("tres", vals[2]) == 0); 269 | PT_ASSERT(strcmp("cuatro", vals[3]) == 0); 270 | 271 | free(vals); 272 | mpc_delete(CommaSepIdent1); 273 | } 274 | 275 | void suite_core(void) { 276 | pt_add_test(test_ident, "Test Ident", "Suite Core"); 277 | pt_add_test(test_maths, "Test Maths", "Suite Core"); 278 | pt_add_test(test_strip, "Test Strip", "Suite Core"); 279 | pt_add_test(test_repeat, "Test Repeat", "Suite Core"); 280 | pt_add_test(test_copy, "Test Copy", "Suite Core"); 281 | pt_add_test(test_reader, "Test Reader", "Suite Core"); 282 | pt_add_test(test_tokens, "Test Tokens", "Suite Core"); 283 | pt_add_test(test_eoi, "Test EOI", "Suite Core"); 284 | pt_add_test(test_sepby, "Test SepBy", "Suite Core"); 285 | } 286 | -------------------------------------------------------------------------------- /tests/digits.txt: -------------------------------------------------------------------------------- 1 | 123 -------------------------------------------------------------------------------- /tests/grammar.c: -------------------------------------------------------------------------------- 1 | #include "ptest.h" 2 | #include "../mpc.h" 3 | 4 | void test_grammar(void) { 5 | 6 | mpc_parser_t *Expr, *Prod, *Value, *Maths; 7 | mpc_ast_t *t0, *t1, *t2; 8 | 9 | Expr = mpc_new("expression"); 10 | Prod = mpc_new("product"); 11 | Value = mpc_new("value"); 12 | Maths = mpc_new("maths"); 13 | 14 | mpc_define(Expr, mpca_grammar(MPCA_LANG_DEFAULT, " (('+' | '-') )* ", Prod)); 15 | mpc_define(Prod, mpca_grammar(MPCA_LANG_DEFAULT, " (('*' | '/') )* ", Value)); 16 | mpc_define(Value, mpca_grammar(MPCA_LANG_DEFAULT, " /[0-9]+/ | '(' ')' ", Expr)); 17 | mpc_define(Maths, mpca_total(Expr)); 18 | 19 | t0 = mpc_ast_new("product|value|regex", "24"); 20 | t1 = mpc_ast_build(1, "product|>", 21 | mpc_ast_build(3, "value|>", 22 | mpc_ast_new("char", "("), 23 | mpc_ast_new("expression|product|value|regex", "5"), 24 | mpc_ast_new("char", ")"))); 25 | 26 | t2 = mpc_ast_build(3, ">", 27 | 28 | mpc_ast_build(3, "product|value|>", 29 | mpc_ast_new("char", "("), 30 | mpc_ast_build(3, "expression|>", 31 | 32 | mpc_ast_build(5, "product|>", 33 | mpc_ast_new("value|regex", "4"), 34 | mpc_ast_new("char", "*"), 35 | mpc_ast_new("value|regex", "2"), 36 | mpc_ast_new("char", "*"), 37 | mpc_ast_new("value|regex", "11")), 38 | 39 | mpc_ast_new("char", "+"), 40 | mpc_ast_new("product|value|regex", "2")), 41 | mpc_ast_new("char", ")")), 42 | 43 | mpc_ast_new("char", "+"), 44 | mpc_ast_new("product|value|regex", "5")); 45 | 46 | PT_ASSERT(mpc_test_pass(Maths, " 24 ", t0, (int(*)(const void*,const void*))mpc_ast_eq, (mpc_dtor_t)mpc_ast_delete, (void(*)(const void*))mpc_ast_print)); 47 | PT_ASSERT(mpc_test_pass(Maths, "(5)", t1, (int(*)(const void*,const void*))mpc_ast_eq, (mpc_dtor_t)mpc_ast_delete, (void(*)(const void*))mpc_ast_print)); 48 | PT_ASSERT(mpc_test_pass(Maths, "(4 * 2 * 11 + 2) + 5", t2, (int(*)(const void*,const void*))mpc_ast_eq, (mpc_dtor_t)mpc_ast_delete, (void(*)(const void*))mpc_ast_print)); 49 | PT_ASSERT(mpc_test_fail(Maths, "a", t0, (int(*)(const void*,const void*))mpc_ast_eq, (mpc_dtor_t)mpc_ast_delete, (void(*)(const void*))mpc_ast_print)); 50 | PT_ASSERT(mpc_test_fail(Maths, "2b+4", t0, (int(*)(const void*,const void*))mpc_ast_eq, (mpc_dtor_t)mpc_ast_delete, (void(*)(const void*))mpc_ast_print)); 51 | 52 | mpc_ast_delete(t0); 53 | mpc_ast_delete(t1); 54 | mpc_ast_delete(t2); 55 | 56 | mpc_cleanup(4, Expr, Prod, Value, Maths); 57 | 58 | } 59 | 60 | void test_language(void) { 61 | 62 | mpc_parser_t *Expr, *Prod, *Value, *Maths; 63 | 64 | Expr = mpc_new("expression"); 65 | Prod = mpc_new("product"); 66 | Value = mpc_new("value"); 67 | Maths = mpc_new("maths"); 68 | 69 | mpca_lang(MPCA_LANG_DEFAULT, 70 | " expression : (('+' | '-') )*; " 71 | " product : (('*' | '/') )*; " 72 | " value : /[0-9]+/ | '(' ')'; " 73 | " maths : /^/ /$/; ", 74 | Expr, Prod, Value, Maths); 75 | 76 | mpc_cleanup(4, Expr, Prod, Value, Maths); 77 | } 78 | 79 | void test_language_file(void) { 80 | 81 | mpc_parser_t *Expr, *Prod, *Value, *Maths; 82 | 83 | Expr = mpc_new("expression"); 84 | Prod = mpc_new("product"); 85 | Value = mpc_new("value"); 86 | Maths = mpc_new("maths"); 87 | 88 | mpca_lang_contents(MPCA_LANG_DEFAULT, "./tests/maths.grammar", Expr, Prod, Value, Maths); 89 | 90 | mpc_cleanup(4, Expr, Prod, Value, Maths); 91 | 92 | } 93 | 94 | void test_doge(void) { 95 | 96 | mpc_ast_t *t0; 97 | mpc_parser_t* Adjective = mpc_new("adjective"); 98 | mpc_parser_t* Noun = mpc_new("noun"); 99 | mpc_parser_t* Phrase = mpc_new("phrase"); 100 | mpc_parser_t* Doge = mpc_new("doge"); 101 | 102 | mpca_lang(MPCA_LANG_DEFAULT, 103 | " adjective : \"wow\" | \"many\" | \"so\" | \"such\"; " 104 | " noun : \"lisp\" | \"language\" | \"c\" | \"book\" | \"build\"; " 105 | " phrase : ; " 106 | " doge : /^/ * /$/; ", 107 | Adjective, Noun, Phrase, Doge, NULL); 108 | 109 | t0 = 110 | mpc_ast_build(4, ">", 111 | mpc_ast_new("regex", ""), 112 | mpc_ast_build(2, "phrase|>", 113 | mpc_ast_new("adjective|string", "so"), 114 | mpc_ast_new("noun|string", "c")), 115 | mpc_ast_build(2, "phrase|>", 116 | mpc_ast_new("adjective|string", "so"), 117 | mpc_ast_new("noun|string", "c")), 118 | mpc_ast_new("regex", "") 119 | ); 120 | 121 | PT_ASSERT(mpc_test_pass(Doge, "so c so c", t0, (int(*)(const void*,const void*))mpc_ast_eq, (mpc_dtor_t)mpc_ast_delete, (void(*)(const void*))mpc_ast_print)); 122 | 123 | PT_ASSERT(mpc_test_fail(Doge, "so a so c", t0, (int(*)(const void*,const void*))mpc_ast_eq, (mpc_dtor_t)mpc_ast_delete, (void(*)(const void*))mpc_ast_print)); 124 | 125 | mpc_ast_delete(t0); 126 | 127 | mpc_cleanup(4, Adjective, Noun, Phrase, Doge); 128 | 129 | } 130 | 131 | void test_partial(void) { 132 | 133 | mpc_ast_t *t0; 134 | mpc_err_t *err; 135 | 136 | mpc_parser_t *Line = mpc_new("line"); 137 | mpc_parser_t *Number = mpc_new("number"); 138 | mpc_parser_t *QuotedString = mpc_new("quoted_string"); 139 | mpc_parser_t *LinePragma = mpc_new("linepragma"); 140 | mpc_parser_t *Parser = mpc_new("parser"); 141 | 142 | mpc_define(Line, mpca_tag(mpc_apply(mpc_sym("#line"), mpcf_str_ast), "string")); 143 | 144 | err = mpca_lang(MPCA_LANG_PREDICTIVE, 145 | "number : /[0-9]+/ ;\n" 146 | "quoted_string : /\"(\\.|[^\"])*\"/ ;\n" 147 | "linepragma : ;\n" 148 | "parser : /^/ ()* /$/ ;\n", 149 | Line, Number, QuotedString, LinePragma, Parser, NULL); 150 | 151 | PT_ASSERT(err == NULL); 152 | 153 | t0 = mpc_ast_build(3, ">", 154 | mpc_ast_new("regex", ""), 155 | mpc_ast_build(3, "linepragma|>", 156 | mpc_ast_new("line|string", "#line"), 157 | mpc_ast_new("number|regex", "10"), 158 | mpc_ast_new("quoted_string|regex", "\"test\"")), 159 | mpc_ast_new("regex", "")); 160 | 161 | PT_ASSERT(mpc_test_pass(Parser, "#line 10 \"test\"", t0, 162 | (int(*)(const void*,const void*))mpc_ast_eq, 163 | (mpc_dtor_t)mpc_ast_delete, 164 | (void(*)(const void*))mpc_ast_print)); 165 | 166 | mpc_ast_delete(t0); 167 | 168 | mpc_cleanup(5, Line, Number, QuotedString, LinePragma, Parser); 169 | 170 | } 171 | 172 | void test_qscript(void) { 173 | 174 | mpc_ast_t *t0; 175 | mpc_parser_t *Qscript = mpc_new("qscript"); 176 | mpc_parser_t *Comment = mpc_new("comment"); 177 | mpc_parser_t *Resource = mpc_new("resource"); 178 | mpc_parser_t *Rtype = mpc_new("rtype"); 179 | mpc_parser_t *Rname = mpc_new("rname"); 180 | mpc_parser_t *InnerBlock = mpc_new("inner_block"); 181 | mpc_parser_t *Statement = mpc_new("statement"); 182 | mpc_parser_t *Function = mpc_new("function"); 183 | mpc_parser_t *Parameter = mpc_new("parameter"); 184 | mpc_parser_t *Literal = mpc_new("literal"); 185 | mpc_parser_t *Block = mpc_new("block"); 186 | mpc_parser_t *Seperator = mpc_new("seperator"); 187 | mpc_parser_t *Qstring = mpc_new("qstring"); 188 | mpc_parser_t *SimpleStr = mpc_new("simplestr"); 189 | mpc_parser_t *ComplexStr = mpc_new("complexstr"); 190 | mpc_parser_t *Number = mpc_new("number"); 191 | mpc_parser_t *Float = mpc_new("float"); 192 | mpc_parser_t *Int = mpc_new("int"); 193 | 194 | mpc_err_t *err = mpca_lang(0, 195 | " qscript : /^/ ( | )* /$/ ;\n" 196 | " comment : '#' /[^\\n]*/ ;\n" 197 | "resource : '[' ( ) ']' ;\n" 198 | " rtype : /[*]*/ ;\n" 199 | " rname : ;\n" 200 | "\n" 201 | "inner_block : ( | )* ;\n" 202 | " statement : '(' ( | | )* ')' ;\n" 203 | " function : ;\n" 204 | " parameter : ( | ) ;\n" 205 | " literal : ( | ) ;\n" 206 | " block : '{' '}' ;\n" 207 | " seperator : ',' | \"\" ;\n" 208 | "\n" 209 | "qstring : ( | ) * ;\n" 210 | " simplestr : /[a-zA-Z0-9_!@#$%^&\\*_+\\-\\.=\\/<>]+/ ;\n" 211 | " complexstr : (/\"[^\"]*\"/ | /'[^']*'/) ;\n" 212 | "\n" 213 | "number : ( | ) ;\n" 214 | " float : /[-+]?[0-9]+\\.[0-9]+/ ;\n" 215 | " int : /[-+]?[0-9]+/ ;\n", 216 | Qscript, Comment, Resource, Rtype, Rname, InnerBlock, Statement, Function, 217 | Parameter, Literal, Block, Seperator, Qstring, SimpleStr, ComplexStr, Number, 218 | Float, Int, NULL); 219 | 220 | PT_ASSERT(err == NULL); 221 | 222 | t0 = mpc_ast_build(3, ">", 223 | mpc_ast_new("regex", ""), 224 | mpc_ast_build(5, "resource|>", 225 | mpc_ast_new("char", "["), 226 | mpc_ast_new("rtype|regex", ""), 227 | mpc_ast_new("rname|qstring|simplestr|regex", "my_func"), 228 | mpc_ast_new("char", "]"), 229 | mpc_ast_build(5, "inner_block|statement|>", 230 | mpc_ast_new("function|qstring|simplestr|regex", "echo"), 231 | mpc_ast_new("char", "("), 232 | mpc_ast_build(2, "parameter|literal|>", 233 | mpc_ast_build(2, "qstring|>", 234 | mpc_ast_new("simplestr|regex", "a"), 235 | mpc_ast_build(2, "qstring|>", 236 | mpc_ast_new("simplestr|regex", "b"), 237 | mpc_ast_new("qstring|simplestr|regex", "c") 238 | ) 239 | ), 240 | mpc_ast_new("seperator|string", "") 241 | ), 242 | mpc_ast_new("char", ")"), 243 | mpc_ast_new("seperator|string", "") 244 | ) 245 | ), 246 | mpc_ast_new("regex", "")); 247 | 248 | PT_ASSERT(mpc_test_pass(Qscript, "[my_func]\n echo (a b c)\n", t0, 249 | (int(*)(const void*,const void*))mpc_ast_eq, 250 | (mpc_dtor_t)mpc_ast_delete, 251 | (void(*)(const void*))mpc_ast_print)); 252 | 253 | mpc_ast_delete(t0); 254 | 255 | mpc_cleanup(18, Qscript, Comment, Resource, Rtype, Rname, InnerBlock, 256 | Statement, Function, Parameter, Literal, Block, Seperator, Qstring, 257 | SimpleStr, ComplexStr, Number, Float, Int); 258 | 259 | } 260 | 261 | void test_missingrule(void) { 262 | 263 | int result; 264 | mpc_err_t *err; 265 | mpc_result_t r; 266 | mpc_parser_t *Parser = mpc_new("parser"); 267 | 268 | err = mpca_lang(MPCA_LANG_DEFAULT, 269 | "parser : /^/ ()* /$/ ;\n", 270 | Parser, NULL); 271 | 272 | PT_ASSERT(err == NULL); 273 | 274 | result = mpc_parse("", "test", Parser, &r); 275 | 276 | PT_ASSERT(result == 0); 277 | PT_ASSERT(r.error != NULL); 278 | PT_ASSERT(strcmp(r.error->failure, "Unknown Parser 'missing'!") == 0); 279 | 280 | mpc_err_delete(r.error); 281 | mpc_cleanup(1, Parser); 282 | 283 | } 284 | 285 | void test_regex_mode(void) { 286 | 287 | mpc_parser_t *Line0, *Line1, *Line2, *Line3; 288 | mpc_ast_t *t0, *t1, *t2, *t3, *t4; 289 | 290 | Line0 = mpc_new("line0"); 291 | Line1 = mpc_new("line1"); 292 | Line2 = mpc_new("line2"); 293 | Line3 = mpc_new("line3"); 294 | 295 | mpca_lang(MPCA_LANG_DEFAULT, " line0 : /.*/; ", Line0); 296 | mpca_lang(MPCA_LANG_DEFAULT, " line1 : /.*/s; ", Line1); 297 | mpca_lang(MPCA_LANG_DEFAULT, " line2 : /(^[a-z]*$)*/; ", Line2); 298 | mpca_lang(MPCA_LANG_DEFAULT, " line3 : /(^[a-z]*$)*/m; ", Line3); 299 | 300 | t0 = mpc_ast_new("regex", "blah"); 301 | t1 = mpc_ast_new("regex", "blah\nblah"); 302 | t2 = mpc_ast_new("regex", ""); 303 | t3 = mpc_ast_new("regex", "blah"); 304 | t4 = mpc_ast_new("regex", "blah\nblah"); 305 | 306 | PT_ASSERT(mpc_test_pass(Line0, "blah\nblah", t0, 307 | (int(*)(const void*,const void*))mpc_ast_eq, 308 | (mpc_dtor_t)mpc_ast_delete, 309 | (void(*)(const void*))mpc_ast_print)); 310 | 311 | PT_ASSERT(mpc_test_pass(Line1, "blah\nblah", t1, 312 | (int(*)(const void*,const void*))mpc_ast_eq, 313 | (mpc_dtor_t)mpc_ast_delete, 314 | (void(*)(const void*))mpc_ast_print)); 315 | 316 | PT_ASSERT(mpc_test_pass(Line2, "blah\nblah", t2, 317 | (int(*)(const void*,const void*))mpc_ast_eq, 318 | (mpc_dtor_t)mpc_ast_delete, 319 | (void(*)(const void*))mpc_ast_print)); 320 | 321 | PT_ASSERT(mpc_test_pass(Line2, "blah", t3, 322 | (int(*)(const void*,const void*))mpc_ast_eq, 323 | (mpc_dtor_t)mpc_ast_delete, 324 | (void(*)(const void*))mpc_ast_print)); 325 | 326 | PT_ASSERT(mpc_test_pass(Line3, "blah\nblah", t4, 327 | (int(*)(const void*,const void*))mpc_ast_eq, 328 | (mpc_dtor_t)mpc_ast_delete, 329 | (void(*)(const void*))mpc_ast_print)); 330 | 331 | mpc_ast_delete(t0); 332 | mpc_ast_delete(t1); 333 | mpc_ast_delete(t2); 334 | mpc_ast_delete(t3); 335 | mpc_ast_delete(t4); 336 | 337 | mpc_cleanup(4, Line0, Line1, Line2, Line3); 338 | } 339 | 340 | void test_digits_file(void) { 341 | 342 | FILE *f; 343 | mpc_result_t r; 344 | mpc_parser_t *Digit = mpc_new("digit"); 345 | mpc_parser_t *Program = mpc_new("program"); 346 | mpc_ast_t* t0; 347 | 348 | mpc_err_t* err = mpca_lang(MPCA_LANG_DEFAULT, 349 | " digit : /[0-9]/ ;" 350 | " program : /^/ + /$/ ;" 351 | , Digit, Program, NULL); 352 | 353 | PT_ASSERT(err == NULL); 354 | 355 | t0 = mpc_ast_build(5, ">", 356 | mpc_ast_new("regex", ""), 357 | mpc_ast_new("digit|regex", "1"), 358 | mpc_ast_new("digit|regex", "2"), 359 | mpc_ast_new("digit|regex", "3"), 360 | mpc_ast_new("regex", "")); 361 | 362 | if (mpc_parse_contents("tests/digits.txt", Program, &r)) { 363 | PT_ASSERT(1); 364 | PT_ASSERT(mpc_ast_eq(t0, r.output)); 365 | mpc_ast_delete(r.output); 366 | } else { 367 | PT_ASSERT(0); 368 | mpc_err_print(r.error); 369 | mpc_err_delete(r.error); 370 | } 371 | 372 | f = fopen("tests/digits.txt", "r"); 373 | PT_ASSERT(f != NULL); 374 | 375 | if (mpc_parse_file("tests/digits.txt", f, Program, &r)) { 376 | PT_ASSERT(1); 377 | PT_ASSERT(mpc_ast_eq(t0, r.output)); 378 | mpc_ast_delete(r.output); 379 | } else { 380 | PT_ASSERT(0); 381 | mpc_err_print(r.error); 382 | mpc_err_delete(r.error); 383 | } 384 | 385 | fclose(f); 386 | 387 | if (mpc_parse("tests/digits.txt", "123", Program, &r)) { 388 | PT_ASSERT(1); 389 | PT_ASSERT(mpc_ast_eq(t0, r.output)); 390 | mpc_ast_delete(r.output); 391 | } else { 392 | PT_ASSERT(0); 393 | mpc_err_print(r.error); 394 | mpc_err_delete(r.error); 395 | } 396 | 397 | mpc_ast_delete(t0); 398 | 399 | mpc_cleanup(2, Digit, Program); 400 | 401 | } 402 | 403 | void suite_grammar(void) { 404 | pt_add_test(test_grammar, "Test Grammar", "Suite Grammar"); 405 | pt_add_test(test_language, "Test Language", "Suite Grammar"); 406 | pt_add_test(test_language_file, "Test Language File", "Suite Grammar"); 407 | pt_add_test(test_doge, "Test Doge", "Suite Grammar"); 408 | pt_add_test(test_partial, "Test Partial", "Suite Grammar"); 409 | pt_add_test(test_qscript, "Test QScript", "Suite Grammar"); 410 | pt_add_test(test_missingrule, "Test Missing Rule", "Suite Grammar"); 411 | pt_add_test(test_regex_mode, "Test Regex Mode", "Suite Grammar"); 412 | pt_add_test(test_digits_file, "Test Digits File", "Suite Grammar"); 413 | } 414 | -------------------------------------------------------------------------------- /tests/maths.grammar: -------------------------------------------------------------------------------- 1 | expression : (('+' | '-') )*; 2 | 3 | product : (('*' | '/') )*; 4 | 5 | value : /[0-9]+/ | '(' ')'; 6 | 7 | maths : /^/ /$/; -------------------------------------------------------------------------------- /tests/ptest.c: -------------------------------------------------------------------------------- 1 | #include "ptest.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | /* Globals */ 10 | 11 | enum { 12 | MAX_NAME = 512 13 | }; 14 | 15 | enum { 16 | MAX_ERROR = 2048 17 | }; 18 | 19 | enum { 20 | MAX_TESTS = 2048 21 | }; 22 | 23 | static int test_passing = 0; 24 | static int suite_passing = 0; 25 | 26 | /* Colors */ 27 | 28 | enum { 29 | BLACK = 0, 30 | BLUE = 1, 31 | GREEN = 2, 32 | AQUA = 3, 33 | RED = 4, 34 | PURPLE = 5, 35 | YELLOW = 6, 36 | WHITE = 7, 37 | GRAY = 8, 38 | 39 | LIGHT_BLUE = 9, 40 | LIGHT_GREEN = 10, 41 | LIGHT_AQUA = 11, 42 | LIGHT_RED = 12, 43 | LIGHT_PURPLE = 13, 44 | LIGHT_YELLOW = 14, 45 | LIGHT_WHITE = 15, 46 | 47 | DEFAULT = 16 48 | }; 49 | 50 | #ifdef _WIN32 51 | 52 | #include 53 | 54 | static WORD defaults; 55 | static int defaults_loaded = 0; 56 | 57 | static void pt_color(int color) { 58 | 59 | HANDLE cnsl = GetStdHandle(STD_OUTPUT_HANDLE); 60 | 61 | if (!defaults_loaded) { 62 | CONSOLE_SCREEN_BUFFER_INFO info; 63 | GetConsoleScreenBufferInfo(cnsl, &info); 64 | defaults = info.wAttributes; 65 | defaults_loaded = 1; 66 | } 67 | 68 | SetConsoleTextAttribute(cnsl, color == DEFAULT ? defaults : color); 69 | } 70 | 71 | #else 72 | 73 | static const char* colors[] = { 74 | "\x1B[0m", 75 | "\x1B[34m", 76 | "\x1B[32m", 77 | "\x1B[36m", 78 | "\x1B[31m", 79 | "\x1B[35m", 80 | "\x1B[33m", 81 | "\x1B[37m", 82 | "", 83 | "\x1B[34m", 84 | "\x1B[32m", 85 | "\x1B[36m", 86 | "\x1B[31m", 87 | "\x1B[35m", 88 | "\x1B[33m", 89 | "\x1B[37m", 90 | "\x1B[39m", 91 | }; 92 | 93 | static void pt_color(int color) { 94 | printf("%s", colors[color]); 95 | } 96 | 97 | #endif 98 | 99 | /* Asserts */ 100 | 101 | static int num_asserts = 0; 102 | static int num_assert_passes = 0; 103 | static int num_assert_fails = 0; 104 | 105 | static char assert_err[MAX_ERROR]; 106 | static char assert_err_buff[MAX_ERROR]; 107 | static int assert_err_num = 0; 108 | 109 | void pt_assert_run(int result, const char* expr, const char* file, int line) { 110 | 111 | num_asserts++; 112 | test_passing = test_passing && result; 113 | 114 | if (result) { 115 | num_assert_passes++; 116 | } else { 117 | sprintf(assert_err_buff, 118 | " %i. Assert [ %s ] (%s:%i)\n", 119 | assert_err_num+1, expr, file, line ); 120 | strcat(assert_err, assert_err_buff); 121 | assert_err_num++; 122 | num_assert_fails++; 123 | } 124 | 125 | } 126 | 127 | static void ptest_signal(int sig) { 128 | 129 | test_passing = 0; 130 | 131 | switch( sig ) { 132 | case SIGFPE: sprintf(assert_err_buff, 133 | " %i. Division by Zero\n", assert_err_num+1); 134 | break; 135 | case SIGILL: sprintf(assert_err_buff, 136 | " %i. Illegal Instruction\n", assert_err_num+1); 137 | break; 138 | case SIGSEGV: sprintf(assert_err_buff, 139 | " %i. Segmentation Fault\n", assert_err_num+1); 140 | break; 141 | default: break; 142 | } 143 | 144 | assert_err_num++; 145 | strcat(assert_err, assert_err_buff); 146 | 147 | pt_color(RED); 148 | printf("Failed! \n\n%s\n", assert_err); 149 | pt_color(DEFAULT); 150 | 151 | puts(" | Stopping Execution."); 152 | fflush(stdout); 153 | exit(0); 154 | 155 | } 156 | 157 | /* Tests */ 158 | 159 | static void pt_title_case(char* output, const char* input) { 160 | 161 | int space = 1; 162 | unsigned int i; 163 | 164 | strcpy(output, input); 165 | 166 | for(i = 0; i < strlen(output); i++) { 167 | 168 | if (output[i] == '_' || output[i] == ' ') { 169 | space = 1; 170 | output[i] = ' '; 171 | continue; 172 | } 173 | 174 | if (space && output[i] >= 'a' && output[i] <= 'z') { 175 | space = 0; 176 | output[i] = output[i] - 32; 177 | continue; 178 | } 179 | 180 | space = 0; 181 | 182 | } 183 | 184 | } 185 | 186 | typedef struct { 187 | void (*func)(void); 188 | char name[MAX_NAME]; 189 | char suite[MAX_NAME]; 190 | } test_t; 191 | 192 | static test_t tests[MAX_TESTS]; 193 | 194 | static int num_tests = 0; 195 | static int num_tests_passes = 0; 196 | static int num_tests_fails = 0; 197 | 198 | void pt_add_test(void (*func)(void), const char* name, const char* suite) { 199 | 200 | test_t test; 201 | 202 | if (num_tests == MAX_TESTS) { 203 | printf("ERROR: Exceeded maximum test count of %i!\n", 204 | MAX_TESTS); abort(); 205 | } 206 | 207 | if (strlen(name) >= MAX_NAME) { 208 | printf("ERROR: Test name '%s' too long (Maximum is %i characters)\n", 209 | name, MAX_NAME); abort(); 210 | } 211 | 212 | if (strlen(suite) >= MAX_NAME) { 213 | printf("ERROR: Test suite '%s' too long (Maximum is %i characters)\n", 214 | suite, MAX_NAME); abort(); 215 | } 216 | 217 | test.func = func; 218 | pt_title_case(test.name, name); 219 | pt_title_case(test.suite, suite); 220 | 221 | tests[num_tests] = test; 222 | num_tests++; 223 | } 224 | 225 | /* Suites */ 226 | 227 | static int num_suites = 0; 228 | static int num_suites_passes = 0; 229 | static int num_suites_fails = 0; 230 | 231 | void pt_add_suite(void (*func)(void)) { 232 | num_suites++; 233 | func(); 234 | } 235 | 236 | /* Running */ 237 | 238 | static clock_t start, end; 239 | static char current_suite[MAX_NAME]; 240 | 241 | int pt_run(void) { 242 | 243 | int i; 244 | double total; 245 | test_t test; 246 | 247 | puts(""); 248 | puts(" +-------------------------------------------+"); 249 | puts(" | ptest MicroTesting Magic for C |"); 250 | puts(" | |"); 251 | puts(" | http://github.com/orangeduck/ptest |"); 252 | puts(" | |"); 253 | puts(" | Daniel Holden (contact@theorangeduck.com) |"); 254 | puts(" +-------------------------------------------+"); 255 | 256 | signal(SIGFPE, ptest_signal); 257 | signal(SIGILL, ptest_signal); 258 | signal(SIGSEGV, ptest_signal); 259 | 260 | start = clock(); 261 | strcpy(current_suite, ""); 262 | 263 | for(i = 0; i < num_tests; i++) { 264 | 265 | test = tests[i]; 266 | 267 | /* Check for transition to a new suite */ 268 | if (strcmp(test.suite, current_suite)) { 269 | 270 | /* Don't increment any counter for first entrance */ 271 | if (strcmp(current_suite, "")) { 272 | if (suite_passing) { 273 | num_suites_passes++; 274 | } else { 275 | num_suites_fails++; 276 | } 277 | } 278 | 279 | suite_passing = 1; 280 | strcpy(current_suite, test.suite); 281 | printf("\n\n ===== %s =====\n\n", current_suite); 282 | } 283 | 284 | /* Run Test */ 285 | 286 | test_passing = 1; 287 | strcpy(assert_err, ""); 288 | strcpy(assert_err_buff, ""); 289 | assert_err_num = 0; 290 | printf(" | %s ... ", test.name); 291 | fflush(stdout); 292 | 293 | test.func(); 294 | 295 | suite_passing = suite_passing && test_passing; 296 | 297 | if (test_passing) { 298 | num_tests_passes++; 299 | pt_color(GREEN); 300 | puts("Passed!"); 301 | pt_color(DEFAULT); 302 | } else { 303 | num_tests_fails++; 304 | pt_color(RED); 305 | printf("Failed! \n\n%s\n", assert_err); 306 | pt_color(DEFAULT); 307 | } 308 | 309 | } 310 | 311 | if (suite_passing) { 312 | num_suites_passes++; 313 | } else { 314 | num_suites_fails++; 315 | } 316 | 317 | end = clock(); 318 | 319 | puts(""); 320 | puts(" +---------------------------------------------------+"); 321 | puts(" | Summary |"); 322 | puts(" +---------++------------+-------------+-------------+"); 323 | 324 | printf(" | Suites ||"); 325 | pt_color(YELLOW); printf(" Total %4d ", num_suites); 326 | pt_color(DEFAULT); putchar('|'); 327 | pt_color(GREEN); printf(" Passed %4d ", num_suites_passes); 328 | pt_color(DEFAULT); putchar('|'); 329 | pt_color(RED); printf(" Failed %4d ", num_suites_fails); 330 | pt_color(DEFAULT); puts("|"); 331 | 332 | printf(" | Tests ||"); 333 | pt_color(YELLOW); printf(" Total %4d ", num_tests); 334 | pt_color(DEFAULT); putchar('|'); 335 | pt_color(GREEN); printf(" Passed %4d ", num_tests_passes); 336 | pt_color(DEFAULT); putchar('|'); 337 | pt_color(RED); printf(" Failed %4d ", num_tests_fails); 338 | pt_color(DEFAULT); puts("|"); 339 | 340 | printf(" | Asserts ||"); 341 | pt_color(YELLOW); printf(" Total %4d ", num_asserts); 342 | pt_color(DEFAULT); putchar('|'); 343 | pt_color(GREEN); printf(" Passed %4d ", num_assert_passes); 344 | pt_color(DEFAULT); putchar('|'); 345 | pt_color(RED); printf(" Failed %4d ", num_assert_fails); 346 | pt_color(DEFAULT); puts("|"); 347 | 348 | puts(" +---------++------------+-------------+-------------+"); 349 | puts(""); 350 | 351 | total = (double)(end - start) / CLOCKS_PER_SEC; 352 | 353 | printf(" Total Running Time: %0.3fs\n\n", total); 354 | 355 | if (num_suites_fails > 0) { return 1; } else { return 0; } 356 | } 357 | -------------------------------------------------------------------------------- /tests/ptest.h: -------------------------------------------------------------------------------- 1 | #ifndef ptest_h 2 | #define ptest_h 3 | 4 | #include 5 | 6 | #define PT_SUITE(name) void name(void) 7 | 8 | #define PT_FUNC(name) static void name(void) 9 | #define PT_REG(name) pt_add_test(name, #name) 10 | #define PT_TEST(name) auto void name(void); PT_REG(name); void name(void) 11 | 12 | #define PT_ASSERT(expr) pt_assert_run((int)(expr), #expr, __FILE__, __LINE__) 13 | #define PT_ASSERT_STR_EQ(fst, snd) pt_assert_run(strcmp(fst, snd) == 0, "strcmp( " #fst ", " #snd " ) == 0", __FILE__, __LINE__) 14 | 15 | void pt_assert_run(int result, const char* expr, const char* file, int line); 16 | 17 | void pt_add_test(void (*func)(void), const char* name, const char* suite); 18 | void pt_add_suite(void (*func)(void)); 19 | int pt_run(void); 20 | 21 | #endif 22 | 23 | -------------------------------------------------------------------------------- /tests/regex.c: -------------------------------------------------------------------------------- 1 | #include "ptest.h" 2 | #include "../mpc.h" 3 | 4 | #include 5 | #include 6 | 7 | static int string_eq(const void* x, const void* y) { return (strcmp(x, y) == 0); } 8 | static void string_print(const void* x) { printf("'%s'", (char*)x); } 9 | 10 | int regex_test_pass(mpc_parser_t *p, const char* value, const char* match) { 11 | return mpc_test_pass(p, value, match, string_eq, free, string_print); 12 | } 13 | 14 | int regex_test_fail(mpc_parser_t *p, const char* value, const char* match) { 15 | return mpc_test_fail(p, value, match, string_eq, free, string_print); 16 | } 17 | 18 | void test_regex_basic(void) { 19 | 20 | mpc_parser_t *re0, *re1, *re2, *re3, *re4, *re5; 21 | 22 | re0 = mpc_re("abc|bcd"); 23 | re1 = mpc_re("abc|bcd|e"); 24 | re2 = mpc_re("ab()c(ab)*"); 25 | re3 = mpc_re("abc(abdd)?"); 26 | re4 = mpc_re("ab|c(abdd)?"); 27 | re5 = mpc_re("abc(ab|dd)+g$"); 28 | 29 | PT_ASSERT(regex_test_pass(re0, "abc", "abc")); 30 | PT_ASSERT(regex_test_pass(re0, "bcd", "bcd")); 31 | PT_ASSERT(regex_test_fail(re0, "bc", "bc")); 32 | PT_ASSERT(regex_test_fail(re0, "ab", "ab")); 33 | PT_ASSERT(regex_test_pass(re1, "e", "e")); 34 | PT_ASSERT(regex_test_pass(re2, "abc", "abc")); 35 | PT_ASSERT(regex_test_pass(re2, "abcabab", "abcabab")); 36 | PT_ASSERT(regex_test_pass(re2, "abcababd", "abcabab")); 37 | PT_ASSERT(regex_test_pass(re5, "abcddg", "abcddg")); 38 | 39 | mpc_delete(re0); 40 | mpc_delete(re1); 41 | mpc_delete(re2); 42 | mpc_delete(re3); 43 | mpc_delete(re4); 44 | mpc_delete(re5); 45 | 46 | } 47 | 48 | void test_regex_boundary(void) { 49 | 50 | mpc_parser_t *re0, *re1, *re2; 51 | 52 | re0 = mpc_re("\\bfoo\\b"); 53 | re1 = mpc_re("(w| )?\\bfoo\\b"); 54 | re2 = mpc_re("py\\B.*"); 55 | 56 | PT_ASSERT(regex_test_pass(re0, "foo", "foo")); 57 | PT_ASSERT(regex_test_pass(re0, "foo.", "foo")); 58 | PT_ASSERT(regex_test_pass(re0, "foo)", "foo")); 59 | PT_ASSERT(regex_test_pass(re0, "foo baz", "foo")); 60 | 61 | PT_ASSERT(regex_test_fail(re0, "foobar", "foo")); 62 | PT_ASSERT(regex_test_fail(re0, "foo3", "foo")); 63 | 64 | PT_ASSERT(regex_test_pass(re1, "foo", "foo")); 65 | PT_ASSERT(regex_test_pass(re1, " foo", " foo")); 66 | PT_ASSERT(regex_test_fail(re1, "wfoo", "foo")); 67 | 68 | PT_ASSERT(regex_test_pass(re2, "python", "python")); 69 | PT_ASSERT(regex_test_pass(re2, "py3", "py3")); 70 | PT_ASSERT(regex_test_pass(re2, "py2", "py2")); 71 | PT_ASSERT(regex_test_fail(re2, "py", "py")); 72 | PT_ASSERT(regex_test_fail(re2, "py.", "py.")); 73 | PT_ASSERT(regex_test_fail(re2, "py!", "py!")); 74 | 75 | mpc_delete(re0); 76 | mpc_delete(re1); 77 | mpc_delete(re2); 78 | 79 | } 80 | 81 | void test_regex_range(void) { 82 | 83 | mpc_parser_t *re0, *re1, *re2, *re3; 84 | 85 | re0 = mpc_re("abg[abcdef]"); 86 | re1 = mpc_re("y*[a-z]"); 87 | re2 = mpc_re("zz(p+)?[A-Z_0\\]123]*"); 88 | re3 = mpc_re("^[^56hy].*$"); 89 | 90 | /* TODO: Testing */ 91 | 92 | mpc_delete(re0); 93 | mpc_delete(re1); 94 | mpc_delete(re2); 95 | mpc_delete(re3); 96 | 97 | } 98 | 99 | void test_regex_string(void) { 100 | 101 | mpc_parser_t *re0 = mpc_re("\"(\\\\.|[^\"])*\""); 102 | 103 | PT_ASSERT(regex_test_pass(re0, "\"there\"", "\"there\"")); 104 | PT_ASSERT(regex_test_pass(re0, "\"hello\"", "\"hello\"")); 105 | PT_ASSERT(regex_test_pass(re0, "\"i am dan\"", "\"i am dan\"")); 106 | PT_ASSERT(regex_test_pass(re0, "\"i a\\\"m dan\"", "\"i a\\\"m dan\"")); 107 | 108 | mpc_delete(re0); 109 | 110 | } 111 | 112 | void test_regex_lisp_comment(void) { 113 | 114 | mpc_parser_t *re0 = mpc_re(";[^\\n\\r]*"); 115 | 116 | PT_ASSERT(regex_test_pass(re0, ";comment", ";comment")); 117 | PT_ASSERT(regex_test_pass(re0, ";i am the\nman", ";i am the")); 118 | 119 | mpc_delete(re0); 120 | 121 | } 122 | 123 | void test_regex_newline(void) { 124 | 125 | mpc_parser_t *re0 = mpc_re("[a-z]*"); 126 | 127 | PT_ASSERT(regex_test_pass(re0, "hi", "hi")); 128 | PT_ASSERT(regex_test_pass(re0, "hi\nk", "hi")); 129 | PT_ASSERT(regex_test_fail(re0, "hi\nk", "hi\nk")); 130 | 131 | mpc_delete(re0); 132 | 133 | } 134 | 135 | void test_regex_multiline(void) { 136 | 137 | mpc_parser_t *re0 = mpc_re_mode("(^[a-z]*$)*", MPC_RE_MULTILINE); 138 | 139 | PT_ASSERT(regex_test_pass(re0, "hello\nhello", "hello\nhello")); 140 | PT_ASSERT(regex_test_pass(re0, "hello\nhello\n", "hello\nhello\n")); 141 | PT_ASSERT(regex_test_pass(re0, "\nblah\n\nblah\n", "\nblah\n\nblah\n")); 142 | PT_ASSERT(regex_test_fail(re0, "45234", "45234")); 143 | PT_ASSERT(regex_test_fail(re0, "\n45234", "\n45234")); 144 | PT_ASSERT(regex_test_pass(re0, "\n45234", "\n")); 145 | 146 | mpc_delete(re0); 147 | 148 | } 149 | 150 | void test_regex_dotall(void) { 151 | 152 | mpc_parser_t *re0 = mpc_re_mode("^.*$", MPC_RE_DEFAULT); 153 | mpc_parser_t *re1 = mpc_re_mode("^.*$", MPC_RE_DOTALL); 154 | 155 | PT_ASSERT(regex_test_pass(re0, "hello", "hello")); 156 | PT_ASSERT(regex_test_fail(re0, "hello\n", "hello")); 157 | PT_ASSERT(regex_test_fail(re0, "he\nllo\n", "he")); 158 | PT_ASSERT(regex_test_pass(re0, "34njaksdklmasd", "34njaksdklmasd")); 159 | PT_ASSERT(regex_test_fail(re0, "34njaksd\nklmasd", "34njaksd")); 160 | 161 | PT_ASSERT(regex_test_pass(re1, "hello", "hello")); 162 | PT_ASSERT(regex_test_pass(re1, "hello\n", "hello\n")); 163 | PT_ASSERT(regex_test_pass(re1, "he\nllo\n", "he\nllo\n")); 164 | PT_ASSERT(regex_test_pass(re1, "34njaksdklmasd", "34njaksdklmasd")); 165 | PT_ASSERT(regex_test_pass(re1, "34njaksd\nklmasd", "34njaksd\nklmasd")); 166 | 167 | mpc_delete(re0); 168 | mpc_delete(re1); 169 | 170 | } 171 | 172 | void suite_regex(void) { 173 | pt_add_test(test_regex_basic, "Test Regex Basic", "Suite Regex"); 174 | pt_add_test(test_regex_range, "Test Regex Range", "Suite Regex"); 175 | pt_add_test(test_regex_string, "Test Regex String", "Suite Regex"); 176 | pt_add_test(test_regex_lisp_comment, "Test Regex Lisp Comment", "Suite Regex"); 177 | pt_add_test(test_regex_boundary, "Test Regex Boundary", "Suite Regex"); 178 | pt_add_test(test_regex_newline, "Test Regex Newline", "Suite Regex"); 179 | pt_add_test(test_regex_multiline, "Test Regex Multiline", "Suite Regex"); 180 | pt_add_test(test_regex_dotall, "Test Regex Dotall", "Suite Regex"); 181 | } 182 | -------------------------------------------------------------------------------- /tests/test.c: -------------------------------------------------------------------------------- 1 | #include "ptest.h" 2 | 3 | void suite_core(void); 4 | void suite_regex(void); 5 | void suite_grammar(void); 6 | void suite_combinators(void); 7 | 8 | int main(int argc, char** argv) { 9 | (void) argc; (void) argv; 10 | pt_add_suite(suite_core); 11 | pt_add_suite(suite_regex); 12 | pt_add_suite(suite_grammar); 13 | pt_add_suite(suite_combinators); 14 | return pt_run(); 15 | } 16 | 17 | --------------------------------------------------------------------------------