-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.cgi
executable file
·84 lines (70 loc) · 2.63 KB
/
parser.cgi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/python
## NOTE: This script is now used as a command line script instead of as a cgi script
## We use it as an interface to GF
import cgi
import os
import sys
from subprocess import Popen, PIPE, call
PARSER = ["/Users/jesjos/.cabal/bin/gf",
"--run", "ShrdliteEng.gf", "ShrdliteSem.gf"]
GFCOMMAND = 'p -lang=ShrdliteEng "%s" | l -lang=ShrdliteSem'
HEADER = "Content-type:text/plain\r\n\r\n"
GF_ERRORS = ["None of these files exists",
" Happened in linearization",
" syntax error",
" constant not found",
" no overload instance",
" function type expected",
" missing record fields",
" cannot unify",
]
PARSER_ERRORS = ["The parser failed",
"The sentence is not complete",
]
def parse_userinput(userinput):
"""
Calls GF with the GRAMMAR and an input string. The input is
converted to lower case before parsing. Also, punctuation
[,;.:!?'\"] is padded with spaces so they will be separate GF
tokens, and double quotes are replaced by single quotes.
Returns the GF syntax trees as a list of strings, or an empty list
if the input is ungrammatical.
"""
gfinput = GFCOMMAND % (
userinput.lower()
.replace('"', " ' ").replace("'", " ' ")
.replace(",", " , ").replace(";", " ; ")
.replace(".", " . ").replace(":", " : ")
.replace("!", " ! ").replace("?", " ? ")
)
process = Popen(PARSER, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate(gfinput)
if process.returncode:
raise OSError("GF exited with returncode %d: %s / %s" % (process.returncode, stdout, stderr))
elif any(err in stdout for err in GF_ERRORS):
raise OSError("GF error: %s / %s" % (stdout, stderr))
elif any(err in stdout for err in PARSER_ERRORS):
return []
else:
return filter(None, stdout.splitlines())
def main_cgi():
print HEADER
form = cgi.FieldStorage()
userinput = form.getfirst("input")
if not userinput:
raise ValueError("I need a CGI parameter 'input'.")
for tree in parse_userinput(userinput):
print tree
def main_command_line(input):
for tree in parse_userinput(input):
print tree
if __name__ == '__main__':
try:
main_command_line(sys.argv[1])
# main_cgi()
except Exception as err:
print "ERROR"
print "%s: %s" % (type(err).__name__, err)
## Uncomment this to show more information about the error:
# import traceback, sys
# traceback.print_exc(file=sys.stdout)