File: GParser.lg

package info (click to toggle)
frown 0.6.1-13
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 9,956 kB
  • sloc: haskell: 35,132; makefile: 228; csh: 35; yacc: 23
file content (360 lines) | stat: -rw-r--r-- 16,087 bytes parent folder | download | duplicates (3)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%   Frown --- An LALR(k) parser generator for Haskell 98                      %
%   Copyright (C) 2001-2005 Ralf Hinze                                        %
%                                                                             %
%   This program is free software; you can redistribute it and/or modify      %
%   it under the terms of the GNU General Public License (version 2) as       %
%   published by the Free Software Foundation.                                %
%                                                                             %
%   This program is distributed in the hope that it will be useful,           %
%   but WITHOUT ANY WARRANTY; without even the implied warranty of            %
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             %
%   GNU General Public License for more details.                              %
%                                                                             %
%   You should have received a copy of the GNU General Public License         %
%   along with this program; see the file COPYING.  If not, write to          %
%   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,          %
%   Boston, MA 02111-1307, USA.                                               %
%                                                                             %
%   Contact information                                                       %
%   Email:      Ralf Hinze <ralf@cs.uni-bonn.de>                              %
%   Homepage:   http://www.informatik.uni-bonn.de/~ralf/                      %
%   Paper mail: Dr. Ralf Hinze                                                %
%               Institut für Informatik III                                   %
%               Universität Bonn                                              %
%               Römerstraße 164                                               %
%               53117 Bonn, Germany                                           %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Compile me with

	frown --lexer --expected --signature --optimize GParser.lg
	frown --lexer --expected --signature --code=stackless --optimize GParser.lg

> module GParser                (  Term, Nonterm, grammar, Sym(..), Decl(..)  )
> where
> import Lexer
> import Grammar
> import Haskell                hiding (  Decl, guard  )
> import Base                   hiding (  Result  )
> import qualified Base
> import Prettier               (  Pretty  )
> import List
> --import Monad                  hiding (  guard  )
> import IO
> import Options

> type Term                     =  Pat
>
> type Nonterm                  =  (Expr, [Quoted])
>
> data Sym                      =  Term Term | Nonterm Nonterm
>                                  deriving (Show)
>
> type AnnTerm                  =  (Term, Bool, Assoc, Maybe String)
>
> data Decl                     =  Terminals    [AnnTerm]
>                               |  Nonterminals [(Nonterm, Bool)]
>                               |  Fixity       Assoc Term
>                               |  TypeSig      Nonterm [Nonterm] Bool
>                               |  Production   Nonterm [(Modifier, Sym)]
>                                  deriving (Show)
>
> instance Pretty Decl
>
> type Terminal                 =  Token
>
> type Result                   =  Lex Base.Result

Final result type of the parser.

