blob: cb5f9aa63aea39f7d0bfa972ec4b0c532e8afe98 [file] [log] [blame]
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001#include <Python.h>
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03002#include "pegen_interface.h"
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003
4PyObject *
5_Py_parse_file(PyObject *self, PyObject *args, PyObject *kwds)
6{
7 static char *keywords[] = {"file", "mode", NULL};
8 char *filename;
9 char *mode_str = "exec";
10
11 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s", keywords, &filename, &mode_str)) {
12 return NULL;
13 }
14
15 int mode;
16 if (strcmp(mode_str, "exec") == 0) {
17 mode = Py_file_input;
18 }
19 else if (strcmp(mode_str, "single") == 0) {
20 mode = Py_single_input;
21 }
22 else {
23 return PyErr_Format(PyExc_ValueError, "mode must be either 'exec' or 'single'");
24 }
25
26 PyArena *arena = PyArena_New();
27 if (arena == NULL) {
28 return NULL;
29 }
30
31 PyObject *result = NULL;
32
33 mod_ty res = PyPegen_ASTFromFile(filename, mode, arena);
34 if (res == NULL) {
35 goto error;
36 }
37 result = PyAST_mod2obj(res);
38
39error:
40 PyArena_Free(arena);
41 return result;
42}
43
44PyObject *
45_Py_parse_string(PyObject *self, PyObject *args, PyObject *kwds)
46{
47 static char *keywords[] = {"string", "mode", NULL};
48 char *the_string;
49 char *mode_str = "exec";
50
51 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s", keywords, &the_string, &mode_str)) {
52 return NULL;
53 }
54
55 int mode;
56 if (strcmp(mode_str, "exec") == 0) {
57 mode = Py_file_input;
58 }
59 else if (strcmp(mode_str, "eval") == 0) {
60 mode = Py_eval_input;
61 }
62 else if (strcmp(mode_str, "single") == 0) {
63 mode = Py_single_input;
64 }
65 else {
66 return PyErr_Format(PyExc_ValueError, "mode must be either 'exec' or 'eval' or 'single'");
67 }
68
69 PyArena *arena = PyArena_New();
70 if (arena == NULL) {
71 return NULL;
72 }
73
74 PyObject *result = NULL;
75
76 PyCompilerFlags flags = _PyCompilerFlags_INIT;
77 flags.cf_flags = PyCF_IGNORE_COOKIE;
78
79 mod_ty res = PyPegen_ASTFromString(the_string, mode, &flags, arena);
80 if (res == NULL) {
81 goto error;
82 }
83 result = PyAST_mod2obj(res);
84
85error:
86 PyArena_Free(arena);
87 return result;
88}
89
90static PyMethodDef ParseMethods[] = {
91 {"parse_file", (PyCFunction)(void (*)(void))_Py_parse_file, METH_VARARGS|METH_KEYWORDS, "Parse a file."},
92 {"parse_string", (PyCFunction)(void (*)(void))_Py_parse_string, METH_VARARGS|METH_KEYWORDS,"Parse a string."},
93 {NULL, NULL, 0, NULL} /* Sentinel */
94};
95
96static struct PyModuleDef parsemodule = {
97 PyModuleDef_HEAD_INIT,
98 .m_name = "peg_parser",
99 .m_doc = "A parser.",
100 .m_methods = ParseMethods,
101};
102
103PyMODINIT_FUNC
104PyInit__peg_parser(void)
105{
106 return PyModule_Create(&parsemodule);
107}