step: start adding C mpc

This commit is contained in:
NunoSempere 2023-04-30 00:41:57 -04:00
parent 7f8b1dfb2f
commit 2ffb9e7d82
38 changed files with 9691 additions and 7 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/src/mpc/.git
/src/mpc/.git/**

View File

@ -13,13 +13,25 @@ DEBUG=-g#-g
## Main file
SRC=./src/mumble.c
MPC=./src/mpc/mpc.c
## Dependencies
DEPS_PC=libedit
# ^ libm, which doesn't have files which pkg-config can find, grr.
DEBUG= #'-g'
INCS=`pkg-config --cflags ${DEPS_PC}`
LIBS_PC=`pkg-config --libs ${DEPS_PC}`
LIBS_DIRECT=-lm
LIBS=$(LIBS_DIRECT) $(LIBS_PC)
# $(CC) $(DEBUG) $(INCS) $(PLUGS) $(SRC) -o rose $(LIBS) $(ADBLOCK)
## Formatter
STYLE_BLUEPRINT=webkit
FORMATTER=clang-format -i -style=$(STYLE_BLUEPRINT)
build: $(SRC)
$(CC) $(SRC) -o mumble $(DEBUG)
$(CC) -Wall $(INCS) $(SRC) $(MPC) -o mumble $(LIBS)
format: $(SRC)
$(FORMATTER) $(SRC)

BIN
mumble

Binary file not shown.

4
notes/reqs.txt Normal file
View File

@ -0,0 +1,4 @@
sudo apt install libedit-dev
# edit line
For Windows: <https://buildyourownlisp.com/chapter4_interactive_prompt>

1
src/mpc/.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
"* text=auto"

11
src/mpc/.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,11 @@
on: [push, pull_request]
name: CI
jobs:
check:
name: Build and test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: make

11
src/mpc/.gitignore vendored Normal file
View File

@ -0,0 +1,11 @@
*~
*.exe
*.dSYM
test
examples/doge
examples/lispy
examples/maths
examples/smallc
examples/foobar
examples/tree_traversal
build/*

28
src/mpc/LICENSE.md Normal file
View File

@ -0,0 +1,28 @@
Licensed Under BSD
Copyright (c) 2013, Daniel Holden
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.

75
src/mpc/Makefile Normal file
View File

@ -0,0 +1,75 @@
PROJ = mpc
CC ?= gcc
STD ?= -ansi
DIST = build
MKDIR ?= mkdir -p
PREFIX ?= /usr/local
CFLAGS ?= $(STD) -pedantic -O3 -g -Wall -Werror -Wextra -Wformat=2 -Wshadow \
-Wno-long-long -Wno-overlength-strings -Wno-format-nonliteral -Wcast-align \
-Wwrite-strings -Wstrict-prototypes -Wold-style-definition -Wredundant-decls \
-Wnested-externs -Wmissing-include-dirs -Wswitch-default
TESTS = $(wildcard tests/*.c)
EXAMPLES = $(wildcard examples/*.c)
EXAMPLESEXE = $(EXAMPLES:.c=)
.PHONY: all check clean libs $(DIST)/$(PROJ).pc
all: $(EXAMPLESEXE) check libs $(DIST)/$(PROJ).pc
$(DIST):
$(MKDIR) $(DIST)
$(MKDIR) $(DIST)/examples
check: $(DIST) $(DIST)/test-file $(DIST)/test-static $(DIST)/test-dynamic
./$(DIST)/test-file
./$(DIST)/test-static
LD_LIBRARY_PATH=$(DIST) ./$(DIST)/test-dynamic
$(DIST)/test-file: $(TESTS) $(PROJ).c $(PROJ).h tests/ptest.h
$(CC) $(filter-out -Werror, $(CFLAGS)) $(TESTS) $(PROJ).c -lm -o $(DIST)/test-file
$(DIST)/test-dynamic: $(TESTS) $(DIST)/lib$(PROJ).so $(PROJ).h tests/ptest.h
$(CC) $(filter-out -Werror, $(CFLAGS)) $(TESTS) -lm -L$(DIST) -l$(PROJ) -o $(DIST)/test-dynamic
$(DIST)/test-static: $(TESTS) $(DIST)/lib$(PROJ).a $(PROJ).h tests/ptest.h
$(CC) $(filter-out -Werror, $(CFLAGS)) $(TESTS) -lm -L$(DIST) -l$(PROJ) -static -o $(DIST)/test-static
examples/%: $(DIST) examples/%.c $(PROJ).c $(PROJ).h
$(CC) $(CFLAGS) $(filter-out $(DIST) $(PROJ).h, $^) -lm -o $(DIST)/$@
$(DIST)/lib$(PROJ).so: $(DIST) $(PROJ).c $(PROJ).h
ifneq ($(OS),Windows_NT)
$(CC) $(CFLAGS) -fPIC -shared $(PROJ).c -o $(DIST)/lib$(PROJ).so
else
$(CC) $(CFLAGS) -shared $(PROJ).c -o $(DIST)/lib$(PROJ).so
endif
$(DIST)/lib$(PROJ).a: $(DIST) $(PROJ).c $(PROJ).h
$(CC) $(CFLAGS) -c $(PROJ).c -o $(DIST)/$(PROJ).o
$(AR) rcs $(DIST)/lib$(PROJ).a $(DIST)/$(PROJ).o
libs: $(DIST)/lib$(PROJ).so $(DIST)/lib$(PROJ).a
$(DIST)/$(PROJ).pc: $(DIST) $(PROJ).pc
cp $(PROJ).pc $(DIST)/$(PROJ).pc
sed -i '1i\prefix=$(PREFIX)/' $(DIST)/$(PROJ).pc
clean:
rm -rf -- $(DIST)
install: all
install -d -m644 $(DESTDIR)$(PREFIX)/include
install -d -m644 $(DESTDIR)$(PREFIX)/lib/pkgconfig
install -d -m644 $(DESTDIR)$(PREFIX)/share/$(PROJ)
install -m755 -t $(DESTDIR)$(PREFIX)/lib $(DIST)/lib*
install -m644 -t $(DESTDIR)$(PREFIX)/share/$(PROJ) $(PROJ).c $(PROJ).h
install -m644 $(PROJ).h $(DESTDIR)$(PREFIX)/include/$(PROJ).h
install -m644 $(DIST)/$(PROJ).pc \
$(DESTDIR)$(PREFIX)/lib/pkgconfig/$(PROJ).pc
uninstall:
rm -rf -- \
$(DESTDIR)$(PREFIX)/include/$(PROJ).h \
$(DESTDIR)$(PREFIX)/share/$(PROJ)/$(PROJ).{c,h} \
$(DESTDIR)$(PREFIX)/lib/lib$(PROJ).{so,a}

999
src/mpc/README.md Normal file
View File

@ -0,0 +1,999 @@
Micro Parser Combinators
========================
Version 0.9.0
About
-----
_mpc_ is a lightweight and powerful Parser Combinator library for C.
Using _mpc_ might be of interest to you if you are...
* Building a new programming language
* Building a new data format
* Parsing an existing programming language
* Parsing an existing data format
* Embedding a Domain Specific Language
* Implementing [Greenspun's Tenth Rule](http://en.wikipedia.org/wiki/Greenspun%27s_tenth_rule)
Features
--------
* Type-Generic
* Predictive, Recursive Descent
* Easy to Integrate (One Source File in ANSI C)
* Automatic Error Message Generation
* Regular Expression Parser Generator
* Language/Grammar Parser Generator
Alternatives
------------
The current main alternative for a C based parser combinator library is a branch of [Cesium3](https://github.com/wbhart/Cesium3/tree/combinators).
_mpc_ provides a number of features that this project does not offer, and also overcomes a number of potential downsides:
* _mpc_ Works for Generic Types
* _mpc_ Doesn't rely on Boehm-Demers-Weiser Garbage Collection
* _mpc_ Doesn't use `setjmp` and `longjmp` for errors
* _mpc_ Doesn't pollute the namespace
Quickstart
==========
Here is how one would use _mpc_ to create a parser for a basic mathematical expression language.
```c
mpc_parser_t *Expr = mpc_new("expression");
mpc_parser_t *Prod = mpc_new("product");
mpc_parser_t *Value = mpc_new("value");
mpc_parser_t *Maths = mpc_new("maths");
mpca_lang(MPCA_LANG_DEFAULT,
" expression : <product> (('+' | '-') <product>)*; "
" product : <value> (('*' | '/') <value>)*; "
" value : /[0-9]+/ | '(' <expression> ')'; "
" maths : /^/ <expression> /$/; ",
Expr, Prod, Value, Maths, NULL);
mpc_result_t r;
if (mpc_parse("input", input, Maths, &r)) {
mpc_ast_print(r.output);
mpc_ast_delete(r.output);
} else {
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
mpc_cleanup(4, Expr, Prod, Value, Maths);
```
If you were to set `input` to the string `(4 * 2 * 11 + 2) - 5`, the printed output would look like this.
```
>
regex
expression|>
value|>
char:1:1 '('
expression|>
product|>
value|regex:1:2 '4'
char:1:4 '*'
value|regex:1:6 '2'
char:1:8 '*'
value|regex:1:10 '11'
char:1:13 '+'
product|value|regex:1:15 '2'
char:1:16 ')'
char:1:18 '-'
product|value|regex:1:20 '5'
regex
```
Getting Started
===============
Introduction
------------
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.
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!
_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.
Basic Parsers
-------------
### String Parsers
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.
* * *
```c
mpc_parser_t *mpc_any(void);
```
Matches any individual character
* * *
```c
mpc_parser_t *mpc_char(char c);
```
Matches a single given character `c`
* * *
```c
mpc_parser_t *mpc_range(char s, char e);
```
Matches any single given character in the range `s` to `e` (inclusive)
* * *
```c
mpc_parser_t *mpc_oneof(const char *s);
```
Matches any single given character in the string `s`
* * *
```c
mpc_parser_t *mpc_noneof(const char *s);
```
Matches any single given character not in the string `s`
* * *
```c
mpc_parser_t *mpc_satisfy(int(*f)(char));
```
Matches any single given character satisfying function `f`
* * *
```c
mpc_parser_t *mpc_string(const char *s);
```
Matches exactly the string `s`
### Other Parsers
Several other functions exist that construct parsers with some other special functionality.
* * *
```c
mpc_parser_t *mpc_pass(void);
```
Consumes no input, always successful, returns `NULL`
* * *
```c
mpc_parser_t *mpc_fail(const char *m);
mpc_parser_t *mpc_failf(const char *fmt, ...);
```
Consumes no input, always fails with message `m` or formatted string `fmt`.
* * *
```c
mpc_parser_t *mpc_lift(mpc_ctor_t f);
```
Consumes no input, always successful, returns the result of function `f`
* * *
```c
mpc_parser_t *mpc_lift_val(mpc_val_t *x);
```
Consumes no input, always successful, returns `x`
* * *
```c
mpc_parser_t *mpc_state(void);
```
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.
* * *
```c
mpc_parser_t *mpc_anchor(int(*f)(char,char));
```
Consumes no input. Successful when function `f` returns true. Always returns `NULL`.
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.
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'`.
Parsing
-------
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.
```c
typedef union {
mpc_err_t *error;
mpc_val_t *output;
} mpc_result_t;
```
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.
* * *
```c
int mpc_parse(const char *filename, const char *string, mpc_parser_t *p, mpc_result_t *r);
```
Run a parser on some string.
* * *
```c
int mpc_parse_file(const char *filename, FILE *file, mpc_parser_t *p, mpc_result_t *r);
```
Run a parser on some file.
* * *
```c
int mpc_parse_pipe(const char *filename, FILE *pipe, mpc_parser_t *p, mpc_result_t *r);
```
Run a parser on some pipe (such as `stdin`).
* * *
```c
int mpc_parse_contents(const char *filename, mpc_parser_t *p, mpc_result_t *r);
```
Run a parser on the contents of some file.
Combinators
-----------
Combinators are functions that take one or more parsers and return a new parser of some given functionality.
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.
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.
Here are the main combinators and how to use then.
* * *
```c
mpc_parser_t *mpc_expect(mpc_parser_t *a, const char *e);
mpc_parser_t *mpc_expectf(mpc_parser_t *a, const char *fmt, ...);
```
Returns a parser that runs `a`, and on success returns the result of `a`, while on failure reports that `e` was expected.
* * *
```c
mpc_parser_t *mpc_apply(mpc_parser_t *a, mpc_apply_t f);
mpc_parser_t *mpc_apply_to(mpc_parser_t *a, mpc_apply_to_t f, void *x);
```
Returns a parser that applies function `f` (optionality taking extra input `x`) to the result of parser `a`.
* * *
```c
mpc_parser_t *mpc_check(mpc_parser_t *a, mpc_dtor_t da, mpc_check_t f, const char *e);
mpc_parser_t *mpc_check_with(mpc_parser_t *a, mpc_dtor_t da, mpc_check_with_t f, void *x, const char *e);
mpc_parser_t *mpc_checkf(mpc_parser_t *a, mpc_dtor_t da, mpc_check_t f, const char *fmt, ...);
mpc_parser_t *mpc_check_withf(mpc_parser_t *a, mpc_dtor_t da, mpc_check_with_t f, void *x, const char *fmt, ...);
```
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`.
* * *
```c
mpc_parser_t *mpc_not(mpc_parser_t *a, mpc_dtor_t da);
mpc_parser_t *mpc_not_lift(mpc_parser_t *a, mpc_dtor_t da, mpc_ctor_t lf);
```
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.
* * *
```c
mpc_parser_t *mpc_maybe(mpc_parser_t *a);
mpc_parser_t *mpc_maybe_lift(mpc_parser_t *a, mpc_ctor_t lf);
```
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`).
* * *
```c
mpc_parser_t *mpc_many(mpc_fold_t f, mpc_parser_t *a);
```
Runs `a` zero or more times until it fails. Results are combined using fold function `f`. See the _Function Types_ section for more details.
* * *
```c
mpc_parser_t *mpc_many1(mpc_fold_t f, mpc_parser_t *a);
```
Runs `a` one or more times until it fails. Results are combined with fold function `f`.
* * *
```c
mpc_parser_t *mpc_count(int n, mpc_fold_t f, mpc_parser_t *a, mpc_dtor_t da);
```
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`.
* * *
```c
mpc_parser_t *mpc_or(int n, ...);
```
Attempts to run `n` parsers in sequence, returning the first one that succeeds. If all fail, returns an error.
* * *
```c
mpc_parser_t *mpc_and(int n, mpc_fold_t f, ...);
```
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.
* * *
```c
mpc_parser_t *mpc_predictive(mpc_parser_t *a);
```
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.
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)`.
Function Types
--------------
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.
* * *
```c
typedef void(*mpc_dtor_t)(mpc_val_t*);
```
Given some pointer to a data value it will ensure the memory it points to is freed correctly.
* * *
```c
typedef mpc_val_t*(*mpc_ctor_t)(void);
```
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.
* * *
```c
typedef mpc_val_t*(*mpc_apply_t)(mpc_val_t*);
typedef mpc_val_t*(*mpc_apply_to_t)(mpc_val_t*,void*);
```
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.
* * *
```c
typedef int(*mpc_check_t)(mpc_val_t**);
typedef int(*mpc_check_with_t)(mpc_val_t**,void*);
```
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.
* * *
```c
typedef mpc_val_t*(*mpc_fold_t)(int,mpc_val_t**);
```
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.
Case Study - Identifier
=======================
Combinator Method
-----------------
Using the above combinators we can create a parser that matches a C identifier.
When using the combinators we need to supply a function that says how to combine two `char *`.
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`.
```c
mpc_val_t *strfold(int n, mpc_val_t **xs) {
char *x = calloc(1, 1);
int i;
for (i = 0; i < n; i++) {
x = realloc(x, strlen(x) + strlen(xs[i]) + 1);
strcat(x, xs[i]);
free(xs[i]);
}
return x;
}
```
We can use this to specify a C identifier, making use of some combinators to say how the basic parsers are combined.
```c
mpc_parser_t *alpha = mpc_or(2, mpc_range('a', 'z'), mpc_range('A', 'Z'));
mpc_parser_t *digit = mpc_range('0', '9');
mpc_parser_t *underscore = mpc_char('_');
mpc_parser_t *ident = mpc_and(2, strfold,
mpc_or(2, alpha, underscore),
mpc_many(strfold, mpc_or(3, alpha, digit, underscore)),
free);
/* Do Some Parsing... */
mpc_delete(ident);
```
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.
Because of this we shouldn't create a parser and input it into multiple places, or it will be doubly freed.
Regex Method
------------
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.
```c
mpc_parser_t *ident = mpc_re("[a-zA-Z_][a-zA-Z_0-9]*");
/* Do Some Parsing... */
mpc_delete(ident);
```
Library Method
--------------
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.
```c
mpc_parser_t *ident = mpc_ident();
/* Do Some Parsing... */
mpc_delete(ident);
```
Parser References
=================
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.
* * *
```c
mpc_parser_t *mpc_new(const char *name);
```
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.
A _retained_ parser can then be _defined_ using...
* * *
```c
mpc_parser_t *mpc_define(mpc_parser_t *p, mpc_parser_t *a);
```
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.
* * *
```c
mpc_parser_t *mpc_undefine(mpc_parser_t *p);
```
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.
* * *
```c
void mpc_cleanup(int n, ...);
```
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.
* * *
```c
mpc_parser_t *mpc_copy(mpc_parser_t *a);
```
This function makes a copy of a parser `a`. This can be useful when you want to
use a parser as input for some other parsers multiple times without retaining
it.
* * *
```c
mpc_parser_t *mpc_re(const char *re);
mpc_parser_t *mpc_re_mode(const char *re, int mode);
```
This function takes as input the regular expression `re` and builds a parser
for it. With the `mpc_re_mode` function optional mode flags can also be given.
Available flags are `MPC_RE_MULTILINE` / `MPC_RE_M` where the start of input
character `^` also matches the beginning of new lines and the end of input `$`
character also matches new lines, and `MPC_RE_DOTALL` / `MPC_RE_S` where the
any character token `.` also matches newlines (by default it doesn't).
Library Reference
=================
Common Parsers
--------------
<table>
<tr><td><code>mpc_soi</code></td><td>Matches only the start of input, returns <code>NULL</code></td></tr>
<tr><td><code>mpc_eoi</code></td><td>Matches only the end of input, returns <code>NULL</code></td></tr>
<tr><td><code>mpc_boundary</code></td><td>Matches only the boundary between words, returns <code>NULL</code></td></tr>
<tr><td><code>mpc_boundary_newline</code></td><td>Matches the start of a new line, returns <code>NULL</code></td></tr>
<tr><td><code>mpc_whitespace</code></td><td>Matches any whitespace character <code>" \f\n\r\t\v"</code></td></tr>
<tr><td><code>mpc_whitespaces</code></td><td>Matches zero or more whitespace characters</td></tr>
<tr><td><code>mpc_blank</code></td><td>Matches whitespaces and frees the result, returns <code>NULL</code></td></tr>
<tr><td><code>mpc_newline</code></td><td>Matches <code>'\n'</code></td></tr>
<tr><td><code>mpc_tab</code></td><td>Matches <code>'\t'</code></td></tr>
<tr><td><code>mpc_escape</code></td><td>Matches a backslash followed by any character</td></tr>
<tr><td><code>mpc_digit</code></td><td>Matches any character in the range <code>'0'</code> - <code>'9'</code></td></tr>
<tr><td><code>mpc_hexdigit</code></td><td>Matches any character in the range <code>'0</code> - <code>'9'</code> as well as <code>'A'</code> - <code>'F'</code> and <code>'a'</code> - <code>'f'</code></td></tr>
<tr><td><code>mpc_octdigit</code></td><td>Matches any character in the range <code>'0'</code> - <code>'7'</code></td></tr>
<tr><td><code>mpc_digits</code></td><td>Matches one or more digit</td></tr>
<tr><td><code>mpc_hexdigits</code></td><td>Matches one or more hexdigit</td></tr>
<tr><td><code>mpc_octdigits</code></td><td>Matches one or more octdigit</td></tr>
<tr><td><code>mpc_lower</code></td><td>Matches any lower case character</td></tr>
<tr><td><code>mpc_upper</code></td><td>Matches any upper case character</td></tr>
<tr><td><code>mpc_alpha</code></td><td>Matches any alphabet character</td></tr>
<tr><td><code>mpc_underscore</code></td><td>Matches <code>'_'</code></td></tr>
<tr><td><code>mpc_alphanum</code></td><td>Matches any alphabet character, underscore or digit</td></tr>
<tr><td><code>mpc_int</code></td><td>Matches digits and returns an <code>int*</code></td></tr>
<tr><td><code>mpc_hex</code></td><td>Matches hexdigits and returns an <code>int*</code></td></tr>
<tr><td><code>mpc_oct</code></td><td>Matches octdigits and returns an <code>int*</code></td></tr>
<tr><td><code>mpc_number</code></td><td>Matches <code>mpc_int</code>, <code>mpc_hex</code> or <code>mpc_oct</code></td></tr>
<tr><td><code>mpc_real</code></td><td>Matches some floating point number as a string</td></tr>
<tr><td><code>mpc_float</code></td><td>Matches some floating point number and returns a <code>float*</code></td></tr>
<tr><td><code>mpc_char_lit</code></td><td>Matches some character literal surrounded by <code>'</code></td></tr>
<tr><td><code>mpc_string_lit</code></td><td>Matches some string literal surrounded by <code>"</code></td></tr>
<tr><td><code>mpc_regex_lit</code></td><td>Matches some regex literal surrounded by <code>/</code></td></tr>
<tr><td><code>mpc_ident</code></td><td>Matches a C style identifier</td></tr>
</table>
Useful Parsers
--------------
<table>
<tr><td><code>mpc_startswith(mpc_parser_t *a);</code></td><td>Matches the start of input followed by <code>a</code></td></tr>
<tr><td><code>mpc_endswith(mpc_parser_t *a, mpc_dtor_t da);</code></td><td>Matches <code>a</code> followed by the end of input</td></tr>
<tr><td><code>mpc_whole(mpc_parser_t *a, mpc_dtor_t da);</code></td><td>Matches the start of input, <code>a</code>, and the end of input</td></tr>
<tr><td><code>mpc_stripl(mpc_parser_t *a);</code></td><td>Matches <code>a</code> first consuming any whitespace to the left</td></tr>
<tr><td><code>mpc_stripr(mpc_parser_t *a);</code></td><td>Matches <code>a</code> then consumes any whitespace to the right</td></tr>
<tr><td><code>mpc_strip(mpc_parser_t *a);</code></td><td>Matches <code>a</code> consuming any surrounding whitespace</td></tr>
<tr><td><code>mpc_tok(mpc_parser_t *a);</code></td><td>Matches <code>a</code> and consumes any trailing whitespace</td></tr>
<tr><td><code>mpc_sym(const char *s);</code></td><td>Matches string <code>s</code> and consumes any trailing whitespace</td></tr>
<tr><td><code>mpc_total(mpc_parser_t *a, mpc_dtor_t da);</code></td><td>Matches the whitespace consumed <code>a</code>, enclosed in the start and end of input</td></tr>
<tr><td><code>mpc_between(mpc_parser_t *a, mpc_dtor_t ad, <br /> const char *o, const char *c);</code></td><td> Matches <code>a</code> between strings <code>o</code> and <code>c</code></td></tr>
<tr><td><code>mpc_parens(mpc_parser_t *a, mpc_dtor_t ad);</code></td><td>Matches <code>a</code> between <code>"("</code> and <code>")"</code></td></tr>
<tr><td><code>mpc_braces(mpc_parser_t *a, mpc_dtor_t ad);</code></td><td>Matches <code>a</code> between <code>"<"</code> and <code>">"</code></td></tr>
<tr><td><code>mpc_brackets(mpc_parser_t *a, mpc_dtor_t ad);</code></td><td>Matches <code>a</code> between <code>"{"</code> and <code>"}"</code></td></tr>
<tr><td><code>mpc_squares(mpc_parser_t *a, mpc_dtor_t ad);</code></td><td>Matches <code>a</code> between <code>"["</code> and <code>"]"</code></td></tr>
<tr><td><code>mpc_tok_between(mpc_parser_t *a, mpc_dtor_t ad, <br /> const char *o, const char *c);</code></td><td>Matches <code>a</code> between <code>o</code> and <code>c</code>, where <code>o</code> and <code>c</code> have their trailing whitespace striped.</td></tr>
<tr><td><code>mpc_tok_parens(mpc_parser_t *a, mpc_dtor_t ad);</code></td><td>Matches <code>a</code> between trailing whitespace consumed <code>"("</code> and <code>")"</code></td></tr>
<tr><td><code>mpc_tok_braces(mpc_parser_t *a, mpc_dtor_t ad);</code></td><td>Matches <code>a</code> between trailing whitespace consumed <code>"<"</code> and <code>">"</code></td></tr>
<tr><td><code>mpc_tok_brackets(mpc_parser_t *a, mpc_dtor_t ad);</code></td><td>Matches <code>a</code> between trailing whitespace consumed <code>"{"</code> and <code>"}"</code></td></tr>
<tr><td><code>mpc_tok_squares(mpc_parser_t *a, mpc_dtor_t ad);</code></td><td>Matches <code>a</code> between trailing whitespace consumed <code>"["</code> and <code>"]"</code></td></tr>
</table>
Apply Functions
---------------
<table>
<tr><td><code>void mpcf_dtor_null(mpc_val_t *x);</code></td><td>Empty destructor. Does nothing</td></tr>
<tr><td><code>mpc_val_t *mpcf_ctor_null(void);</code></td><td>Returns <code>NULL</code></td></tr>
<tr><td><code>mpc_val_t *mpcf_ctor_str(void);</code></td><td>Returns <code>""</code></td></tr>
<tr><td><code>mpc_val_t *mpcf_free(mpc_val_t *x);</code></td><td>Frees <code>x</code> and returns <code>NULL</code></td></tr>
<tr><td><code>mpc_val_t *mpcf_int(mpc_val_t *x);</code></td><td>Converts a decimal string <code>x</code> to an <code>int*</code></td></tr>
<tr><td><code>mpc_val_t *mpcf_hex(mpc_val_t *x);</code></td><td>Converts a hex string <code>x</code> to an <code>int*</code></td></tr>
<tr><td><code>mpc_val_t *mpcf_oct(mpc_val_t *x);</code></td><td>Converts a oct string <code>x</code> to an <code>int*</code></td></tr>
<tr><td><code>mpc_val_t *mpcf_float(mpc_val_t *x);</code></td><td>Converts a string <code>x</code> to a <code>float*</code></td></tr>
<tr><td><code>mpc_val_t *mpcf_escape(mpc_val_t *x);</code></td><td>Converts a string <code>x</code> to an escaped version</td></tr>
<tr><td><code>mpc_val_t *mpcf_escape_regex(mpc_val_t *x);</code></td><td>Converts a regex <code>x</code> to an escaped version</td></tr>
<tr><td><code>mpc_val_t *mpcf_escape_string_raw(mpc_val_t *x);</code></td><td>Converts a raw string <code>x</code> to an escaped version</td></tr>
<tr><td><code>mpc_val_t *mpcf_escape_char_raw(mpc_val_t *x);</code></td><td>Converts a raw character <code>x</code> to an escaped version</td></tr>
<tr><td><code>mpc_val_t *mpcf_unescape(mpc_val_t *x);</code></td><td>Converts a string <code>x</code> to an unescaped version</td></tr>
<tr><td><code>mpc_val_t *mpcf_unescape_regex(mpc_val_t *x);</code></td><td>Converts a regex <code>x</code> to an unescaped version</td></tr>
<tr><td><code>mpc_val_t *mpcf_unescape_string_raw(mpc_val_t *x);</code></td><td>Converts a raw string <code>x</code> to an unescaped version</td></tr>
<tr><td><code>mpc_val_t *mpcf_unescape_char_raw(mpc_val_t *x);</code></td><td>Converts a raw character <code>x</code> to an unescaped version</td></tr>
<tr><td><code>mpc_val_t *mpcf_strtriml(mpc_val_t *x);</code></td><td>Trims whitespace from the left of string <code>x</code></td></tr>
<tr><td><code>mpc_val_t *mpcf_strtrimr(mpc_val_t *x);</code></td><td>Trims whitespace from the right of string <code>x</code></td></tr>
<tr><td><code>mpc_val_t *mpcf_strtrim(mpc_val_t *x);</code></td><td>Trims whitespace from either side of string <code>x</code></td></tr>
</table>
Fold Functions
--------------
<table>
<tr><td><code>mpc_val_t *mpcf_null(int n, mpc_val_t** xs);</code></td><td>Returns <code>NULL</code></td></tr>
<tr><td><code>mpc_val_t *mpcf_fst(int n, mpc_val_t** xs);</code></td><td>Returns first element of <code>xs</code></td></tr>
<tr><td><code>mpc_val_t *mpcf_snd(int n, mpc_val_t** xs);</code></td><td>Returns second element of <code>xs</code></td></tr>
<tr><td><code>mpc_val_t *mpcf_trd(int n, mpc_val_t** xs);</code></td><td>Returns third element of <code>xs</code></td></tr>
<tr><td><code>mpc_val_t *mpcf_fst_free(int n, mpc_val_t** xs);</code></td><td>Returns first element of <code>xs</code> and calls <code>free</code> on others</td></tr>
<tr><td><code>mpc_val_t *mpcf_snd_free(int n, mpc_val_t** xs);</code></td><td>Returns second element of <code>xs</code> and calls <code>free</code> on others</td></tr>
<tr><td><code>mpc_val_t *mpcf_trd_free(int n, mpc_val_t** xs);</code></td><td>Returns third element of <code>xs</code> and calls <code>free</code> on others</td></tr>
<tr><td><code>mpc_val_t *mpcf_all_free(int n, mpc_val_t** xs);</code></td><td>Calls <code>free</code> on all elements of <code>xs</code> and returns <code>NULL</code></td></tr>
<tr><td><code>mpc_val_t *mpcf_strfold(int n, mpc_val_t** xs);</code></td><td>Concatenates all <code>xs</code> together as strings and returns result </td></tr>
</table>
Case Study - Maths Language
===========================
Combinator Approach
-------------------
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.
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.
We start with a fold function that will fold two `int *` into a new `int *` based on some `char *` operator.
```c
mpc_val_t *fold_maths(int n, mpc_val_t **xs) {
int **vs = (int**)xs;
if (strcmp(xs[1], "*") == 0) { *vs[0] *= *vs[2]; }
if (strcmp(xs[1], "/") == 0) { *vs[0] /= *vs[2]; }
if (strcmp(xs[1], "%") == 0) { *vs[0] %= *vs[2]; }
if (strcmp(xs[1], "+") == 0) { *vs[0] += *vs[2]; }
if (strcmp(xs[1], "-") == 0) { *vs[0] -= *vs[2]; }
free(xs[1]); free(xs[2]);
return xs[0];
}
```
And then we use this to specify a basic grammar, which folds together any results.
```c
mpc_parser_t *Expr = mpc_new("expr");
mpc_parser_t *Factor = mpc_new("factor");
mpc_parser_t *Term = mpc_new("term");
mpc_parser_t *Maths = mpc_new("maths");
mpc_define(Expr, mpc_or(2,
mpc_and(3, fold_maths,
Factor, mpc_oneof("+-"), Factor,
free, free),
Factor
));
mpc_define(Factor, mpc_or(2,
mpc_and(3, fold_maths,
Term, mpc_oneof("*/"), Term,
free, free),
Term
));
mpc_define(Term, mpc_or(2, mpc_int(), mpc_parens(Expr, free)));
mpc_define(Maths, mpc_whole(Expr, free));
/* Do Some Parsing... */
mpc_delete(Maths);
```
If we supply this function with something like `(4*2)+5`, we can expect it to output `13`.
Language Approach
-----------------
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_*`.
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.
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.
```
number "number" : /[0-9]+/ ;
expression : <product> (('+' | '-') <product>)* ;
product : <value> (('*' | '/') <value>)* ;
value : <number> | '(' <expression> ')' ;
maths : /^/ <expression> /$/ ;
```
The syntax for this is defined as follows.
<table class='table'>
<tr><td><code>"ab"</code></td><td>The string <code>ab</code> is required.</td></tr>
<tr><td><code>'a'</code></td><td>The character <code>a</code> is required.</td></tr>
<tr><td><code>'a' 'b'</code></td><td>First <code>'a'</code> is required, then <code>'b'</code> is required..</td></tr>
<tr><td><code>'a' | 'b'</code></td><td>Either <code>'a'</code> is required, or <code>'b'</code> is required.</td></tr>
<tr><td><code>'a'*</code></td><td>Zero or more <code>'a'</code> are required.</td></tr>
<tr><td><code>'a'+</code></td><td>One or more <code>'a'</code> are required.</td></tr>
<tr><td><code>'a'?</code></td><td>Zero or one <code>'a'</code> is required.</td></tr>
<tr><td><code>'a'{x}</code></td><td>Exactly <code>x</code> (integer) copies of <code>'a'</code> are required.</td></tr>
<tr><td><code>&lt;abba&gt;</code></td><td>The rule called <code>abba</code> is required.</td></tr>
</table>
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.
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.
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.
* * *
```c
mpc_parser_t *mpca_grammar(int flags, const char *grammar, ...);
```
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.
* * *
```c
mpc_err_t *mpca_lang(int flags, const char *lang, ...);
```
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.
* * *
```c
mpc_err_t *mpca_lang_file(int flags, FILE* f, ...);
```
This reads in the contents of file `f` and inputs it into `mpca_lang`.
* * *
```c
mpc_err_t *mpca_lang_contents(int flags, const char *filename, ...);
```
This opens and reads in the contents of the file given by `filename` and passes it to `mpca_lang`.
Case Study - Tokenizer
======================
Another common task we might be interested in doing is tokenizing some block of
text (splitting the text into individual elements) and performing some function
on each one of these elements as it is read. We can do this with `mpc` too.
First, we can build a regular expression which parses an individual token. For
example if our tokens are identifiers, integers, commas, periods and colons we
could build something like this `mpc_re("\\s*([a-zA-Z_]+|[0-9]+|,|\\.|:)")`.
Next we can strip any whitespace, and add a callback function using `mpc_apply`
which gets called every time this regex is parsed successfully
`mpc_apply(mpc_strip(mpc_re("\\s*([a-zA-Z_]+|[0-9]+|,|\\.|:)")), print_token)`.
Finally we can surround all of this in `mpc_many` to parse it zero or more
times. The final code might look something like this:
```c
static mpc_val_t *print_token(mpc_val_t *x) {
printf("Token: '%s'\n", (char*)x);
return x;
}
int main(int argc, char **argv) {
const char *input = " hello 4352 , \n foo.bar \n\n test:ing ";
mpc_parser_t* Tokens = mpc_many(
mpcf_all_free,
mpc_apply(mpc_strip(mpc_re("\\s*([a-zA-Z_]+|[0-9]+|,|\\.|:)")), print_token));
mpc_result_t r;
mpc_parse("input", input, Tokens, &r);
mpc_delete(Tokens);
return 0;
}
```
Running this program will produce an output something like this:
```
Token: 'hello'
Token: '4352'
Token: ','
Token: 'foo'
Token: '.'
Token: 'bar'
Token: 'test'
Token: ':'
Token: 'ing'
```
By extending the regex we can easily extend this to parse many more types of
tokens and quickly and easily build a tokenizer for whatever language we are
interested in.
Error Reporting
===============
_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:
```
<test>:0:3: error: expected one or more of 'a' or 'd' at 'k'
```
Misc
====
Here are some other misc functions that mpc provides. These functions are susceptible to change between versions so use them with some care.
* * *
```c
void mpc_print(mpc_parser_t *p);
```
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.
* * *
```c
void mpc_stats(mpc_parser_t *p);
```
Prints out some basic stats about a parser. Again used for debugging and optimisation.
* * *
```c
void mpc_optimise(mpc_parser_t *p);
```
Performs some basic optimisations on a parser to reduce it's size and increase its running speed.
Limitations & FAQ
=================
### I'm getting namespace issues due to `libmpc`, what can I do?
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.
### Does _mpc_ support Unicode?
_mpc_ Only supports ASCII. Sorry! Writing a parser library that supports Unicode is pretty difficult. I welcome contributions!
### Is _mpc_ binary safe?
No. Sorry! Including NULL characters in a string or a file will probably break it. Avoid this if possible.
### The Parser is going into an infinite loop!
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.
```
expr : <expr> '+' (<expr> | <int> | <string>);
```
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.
```
value : <int> | <string> ;
expr : <value> ('+' <expr>)* ;
```
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.
### Backtracking isn't working!
_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.
```
factor : <ident>
| <ident> '(' <expr>? (',' <expr>)* ')' ;
```
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.
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.
Now the parser will try to match a function first, and if this fails backtrack and try to match just an identifier.
```
factor : <ident> '(' <expr>? (',' <expr>)* ')'
| <ident> ;
```
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!
```
factor : <ident> ('(' <expr>? (',' <expr>)* ')')? ;
```
### How can I avoid the maximum string literal length?
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.
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.
### The automatic tags in the AST are annoying!
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.
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.
Yes it is annoying but its probably not going to change!