> type Answer                   =  ([Token], [Decl], [Token])
>
> --file                          :: Result Answer
>
> %{
>
> Terminal                      =  Conid   "Terminal"    as "Terminal"
>                               |  Conid   "Nonterminal" as "Nonterminal"
>                               |  Conid   {String}      as "<constructor>"
>                               |  Varid   "insert"      as "insert"
>                               |  Varid   "delete"      as "delete"
>                               |  Varid   "guard"       as "guard"
>                               |  Varid   "prec"        as "prec"
>                               |  Varid   "left"        as "left"
>                               |  Varid   "right"       as "right"
>                               |  Varid   "nonassoc"    as "nonassoc"
>                               |  Varid   "as"          as "as"
>                               |  Varid   {String}      as "<variable>"
>                               |  Consym  ":"           as ":"
>                               |  Consym  "::"          as "::"
>                               |  Varsym  "="           as "="
>                               |  Varsym  "*"           as "*"
>                               |  Varsym  "|"           as "|"
>                               |  Varsym  "<-"          as "<-"
>                               |  Numeral {String}      as "<numeral>"
>                               |  Char    {String}      as "<char literal>"
>                               |  String  {String}      as "<string literal>"
>                               |  Special '('           as "("
>                               |  Special ')'           as ")"
>                               |  Special '['           as "[" 
>                               |  Special ']'           as "]"
>                               |  Special '{'           as "{" 
>                               |  Special '}'           as "}"
>                               |  Special ','           as ","
>                               |  Special ';'           as ";"
>                               |  LQuote                as "%{"
>                               |  RQuote                as "}%"
>--                               |  Unquote {[Token]}     as "{..}"
>                               |  guard {isWhite}       as "white"
>                               |  guard {notQuote}      as "not quote"
>                               |  guard {notBrace}      as "not brace"
>                               | *EOF                   as "<end of input>";

Grammar file.

>*file {Answer};
> file {(ts, ds, us)}           :  many "not quote" {ts},
>                                  open {_}, opt "white" {_},
>                                  declarations {ds},
>                                  close {_},
>                                  many "not quote" {us};
>
> open  {()};
> open  {% skipWhite True}      : "%{";
> close {()};
> close {% skipWhite False}     : "}%";

Subtle: the effect of |skipWhite True| only takes place after the
lookahead token has been read, so we have to consume one token of
white space manually.

Declarations.

> declarations {[Decl]};
> declarations {concat dss}     :  many decl {dss};
>
> decl {[Decl]};
> decl {[d]}                    :  terminals    {d};
>      {[d]}                    |  nonterminals {d};
>      {[d]}                    |  fixity       {d};
>      {[d]}                    |  signature    {d};
>      {ds}                     |  productions  {ds};

Terminal declaration.

> terminals {Decl};
> terminals {Terminals cs}      :  "Terminal", "=", sepBy term "|" {cs}, ";";
>
> term {AnnTerm};
> term {(p, m, a, Nothing)}     :  mark {m}, assoc{a}, terminal {p};
>      {(p, m, a, Just s)}      |  mark {m}, assoc{a}, String {s}, "=", terminal {p}; -- deprecated
>      {(p, m, a, Just s)}      |  mark {m}, assoc{a}, terminal {p}, "as", String {s};
>      {(guard q, m, a, Just s)}|  mark {m}, assoc{a}, "guard", haskell {q}, "as", String {s};
>
> mark {Bool};
> mark {False}                  :  ;
>      {True}                   |  "*";
>
> assoc {Assoc};
> assoc {Unspecified}           :  ;
>       {left n}                |  "left",     Numeral {n}; 
>       {right n}               |  "right",    Numeral {n};
>       {nonassoc n}            |  "nonassoc", Numeral {n};

Nonterminal declaration.

> nonterminals {Decl};
> nonterminals {Nonterminals cs}:  "Nonterminal", "=", sepBy nonterm "|" {cs}, ";";
>
> nonterm {(Nonterm, Bool)};
> nonterm {(p, m)}              :  mark {m}, nonterminal {p};

Fixity declaration.

> fixity {Decl};
> fixity {Fixity (left n) t}    : "left",     Numeral {n}, terminal {t}, ";";
>        {Fixity (right n) t}   | "right",    Numeral {n}, terminal {t}, ";";
>        {Fixity (nonassoc n) t}| "nonassoc", Numeral {n}, terminal {t}, ";";

Type signature.

> signature {Decl};
> signature {TypeSig n ns False}:  "::", nonterminal {n}, premise {ns}, ";";
>           {TypeSig n ns False}|  nonterminal {n}, premise {ns}, ";";
>           {TypeSig n [] True} |  "::", "*", nonterminal {n}, ";";
>           {TypeSig n [] True} |  "*", nonterminal {n}, ";";
>
> premise {[Nonterm]};
> premise {[]}                  :  ;
>         {ns}                  |  "<-", sepBy1 nonterminal "," {ns};

Productions.

> productions {[Decl]};
> productions {prods c ((us, vs) : alts)}
>                               :  expr {c}, attributes {us}, ":", sepBy symbol "," {vs}, ";", alts {alts};
>
> alts {[([Quoted], [(Modifier, Sym)])]};
> alts {[]}                     :  ;
>      {(us, vs) : alts}        |  attributes {us}, "|", sepBy symbol "," {vs}, ";", alts {alts};
>
> symbol {(Modifier, Sym)};
> symbol {(Insert, Term p)}     :  "insert", terminal {p};
>        {(Delete, Term p)}     |  "delete", terminal {p};
>        {(Prec,   Term p)}     |  "prec",   terminal {p};
>        {(Copy,   Term p)}     |  terminal {p};
>        {(Copy,   Nonterm n)}  |  nonterminal {n};

Nonterminal symbols.

> nonterminal {Nonterm};
> nonterminal {(e, qs)}         :  expr {e}, attributes {qs};
>
> expr {Expr};
> expr {Var n <$> es}           :  Varid {n}, many aexpr {es};
>
> aexpr {Expr};
> aexpr {Var n}                 :  Varid {n};
>       {Con k}                 |  Conid {k};
>       {Literal n}             |  Numeral {n};
>       {Literal c}             |  Char {c};
>       {Literal s}             |  String {s};
>       {tuple ps}              |  "(", sepBy pat "," {ps}, ")";
>       {List ps}               |  "[", sepBy pat "," {ps}, "]";
>       {e}                     |  "(", expr {e}, ")";

Terminal symbols.

> terminal {Term};
> terminal {p}                  :  pat {p};
>          {Literal s <$> map Quoted (q : qs)}
>                               |  String {s}, haskell {q}, attributes {qs}; -- shortcut
>
> pat {Pat};
> pat {p}                       :  apat {p};
>     {Con k <$> ps}            |  Conid {k}, many1 apat {ps};
>
> apat {Pat};
> apat {Con k}                  :  Conid {k};
>      {Literal n}              |  Numeral {n};
>      {Literal c}              |  Char {c};
>      {Literal s}              |  String {s}; -- either string literal or shortcut
>      {tuple ps}               |  "(", sepBy pat "," {ps}, ")";
>      {List ps}                |  "[", sepBy pat "," {ps}, "]";
>      {Quoted ts}              |  haskell {ts};

Embedded Haskell (types, patterns, and expressions).

> attributes {[Quoted]};
> attributes {[]}               :  ;
>            {q : qs}           |  haskell {q}, attributes {qs};

> haskell {[Token]};
> haskell {conc ts []}          :  hsOpen {_}, many hs {ts}, hsClose {_}, opt "white" {_};
>
> hs {[Token] -> [Token]};
> hs {single t}                 :  "not brace" {t};
>    {single (Special '{') . conc ts . single (Special '}')}
>                               |  "{", many hs {ts}, "}";
>
> hsOpen  {()};
> hsOpen  {% skipWhite False}    : "{";
> hsClose {()};
> hsClose {% skipWhite True}     : "}";
>
> }%

