parsermodule.c revision 3bbc62e9c25d4c006cd21d6b1314ccf0ba211382
1/***********************************************************
2Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
3Amsterdam, The Netherlands.
4
5                        All Rights Reserved
6
7Permission to use, copy, modify, and distribute this software and its
8documentation for any purpose and without fee is hereby granted,
9provided that the above copyright notice appear in all copies and that
10both that copyright notice and this permission notice appear in
11supporting documentation, and that the names of Stichting Mathematisch
12Centrum or CWI not be used in advertising or publicity pertaining to
13distribution of the software without specific, written prior permission.
14
15STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
16THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
17FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
18FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
20ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
21OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22
23******************************************************************/
24
25/* Raw interface to the parser. */
26
27#include "allobjects.h"
28#include "node.h"
29#include "token.h"
30#include "pythonrun.h"
31#include "graminit.h"
32#include "errcode.h"
33
34object *
35node2tuple(n)
36	node *n;
37{
38	if (n == NULL) {
39		INCREF(None);
40		return None;
41	}
42	if (ISNONTERMINAL(TYPE(n))) {
43		int i;
44		object *v, *w;
45		v = newtupleobject(1 + NCH(n));
46		if (v == NULL)
47			return v;
48		w = newintobject(TYPE(n));
49		if (w == NULL) {
50			DECREF(v);
51			return NULL;
52		}
53		settupleitem(v, 0, w);
54		for (i = 0; i < NCH(n); i++) {
55			w = node2tuple(CHILD(n, i));
56			if (w == NULL) {
57				DECREF(v);
58				return NULL;
59			}
60			settupleitem(v, i+1, w);
61		}
62		return v;
63	}
64	else if (ISTERMINAL(TYPE(n))) {
65		return mkvalue("(is)", TYPE(n), STR(n));
66	}
67	else {
68		err_setstr(SystemError, "unrecognized parse tree node type");
69		return NULL;
70	}
71}
72
73static object *
74parser_parsefile(self, args)
75	object *self;
76	object *args;
77{
78	char *filename;
79	FILE *fp;
80	node *n = NULL;
81	object *res;
82	if (!getargs(args, "s", &filename))
83		return NULL;
84	fp = fopen(filename, "r");
85	if (fp == NULL) {
86		err_errno(IOError);
87		return NULL;
88	}
89	n = parse_file(fp, filename, file_input);
90	fclose(fp);
91	if (n == NULL)
92		return NULL;
93	res = node2tuple(n);
94	freetree(n);
95	return res;
96}
97
98static struct methodlist parser_methods[] = {
99	{"parsefile", parser_parsefile},
100	{0, 0} /* Sentinel */
101};
102
103void
104initparser()
105{
106	initmodule("parser", parser_methods);
107}
108