View File

@ -0,0 +1 @@
wow c so language such book

46
src/mpc/examples/doge.c Normal file
View File

@ -0,0 +1,46 @@
#include "../mpc.h"
int main(int argc, char **argv) {
mpc_result_t r;
mpc_parser_t* Adjective = mpc_new("adjective");
mpc_parser_t* Noun = mpc_new("noun");
mpc_parser_t* Phrase = mpc_new("phrase");
mpc_parser_t* Doge = mpc_new("doge");
mpca_lang(MPCA_LANG_DEFAULT,
" adjective : \"wow\" | \"many\" | \"so\" | \"such\"; "
" noun : \"lisp\" | \"language\" | \"c\" | \"book\" | \"build\"; "
" phrase : <adjective> <noun>; "
" doge : /^/ <phrase>* /$/; ",
Adjective, Noun, Phrase, Doge, NULL);
if (argc > 1) {
if (mpc_parse_contents(argv[1], Doge, &r)) {
mpc_ast_print(r.output);
mpc_ast_delete(r.output);
} else {
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
} else {
if (mpc_parse_pipe("<stdin>", stdin, Doge, &r)) {
mpc_ast_print(r.output);
mpc_ast_delete(r.output);
} else {
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
}
mpc_cleanup(4, Adjective, Noun, Phrase, Doge);
return 0;
}

View File

@ -0,0 +1,21 @@
#include "stdio.h"
int fib(int n) {
if (n == 0) { return 0; }
if (n == 1) { return 1; }
return fib(n - 1) + fib(n - 2);
}
main() {
int n;
int i;
while (i < 10) {
n = fib(10);
print(n);
i = i + 1;
}
return 0;
}

28
src/mpc/examples/foobar.c Normal file
View File

@ -0,0 +1,28 @@
#include "../mpc.h"
int main(int argc, char** argv) {
mpc_result_t r;
mpc_parser_t* Foobar;
if (argc != 2) {
printf("Usage: ./foobar <foo/bar>\n");
exit(0);
}
Foobar = mpc_new("foobar");
mpca_lang(MPCA_LANG_DEFAULT, "foobar : \"foo\" | \"bar\";", Foobar);
if (mpc_parse("<stdin>", argv[1], Foobar, &r)) {
mpc_ast_print(r.output);
mpc_ast_delete(r.output);
} else {
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
mpc_cleanup(1, Foobar);
return 0;
}

View File

@ -0,0 +1,34 @@
#include "../mpc.h"
static void* read_line(void* line) {
printf("Reading Line: %s", (char*)line);
return line;
}
int main(int argc, char **argv) {
const char *input =
"abcHVwufvyuevuy3y436782\n"
"\n"
"\n"
"rehre\n"
"rew\n"
"-ql.;qa\n"
"eg";
mpc_parser_t* Line = mpc_many(
mpcf_strfold,
mpc_apply(mpc_re("[^\\n]*(\\n|$)"), read_line));
mpc_result_t r;
(void)argc; (void)argv;
mpc_parse("input", input, Line, &r);
printf("\nParsed String: %s", (char*)r.output);
free(r.output);
mpc_delete(Line);
return 0;
}

55
src/mpc/examples/lispy.c Normal file
View File

@ -0,0 +1,55 @@
#include "../mpc.h"
int main(int argc, char **argv) {
mpc_result_t r;
mpc_parser_t* Number = mpc_new("number");
mpc_parser_t* Symbol = mpc_new("symbol");
mpc_parser_t* String = mpc_new("string");
mpc_parser_t* Comment = mpc_new("comment");
mpc_parser_t* Sexpr = mpc_new("sexpr");
mpc_parser_t* Qexpr = mpc_new("qexpr");
mpc_parser_t* Expr = mpc_new("expr");
mpc_parser_t* Lispy = mpc_new("lispy");
mpca_lang(MPCA_LANG_PREDICTIVE,
" number \"number\" : /[0-9]+/ ; "
" symbol \"symbol\" : /[a-zA-Z0-9_+\\-*\\/\\\\=<>!&]+/ ; "
" string \"string\" : /\"(\\\\.|[^\"])*\"/ ; "
" comment : /;[^\\r\\n]*/ ; "
" sexpr : '(' <expr>* ')' ; "
" qexpr : '{' <expr>* '}' ; "
" expr : <number> | <symbol> | <string> "
" | <comment> | <sexpr> | <qexpr> ; "
" lispy : /^/ <expr>* /$/ ; ",
Number, Symbol, String, Comment, Sexpr, Qexpr, Expr, Lispy, NULL);
if (argc > 1) {
if (mpc_parse_contents(argv[1], Lispy, &r)) {
mpc_ast_print(r.output);
mpc_ast_delete(r.output);
} else {
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
} else {
if (mpc_parse_pipe("<stdin>", stdin, Lispy, &r)) {
mpc_ast_print(r.output);
mpc_ast_delete(r.output);
} else {
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
}
mpc_cleanup(8, Number, Symbol, String, Comment, Sexpr, Qexpr, Expr, Lispy);
return 0;
}

51
src/mpc/examples/maths.c Normal file
View File

@ -0,0 +1,51 @@
#include "../mpc.h"
int main(int argc, char **argv) {
mpc_parser_t *Expr = mpc_new("expression");
mpc_parser_t *Prod = mpc_new("product");
mpc_parser_t *Value = mpc_new("value");
mpc_parser_t *Maths = mpc_new("maths");
mpca_lang(MPCA_LANG_PREDICTIVE,
" expression : <product> (('+' | '-') <product>)*; "
" product : <value> (('*' | '/') <value>)*; "
" value : /[0-9]+/ | '(' <expression> ')'; "
" maths : /^/ <expression> /$/; ",
Expr, Prod, Value, Maths, NULL);
mpc_print(Expr);
mpc_print(Prod);
mpc_print(Value);
mpc_print(Maths);
if (argc > 1) {
mpc_result_t r;
if (mpc_parse_contents(argv[1], Maths, &r)) {
mpc_ast_print(r.output);
mpc_ast_delete(r.output);
} else {
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
} else {
mpc_result_t r;
if (mpc_parse_pipe("<stdin>", stdin, Maths, &r)) {
mpc_ast_print(r.output);
mpc_ast_delete(r.output);
} else {
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
}
mpc_cleanup(4, Expr, Prod, Value, Maths);
return 0;
}

View File

@ -0,0 +1,11 @@
#include "stdio.h"
main() {
int i;
int j;
j = 10;
return 0;
}

View File

@ -0,0 +1,239 @@
;;;
;;; Lispy Standard Prelude
;;;
;;; Atoms
(def {nil} {})
(def {true} 1)
(def {false} 0)
;;; Functional Functions
; Function Definitions
(def {fun} (\ {f b} {
def (head f) (\ (tail f) b)
}))
; Open new scope
(fun {let b} {
((\ {_} b) ())
})
; Unpack List to Function
(fun {unpack f l} {
eval (join (list f) l)
})
; Unapply List to Function
(fun {pack f & xs} {f xs})
; Curried and Uncurried calling
(def {curry} {unpack})
(def {uncurry} {pack})
; Perform Several things in Sequence
(fun {do & l} {
if (== l {})
{{}}
{last l}
})
;;; Logical Functions
; Logical Functions
(fun {not x} {- 1 x})
(fun {or x y} {+ x y})
(fun {and x y} {* x y})
;;; Numeric Functions
; Minimum of Arguments
(fun {min & xs} {
if (== (tail xs) {}) {fst xs}
{do
(= {rest} (unpack min (tail xs)))
(= {item} (fst xs))
(if (< item rest) {item} {rest})
}
})
; Minimum of Arguments
(fun {max & xs} {
if (== (tail xs) {}) {fst xs}
{do
(= {rest} (unpack max (tail xs)))
(= {item} (fst xs))
(if (> item rest) {item} {rest})
}
})
;;; Conditional Functions
(fun {select & cs} {
if (== cs {})
{error "No Selection Found"}
{if (fst (fst cs)) {snd (fst cs)} {unpack select (tail cs)}}
})
(fun {case x & cs} {
if (== cs {})
{error "No Case Found"}
{if (== x (fst (fst cs))) {snd (fst cs)} {unpack case (join (list x) (tail cs))}}
})
(def {otherwise} true)
;;; Misc Functions
(fun {flip f a b} {f b a})
(fun {ghost & xs} {eval xs})
(fun {comp f g x} {f (g x)})
;;; List Functions
; First, Second, or Third Item in List
(fun {fst l} { eval (head l) })
(fun {snd l} { eval (head (tail l)) })
(fun {trd l} { eval (head (tail (tail l))) })
; List Length
(fun {len l} {
if (== l {})
{0}
{+ 1 (len (tail l))}
})
; Nth item in List
(fun {nth n l} {
if (== n 0)
{fst l}
{nth (- n 1) (tail l)}
})
; Last item in List
(fun {last l} {nth (- (len l) 1) l})
; Apply Function to List
(fun {map f l} {
if (== l {})
{{}}
{join (list (f (fst l))) (map f (tail l))}
})
; Apply Filter to List
(fun {filter f l} {
if (== l {})
{{}}
{join (if (f (fst l)) {head l} {{}}) (filter f (tail l))}
})
; Return all of list but last element
(fun {init l} {
if (== (tail l) {})
{{}}
{join (head l) (init (tail l))}
})
; Reverse List
(fun {reverse l} {
if (== l {})
{{}}
{join (reverse (tail l)) (head l)}
})
; Fold Left
(fun {foldl f z l} {
if (== l {})
{z}
{foldl f (f z (fst l)) (tail l)}
})
; Fold Right
(fun {foldr f z l} {
if (== l {})
{z}
{f (fst l) (foldr f z (tail l))}
})
(fun {sum l} {foldl + 0 l})
(fun {product l} {foldl * 1 l})
; Take N items
(fun {take n l} {
if (== n 0)
{{}}
{join (head l) (take (- n 1) (tail l))}
})
; Drop N items
(fun {drop n l} {
if (== n 0)
{l}
{drop (- n 1) (tail l)}
})
; Split at N
(fun {split n l} {list (take n l) (drop n l)})
; Take While
(fun {take-while f l} {
if (not (unpack f (head l)))
{{}}
{join (head l) (take-while f (tail l))}
})
; Drop While
(fun {drop-while f l} {
if (not (unpack f (head l)))
{l}
{drop-while f (tail l)}
})
; Element of List
(fun {elem x l} {
if (== l {})
{false}
{if (== x (fst l)) {true} {elem x (tail l)}}
})
; Find element in list of pairs
(fun {lookup x l} {
if (== l {})
{error "No Element Found"}
{do
(= {key} (fst (fst l)))
(= {val} (snd (fst l)))
(if (== key x) {val} {lookup x (tail l)})
}
})
; Zip two lists together into a list of pairs
(fun {zip x y} {
if (or (== x {}) (== y {}))
{{}}
{join (list (join (head x) (head y))) (zip (tail x) (tail y))}
})
; Unzip a list of pairs into two lists
(fun {unzip l} {
if (== l {})
{{{} {}}}
{do
(= {x} (fst l))
(= {xs} (unzip (tail l)))
(list (join (head x) (fst xs)) (join (tail x) (snd xs)))
}
})
;;; Other Fun
; Fibonacci
(fun {fib n} {
select
{ (== n 0) 0 }
{ (== n 1) 1 }
{ otherwise (+ (fib (- n 1)) (fib (- n 2))) }
})

View File

@ -0,0 +1 @@
(4 * 2 * 11 + 2) - 5

View File

@ -0,0 +1 @@
29 + 2 * 3 - 99 - (5 + 5 + 2) / 100

101
src/mpc/examples/smallc.c Normal file
View File

@ -0,0 +1,101 @@
#include "../mpc.h"
int main(int argc, char **argv) {
mpc_parser_t* Ident = mpc_new("ident");
mpc_parser_t* Number = mpc_new("number");
mpc_parser_t* Character = mpc_new("character");
mpc_parser_t* String = mpc_new("string");
mpc_parser_t* Factor = mpc_new("factor");
mpc_parser_t* Term = mpc_new("term");
mpc_parser_t* Lexp = mpc_new("lexp");
mpc_parser_t* Stmt = mpc_new("stmt");
mpc_parser_t* Exp = mpc_new("exp");
mpc_parser_t* Typeident = mpc_new("typeident");
mpc_parser_t* Decls = mpc_new("decls");
mpc_parser_t* Args = mpc_new("args");
mpc_parser_t* Body = mpc_new("body");
mpc_parser_t* Procedure = mpc_new("procedure");
mpc_parser_t* Main = mpc_new("main");
mpc_parser_t* Includes = mpc_new("includes");
mpc_parser_t* Smallc = mpc_new("smallc");
mpc_err_t* err = mpca_lang(MPCA_LANG_DEFAULT,
" ident : /[a-zA-Z_][a-zA-Z0-9_]*/ ; \n"
" number : /[0-9]+/ ; \n"
" character : /'.'/ ; \n"
" string : /\"(\\\\.|[^\"])*\"/ ; \n"
" \n"
" factor : '(' <lexp> ')' \n"
" | <number> \n"
" | <character> \n"
" | <string> \n"
" | <ident> '(' <lexp>? (',' <lexp>)* ')' \n"
" | <ident> ; \n"
" \n"
" term : <factor> (('*' | '/' | '%') <factor>)* ; \n"
" lexp : <term> (('+' | '-') <term>)* ; \n"
" \n"
" stmt : '{' <stmt>* '}' \n"
" | \"while\" '(' <exp> ')' <stmt> \n"
" | \"if\" '(' <exp> ')' <stmt> \n"
" | <ident> '=' <lexp> ';' \n"
" | \"print\" '(' <lexp>? ')' ';' \n"
" | \"return\" <lexp>? ';' \n"
" | <ident> '(' <ident>? (',' <ident>)* ')' ';' ; \n"
" \n"
" exp : <lexp> '>' <lexp> \n"
" | <lexp> '<' <lexp> \n"
" | <lexp> \">=\" <lexp> \n"
" | <lexp> \"<=\" <lexp> \n"
" | <lexp> \"!=\" <lexp> \n"
" | <lexp> \"==\" <lexp> ; \n"
" \n"
" typeident : (\"int\" | \"char\") <ident> ; \n"
" decls : (<typeident> ';')* ; \n"
" args : <typeident>? (',' <typeident>)* ; \n"
" body : '{' <decls> <stmt>* '}' ; \n"
" procedure : (\"int\" | \"char\") <ident> '(' <args> ')' <body> ; \n"
" main : \"main\" '(' ')' <body> ; \n"
" includes : (\"#include\" <string>)* ; \n"
" smallc : /^/ <includes> <decls> <procedure>* <main> /$/ ; \n",
Ident, Number, Character, String, Factor, Term, Lexp, Stmt, Exp,
Typeident, Decls, Args, Body, Procedure, Main, Includes, Smallc, NULL);
if (err != NULL) {
mpc_err_print(err);
mpc_err_delete(err);
exit(1);
}
if (argc > 1) {
mpc_result_t r;
if (mpc_parse_contents(argv[1], Smallc, &r)) {
mpc_ast_print(r.output);
mpc_ast_delete(r.output);
} else {
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
} else {
mpc_result_t r;
if (mpc_parse_pipe("<stdin>", stdin, Smallc, &r)) {
mpc_ast_print(r.output);
mpc_ast_delete(r.output);
} else {
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
}
mpc_cleanup(17, Ident, Number, Character, String, Factor, Term, Lexp, Stmt, Exp,
Typeident, Decls, Args, Body, Procedure, Main, Includes, Smallc);
return 0;
}

2009
src/mpc/examples/so_c.doge Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,119 @@
#include "../mpc.h"
int main(int argc, char *argv[]) {
mpc_parser_t *Input = mpc_new("input");
mpc_parser_t *Node = mpc_new("node");
mpc_parser_t *Leaf = mpc_new("leaf");
mpc_ast_t *ast, *tree, *child, *child_sub, *ast_next;
mpc_ast_trav_t *trav;
mpc_result_t r;
int index, lb, i;
mpca_lang(MPCA_LANG_PREDICTIVE,
" node : '(' <node> ',' /foo/ ',' <node> ')' | <leaf>;"
" leaf : /bar/;"
" input : /^/ <node> /$/;",
Node, Leaf, Input, NULL);
if (argc > 1) {
if (mpc_parse_contents(argv[1], Input, &r)) {
ast = r.output;
} else {
mpc_err_print(r.error);
mpc_err_delete(r.error);
mpc_cleanup(3, Node, Leaf, Input);
return EXIT_FAILURE;
}
} else {
if (mpc_parse_pipe("<stdin>", stdin, Input, &r)) {
ast = r.output;
} else {
mpc_err_print(r.error);
mpc_err_delete(r.error);
mpc_cleanup(3, Node, Leaf, Input);
return EXIT_FAILURE;
}
}
/* Get index or child of tree */
tree = ast->children[1];
index = mpc_ast_get_index(tree, "node|>");
child = mpc_ast_get_child(tree, "node|>");
if(child == NULL) {
mpc_cleanup(3, Node, Leaf, Input);
mpc_ast_delete(ast);
return EXIT_FAILURE;
}
printf("Index: %d; Child: \"%s\"\n", index, child->tag);
/* Get multiple indexes or children of trees */
index = mpc_ast_get_index_lb(child, "node|leaf|regex", 0);
child_sub = mpc_ast_get_child_lb(child, "node|leaf|regex", 0);
while(index != -1) {
printf("-- Index: %d; Child: \"%s\"\n", index, child_sub->tag);
lb = index + 1;
index = mpc_ast_get_index_lb(child, "node|leaf|regex", lb);
child_sub = mpc_ast_get_child_lb(child, "node|leaf|regex", lb);
}
/* Traversal */
printf("Pre order tree traversal.\n");
trav = mpc_ast_traverse_start(ast, mpc_ast_trav_order_pre);
ast_next = mpc_ast_traverse_next(&trav);
while(ast_next != NULL) {
printf("Tag: %s; Contents: %s\n",
ast_next->tag,
ast_next->contents);
ast_next = mpc_ast_traverse_next(&trav);
}
mpc_ast_traverse_free(&trav);
printf("Post order tree traversal.\n");
trav = mpc_ast_traverse_start(ast, mpc_ast_trav_order_post);
ast_next = mpc_ast_traverse_next(&trav);
while(ast_next != NULL) {
printf("Tag: %s; Contents: %s\n",
ast_next->tag,
ast_next->contents);
ast_next = mpc_ast_traverse_next(&trav);
}
mpc_ast_traverse_free(&trav);
printf("Partial traversal.\n");
trav = mpc_ast_traverse_start(ast, mpc_ast_trav_order_post);
ast_next = mpc_ast_traverse_next(&trav);
for(i=0; i<2 && ast_next != NULL; i++) {
printf("Tag: %s; Contents: %s\n",
ast_next->tag,
ast_next->contents);
ast_next = mpc_ast_traverse_next(&trav);
}
mpc_ast_traverse_free(&trav);
/* Clean up and return */
mpc_cleanup(3, Node, Leaf, Input);
mpc_ast_delete(ast);
return EXIT_SUCCESS;
}

4056
src/mpc/mpc.c Normal file

File diff suppressed because it is too large Load Diff

389
src/mpc/mpc.h Normal file
View File

@ -0,0 +1,389 @@
/*
** mpc - Micro Parser Combinator library for C
**
** https://github.com/orangeduck/mpc
**
** Daniel Holden - contact@daniel-holden.com
** Licensed under BSD3
*/
#ifndef mpc_h
#define mpc_h
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <errno.h>
#include <ctype.h>
/*
** State Type
*/
typedef struct {
long pos;
long row;
long col;
int term;
} mpc_state_t;
/*
** Error Type
*/
typedef struct {
mpc_state_t state;
int expected_num;
char *filename;
char *failure;
char **expected;
char received;
} mpc_err_t;
void mpc_err_delete(mpc_err_t *e);
char *mpc_err_string(mpc_err_t *e);
void mpc_err_print(mpc_err_t *e);
void mpc_err_print_to(mpc_err_t *e, FILE *f);
/*
** Parsing
*/
typedef void mpc_val_t;
typedef union {
mpc_err_t *error;
mpc_val_t *output;
} mpc_result_t;
struct mpc_parser_t;
typedef struct mpc_parser_t mpc_parser_t;
int mpc_parse(const char *filename, const char *string, mpc_parser_t *p, mpc_result_t *r);
int mpc_nparse(const char *filename, const char *string, size_t length, mpc_parser_t *p, mpc_result_t *r);
int mpc_parse_file(const char *filename, FILE *file, mpc_parser_t *p, mpc_result_t *r);
int mpc_parse_pipe(const char *filename, FILE *pipe, mpc_parser_t *p, mpc_result_t *r);
int mpc_parse_contents(const char *filename, mpc_parser_t *p, mpc_result_t *r);
/*
** Function Types
*/
typedef void(*mpc_dtor_t)(mpc_val_t*);
typedef mpc_val_t*(*mpc_ctor_t)(void);
typedef mpc_val_t*(*mpc_apply_t)(mpc_val_t*);
typedef mpc_val_t*(*mpc_apply_to_t)(mpc_val_t*,void*);
typedef mpc_val_t*(*mpc_fold_t)(int,mpc_val_t**);
typedef int(*mpc_check_t)(mpc_val_t**);
typedef int(*mpc_check_with_t)(mpc_val_t**,void*);
/*
** Building a Parser
*/
mpc_parser_t *mpc_new(const char *name);
mpc_parser_t *mpc_copy(mpc_parser_t *a);
mpc_parser_t *mpc_define(mpc_parser_t *p, mpc_parser_t *a);
mpc_parser_t *mpc_undefine(mpc_parser_t *p);
void mpc_delete(mpc_parser_t *p);
void mpc_cleanup(int n, ...);
/*
** Basic Parsers
*/
mpc_parser_t *mpc_any(void);
mpc_parser_t *mpc_char(char c);
mpc_parser_t *mpc_range(char s, char e);
mpc_parser_t *mpc_oneof(const char *s);
mpc_parser_t *mpc_noneof(const char *s);
mpc_parser_t *mpc_satisfy(int(*f)(char));
mpc_parser_t *mpc_string(const char *s);
/*
** Other Parsers
*/
mpc_parser_t *mpc_pass(void);
mpc_parser_t *mpc_fail(const char *m);
mpc_parser_t *mpc_failf(const char *fmt, ...);
mpc_parser_t *mpc_lift(mpc_ctor_t f);
mpc_parser_t *mpc_lift_val(mpc_val_t *x);
mpc_parser_t *mpc_anchor(int(*f)(char,char));
mpc_parser_t *mpc_state(void);
/*
** Combinator Parsers
*/
mpc_parser_t *mpc_expect(mpc_parser_t *a, const char *e);
mpc_parser_t *mpc_expectf(mpc_parser_t *a, const char *fmt, ...);
mpc_parser_t *mpc_apply(mpc_parser_t *a, mpc_apply_t f);
mpc_parser_t *mpc_apply_to(mpc_parser_t *a, mpc_apply_to_t f, void *x);
mpc_parser_t *mpc_check(mpc_parser_t *a, mpc_dtor_t da, mpc_check_t f, const char *e);
mpc_parser_t *mpc_check_with(mpc_parser_t *a, mpc_dtor_t da, mpc_check_with_t f, void *x, const char *e);
mpc_parser_t *mpc_checkf(mpc_parser_t *a, mpc_dtor_t da, mpc_check_t f, const char *fmt, ...);
mpc_parser_t *mpc_check_withf(mpc_parser_t *a, mpc_dtor_t da, mpc_check_with_t f, void *x, const char *fmt, ...);
mpc_parser_t *mpc_not(mpc_parser_t *a, mpc_dtor_t da);
mpc_parser_t *mpc_not_lift(mpc_parser_t *a, mpc_dtor_t da, mpc_ctor_t lf);
mpc_parser_t *mpc_maybe(mpc_parser_t *a);
mpc_parser_t *mpc_maybe_lift(mpc_parser_t *a, mpc_ctor_t lf);
mpc_parser_t *mpc_many(mpc_fold_t f, mpc_parser_t *a);
mpc_parser_t *mpc_many1(mpc_fold_t f, mpc_parser_t *a);
mpc_parser_t *mpc_count(int n, mpc_fold_t f, mpc_parser_t *a, mpc_dtor_t da);
mpc_parser_t *mpc_or(int n, ...);
mpc_parser_t *mpc_and(int n, mpc_fold_t f, ...);
mpc_parser_t *mpc_predictive(mpc_parser_t *a);
/*
** Common Parsers
*/
mpc_parser_t *mpc_eoi(void);
mpc_parser_t *mpc_soi(void);
mpc_parser_t *mpc_boundary(void);
mpc_parser_t *mpc_boundary_newline(void);
mpc_parser_t *mpc_whitespace(void);
mpc_parser_t *mpc_whitespaces(void);
mpc_parser_t *mpc_blank(void);
mpc_parser_t *mpc_newline(void);
mpc_parser_t *mpc_tab(void);
mpc_parser_t *mpc_escape(void);
mpc_parser_t *mpc_digit(void);
mpc_parser_t *mpc_hexdigit(void);
mpc_parser_t *mpc_octdigit(void);
mpc_parser_t *mpc_digits(void);
mpc_parser_t *mpc_hexdigits(void);
mpc_parser_t *mpc_octdigits(void);
mpc_parser_t *mpc_lower(void);
mpc_parser_t *mpc_upper(void);
mpc_parser_t *mpc_alpha(void);
mpc_parser_t *mpc_underscore(void);
mpc_parser_t *mpc_alphanum(void);
mpc_parser_t *mpc_int(void);
mpc_parser_t *mpc_hex(void);
mpc_parser_t *mpc_oct(void);
mpc_parser_t *mpc_number(void);
mpc_parser_t *mpc_real(void);
mpc_parser_t *mpc_float(void);
mpc_parser_t *mpc_char_lit(void);
mpc_parser_t *mpc_string_lit(void);
mpc_parser_t *mpc_regex_lit(void);
mpc_parser_t *mpc_ident(void);
/*
** Useful Parsers
*/
mpc_parser_t *mpc_startwith(mpc_parser_t *a);
mpc_parser_t *mpc_endwith(mpc_parser_t *a, mpc_dtor_t da);
mpc_parser_t *mpc_whole(mpc_parser_t *a, mpc_dtor_t da);
mpc_parser_t *mpc_stripl(mpc_parser_t *a);
mpc_parser_t *mpc_stripr(mpc_parser_t *a);
mpc_parser_t *mpc_strip(mpc_parser_t *a);
mpc_parser_t *mpc_tok(mpc_parser_t *a);
mpc_parser_t *mpc_sym(const char *s);
mpc_parser_t *mpc_total(mpc_parser_t *a, mpc_dtor_t da);
mpc_parser_t *mpc_between(mpc_parser_t *a, mpc_dtor_t ad, const char *o, const char *c);
mpc_parser_t *mpc_parens(mpc_parser_t *a, mpc_dtor_t ad);
mpc_parser_t *mpc_braces(mpc_parser_t *a, mpc_dtor_t ad);
mpc_parser_t *mpc_brackets(mpc_parser_t *a, mpc_dtor_t ad);
mpc_parser_t *mpc_squares(mpc_parser_t *a, mpc_dtor_t ad);
mpc_parser_t *mpc_tok_between(mpc_parser_t *a, mpc_dtor_t ad, const char *o, const char *c);
mpc_parser_t *mpc_tok_parens(mpc_parser_t *a, mpc_dtor_t ad);
mpc_parser_t *mpc_tok_braces(mpc_parser_t *a, mpc_dtor_t ad);
mpc_parser_t *mpc_tok_brackets(mpc_parser_t *a, mpc_dtor_t ad);
mpc_parser_t *mpc_tok_squares(mpc_parser_t *a, mpc_dtor_t ad);
/*
** Common Function Parameters
*/
void mpcf_dtor_null(mpc_val_t *x);
mpc_val_t *mpcf_ctor_null(void);
mpc_val_t *mpcf_ctor_str(void);
mpc_val_t *mpcf_free(mpc_val_t *x);
mpc_val_t *mpcf_int(mpc_val_t *x);
mpc_val_t *mpcf_hex(mpc_val_t *x);
mpc_val_t *mpcf_oct(mpc_val_t *x);
mpc_val_t *mpcf_float(mpc_val_t *x);
mpc_val_t *mpcf_strtriml(mpc_val_t *x);
mpc_val_t *mpcf_strtrimr(mpc_val_t *x);
mpc_val_t *mpcf_strtrim(mpc_val_t *x);
mpc_val_t *mpcf_escape(mpc_val_t *x);
mpc_val_t *mpcf_escape_regex(mpc_val_t *x);
mpc_val_t *mpcf_escape_string_raw(mpc_val_t *x);
mpc_val_t *mpcf_escape_char_raw(mpc_val_t *x);
mpc_val_t *mpcf_unescape(mpc_val_t *x);
mpc_val_t *mpcf_unescape_regex(mpc_val_t *x);
mpc_val_t *mpcf_unescape_string_raw(mpc_val_t *x);
mpc_val_t *mpcf_unescape_char_raw(mpc_val_t *x);
mpc_val_t *mpcf_null(int n, mpc_val_t** xs);
mpc_val_t *mpcf_fst(int n, mpc_val_t** xs);
mpc_val_t *mpcf_snd(int n, mpc_val_t** xs);
mpc_val_t *mpcf_trd(int n, mpc_val_t** xs);
mpc_val_t *mpcf_fst_free(int n, mpc_val_t** xs);
mpc_val_t *mpcf_snd_free(int n, mpc_val_t** xs);
mpc_val_t *mpcf_trd_free(int n, mpc_val_t** xs);
mpc_val_t *mpcf_all_free(int n, mpc_val_t** xs);
mpc_val_t *mpcf_freefold(int n, mpc_val_t** xs);
mpc_val_t *mpcf_strfold(int n, mpc_val_t** xs);
/*
** Regular Expression Parsers
*/
enum {
MPC_RE_DEFAULT = 0,
MPC_RE_M = 1,
MPC_RE_S = 2,
MPC_RE_MULTILINE = 1,
MPC_RE_DOTALL = 2
};
mpc_parser_t *mpc_re(const char *re);
mpc_parser_t *mpc_re_mode(const char *re, int mode);
/*
** AST
*/
typedef struct mpc_ast_t {
char *tag;
char *contents;
mpc_state_t state;
int children_num;
struct mpc_ast_t** children;
} mpc_ast_t;
mpc_ast_t *mpc_ast_new(const char *tag, const char *contents);
mpc_ast_t *mpc_ast_build(int n, const char *tag, ...);
mpc_ast_t *mpc_ast_add_root(mpc_ast_t *a);
mpc_ast_t *mpc_ast_add_child(mpc_ast_t *r, mpc_ast_t *a);
mpc_ast_t *mpc_ast_add_tag(mpc_ast_t *a, const char *t);
mpc_ast_t *mpc_ast_add_root_tag(mpc_ast_t *a, const char *t);
mpc_ast_t *mpc_ast_tag(mpc_ast_t *a, const char *t);
mpc_ast_t *mpc_ast_state(mpc_ast_t *a, mpc_state_t s);
void mpc_ast_delete(mpc_ast_t *a);
void mpc_ast_print(mpc_ast_t *a);
void mpc_ast_print_to(mpc_ast_t *a, FILE *fp);
int mpc_ast_get_index(mpc_ast_t *ast, const char *tag);
int mpc_ast_get_index_lb(mpc_ast_t *ast, const char *tag, int lb);
mpc_ast_t *mpc_ast_get_child(mpc_ast_t *ast, const char *tag);
mpc_ast_t *mpc_ast_get_child_lb(mpc_ast_t *ast, const char *tag, int lb);
typedef enum {
mpc_ast_trav_order_pre,
mpc_ast_trav_order_post
} mpc_ast_trav_order_t;
typedef struct mpc_ast_trav_t {
mpc_ast_t *curr_node;
struct mpc_ast_trav_t *parent;
int curr_child;
mpc_ast_trav_order_t order;
} mpc_ast_trav_t;
mpc_ast_trav_t *mpc_ast_traverse_start(mpc_ast_t *ast,
mpc_ast_trav_order_t order);
mpc_ast_t *mpc_ast_traverse_next(mpc_ast_trav_t **trav);
void mpc_ast_traverse_free(mpc_ast_trav_t **trav);
/*
** Warning: This function currently doesn't test for equality of the `state` member!
*/
int mpc_ast_eq(mpc_ast_t *a, mpc_ast_t *b);
mpc_val_t *mpcf_fold_ast(int n, mpc_val_t **as);
mpc_val_t *mpcf_str_ast(mpc_val_t *c);
mpc_val_t *mpcf_state_ast(int n, mpc_val_t **xs);
mpc_parser_t *mpca_tag(mpc_parser_t *a, const char *t);
mpc_parser_t *mpca_add_tag(mpc_parser_t *a, const char *t);
mpc_parser_t *mpca_root(mpc_parser_t *a);
mpc_parser_t *mpca_state(mpc_parser_t *a);
mpc_parser_t *mpca_total(mpc_parser_t *a);
mpc_parser_t *mpca_not(mpc_parser_t *a);
mpc_parser_t *mpca_maybe(mpc_parser_t *a);
mpc_parser_t *mpca_many(mpc_parser_t *a);
mpc_parser_t *mpca_many1(mpc_parser_t *a);
mpc_parser_t *mpca_count(int n, mpc_parser_t *a);
mpc_parser_t *mpca_or(int n, ...);
mpc_parser_t *mpca_and(int n, ...);
enum {
MPCA_LANG_DEFAULT = 0,
MPCA_LANG_PREDICTIVE = 1,
MPCA_LANG_WHITESPACE_SENSITIVE = 2
};
mpc_parser_t *mpca_grammar(int flags, const char *grammar, ...);
mpc_err_t *mpca_lang(int flags, const char *language, ...);
mpc_err_t *mpca_lang_file(int flags, FILE *f, ...);
mpc_err_t *mpca_lang_pipe(int flags, FILE *f, ...);
mpc_err_t *mpca_lang_contents(int flags, const char *filename, ...);
/*
** Misc
*/
void mpc_print(mpc_parser_t *p);
void mpc_optimise(mpc_parser_t *p);
void mpc_stats(mpc_parser_t *p);
int mpc_test_pass(mpc_parser_t *p, const char *s, const void *d,
int(*tester)(const void*, const void*),
mpc_dtor_t destructor,
void(*printer)(const void*));
int mpc_test_fail(mpc_parser_t *p, const char *s, const void *d,
int(*tester)(const void*, const void*),
mpc_dtor_t destructor,
void(*printer)(const void*));
#ifdef __cplusplus
}
#endif
#endif

8
src/mpc/mpc.pc Normal file
View File

@ -0,0 +1,8 @@
libdir=${prefix}/lib
includedir=${prefix}/include
Name: mpc
Description: Library for creating parser combinators
Version: 0.9.0
Libs: -L${libdir} -lmpc
Cflags: -I${includedir}

9
src/mpc/package.json Normal file
View File

@ -0,0 +1,9 @@
{
"name": "mpc",
"version": "0.9.8",
"repo": "orangeduck/mpc",
"description": "A Parser Combinator library for C",
"keywords": ["parser", "combinator", "library", "c", "mpc"],
"license": "BSD",
"src": ["mpc.c", "mpc.h"]
}

View File

@ -0,0 +1,89 @@
#include "ptest.h"
#include "../mpc.h"
static int check_is_a(mpc_val_t** x) {
return strcmp(*x, "a") == 0;
}
static int check_is(mpc_val_t** x, void* t) {
return strcmp(*x, t) == 0;
}
void test_check(void) {
int success;
mpc_result_t r;
mpc_parser_t* p = mpc_check(mpc_or(2, mpc_char('a'), mpc_char('b')), free, check_is_a, "Expected 'a'");
success = mpc_parse("test", "a", p, &r);
PT_ASSERT(success);
PT_ASSERT_STR_EQ(r.output, "a");
if (success) free(r.output); else mpc_err_delete(r.error);
success = mpc_parse("test", "b", p, &r);
PT_ASSERT(!success);
PT_ASSERT_STR_EQ(r.error->failure, "Expected 'a'");
if (success) free(r.output); else mpc_err_delete(r.error);
mpc_delete(p);
}
void test_check_with(void) {
int success;
mpc_result_t r;
mpc_parser_t* p = mpc_check_with(mpc_or(2, mpc_char('a'), mpc_char('b')), free, check_is, (void*)"a", "Expected 'a'");
success = mpc_parse("test", "a", p, &r);
PT_ASSERT(success);
if (success) PT_ASSERT_STR_EQ(r.output, "a");
if (success) free(r.output); else mpc_err_delete(r.error);
success = mpc_parse("test", "b", p, &r);
PT_ASSERT(!success);
if (!success) PT_ASSERT_STR_EQ(r.error->failure, "Expected 'a'");
if (success) free(r.output); else mpc_err_delete(r.error);
mpc_delete(p);
}
void test_checkf(void) {
int success;
mpc_result_t r;
mpc_parser_t* p = mpc_checkf(mpc_or(2, mpc_char('a'), mpc_char('b')), free, check_is_a, "Expected '%s'", "a");
success = mpc_parse("test", "a", p, &r);
PT_ASSERT(success);
PT_ASSERT_STR_EQ(r.output, "a");
if (success) free(r.output); else mpc_err_delete(r.error);
success = mpc_parse("test", "b", p, &r);
PT_ASSERT(!success);
PT_ASSERT_STR_EQ(r.error->failure, "Expected 'a'");
if (success) free(r.output); else mpc_err_delete(r.error);
mpc_delete(p);
}
void test_check_withf(void) {
int success;
mpc_result_t r;
mpc_parser_t* p = mpc_check_withf(mpc_or(2, mpc_char('a'), mpc_char('b')), free, check_is, (void*)"a", "Expected '%s'", "a");
success = mpc_parse("test", "a", p, &r);
PT_ASSERT(success);
if (success) PT_ASSERT_STR_EQ(r.output, "a");
if (success) free(r.output); else mpc_err_delete(r.error);
success = mpc_parse("test", "b", p, &r);
PT_ASSERT(!success);
if (!success) PT_ASSERT_STR_EQ(r.error->failure, "Expected 'a'");
if (success) free(r.output); else mpc_err_delete(r.error);
mpc_delete(p);
}
void suite_combinators(void) {
pt_add_test(test_check, "Test Check", "Suite Combinators");
pt_add_test(test_check_with, "Test Check with", "Suite Combinators");
pt_add_test(test_checkf, "Test Check F", "Suite Combinators");
pt_add_test(test_check_withf, "Test Check with F", "Suite Combinators");
}

254
src/mpc/tests/core.c Normal file
View File

@ -0,0 +1,254 @@
#include "ptest.h"
#include "../mpc.h"
#include <stdlib.h>
#include <string.h>
static int int_eq(const void* x, const void* y) { return (*(int*)x == *(int*)y); }
static void int_print(const void* x) { printf("'%i'", *((int*)x)); }
static int streq(const void* x, const void* y) { return (strcmp(x, y) == 0); }
static void strprint(const void* x) { printf("'%s'", (char*)x); }
void test_ident(void) {
/* ^[a-zA-Z_][a-zA-Z0-9_]*$ */
mpc_parser_t* Ident = mpc_whole(
mpc_and(2, mpcf_strfold,
mpc_or(2, mpc_alpha(), mpc_underscore()),
mpc_many1(mpcf_strfold, mpc_or(3, mpc_alpha(), mpc_underscore(), mpc_digit())),
free),
free
);
PT_ASSERT(mpc_test_pass(Ident, "test", "test", streq, free, strprint));
PT_ASSERT(mpc_test_fail(Ident, " blah", "", streq, free, strprint));
PT_ASSERT(mpc_test_pass(Ident, "anoth21er", "anoth21er", streq, free, strprint));
PT_ASSERT(mpc_test_pass(Ident, "du__de", "du__de", streq, free, strprint));
PT_ASSERT(mpc_test_fail(Ident, "some spaces", "", streq, free, strprint));
PT_ASSERT(mpc_test_fail(Ident, "", "", streq, free, strprint));
PT_ASSERT(mpc_test_fail(Ident, "18nums", "", streq, free, strprint));
mpc_delete(Ident);
}
static mpc_val_t *mpcf_maths(int n, mpc_val_t **xs) {
int **vs = (int**)xs;
(void) n;
switch(((char*)xs[1])[0])
{
case '*': { *vs[0] *= *vs[2]; }; break;
case '/': { *vs[0] /= *vs[2]; }; break;
case '%': { *vs[0] %= *vs[2]; }; break;
case '+': { *vs[0] += *vs[2]; }; break;
case '-': { *vs[0] -= *vs[2]; }; break;
default: break;
}
free(xs[1]); free(xs[2]);
return xs[0];
}
void test_maths(void) {
mpc_parser_t *Expr, *Factor, *Term, *Maths;
int r0 = 1, r1 = 5, r2 = 13, r3 = 0, r4 = 2;
Expr = mpc_new("expr");
Factor = mpc_new("factor");
Term = mpc_new("term");
Maths = mpc_new("maths");
mpc_define(Expr, mpc_or(2,
mpc_and(3, mpcf_maths, Factor, mpc_oneof("+-"), Factor, free, free),
Factor
));
mpc_define(Factor, mpc_or(2,
mpc_and(3, mpcf_maths, Term, mpc_oneof("*/"), Term, free, free),
Term
));
mpc_define(Term, mpc_or(2,
mpc_int(),
mpc_parens(Expr, free)
));
mpc_define(Maths, mpc_whole(Expr, free));
PT_ASSERT(mpc_test_pass(Maths, "1", &r0, int_eq, free, int_print));
PT_ASSERT(mpc_test_pass(Maths, "(5)", &r1, int_eq, free, int_print));
PT_ASSERT(mpc_test_pass(Maths, "(4*2)+5", &r2, int_eq, free, int_print));
PT_ASSERT(mpc_test_pass(Maths, "4*2+5", &r2, int_eq, free, int_print));
PT_ASSERT(mpc_test_fail(Maths, "a", &r3, int_eq, free, int_print));
PT_ASSERT(mpc_test_fail(Maths, "2b+4", &r4, int_eq, free, int_print));
mpc_cleanup(4, Expr, Factor, Term, Maths);
}
void test_strip(void) {
mpc_parser_t *Stripperl = mpc_apply(mpc_many(mpcf_strfold, mpc_any()), mpcf_strtriml);
mpc_parser_t *Stripperr = mpc_apply(mpc_many(mpcf_strfold, mpc_any()), mpcf_strtrimr);
mpc_parser_t *Stripper = mpc_apply(mpc_many(mpcf_strfold, mpc_any()), mpcf_strtrim);
PT_ASSERT(mpc_test_pass(Stripperl, " asdmlm dasd ", "asdmlm dasd ", streq, free, strprint));
PT_ASSERT(mpc_test_pass(Stripperr, " asdmlm dasd ", " asdmlm dasd", streq, free, strprint));
PT_ASSERT(mpc_test_pass(Stripper, " asdmlm dasd ", "asdmlm dasd", streq, free, strprint));
mpc_delete(Stripperl);
mpc_delete(Stripperr);
mpc_delete(Stripper);
}
void test_repeat(void) {
int success;
mpc_result_t r;
mpc_parser_t *p = mpc_count(3, mpcf_strfold, mpc_digit(), free);
success = mpc_parse("test", "046", p, &r);
PT_ASSERT(success);
PT_ASSERT_STR_EQ(r.output, "046");
free(r.output);
success = mpc_parse("test", "046aa", p, &r);
PT_ASSERT(success);
PT_ASSERT_STR_EQ(r.output, "046");
free(r.output);
success = mpc_parse("test", "04632", p, &r);
PT_ASSERT(success);
PT_ASSERT_STR_EQ(r.output, "046");
free(r.output);
success = mpc_parse("test", "04", p, &r);
PT_ASSERT(!success);
mpc_err_delete(r.error);
mpc_delete(p);
}
void test_copy(void) {
int success;
mpc_result_t r;
mpc_parser_t* p = mpc_or(2, mpc_char('a'), mpc_char('b'));
mpc_parser_t* q = mpc_and(2, mpcf_strfold, p, mpc_copy(p), free);
success = mpc_parse("test", "aa", q, &r);
PT_ASSERT(success);
PT_ASSERT_STR_EQ(r.output, "aa");
free(r.output);
success = mpc_parse("test", "bb", q, &r);
PT_ASSERT(success);
PT_ASSERT_STR_EQ(r.output, "bb");
free(r.output);
success = mpc_parse("test", "ab", q, &r);
PT_ASSERT(success);
PT_ASSERT_STR_EQ(r.output, "ab");
free(r.output);
success = mpc_parse("test", "ba", q, &r);
PT_ASSERT(success);
PT_ASSERT_STR_EQ(r.output, "ba");
free(r.output);
success = mpc_parse("test", "c", p, &r);
PT_ASSERT(!success);
mpc_err_delete(r.error);
mpc_delete(mpc_copy(p));
mpc_delete(mpc_copy(q));
mpc_delete(q);
}
static int line_count = 0;
static mpc_val_t* read_line(mpc_val_t* line) {
line_count++;
return line;
}
void test_reader(void) {
mpc_parser_t* Line = mpc_many(
mpcf_strfold,
mpc_apply(mpc_re("[^\\n]*(\\n|$)"), read_line));
line_count = 0;
PT_ASSERT(mpc_test_pass(Line,
"hello\nworld\n\nthis\nis\ndan",
"hello\nworld\n\nthis\nis\ndan", streq, free, strprint));
PT_ASSERT(line_count == 6);
line_count = 0;
PT_ASSERT(mpc_test_pass(Line,
"abcHVwufvyuevuy3y436782\n\n\nrehre\nrew\n-ql.;qa\neg",
"abcHVwufvyuevuy3y436782\n\n\nrehre\nrew\n-ql.;qa\neg", streq, free, strprint));
PT_ASSERT(line_count == 7);
mpc_delete(Line);
}
static int token_count = 0;
static mpc_val_t *print_token(mpc_val_t *x) {
/*printf("Token: '%s'\n", (char*)x);*/
token_count++;
return x;
}
void test_tokens(void) {
mpc_parser_t* Tokens = mpc_many(
mpcf_strfold,
mpc_apply(mpc_strip(mpc_re("\\s*([a-zA-Z_]+|[0-9]+|,|\\.|:)")), print_token));
token_count = 0;
PT_ASSERT(mpc_test_pass(Tokens,
" hello 4352 , \n foo.bar \n\n test:ing ",
"hello4352,foo.bartest:ing", streq, free, strprint));
PT_ASSERT(token_count == 9);
mpc_delete(Tokens);
}
void test_eoi(void) {
mpc_parser_t* Line = mpc_re("[^\\n]*$");
PT_ASSERT(mpc_test_pass(Line, "blah", "blah", streq, free, strprint));
PT_ASSERT(mpc_test_pass(Line, "blah\n", "blah\n", streq, free, strprint));
mpc_delete(Line);
}
void suite_core(void) {
pt_add_test(test_ident, "Test Ident", "Suite Core");
pt_add_test(test_maths, "Test Maths", "Suite Core");
pt_add_test(test_strip, "Test Strip", "Suite Core");
pt_add_test(test_repeat, "Test Repeat", "Suite Core");
pt_add_test(test_copy, "Test Copy", "Suite Core");
pt_add_test(test_reader, "Test Reader", "Suite Core");
pt_add_test(test_tokens, "Test Tokens", "Suite Core");
pt_add_test(test_eoi, "Test EOI", "Suite Core");
}

1
src/mpc/tests/digits.txt Normal file
View File

@ -0,0 +1 @@
123

413
src/mpc/tests/grammar.c Normal file
View File

@ -0,0 +1,413 @@
#include "ptest.h"
#include "../mpc.h"
void test_grammar(void) {
mpc_parser_t *Expr, *Prod, *Value, *Maths;
mpc_ast_t *t0, *t1, *t2;
Expr = mpc_new("expression");
Prod = mpc_new("product");
Value = mpc_new("value");
Maths = mpc_new("maths");
mpc_define(Expr, mpca_grammar(MPCA_LANG_DEFAULT, " <product> (('+' | '-') <product>)* ", Prod));
mpc_define(Prod, mpca_grammar(MPCA_LANG_DEFAULT, " <value> (('*' | '/') <value>)* ", Value));
mpc_define(Value, mpca_grammar(MPCA_LANG_DEFAULT, " /[0-9]+/ | '(' <expression> ')' ", Expr));
mpc_define(Maths, mpca_total(Expr));
t0 = mpc_ast_new("product|value|regex", "24");
t1 = mpc_ast_build(1, "product|>",
mpc_ast_build(3, "value|>",
mpc_ast_new("char", "("),
mpc_ast_new("expression|product|value|regex", "5"),
mpc_ast_new("char", ")")));
t2 = mpc_ast_build(3, ">",
mpc_ast_build(3, "product|value|>",
mpc_ast_new("char", "("),
mpc_ast_build(3, "expression|>",
mpc_ast_build(5, "product|>",
mpc_ast_new("value|regex", "4"),
mpc_ast_new("char", "*"),
mpc_ast_new("value|regex", "2"),
mpc_ast_new("char", "*"),
mpc_ast_new("value|regex", "11")),
mpc_ast_new("char", "+"),
mpc_ast_new("product|value|regex", "2")),
mpc_ast_new("char", ")")),
mpc_ast_new("char", "+"),
mpc_ast_new("product|value|regex", "5"));
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));
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));
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));
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));
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));
mpc_ast_delete(t0);
mpc_ast_delete(t1);
mpc_ast_delete(t2);
mpc_cleanup(4, Expr, Prod, Value, Maths);
}
void test_language(void) {
mpc_parser_t *Expr, *Prod, *Value, *Maths;
Expr = mpc_new("expression");
Prod = mpc_new("product");
Value = mpc_new("value");
Maths = mpc_new("maths");
mpca_lang(MPCA_LANG_DEFAULT,
" expression : <product> (('+' | '-') <product>)*; "
" product : <value> (('*' | '/') <value>)*; "
" value : /[0-9]+/ | '(' <expression> ')'; "
" maths : /^/ <expression> /$/; ",
Expr, Prod, Value, Maths);
mpc_cleanup(4, Expr, Prod, Value, Maths);
}
void test_language_file(void) {
mpc_parser_t *Expr, *Prod, *Value, *Maths;
Expr = mpc_new("expression");
Prod = mpc_new("product");
Value = mpc_new("value");
Maths = mpc_new("maths");
mpca_lang_contents(MPCA_LANG_DEFAULT, "./tests/maths.grammar", Expr, Prod, Value, Maths);
mpc_cleanup(4, Expr, Prod, Value, Maths);
}
void test_doge(void) {
mpc_ast_t *t0;
mpc_parser_t* Adjective = mpc_new("adjective");
mpc_parser_t* Noun = mpc_new("noun");
mpc_parser_t* Phrase = mpc_new("phrase");
mpc_parser_t* Doge = mpc_new("doge");
mpca_lang(MPCA_LANG_DEFAULT,
" adjective : \"wow\" | \"many\" | \"so\" | \"such\"; "
" noun : \"lisp\" | \"language\" | \"c\" | \"book\" | \"build\"; "
" phrase : <adjective> <noun>; "
" doge : /^/ <phrase>* /$/; ",
Adjective, Noun, Phrase, Doge, NULL);
t0 =
mpc_ast_build(4, ">",
mpc_ast_new("regex", ""),
mpc_ast_build(2, "phrase|>",
mpc_ast_new("adjective|string", "so"),
mpc_ast_new("noun|string", "c")),
mpc_ast_build(2, "phrase|>",
mpc_ast_new("adjective|string", "so"),
mpc_ast_new("noun|string", "c")),
mpc_ast_new("regex", "")
);
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));
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));
mpc_ast_delete(t0);
mpc_cleanup(4, Adjective, Noun, Phrase, Doge);
}
void test_partial(void) {
mpc_ast_t *t0;
mpc_err_t *err;
mpc_parser_t *Line = mpc_new("line");
mpc_parser_t *Number = mpc_new("number");
mpc_parser_t *QuotedString = mpc_new("quoted_string");
mpc_parser_t *LinePragma = mpc_new("linepragma");
mpc_parser_t *Parser = mpc_new("parser");
mpc_define(Line, mpca_tag(mpc_apply(mpc_sym("#line"), mpcf_str_ast), "string"));
err = mpca_lang(MPCA_LANG_PREDICTIVE,
"number : /[0-9]+/ ;\n"
"quoted_string : /\"(\\.|[^\"])*\"/ ;\n"
"linepragma : <line> <number> <quoted_string>;\n"
"parser : /^/ (<linepragma>)* /$/ ;\n",
Line, Number, QuotedString, LinePragma, Parser, NULL);
PT_ASSERT(err == NULL);
t0 = mpc_ast_build(3, ">",
mpc_ast_new("regex", ""),
mpc_ast_build(3, "linepragma|>",
mpc_ast_new("line|string", "#line"),
mpc_ast_new("number|regex", "10"),
mpc_ast_new("quoted_string|regex", "\"test\"")),
mpc_ast_new("regex", ""));
PT_ASSERT(mpc_test_pass(Parser, "#line 10 \"test\"", t0,
(int(*)(const void*,const void*))mpc_ast_eq,
(mpc_dtor_t)mpc_ast_delete,
(void(*)(const void*))mpc_ast_print));
mpc_ast_delete(t0);
mpc_cleanup(5, Line, Number, QuotedString, LinePragma, Parser);
}
void test_qscript(void) {
mpc_ast_t *t0;
mpc_parser_t *Qscript = mpc_new("qscript");
mpc_parser_t *Comment = mpc_new("comment");
mpc_parser_t *Resource = mpc_new("resource");
mpc_parser_t *Rtype = mpc_new("rtype");
mpc_parser_t *Rname = mpc_new("rname");
mpc_parser_t *InnerBlock = mpc_new("inner_block");
mpc_parser_t *Statement = mpc_new("statement");
mpc_parser_t *Function = mpc_new("function");
mpc_parser_t *Parameter = mpc_new("parameter");
mpc_parser_t *Literal = mpc_new("literal");
mpc_parser_t *Block = mpc_new("block");
mpc_parser_t *Seperator = mpc_new("seperator");
mpc_parser_t *Qstring = mpc_new("qstring");
mpc_parser_t *SimpleStr = mpc_new("simplestr");
mpc_parser_t *ComplexStr = mpc_new("complexstr");
mpc_parser_t *Number = mpc_new("number");
mpc_parser_t *Float = mpc_new("float");
mpc_parser_t *Int = mpc_new("int");
mpc_err_t *err = mpca_lang(0,
" qscript : /^/ (<comment> | <resource>)* /$/ ;\n"
" comment : '#' /[^\\n]*/ ;\n"
"resource : '[' (<rtype> <rname>) ']' <inner_block> ;\n"
" rtype : /[*]*/ ;\n"
" rname : <qstring> ;\n"
"\n"
"inner_block : (<comment> | <statement>)* ;\n"
" statement : <function> '(' (<comment> | <parameter> | <block>)* ')' <seperator> ;\n"
" function : <qstring> ;\n"
" parameter : (<statement> | <literal>) ;\n"
" literal : (<number> | <qstring>) <seperator> ;\n"
" block : '{' <inner_block> '}' ;\n"
" seperator : ',' | \"\" ;\n"
"\n"
"qstring : (<complexstr> | <simplestr>) <qstring>* ;\n"
" simplestr : /[a-zA-Z0-9_!@#$%^&\\*_+\\-\\.=\\/<>]+/ ;\n"
" complexstr : (/\"[^\"]*\"/ | /'[^']*'/) ;\n"
"\n"
"number : (<float> | <int>) ;\n"
" float : /[-+]?[0-9]+\\.[0-9]+/ ;\n"
" int : /[-+]?[0-9]+/ ;\n",
Qscript, Comment, Resource, Rtype, Rname, InnerBlock, Statement, Function,
Parameter, Literal, Block, Seperator, Qstring, SimpleStr, ComplexStr, Number,
Float, Int, NULL);
PT_ASSERT(err == NULL);
t0 = mpc_ast_build(3, ">",
mpc_ast_new("regex", ""),
mpc_ast_build(5, "resource|>",
mpc_ast_new("char", "["),
mpc_ast_new("rtype|regex", ""),
mpc_ast_new("rname|qstring|simplestr|regex", "my_func"),
mpc_ast_new("char", "]"),
mpc_ast_build(5, "inner_block|statement|>",
mpc_ast_new("function|qstring|simplestr|regex", "echo"),
mpc_ast_new("char", "("),
mpc_ast_build(2, "parameter|literal|>",
mpc_ast_build(2, "qstring|>",
mpc_ast_new("simplestr|regex", "a"),
mpc_ast_build(2, "qstring|>",
mpc_ast_new("simplestr|regex", "b"),
mpc_ast_new("qstring|simplestr|regex", "c")
)
),
mpc_ast_new("seperator|string", "")
),
mpc_ast_new("char", ")"),
mpc_ast_new("seperator|string", "")
)
),
mpc_ast_new("regex", ""));
PT_ASSERT(mpc_test_pass(Qscript, "[my_func]\n echo (a b c)\n", t0,
(int(*)(const void*,const void*))mpc_ast_eq,
(mpc_dtor_t)mpc_ast_delete,
(void(*)(const void*))mpc_ast_print));
mpc_ast_delete(t0);
mpc_cleanup(18, Qscript, Comment, Resource, Rtype, Rname, InnerBlock,
Statement, Function, Parameter, Literal, Block, Seperator, Qstring,
SimpleStr, ComplexStr, Number, Float, Int);
}
void test_missingrule(void) {
int result;
mpc_err_t *err;
mpc_result_t r;
mpc_parser_t *Parser = mpc_new("parser");
err = mpca_lang(MPCA_LANG_DEFAULT,
"parser : /^/ (<missing>)* /$/ ;\n",
Parser, NULL);
PT_ASSERT(err == NULL);
result = mpc_parse("<stdin>", "test", Parser, &r);
PT_ASSERT(result == 0);
PT_ASSERT(r.error != NULL);
PT_ASSERT(strcmp(r.error->failure, "Unknown Parser 'missing'!") == 0);
mpc_err_delete(r.error);
mpc_cleanup(1, Parser);
}
void test_regex_mode(void) {
mpc_parser_t *Line0, *Line1, *Line2, *Line3;
mpc_ast_t *t0, *t1, *t2, *t3, *t4;
Line0 = mpc_new("line0");
Line1 = mpc_new("line1");
Line2 = mpc_new("line2");
Line3 = mpc_new("line3");
mpca_lang(MPCA_LANG_DEFAULT, " line0 : /.*/; ", Line0);
mpca_lang(MPCA_LANG_DEFAULT, " line1 : /.*/s; ", Line1);
mpca_lang(MPCA_LANG_DEFAULT, " line2 : /(^[a-z]*$)*/; ", Line2);
mpca_lang(MPCA_LANG_DEFAULT, " line3 : /(^[a-z]*$)*/m; ", Line3);
t0 = mpc_ast_new("regex", "blah");
t1 = mpc_ast_new("regex", "blah\nblah");
t2 = mpc_ast_new("regex", "");
t3 = mpc_ast_new("regex", "blah");
t4 = mpc_ast_new("regex", "blah\nblah");
PT_ASSERT(mpc_test_pass(Line0, "blah\nblah", t0,
(int(*)(const void*,const void*))mpc_ast_eq,
(mpc_dtor_t)mpc_ast_delete,
(void(*)(const void*))mpc_ast_print));
PT_ASSERT(mpc_test_pass(Line1, "blah\nblah", t1,
(int(*)(const void*,const void*))mpc_ast_eq,
(mpc_dtor_t)mpc_ast_delete,
(void(*)(const void*))mpc_ast_print));
PT_ASSERT(mpc_test_pass(Line2, "blah\nblah", t2,
(int(*)(const void*,const void*))mpc_ast_eq,
(mpc_dtor_t)mpc_ast_delete,
(void(*)(const void*))mpc_ast_print));
PT_ASSERT(mpc_test_pass(Line2, "blah", t3,
(int(*)(const void*,const void*))mpc_ast_eq,
(mpc_dtor_t)mpc_ast_delete,
(void(*)(const void*))mpc_ast_print));
PT_ASSERT(mpc_test_pass(Line3, "blah\nblah", t4,
(int(*)(const void*,const void*))mpc_ast_eq,
(mpc_dtor_t)mpc_ast_delete,
(void(*)(const void*))mpc_ast_print));
mpc_ast_delete(t0);
mpc_ast_delete(t1);
mpc_ast_delete(t2);
mpc_ast_delete(t3);
mpc_ast_delete(t4);
mpc_cleanup(4, Line0, Line1, Line2, Line3);
}
void test_digits_file(void) {
FILE *f;
mpc_result_t r;
mpc_parser_t *Digit = mpc_new("digit");
mpc_parser_t *Program = mpc_new("program");
mpc_ast_t* t0;
mpc_err_t* err = mpca_lang(MPCA_LANG_DEFAULT,
" digit : /[0-9]/ ;"
" program : /^/ <digit>+ /$/ ;"
, Digit, Program, NULL);
PT_ASSERT(err == NULL);
t0 = mpc_ast_build(5, ">",
mpc_ast_new("regex", ""),
mpc_ast_new("digit|regex", "1"),
mpc_ast_new("digit|regex", "2"),
mpc_ast_new("digit|regex", "3"),
mpc_ast_new("regex", ""));
if (mpc_parse_contents("tests/digits.txt", Program, &r)) {
PT_ASSERT(1);
PT_ASSERT(mpc_ast_eq(t0, r.output));
mpc_ast_delete(r.output);
} else {
PT_ASSERT(0);
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
f = fopen("tests/digits.txt", "r");
PT_ASSERT(f != NULL);
if (mpc_parse_file("tests/digits.txt", f, Program, &r)) {
PT_ASSERT(1);
PT_ASSERT(mpc_ast_eq(t0, r.output));
mpc_ast_delete(r.output);
} else {
PT_ASSERT(0);
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
fclose(f);
if (mpc_parse("tests/digits.txt", "123", Program, &r)) {
PT_ASSERT(1);
PT_ASSERT(mpc_ast_eq(t0, r.output));
mpc_ast_delete(r.output);
} else {
PT_ASSERT(0);
mpc_err_print(r.error);
mpc_err_delete(r.error);
}
mpc_ast_delete(t0);
mpc_cleanup(2, Digit, Program);
}
void suite_grammar(void) {
pt_add_test(test_grammar, "Test Grammar", "Suite Grammar");
pt_add_test(test_language, "Test Language", "Suite Grammar");
pt_add_test(test_language_file, "Test Language File", "Suite Grammar");
pt_add_test(test_doge, "Test Doge", "Suite Grammar");
pt_add_test(test_partial, "Test Partial", "Suite Grammar");
pt_add_test(test_qscript, "Test QScript", "Suite Grammar");
pt_add_test(test_missingrule, "Test Missing Rule", "Suite Grammar");
pt_add_test(test_regex_mode, "Test Regex Mode", "Suite Grammar");
pt_add_test(test_digits_file, "Test Digits File", "Suite Grammar");
}

View File

@ -0,0 +1,7 @@
expression : <product> (('+' | '-') <product>)*;
product : <value> (('*' | '/') <value>)*;
value : /[0-9]+/ | '(' <expression> ')';
maths : /^/ <expression> /$/;

356
src/mpc/tests/ptest.c Normal file
View File

@ -0,0 +1,356 @@
#include "ptest.h"
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
/* Globals */
enum {
MAX_NAME = 512
};
enum {
MAX_ERROR = 2048
};
enum {
MAX_TESTS = 2048
};
static int test_passing = 0;
static int suite_passing = 0;
/* Colors */
enum {
BLACK = 0,
BLUE = 1,
GREEN = 2,
AQUA = 3,
RED = 4,
PURPLE = 5,
YELLOW = 6,
WHITE = 7,
GRAY = 8,
LIGHT_BLUE = 9,
LIGHT_GREEN = 10,
LIGHT_AQUA = 11,
LIGHT_RED = 12,
LIGHT_PURPLE = 13,
LIGHT_YELLOW = 14,
LIGHT_WHITE = 15,
DEFAULT = 16
};
#ifdef _WIN32
#include <windows.h>
static WORD defaults;
static int defaults_loaded = 0;
static void pt_color(int color) {
HANDLE cnsl = GetStdHandle(STD_OUTPUT_HANDLE);
if (!defaults_loaded) {
CONSOLE_SCREEN_BUFFER_INFO info;
GetConsoleScreenBufferInfo(cnsl, &info);
defaults = info.wAttributes;
defaults_loaded = 1;
}
SetConsoleTextAttribute(cnsl, color == DEFAULT ? defaults : color);
}
#else
static const char* colors[] = {
"\x1B[0m",
"\x1B[34m",
"\x1B[32m",
"\x1B[36m",
"\x1B[31m",
"\x1B[35m",
"\x1B[33m",
"\x1B[37m",
"",
"\x1B[34m",
"\x1B[32m",
"\x1B[36m",
"\x1B[31m",
"\x1B[35m",
"\x1B[33m",
"\x1B[37m",
"\x1B[39m",
};
static void pt_color(int color) {
printf("%s", colors[color]);
}
#endif
/* Asserts */
static int num_asserts = 0;
static int num_assert_passes = 0;
static int num_assert_fails = 0;
static char assert_err[MAX_ERROR];
static char assert_err_buff[MAX_ERROR];
static int assert_err_num = 0;
void pt_assert_run(int result, const char* expr, const char* file, int line) {
num_asserts++;
test_passing = test_passing && result;
if (result) {
num_assert_passes++;
} else {
sprintf(assert_err_buff,
" %i. Assert [ %s ] (%s:%i)\n",
assert_err_num+1, expr, file, line );
strcat(assert_err, assert_err_buff);
assert_err_num++;
num_assert_fails++;
}
}
static void ptest_signal(int sig) {
test_passing = 0;
switch( sig ) {
case SIGFPE: sprintf(assert_err_buff,
" %i. Division by Zero\n", assert_err_num+1);
break;
case SIGILL: sprintf(assert_err_buff,
" %i. Illegal Instruction\n", assert_err_num+1);
break;
case SIGSEGV: sprintf(assert_err_buff,
" %i. Segmentation Fault\n", assert_err_num+1);
break;
default: break;
}
assert_err_num++;
strcat(assert_err, assert_err_buff);
pt_color(RED);
printf("Failed! \n\n%s\n", assert_err);
pt_color(DEFAULT);
puts(" | Stopping Execution.");
fflush(stdout);
exit(0);
}
/* Tests */
static void pt_title_case(char* output, const char* input) {
int space = 1;
unsigned int i;
strcpy(output, input);
for(i = 0; i < strlen(output); i++) {
if (output[i] == '_' || output[i] == ' ') {
space = 1;
output[i] = ' ';
continue;
}
if (space && output[i] >= 'a' && output[i] <= 'z') {
space = 0;
output[i] = output[i] - 32;
continue;
}
space = 0;
}
}
typedef struct {
void (*func)(void);
char name[MAX_NAME];
char suite[MAX_NAME];
} test_t;
static test_t tests[MAX_TESTS];
static int num_tests = 0;
static int num_tests_passes = 0;
static int num_tests_fails = 0;
void pt_add_test(void (*func)(void), const char* name, const char* suite) {
test_t test;
if (num_tests == MAX_TESTS) {
printf("ERROR: Exceeded maximum test count of %i!\n",
MAX_TESTS); abort();
}
if (strlen(name) >= MAX_NAME) {
printf("ERROR: Test name '%s' too long (Maximum is %i characters)\n",
name, MAX_NAME); abort();
}
if (strlen(suite) >= MAX_NAME) {
printf("ERROR: Test suite '%s' too long (Maximum is %i characters)\n",
suite, MAX_NAME); abort();
}
test.func = func;
pt_title_case(test.name, name);
pt_title_case(test.suite, suite);
tests[num_tests] = test;
num_tests++;
}
/* Suites */
static int num_suites = 0;
static int num_suites_passes = 0;
static int num_suites_fails = 0;
void pt_add_suite(void (*func)(void)) {
num_suites++;
func();
}
/* Running */
static clock_t start, end;
static char current_suite[MAX_NAME];
int pt_run(void) {
int i;
double total;
test_t test;
puts("");
puts(" +-------------------------------------------+");
puts(" | ptest MicroTesting Magic for C |");
puts(" | |");
puts(" | http://github.com/orangeduck/ptest |");
puts(" | |");
puts(" | Daniel Holden (contact@theorangeduck.com) |");
puts(" +-------------------------------------------+");
signal(SIGFPE, ptest_signal);
signal(SIGILL, ptest_signal);
signal(SIGSEGV, ptest_signal);
start = clock();
strcpy(current_suite, "");
for(i = 0; i < num_tests; i++) {
test = tests[i];
/* Check for transition to a new suite */
if (strcmp(test.suite, current_suite)) {
/* Don't increment any counter for first entrance */
if (strcmp(current_suite, "")) {
if (suite_passing) {
num_suites_passes++;
} else {
num_suites_fails++;
}
}
suite_passing = 1;
strcpy(current_suite, test.suite);
printf("\n\n ===== %s =====\n\n", current_suite);
}
/* Run Test */
test_passing = 1;
strcpy(assert_err, "");
strcpy(assert_err_buff, "");
assert_err_num = 0;
printf(" | %s ... ", test.name);
fflush(stdout);
test.func();
suite_passing = suite_passing && test_passing;
if (test_passing) {
num_tests_passes++;
pt_color(GREEN);
puts("Passed!");
pt_color(DEFAULT);
} else {
num_tests_fails++;
pt_color(RED);
printf("Failed! \n\n%s\n", assert_err);
pt_color(DEFAULT);
}
}
if (suite_passing) {
num_suites_passes++;
} else {
num_suites_fails++;
}
end = clock();
puts("");
puts(" +---------------------------------------------------+");
puts(" | Summary |");
puts(" +---------++------------+-------------+-------------+");
printf(" | Suites ||");
pt_color(YELLOW); printf(" Total %4d ", num_suites);
pt_color(DEFAULT); putchar('|');
pt_color(GREEN); printf(" Passed %4d ", num_suites_passes);
pt_color(DEFAULT); putchar('|');
pt_color(RED); printf(" Failed %4d ", num_suites_fails);
pt_color(DEFAULT); puts("|");
printf(" | Tests ||");
pt_color(YELLOW); printf(" Total %4d ", num_tests);
pt_color(DEFAULT); putchar('|');
pt_color(GREEN); printf(" Passed %4d ", num_tests_passes);
pt_color(DEFAULT); putchar('|');
pt_color(RED); printf(" Failed %4d ", num_tests_fails);
pt_color(DEFAULT); puts("|");
printf(" | Asserts ||");
pt_color(YELLOW); printf(" Total %4d ", num_asserts);
pt_color(DEFAULT); putchar('|');
pt_color(GREEN); printf(" Passed %4d ", num_assert_passes);
pt_color(DEFAULT); putchar('|');
pt_color(RED); printf(" Failed %4d ", num_assert_fails);
pt_color(DEFAULT); puts("|");
puts(" +---------++------------+-------------+-------------+");
puts("");
total = (double)(end - start) / CLOCKS_PER_SEC;
printf(" Total Running Time: %0.3fs\n\n", total);
if (num_suites_fails > 0) { return 1; } else { return 0; }
}

22
src/mpc/tests/ptest.h Normal file
View File

@ -0,0 +1,22 @@
#ifndef ptest_h
#define ptest_h
#include <string.h>
#define PT_SUITE(name) void name(void)
#define PT_FUNC(name) static void name(void)
#define PT_REG(name) pt_add_test(name, #name)
#define PT_TEST(name) auto void name(void); PT_REG(name); void name(void)
#define PT_ASSERT(expr) pt_assert_run((int)(expr), #expr, __FILE__, __LINE__)
#define PT_ASSERT_STR_EQ(fst, snd) pt_assert_run(strcmp(fst, snd) == 0, "strcmp( " #fst ", " #snd " ) == 0", __FILE__, __LINE__)
void pt_assert_run(int result, const char* expr, const char* file, int line);
void pt_add_test(void (*func)(void), const char* name, const char* suite);
void pt_add_suite(void (*func)(void));
int pt_run(void);
#endif

181
src/mpc/tests/regex.c Normal file
View File

@ -0,0 +1,181 @@
#include "ptest.h"
#include "../mpc.h"
#include <string.h>
#include <stdlib.h>
static int string_eq(const void* x, const void* y) { return (strcmp(x, y) == 0); }
static void string_print(const void* x) { printf("'%s'", (char*)x); }
int regex_test_pass(mpc_parser_t *p, const char* value, const char* match) {
return mpc_test_pass(p, value, match, string_eq, free, string_print);
}
int regex_test_fail(mpc_parser_t *p, const char* value, const char* match) {
return mpc_test_fail(p, value, match, string_eq, free, string_print);
}
void test_regex_basic(void) {
mpc_parser_t *re0, *re1, *re2, *re3, *re4, *re5;
re0 = mpc_re("abc|bcd");
re1 = mpc_re("abc|bcd|e");
re2 = mpc_re("ab()c(ab)*");
re3 = mpc_re("abc(abdd)?");
re4 = mpc_re("ab|c(abdd)?");
re5 = mpc_re("abc(ab|dd)+g$");
PT_ASSERT(regex_test_pass(re0, "abc", "abc"));
PT_ASSERT(regex_test_pass(re0, "bcd", "bcd"));
PT_ASSERT(regex_test_fail(re0, "bc", "bc"));
PT_ASSERT(regex_test_fail(re0, "ab", "ab"));
PT_ASSERT(regex_test_pass(re1, "e", "e"));
PT_ASSERT(regex_test_pass(re2, "abc", "abc"));
PT_ASSERT(regex_test_pass(re2, "abcabab", "abcabab"));
PT_ASSERT(regex_test_pass(re2, "abcababd", "abcabab"));
PT_ASSERT(regex_test_pass(re5, "abcddg", "abcddg"));
mpc_delete(re0);
mpc_delete(re1);
mpc_delete(re2);
mpc_delete(re3);
mpc_delete(re4);
mpc_delete(re5);
}
void test_regex_boundary(void) {
mpc_parser_t *re0, *re1, *re2;
re0 = mpc_re("\\bfoo\\b");
re1 = mpc_re("(w| )?\\bfoo\\b");
re2 = mpc_re("py\\B.*");
PT_ASSERT(regex_test_pass(re0, "foo", "foo"));
PT_ASSERT(regex_test_pass(re0, "foo.", "foo"));
PT_ASSERT(regex_test_pass(re0, "foo)", "foo"));
PT_ASSERT(regex_test_pass(re0, "foo baz", "foo"));
PT_ASSERT(regex_test_fail(re0, "foobar", "foo"));
PT_ASSERT(regex_test_fail(re0, "foo3", "foo"));
PT_ASSERT(regex_test_pass(re1, "foo", "foo"));
PT_ASSERT(regex_test_pass(re1, " foo", " foo"));
PT_ASSERT(regex_test_fail(re1, "wfoo", "foo"));
PT_ASSERT(regex_test_pass(re2, "python", "python"));
PT_ASSERT(regex_test_pass(re2, "py3", "py3"));
PT_ASSERT(regex_test_pass(re2, "py2", "py2"));
PT_ASSERT(regex_test_fail(re2, "py", "py"));
PT_ASSERT(regex_test_fail(re2, "py.", "py."));
PT_ASSERT(regex_test_fail(re2, "py!", "py!"));
mpc_delete(re0);
mpc_delete(re1);
mpc_delete(re2);
}
void test_regex_range(void) {
mpc_parser_t *re0, *re1, *re2, *re3;
re0 = mpc_re("abg[abcdef]");
re1 = mpc_re("y*[a-z]");
re2 = mpc_re("zz(p+)?[A-Z_0\\]123]*");
re3 = mpc_re("^[^56hy].*$");
/* TODO: Testing */
mpc_delete(re0);
mpc_delete(re1);
mpc_delete(re2);
mpc_delete(re3);
}
void test_regex_string(void) {
mpc_parser_t *re0 = mpc_re("\"(\\\\.|[^\"])*\"");
PT_ASSERT(regex_test_pass(re0, "\"there\"", "\"there\""));
PT_ASSERT(regex_test_pass(re0, "\"hello\"", "\"hello\""));
PT_ASSERT(regex_test_pass(re0, "\"i am dan\"", "\"i am dan\""));
PT_ASSERT(regex_test_pass(re0, "\"i a\\\"m dan\"", "\"i a\\\"m dan\""));
mpc_delete(re0);
}
void test_regex_lisp_comment(void) {
mpc_parser_t *re0 = mpc_re(";[^\\n\\r]*");
PT_ASSERT(regex_test_pass(re0, ";comment", ";comment"));
PT_ASSERT(regex_test_pass(re0, ";i am the\nman", ";i am the"));
mpc_delete(re0);
}
void test_regex_newline(void) {
mpc_parser_t *re0 = mpc_re("[a-z]*");
PT_ASSERT(regex_test_pass(re0, "hi", "hi"));
PT_ASSERT(regex_test_pass(re0, "hi\nk", "hi"));
PT_ASSERT(regex_test_fail(re0, "hi\nk", "hi\nk"));
mpc_delete(re0);
}
void test_regex_multiline(void) {
mpc_parser_t *re0 = mpc_re_mode("(^[a-z]*$)*", MPC_RE_MULTILINE);
PT_ASSERT(regex_test_pass(re0, "hello\nhello", "hello\nhello"));
PT_ASSERT(regex_test_pass(re0, "hello\nhello\n", "hello\nhello\n"));
PT_ASSERT(regex_test_pass(re0, "\nblah\n\nblah\n", "\nblah\n\nblah\n"));
PT_ASSERT(regex_test_fail(re0, "45234", "45234"));
PT_ASSERT(regex_test_fail(re0, "\n45234", "\n45234"));
PT_ASSERT(regex_test_pass(re0, "\n45234", "\n"));
mpc_delete(re0);
}
void test_regex_dotall(void) {
mpc_parser_t *re0 = mpc_re_mode("^.*$", MPC_RE_DEFAULT);
mpc_parser_t *re1 = mpc_re_mode("^.*$", MPC_RE_DOTALL);
PT_ASSERT(regex_test_pass(re0, "hello", "hello"));
PT_ASSERT(regex_test_fail(re0, "hello\n", "hello"));
PT_ASSERT(regex_test_fail(re0, "he\nllo\n", "he"));
PT_ASSERT(regex_test_pass(re0, "34njaksdklmasd", "34njaksdklmasd"));
PT_ASSERT(regex_test_fail(re0, "34njaksd\nklmasd", "34njaksd"));
PT_ASSERT(regex_test_pass(re1, "hello", "hello"));
PT_ASSERT(regex_test_pass(re1, "hello\n", "hello\n"));
PT_ASSERT(regex_test_pass(re1, "he\nllo\n", "he\nllo\n"));
PT_ASSERT(regex_test_pass(re1, "34njaksdklmasd", "34njaksdklmasd"));
PT_ASSERT(regex_test_pass(re1, "34njaksd\nklmasd", "34njaksd\nklmasd"));
mpc_delete(re0);
mpc_delete(re1);
}
void suite_regex(void) {
pt_add_test(test_regex_basic, "Test Regex Basic", "Suite Regex");
pt_add_test(test_regex_range, "Test Regex Range", "Suite Regex");
pt_add_test(test_regex_string, "Test Regex String", "Suite Regex");
pt_add_test(test_regex_lisp_comment, "Test Regex Lisp Comment", "Suite Regex");
pt_add_test(test_regex_boundary, "Test Regex Boundary", "Suite Regex");
pt_add_test(test_regex_newline, "Test Regex Newline", "Suite Regex");
pt_add_test(test_regex_multiline, "Test Regex Multiline", "Suite Regex");
pt_add_test(test_regex_dotall, "Test Regex Dotall", "Suite Regex");
}

16
src/mpc/tests/test.c Normal file
View File

@ -0,0 +1,16 @@
#include "ptest.h"
void suite_core(void);
void suite_regex(void);
void suite_grammar(void);
void suite_combinators(void);
int main(int argc, char** argv) {
(void) argc; (void) argv;
pt_add_suite(suite_core);
pt_add_suite(suite_regex);
pt_add_suite(suite_grammar);
pt_add_suite(suite_combinators);
return pt_run();
}

View File

@ -1,22 +1,44 @@
#include <editline/history.h>
#include <editline/readline.h>
#include <stdio.h>
#include <stdlib.h>
static char input[2048];
#include "mpc/mpc.h"
int main(int argc, char** argv)
{
puts("Mumble version 0.0.1\n");
puts("Press Ctrl+C to exit\n");
puts("Press Ctrl+C/Ctrl+D to exit\n");
/* Create Some Parsers */
mpc_parser_t* Number = mpc_new("number");
mpc_parser_t* Operator = mpc_new("operator");
mpc_parser_t* Expr = mpc_new("expr");
mpc_parser_t* Lispy = mpc_new("lispy");
/* Define them with the following Language */
mpca_lang(MPCA_LANG_DEFAULT,
" \
number : /-?[0-9]+/ ; \
operator : '+' | '-' | '*' | '/' ; \
expr : <number> | '(' <operator> <expr>+ ')' ; \
lispy : /^/ <operator> <expr>+ /$/ ; \
",
Number, Operator, Expr, Lispy);
int loop = 1;
while (loop) {
fputs("mumble> ", stdout);
void* catcher = fgets(input, 2048, stdin);
if (catcher == NULL) {
char* input = readline("mumble> ");
if (input == NULL) {
// ^ catches Ctrl+D
loop = 0;
puts("");
} else {
printf("You said: %s", input);
printf("You said: %s\n", input);
add_history(input);
// can't add if input is NULL
}
free(input);
}
return 0;
}