Helper functions.

> notQuote, notBrace            :: Token -> Bool
> notQuote LQuote               =  False
> notQuote RQuote               =  False
> notQuote EOF                  =  False  -- important to ensure termination!
> notQuote _                    =  True
>
> notBrace (Special '{')        =  False
> notBrace (Special '}')        =  False
> notBrace EOF                  =  False
> notBrace _                    =  True

> single a                      =  \ x -> a : x
> conc                          =  foldr (.) id

> prods                         :: Expr -> [([Quoted], [(Modifier, Sym)])] -> [Decl]
> prods e alts                  =  [ Production (e, us) vs | (us, vs) <- alts ]
>
> guard                         :: Quoted -> Pat
> guard q                       =  Guard (Quoted [Conid "Terminal"]) (Quoted q) -- HACK
>
> left, right, nonassoc         :: String -> Assoc
> left s                        =  LeftAssoc  (read s)
> right s                       =  RightAssoc (read s)
> nonassoc s                    =  NonAssoc   (read s)

Main function.

> grammar                       :: [Flag] -> [Token] -> IO Answer
> grammar opts ts               =  do verb "* Parsing ..."
>-- IO                                     (l, ds, r) <- parse 1 ts
>                                     (l, ds, r) <- case parse 1 ts of
>                                                       Fail s   -> panic s
>                                                       Return x -> return x
>                                     verb ("  " ++ show (length ds) ++ " declarations")
>                                     return (l, ds, r)
>     where verb                =  verbose opts

> {-
> grammar'                      :: Int -> [Token] -> IO ([Token], [Decl], [Token])
> grammar' _n []                =  return ([], [], [])
> grammar' n (Quote ts : us)    =  case parse n ts of
>                                      Fail s    -> panic s
>                                      Return ds -> return ([], ds, us)
> grammar' n (t : ts)           =  do let n' = if isWhite t then newlines t + n else n
>                                     (l, ds, r) <- grammar' n' ts
>                                     return (t : l, ds, r)
> -}

Lexer monad (input, line number, skip white space).

> data Lex m a                  =  Lex { unLex :: (a -> [Token] -> Int -> Bool -> m Answer)
>                                                    -> [Token] -> Int -> Bool -> m Answer }
>
> instance Monad (Lex m) where
>     return a                  =  Lex (\ cont -> cont a)
>     m >>= k                   =  Lex (\ cont -> unLex m (\ a -> unLex (k a) cont))
>
> frown                         :: [String] -> Token -> Result a
> frown la t                    =  Lex (\ _cont inp n _skip ->
>                                       fail (lineNo n ++ "syntax error"
>                                             ++ "\nexpected: " ++ concat (intersperse ", " (map wrap la))
>                                             ++ "\nfound   : " ++ next 3 (concatMap toString (t : inp))))
>
> skipWhite                     :: Bool -> Result ()
> skipWhite flag                =  Lex (\ cont inp n _skip -> cont () inp n flag)
>
> get                           :: Result Token
> get                           =  Lex (\ cont inp n skip ->
>                                       case inp of
>                                           []              -> cont EOF inp n skip
>--                                           Error s : _     -> fail (lineNo n ++ s)
>                                           t : ts
>                                               | isWhite t -> (if skip then unLex get cont else cont t)
>                                                                  ts (newlines t + n) skip
>                                               | otherwise -> cont t ts n skip)
>
> lineNo                        :: Int -> String
> lineNo n                      =  show n ++ ": "
>
> parse                         :: Int -> [Token] -> Base.Result Answer
> parse n inp                   =  unLex file (\a _ _ _ -> return a) inp n False
>
> newlines                      :: Token -> Int
> newlines t		        =  length [ c | c <- toString t, c == '\n' ]
>
> wrap                          :: String -> String
> wrap ""                       =  ""
> wrap s@('<' : _)              =  s
> wrap s                        =  "`" ++ s ++ "'"