[project @ 1999-10-15 11:02:06 by sewardj]
[ghc-hetmet.git] / ghc / interpreter / parser.y
1
2 /* --------------------------------------------------------------------------
3  * Hugs parser (included as part of input.c)
4  *
5  * Expect 6 shift/reduce conflicts when passing this grammar through yacc,
6  * but don't worry; they should all be resolved in an appropriate manner.
7  *
8  * Hugs 98 is Copyright (c) Mark P Jones, Alastair Reid and the Yale
9  * Haskell Group 1994-99, and is distributed as Open Source software
10  * under the Artistic License; see the file "Artistic" that is included
11  * in the distribution for details.
12  *
13  * $RCSfile: parser.y,v $
14  * $Revision: 1.8 $
15  * $Date: 1999/10/15 11:02:20 $
16  * ------------------------------------------------------------------------*/
17
18 %{
19 #ifndef lint
20 #define lint
21 #endif
22 #define defTycon(n,l,lhs,rhs,w)  tyconDefn(intOf(l),lhs,rhs,w); sp-=n
23 #define sigdecl(l,vs,t)          ap(SIGDECL,triple(l,vs,t))
24 #define fixdecl(l,ops,a,p)       ap(FIXDECL,\
25                                     triple(l,ops,mkInt(mkSyntax(a,intOf(p)))))
26 #define grded(gs)                ap(GUARDED,gs)
27 #define bang(t)                  ap(BANG,t)
28 #define only(t)                  ap(ONLY,t)
29 #define letrec(bs,e)             (nonNull(bs) ? ap(LETREC,pair(bs,e)) : e)
30 #define qualify(ps,t)            (nonNull(ps) ? ap(QUAL,pair(ps,t)) : t)
31 #define exportSelf()             singleton(ap(MODULEENT, \
32                                     mkCon(module(currentModule).text)))
33 #define yyerror(s)               /* errors handled elsewhere */
34 #define YYSTYPE                  Cell
35
36 static Cell   local gcShadow     Args((Int,Cell));
37 static Void   local syntaxError  Args((String));
38 static String local unexpected   Args((Void));
39 static Cell   local checkPrec    Args((Cell));
40 static Void   local fixDefn      Args((Syntax,Cell,Cell,List));
41 static Cell   local buildTuple   Args((List));
42 static List   local checkContext Args((List));
43 static Cell   local checkPred    Args((Cell));
44 static Pair   local checkDo      Args((List));
45 static Cell   local checkTyLhs   Args((Cell));
46 #if !TREX
47 static Void   local noTREX       Args((String));
48 #endif
49
50 /* For the purposes of reasonably portable garbage collection, it is
51  * necessary to simulate the YACC stack on the Hugs stack to keep
52  * track of all intermediate constructs.  The lexical analyser
53  * pushes a token onto the stack for each token that is found, with
54  * these elements being removed as reduce actions are performed,
55  * taking account of look-ahead tokens as described by gcShadow()
56  * below.
57  *
58  * Of the non-terminals used below, only start, topDecl & begin
59  * do not leave any values on the Hugs stack.  The same is true for the
60  * terminals EXPR and SCRIPT.  At the end of a successful parse, there
61  * should only be one element left on the stack, containing the result
62  * of the parse.
63  */
64
65 #define gc0(e)                  gcShadow(0,e)
66 #define gc1(e)                  gcShadow(1,e)
67 #define gc2(e)                  gcShadow(2,e)
68 #define gc3(e)                  gcShadow(3,e)
69 #define gc4(e)                  gcShadow(4,e)
70 #define gc5(e)                  gcShadow(5,e)
71 #define gc6(e)                  gcShadow(6,e)
72 #define gc7(e)                  gcShadow(7,e)
73
74 %}
75
76 %token EXPR       SCRIPT
77 %token CASEXP     OF         DATA       TYPE       IF
78 %token THEN       ELSE       WHERE      LET        IN
79 %token INFIXN     INFIXL     INFIXR     FOREIGN    TNEWTYPE
80 %token DEFAULT    DERIVING   DO         TCLASS     TINSTANCE
81 %token REPEAT     ALL        NUMLIT     CHARLIT    STRINGLIT
82 %token VAROP      VARID      CONOP      CONID
83 %token QVAROP     QVARID     QCONOP     QCONID
84 /*#if TREX*/
85 %token RECSELID
86 /*#endif*/
87 %token COCO       '='        UPTO       '@'        '\\'
88 %token '|'        '-'        FROM       ARROW      '~'
89 %token '!'        IMPLIES    '('        ','        ')'
90 %token '['        ';'        ']'        '`'        '.'
91 %token TMODULE    IMPORT     HIDING     QUALIFIED  ASMOD
92 %token EXPORT     UUEXPORT   INTERFACE  REQUIRES   UNSAFE     
93 %token INSTIMPORT DYNAMIC
94
95 %%
96 /*- Top level script/module structure -------------------------------------*/
97
98 start     : EXPR exp wherePart          {inputExpr = letrec($3,$2); sp-=2;}
99           | SCRIPT topModule            {valDefns  = $2;            sp-=1;}
100           | INTERFACE iface             {sp-=1;}
101           | error                       {syntaxError("input");}
102           ;
103
104
105 /*- GHC interface file parsing: -------------------------------------------*/
106
107 /* Reading in an interface file is surprisingly like reading
108  * a normal Haskell module: we read in a bunch of declarations,
109  * construct symbol table entries, etc.  The "only" differences
110  * are that there's no syntactic sugar to deal with and we don't
111  * have to read in expressions.
112  */
113
114 /*- Top-level interface files -----------------------------*/
115 iface     : INTERFACE ifName NUMLIT checkVersion WHERE ifDecls 
116                                         {$$ = gc6(NIL); }
117           | INTERFACE error             {syntaxError("interface file");}
118           ;
119 ifDecls:                                {$$=gc0(NIL);}
120           | ifDecl ';' ifDecls          {$$=gc3(cons($1,$3));}
121           ;
122 varid_or_conid
123           : VARID                       { $$=gc1($1); }
124           | CONID                       { $$=gc1($1); }
125           ;
126 opt_bang  : '!'                         {$$=gc1(NIL);}
127           |                             {$$=gc0(NIL);}
128           ;
129 ifName    : CONID                       {openGHCIface(textOf($1)); 
130                                          $$ = gc1(NIL);}
131 checkVersion
132           : NUMLIT                      {$$ = gc1(NIL); }
133           ;
134 ifDecl    
135           : IMPORT CONID opt_bang NUMLIT COCO version_list_junk
136                                         { addGHCImports(intOf($4),textOf($2),
137                                                        $6);
138                                           $$ = gc6(NIL); 
139                                         }
140
141           | INSTIMPORT CONID            {$$=gc2(NIL);}
142
143           | UUEXPORT CONID ifEntities   { addGHCExports($2,$3);
144                                           $$=gc3(NIL);}
145
146           | NUMLIT INFIXL optDigit varid_or_conid   
147                                         {$$ = gc4(fixdecl($2,singleton($4),
148                                                           LEFT_ASS,$3)); }
149           | NUMLIT INFIXR optDigit varid_or_conid   
150                                         {$$ = gc4(fixdecl($2,singleton($4),
151                                                           RIGHT_ASS,$3)); }
152           | NUMLIT INFIXN optDigit varid_or_conid   
153                                         {$$ = gc4(fixdecl($2,singleton($4),
154                                                           NON_ASS,$3)); }
155
156           | TINSTANCE ifCtxInst ifInstHd '=' ifVar
157                                         { addGHCInstance(intOf($1),$2,$3,
158                                           textOf($5)); 
159                                           $$ = gc5(NIL); }
160           | NUMLIT TYPE ifCon ifKindedTyvarL '=' ifType
161                                         { addGHCSynonym(intOf($2),$3,$4,$6);
162                                           $$ = gc6(NIL); }
163
164           | NUMLIT DATA ifCtxDecl ifConData ifKindedTyvarL ifConstrs
165                                         { addGHCDataDecl(intOf($2),
166                                                          $3,$4,$5,$6);
167                                           $$ = gc6(NIL); }
168
169           | NUMLIT TNEWTYPE ifCtxDecl ifConData ifKindedTyvarL ifNewTypeConstr
170                                         { addGHCNewType(intOf($2),
171                                                         $3,$4,$5,$6);
172                                           $$ = gc6(NIL); }
173           | NUMLIT TCLASS ifCtxDecl ifCon ifTyvar ifCmeths
174                                         { addGHCClass(intOf($2),$3,$4,$5,$6);
175                                           $$ = gc6(NIL); }
176           | NUMLIT ifVar COCO ifType
177                                         { addGHCVar(intOf($3),textOf($2),$4);
178                                           $$ = gc4(NIL); }
179           | error                       { syntaxError(
180                                              "interface declaration"); }
181           ;
182
183
184 /*- Interface variable and constructor ids ----------------*/
185 ifTyvar   : VARID                       {$$ = $1;}
186           ;
187 ifVar     : VARID                       {$$ = gc1($1);}
188           ;
189 ifCon     : CONID                       {$$ = gc1($1);}
190           ;
191 ifQCon    : CONID                       {$$ = gc1($1);}
192           | QCONID                      {$$ = gc1($1);}
193           ;
194 ifConData : ifCon                       {$$ = gc1($1);}
195           | '(' ')'                     {$$ = gc2(typeUnit);}
196           | '[' ']'                     {$$ = gc2(typeList);}
197           | '(' ARROW ')'               {$$ = gc3(typeArrow);}
198           ;
199 ifTCName  : CONID                       { $$ = gc1($1); }
200           | CONOP                       { $$ = gc1($1); }
201           | '(' ARROW ')'               { $$ = gc3(typeArrow); }
202           | '[' ']'                     { $$ = gc1(typeList);  }
203           ; 
204 ifQTCName : ifTCName                    { $$ = gc1($1); }
205           | QCONID                      { $$ = gc1($1); }
206           | QCONOP                      { $$ = gc1($1); }
207           ; 
208
209
210 /*- Interface contexts ------------------------------------*/
211 ifCtxInst /* __forall [a b] {M.C1 a, M.C2 b} =>  */
212           /* :: [(QConId, VarId)]                */
213           : ALL ifForall ifCtxDecl      {$$=gc3($3);}
214           | ALL ifForall IMPLIES        {$$=gc3(NIL);}
215           |                             {$$=gc0(NIL);}
216           ;
217 ifInstHd  /* { Class aType }    :: (ConId, Type) */
218           : '{' ifCon ifAType '}'       {$$=gc4(pair($2,$3));}
219           ;
220
221 ifCtxDecl /* {M.C1 a, C2 b} :: [(QConId, VarId)] */ 
222           :                             { $$ = gc0(NIL); }
223           | '{' ifCtxDeclL '}' IMPLIES  { $$ = gc4($2);  }
224           ;                                     
225 ifCtxDeclT /* {M.C1 a, C2 b} :: [(QConId, VarId)] */ 
226           :                             { $$ = gc0(NIL); }
227           | '{' ifCtxDeclL '}'          { $$ = gc3($2);  }
228           ;                                     
229 ifCtxDeclL /* M.C1 a, C2 b :: [(QConId, VarId)] */
230           : ifCtxDeclLE ',' ifCtxDeclL  {$$=gc3(cons($1,$3));}
231           | ifCtxDeclLE                 {$$=gc1(cons($1,NIL));}
232           |                             {$$=gc0(NIL);}
233           ;
234 ifCtxDeclLE /* M.C1 a   :: (QConId,VarId) */
235           : ifQCon ifTyvar              {$$=gc2(pair($1,$2));}
236           ;
237
238
239 /*- Interface data declarations - constructor lists -------*/
240 ifConstrs /* = Con1 | ... | ConN  :: [(ConId,[(Type,Text)],NIL)] */
241           :                             {$$ = gc0(NIL);}
242           | '=' ifConstrL               {$$ = gc2($2);}
243           ;
244 ifConstrL /* [(ConId,[(Type,Text)],NIL)] */
245           : ifConstr                    {$$ = gc1(singleton($1));}
246           | ifConstr '|' ifConstrL      {$$ = gc3(cons($1,$3));}
247           ;
248 ifConstr /* (ConId,[(Type,Text)],NIL) */
249           : ifConData ifDataAnonFieldL  {$$ = gc2(triple($1,$2,NIL));}
250           | ifConData '{' ifDataNamedFieldL '}' 
251                                         {$$ = gc4(triple($1,$3,NIL));}
252           ;
253 ifDataAnonFieldL /* [(Type,Text)] */
254           :                             {$$=gc0(NIL);}
255           | ifDataAnonField ifDataAnonFieldL
256                                         {$$=gc2(cons($1,$2));}
257           ;
258 ifDataNamedFieldL /* [(Type,Text)] */
259           :                             {$$=gc0(NIL);}
260           | ifDataNamedField            {$$=gc1(cons($1,NIL));}
261           | ifDataNamedField ',' ifDataNamedFieldL 
262                                         {$$=gc3(cons($1,$3));}
263           ;
264 ifDataAnonField /* (Type,Text) */
265           : ifAType                     {$$=gc1(pair($1,NIL));}
266           ;
267 ifDataNamedField  /* (Type,Text) */
268           : VARID COCO ifAType          {$$=gc3(pair($3,$1));}
269           ;
270
271
272 /*- Interface class declarations - methods ----------------*/
273 ifCmeths /* [(VarId,Type)] */
274           :                             { $$ = gc0(NIL); }
275           | WHERE '{' ifCmethL '}'      { $$ = gc4($3); }
276           ;
277 ifCmethL /* [(VarId,Type)] */
278           : ifCmeth                     { $$ = gc1(singleton($1)); }
279           | ifCmeth ';' ifCmethL        { $$ = gc3(cons($1,$3));    }
280           ;
281 ifCmeth /* (VarId,Type) */
282           : ifVar     COCO ifType       { $$ = gc3(pair($1,$3)); }
283           | ifVar '=' COCO ifType       { $$ = gc4(pair($1,$4)); } 
284                                               /* has default method */
285           ;
286
287
288 /*- Interface newtype declararions ------------------------*/
289 ifNewTypeConstr /* (ConId,Type) */
290           : '=' ifCon ifAType           { $$ = gc3(pair($2,$3)); }
291           ;
292
293
294 /*- Interface type expressions ----------------------------*/
295 ifType    : ALL ifForall ifCtxDeclT IMPLIES ifType 
296                                         { if ($3 == NIL)
297                                            $$=gc5($5); else
298                                            $$=gc5(pair(QUAL,pair($3,$5)));
299                                         }
300           | ifBType ARROW ifType        { $$ = gc3(fn($1,$3)); }
301           | ifBType                     { $$ = gc1($1); }
302           ;                                     
303 ifForall /* [(VarId,Kind)] */
304           : '[' ifKindedTyvarL ']'      { $$ = gc3($2); }
305           ;                                     
306 ifTypes2  : ifType ',' ifType           { $$ = gc3(doubleton($1,$3)); }
307           | ifType ',' ifTypes2         { $$ = gc3(cons($1,$3));      }
308           ;
309 ifBType   : ifAType                     { $$ = gc1($1);        } 
310           | ifBType ifAType             { $$ = gc2(ap($1,$2)); }
311           ;
312 ifAType   : ifQTCName                   { $$ = gc1($1); }
313           | ifTyvar                     { $$ = gc1($1); }
314           | '(' ')'                     { $$ = gc2(typeUnit); }
315           | '(' ifTypes2 ')'            { $$ = gc3(buildTuple($2)); }
316           | '[' ifType ']'              { $$ = gc3(ap(typeList,$2));}
317           | '{' ifQTCName ifATypes '}'  { $$ = gc4(ap(DICTAP,
318                                                       pair($2,$3))); }
319           | '(' ifType ')'              { $$ = gc3($2); }
320           ;
321 ifATypes  :                             { $$ = gc0(NIL);         }
322           | ifAType ifATypes            { $$ = gc2(cons($1,$2)); }
323           ;
324
325
326 /*- Interface kinds ---------------------------------------*/
327 ifKindedTyvarL /* [(VarId,Kind)] */
328           :                              { $$ = gc0(NIL);         }
329           | ifKindedTyvar ifKindedTyvarL { $$ = gc2(cons($1,$2)); }
330           ;
331 ifKindedTyvar /* (VarId,Kind) */
332           : ifTyvar                     { $$ = gc1(pair($1,STAR)); }
333           | ifTyvar COCO ifAKind        { $$ = gc3(pair($1,$3));   }
334           ; 
335 ifKind    : ifAKind                     { $$ = gc1($1);        }
336           | ifAKind ARROW ifKind        { $$ = gc3(fn($1,$3)); }
337           ;
338 ifAKind   : VAROP                       { $$ = gc1(STAR); } 
339                                             /* should be '*' */
340           | '(' ifKind ')'              { $$ = gc3($2);   }
341           ;
342
343
344 /*- Interface version/export/import stuff -----------------*/
345 ifEntities                                      
346           :                             { $$ = gc0(NIL);         }
347           | ifEntity ifEntities         { $$ = gc2(cons($1,$2)); }
348           ;
349 ifEntity
350           : ifEntityOcc                 {$$=gc1($1);}
351           | ifEntityOcc ifStuffInside   {$$=gc2(pair($1,$2));}
352           ;
353 ifEntityOcc
354           : ifVar                       { $$ = gc1($1); }
355           | ifCon                       { $$ = gc1($1); }
356           | ARROW                       { $$ = gc1(typeArrow); }
357           | '(' ARROW ')'               { $$ = gc3(typeArrow); }  
358                                         /* why allow both? */
359           ;
360 ifStuffInside
361           : '{' ifValOccs '}'           { $$ = gc3($2); }
362           ;
363 ifValOccs
364           :                             { $$ = gc0(NIL); }
365           | ifVar ifValOccs             { $$ = gc2(cons($1,$2));   }
366           | ifCon ifValOccs             { $$ = gc2(cons($1,$2));   }
367           ;
368 version_list_junk
369           :                                {$$=gc0(NIL);}
370           | VARID NUMLIT version_list_junk {$$=gc3(cons($1,$3));} 
371           | CONID NUMLIT version_list_junk {$$=gc3(cons($1,$3));}
372           ;
373
374
375 /*- Haskell module header/import parsing: -----------------------------------
376
377  * Syntax for Haskell modules (module headers and imports) is parsed but
378  * most of it is ignored.  However, module names in import declarations
379  * are used, of course, if import chasing is turned on.
380  *-------------------------------------------------------------------------*/
381
382 /* In Haskell 1.2, the default module header was "module Main where"
383  * In 1.3, this changed to "module Main(main) where".
384  * We use the 1.2 header because it breaks much less pre-module code.
385  */
386 topModule : startMain begin modBody end {
387                                          setExportList(singleton(
388                                             ap(MODULEENT,
389                                             mkCon(module(currentModule).text)
390                                             )));
391                                          $$ = gc3($3);
392                                         }
393           | TMODULE modname expspec WHERE '{' modBody end
394                                         {setExportList($3);   $$ = gc7($6);}
395           | TMODULE error               {syntaxError("module definition");}
396           ;
397 /* To implement the Haskell module system, we have to keep track of the
398  * current module.  We rely on the use of LALR parsing to ensure that this 
399  * side effect happens before any declarations within the module.
400  */
401 startMain : /* empty */                 {startModule(conMain); 
402                                          $$ = gc0(NIL);}
403           ;
404 modname   : CONID                       {startModule($1); $$ = gc1(NIL);}
405           ;
406 modid     : CONID                       {$$ = $1;}
407           | STRINGLIT                   { extern String scriptFile;
408                                           String modName 
409                                              = findPathname(scriptFile,
410                                                  textToStr(textOf($1)));
411                                           if (modName) { 
412                                               /* fillin pathname if known */
413                                               $$ = mkStr(findText(modName));
414                                           } else {
415                                               $$ = $1;
416                                           }
417                                         }
418           ;
419 modBody   : topDecls                    {$$ = $1;}
420           | impDecls chase              {$$ = gc2(NIL);}
421           | impDecls ';' chase topDecls {$$ = gc4($4);}
422           ;
423
424 /*- Exports: --------------------------------------------------------------*/
425
426 expspec   : /* empty */                 {$$ = gc0(exportSelf());}
427           | '(' ')'                     {$$ = gc2(NIL);}
428           | '(' exports ')'             {$$ = gc3($2);}
429           | '(' exports ',' ')'         {$$ = gc4($2);}
430           ;
431 exports   : exports ',' export          {$$ = gc3(cons($3,$1));}
432           | export                      {$$ = gc1(singleton($1));}
433           ;
434 /* The qcon should be qconid.  
435  * Relaxing the rule lets us explicitly export (:) from the Prelude.
436  */
437 export    : qvar                        {$$ = $1;}
438           | qcon                        {$$ = $1;}
439           | qconid '(' UPTO ')'         {$$ = gc4(pair($1,DOTDOT));}
440           | qconid '(' qnames ')'       {$$ = gc4(pair($1,$3));}
441           | TMODULE modid               {$$ = gc2(ap(MODULEENT,$2));}
442           ;
443 qnames    : /* empty */                 {$$ = gc0(NIL);}
444           | ','                         {$$ = gc1(NIL);}
445           | qnames1                     {$$ = $1;}
446           | qnames1 ','                 {$$ = gc2($1);}
447           ;
448 qnames1   : qnames1 ',' qname           {$$ = gc3(cons($3,$1));}
449           | qname                       {$$ = gc1(singleton($1));}
450           ;
451 qname     : qvar                        {$$ = $1;}
452           | qcon                        {$$ = $1;}
453           ;
454
455 /*- Import declarations: --------------------------------------------------*/
456
457 impDecls  : impDecls ';' impDecl        {imps = cons($3,imps); $$=gc3(NIL);}
458           | impDecl                     {imps = singleton($1); $$=gc1(NIL);}
459           ;
460 chase     : /* empty */                 {if (chase(imps)) {
461                                              clearStack();
462                                              onto(imps);
463                                              done();
464                                              closeAnyInput();
465                                              return 0;
466                                          }
467                                          $$ = gc0(NIL);
468                                         }
469           ;
470 /* Note that qualified import ignores the import list. */
471 impDecl   : IMPORT modid impspec        {addQualImport($2,$2);
472                                          addUnqualImport($2,$3);
473                                          $$ = gc3($2);}
474           | IMPORT modid ASMOD modid impspec
475                                         {addQualImport($2,$4);
476                                          addUnqualImport($2,$5);
477                                          $$ = gc5($2);}
478           | IMPORT QUALIFIED modid ASMOD modid impspec
479                                         {addQualImport($3,$5);
480                                          $$ = gc6($3);}
481           | IMPORT QUALIFIED modid impspec
482                                         {addQualImport($3,$3);
483                                          $$ = gc4($3);}
484           | IMPORT error                {syntaxError("import declaration");}
485           ;
486 impspec   : /* empty */                 {$$ = gc0(DOTDOT);}
487           | HIDING '(' imports ')'      {$$ = gc4(ap(HIDDEN,$3));}
488           | '(' imports ')'             {$$ = gc3($2);}
489           ;
490 imports   : /* empty */                 {$$ = gc0(NIL);}
491           | ','                         {$$ = gc1(NIL);}
492           | imports1                    {$$ = $1;}
493           | imports1 ','                {$$ = gc2($1);}
494           ;
495 imports1  : imports1 ',' import         {$$ = gc3(cons($3,$1));}
496           | import                      {$$ = gc1(singleton($1));}
497           ;
498 import    : var                         {$$ = $1;}
499           | CONID                       {$$ = $1;}
500           | CONID '(' UPTO ')'          {$$ = gc4(pair($1,DOTDOT));}
501           | CONID '(' names ')'         {$$ = gc4(pair($1,$3));}
502           ;
503 names     : /* empty */                 {$$ = gc0(NIL);}
504           | ','                         {$$ = gc1(NIL);}
505           | names1                      {$$ = $1;}
506           | names1 ','                  {$$ = gc2($1);}
507           ;
508 names1    : names1 ',' name             {$$ = gc3(cons($3,$1));}
509           | name                        {$$ = gc1(singleton($1));}
510           ;
511 name      : var                         {$$ = $1;}
512           | con                         {$$ = $1;}
513           ;
514
515 /*- Top-level declarations: -----------------------------------------------*/
516
517 topDecls  : /* empty */                 {$$ = gc0(NIL);}
518           | ';'                         {$$ = gc1(NIL);}
519           | topDecls1                   {$$ = $1;}
520           | topDecls1 ';'               {$$ = gc2($1);}
521           ;
522 topDecls1 : topDecls1 ';' topDecl       {$$ = gc2($1);}
523           | topDecls1 ';' decl          {$$ = gc3(cons($3,$1));}
524           | topDecl                     {$$ = gc0(NIL);}
525           | decl                        {$$ = gc1(cons($1,NIL));}
526           ;
527
528 /*- Type declarations: ----------------------------------------------------*/
529
530 topDecl   : TYPE tyLhs '=' type         {defTycon(4,$3,$2,$4,SYNONYM);}
531           | TYPE tyLhs '=' type IN invars
532                                         {defTycon(6,$3,$2,
533                                                     ap($4,$6),RESTRICTSYN);}
534           | TYPE error                  {syntaxError("type definition");}
535           | DATA btype2 '=' constrs deriving
536                                         {defTycon(5,$3,checkTyLhs($2),
537                                                    ap(rev($4),$5),DATATYPE);}
538           | DATA context IMPLIES tyLhs '=' constrs deriving
539                                         {defTycon(7,$5,$4,
540                                                   ap(qualify($2,rev($6)),
541                                                      $7),DATATYPE);}
542           | DATA btype2                 {defTycon(2,$1,checkTyLhs($2),
543                                                     ap(NIL,NIL),DATATYPE);}
544           | DATA context IMPLIES tyLhs  {defTycon(4,$1,$4,
545                                                   ap(qualify($2,NIL),
546                                                      NIL),DATATYPE);}
547           | DATA error                  {syntaxError("data definition");}
548           | TNEWTYPE btype2 '=' nconstr deriving
549                                         {defTycon(5,$3,checkTyLhs($2),
550                                                     ap($4,$5),NEWTYPE);}
551           | TNEWTYPE context IMPLIES tyLhs '=' nconstr deriving
552                                         {defTycon(7,$5,$4,
553                                                   ap(qualify($2,$6),
554                                                      $7),NEWTYPE);}
555           | TNEWTYPE error              {syntaxError("newtype definition");}
556           ;
557 tyLhs     : tyLhs varid                 {$$ = gc2(ap($1,$2));}
558           | CONID                       {$$ = $1;}
559           | error                       {syntaxError("type defn lhs");}
560           ;
561 invars    : invars ',' invar            {$$ = gc3(cons($3,$1));}
562           | invar                       {$$ = gc1(cons($1,NIL));}
563           ;
564 invar     : var COCO topType            {$$ = gc3(sigdecl($2,singleton($1),
565                                                                        $3));}
566           | var                         {$$ = $1;}
567           ;
568 constrs   : constrs '|' pconstr         {$$ = gc3(cons($3,$1));}
569           | pconstr                     {$$ = gc1(cons($1,NIL));}
570           ;
571 pconstr   : ALL varids '.' qconstr      {$$ = gc4(ap(POLYTYPE,
572                                                      pair(rev($2),$4)));}
573           | qconstr                     {$$ = $1;}
574           ;
575 qconstr   : context IMPLIES constr      {$$ = gc3(qualify($1,$3));}
576           | constr                      {$$ = $1;}
577           ;
578 constr    : '!' btype conop bbtype      {$$ = gc4(ap(ap($3,bang($2)),$4));}
579           | btype1    conop bbtype      {$$ = gc3(ap(ap($2,$1),$3));}
580           | btype2    conop bbtype      {$$ = gc3(ap(ap($2,$1),$3));}
581           | bpolyType conop bbtype      {$$ = gc3(ap(ap($2,$1),$3));}
582           | btype2                      {$$ = $1;}
583           | btype3                      {$$ = $1;}
584           | btype4                      {$$ = $1;}
585           | con '{' fieldspecs '}'      {$$ = gc4(ap(LABC,pair($1,rev($3))));}
586           | con '{' '}'                 {$$ = gc3(ap(LABC,pair($1,NIL)));}
587           | error                       {syntaxError("data type definition");}
588           ;
589 btype3    : btype2 '!' atype            {$$ = gc3(ap($1,bang($3)));}
590           | btype3 '!' atype            {$$ = gc3(ap($1,bang($3)));}
591           | btype3 atype                {$$ = gc2(ap($1,$2));}
592           ;
593 btype4    : btype2 bpolyType            {$$ = gc2(ap($1,$2));}
594           | btype3 bpolyType            {$$ = gc2(ap($1,$2));}
595           | btype4 bpolyType            {$$ = gc2(ap($1,$2));}
596           | btype4 atype                {$$ = gc2(ap($1,$2));}
597           | btype4 '!' atype            {$$ = gc3(ap($1,bang($3)));}
598           ;
599 bbtype    : '!' btype                   {$$ = gc2(bang($2));}
600           | btype                       {$$ = $1;}
601           | bpolyType                   {$$ = $1;}
602           ;
603 nconstr   : pconstr                     {$$ = gc1(singleton($1));}
604           ;
605 fieldspecs: fieldspecs ',' fieldspec    {$$ = gc3(cons($3,$1));}
606           | fieldspec                   {$$ = gc1(cons($1,NIL));}
607           ;
608 fieldspec : vars COCO polyType          {$$ = gc3(pair(rev($1),$3));}
609           | vars COCO type              {$$ = gc3(pair(rev($1),$3));}
610           | vars COCO '!' type          {$$ = gc4(pair(rev($1),bang($4)));}
611           ;
612 deriving  : /* empty */                 {$$ = gc0(NIL);}
613           | DERIVING qconid             {$$ = gc2(singleton($2));}
614           | DERIVING '(' derivs0 ')'    {$$ = gc4($3);}
615           ;
616 derivs0   : /* empty */                 {$$ = gc0(NIL);}
617           | derivs                      {$$ = gc1(rev($1));}
618           ;
619 derivs    : derivs ',' qconid           {$$ = gc3(cons($3,$1));}
620           | qconid                      {$$ = gc1(singleton($1));}
621           ;
622
623 /*- Processing definitions of primitives ----------------------------------*/
624
625 topDecl   : FOREIGN IMPORT callconv ext_loc ext_name unsafe_flag var COCO type 
626                                         {foreignImport($1,pair($4,$5),$7,$9); sp-=9;}
627           | FOREIGN EXPORT callconv DYNAMIC qvarid COCO type 
628                                         {foreignExport($1,$4,$5,$7); sp-=7;}
629           ;
630
631 callconv  : var                  {$$ = gc1(NIL); /* ignored */ }
632           ;
633 ext_loc   : STRINGLIT            {$$ = $1;}
634           ;
635 ext_name  : STRINGLIT            {$$ = $1;}
636           ;
637 unsafe_flag: /* empty */         {$$ = gc0(NIL);}
638           | UNSAFE               {$$ = gc1(NIL); /* ignored */ }
639           ;
640
641
642 /*- Class declarations: ---------------------------------------------------*/
643
644 topDecl   : TCLASS crule wherePart      {classDefn(intOf($1),$2,$3); sp-=3;}
645           | TINSTANCE irule wherePart   {instDefn(intOf($1),$2,$3);  sp-=3;}
646           | DEFAULT '(' dtypes ')'      {defaultDefn(intOf($1),$3);  sp-=4;}
647           | TCLASS error                {syntaxError("class declaration");}
648           | TINSTANCE error             {syntaxError("instance declaration");}
649           | DEFAULT error               {syntaxError("default declaration");}
650           ;
651 crule     : context IMPLIES btype2      {$$ = gc3(pair($1,checkPred($3)));}
652           | btype2                      {$$ = gc1(pair(NIL,checkPred($1)));}
653           ;
654 irule     : context IMPLIES btype2      {$$ = gc3(pair($1,checkPred($3)));}
655           | btype2                      {$$ = gc1(pair(NIL,checkPred($1)));}
656           ;
657 dtypes    : /* empty */                 {$$ = gc0(NIL);}
658           | dtypes1                     {$$ = gc1(rev($1));}
659           ;
660 dtypes1   : dtypes1 ',' type            {$$ = gc3(cons($3,$1));}
661           | type                        {$$ = gc1(cons($1,NIL));}
662           ;
663
664 /*- Type expressions: -----------------------------------------------------*/
665
666 topType   : context IMPLIES topType1    {$$ = gc3(qualify($1,$3));}
667           | topType1                    {$$ = $1;}
668           ;
669 topType1  : bpolyType ARROW topType1    {$$ = gc3(fn($1,$3));}
670           | btype1    ARROW topType1    {$$ = gc3(fn($1,$3));}
671           | btype2    ARROW topType1    {$$ = gc3(fn($1,$3));}
672           | btype                       {$$ = $1;}
673           ;
674 polyType  : ALL varids '.' sigType      {$$ = gc4(ap(POLYTYPE,
675                                                      pair(rev($2),$4)));}
676           | bpolyType                   {$$ = $1;}
677           ;
678 bpolyType : '(' polyType ')'            {$$ = gc3($2);}
679           ;
680 varids    : varids ',' varid            {$$ = gc3(cons($3,$1));}
681           | varid                       {$$ = gc1(singleton($1));}
682           ;
683 sigType   : context IMPLIES type        {$$ = gc3(qualify($1,$3));}
684           | type                        {$$ = $1;}
685           ;
686 context   : '(' ')'                     {$$ = gc2(NIL);}
687           | btype2                      {$$ = gc1(singleton(checkPred($1)));}
688           | '(' btype2 ')'              {$$ = gc3(singleton(checkPred($2)));}
689           | '(' btypes2 ')'             {$$ = gc3(checkContext(rev($2)));}
690 /*#if TREX*/
691           | lacks                       {$$ = gc1(singleton($1));}
692           | '(' lacks1 ')'              {$$ = gc3(checkContext(rev($2)));}
693           ;
694 lacks     : varid '\\' varid            {
695 #if TREX
696                                          $$ = gc3(ap(mkExt(textOf($3)),$1));
697 #else
698                                          noTREX("a type context");
699 #endif
700                                         }
701           ;
702 lacks1    : btypes2 ',' lacks           {$$ = gc3(cons($3,$1));}
703           | lacks1  ',' btype2          {$$ = gc3(cons($3,$1));}
704           | lacks1  ',' lacks           {$$ = gc3(cons($3,$1));}
705           | btype2  ',' lacks           {$$ = gc3(cons($3,cons($1,NIL)));}
706           | lacks                       {$$ = gc1(singleton($1));}
707           ;
708 /*#endif*/
709
710 type      : type1                       {$$ = $1;}
711           | btype2                      {$$ = $1;}
712           ;
713 type1     : btype1                      {$$ = $1;}
714           | btype1 ARROW type           {$$ = gc3(fn($1,$3));}
715           | btype2 ARROW type           {$$ = gc3(fn($1,$3));}
716           | error                       {syntaxError("type expression");}
717           ;
718 btype     : btype1                      {$$ = $1;}
719           | btype2                      {$$ = $1;}
720           ;
721 btype1    : btype1 atype                {$$ = gc2(ap($1,$2));}
722           | atype1                      {$$ = $1;}
723           ;
724 btype2    : btype2 atype                {$$ = gc2(ap($1,$2));}
725           | qconid                      {$$ = $1;}
726           ;
727 atype     : atype1                      {$$ = $1;}
728           | qconid                      {$$ = $1;}
729           ;
730 atype1    : varid                       {$$ = $1;}
731           | '(' ')'                     {$$ = gc2(typeUnit);}
732           | '(' ARROW ')'               {$$ = gc3(typeArrow);}
733           | '(' type1 ')'               {$$ = gc3($2);}
734           | '(' btype2 ')'              {$$ = gc3($2);}
735           | '(' tupCommas ')'           {$$ = gc3($2);}
736           | '(' btypes2 ')'             {$$ = gc3(buildTuple($2));}
737           | '(' typeTuple ')'           {$$ = gc3(buildTuple($2));}
738 /*#if TREX*/
739           | '(' tfields ')'             {
740 #if TREX
741                                          $$ = gc3(revOnto($2,typeNoRow));
742 #else
743                                          noTREX("a type");
744 #endif
745                                         }
746           | '(' tfields '|' type ')'    {$$ = gc5(revOnto($2,$4));}
747 /*#endif*/
748           | '[' type ']'                {$$ = gc3(ap(typeList,$2));}
749           | '[' ']'                     {$$ = gc2(typeList);}
750           | '_'                         {$$ = gc1(inventVar());}
751           ;
752 btypes2   : btypes2 ',' btype2          {$$ = gc3(cons($3,$1));}
753           | btype2  ',' btype2          {$$ = gc3(cons($3,cons($1,NIL)));}
754           ;
755 typeTuple : type1     ',' type          {$$ = gc3(cons($3,cons($1,NIL)));}
756           | btype2    ',' type1         {$$ = gc3(cons($3,cons($1,NIL)));}
757           | btypes2   ',' type1         {$$ = gc3(cons($3,$1));}
758           | typeTuple ',' type          {$$ = gc3(cons($3,$1));}
759           ;
760 /*#if TREX*/
761 tfields   : tfields ',' tfield          {$$ = gc3(cons($3,$1));}
762           | tfield                      {$$ = gc1(singleton($1));}
763           ;
764 tfield    : varid COCO type             {$$ = gc3(ap(mkExt(textOf($1)),$3));}
765           ;
766 /*#endif*/
767
768 /*- Value declarations: ---------------------------------------------------*/
769
770 gendecl   : INFIXN optDigit ops         {$$ = gc3(fixdecl($1,$3,NON_ASS,$2));}
771           | INFIXN error                {syntaxError("fixity decl");}
772           | INFIXL optDigit ops         {$$ = gc3(fixdecl($1,$3,LEFT_ASS,$2));}
773           | INFIXL error                {syntaxError("fixity decl");}
774           | INFIXR optDigit ops         {$$ = gc3(fixdecl($1,$3,RIGHT_ASS,$2));}
775           | INFIXR error                {syntaxError("fixity decl");}
776           | vars COCO topType           {$$ = gc3(sigdecl($2,$1,$3));}
777           | vars COCO error             {syntaxError("type signature");}
778           ;
779 optDigit  : NUMLIT                      {$$ = gc1(checkPrec($1));}
780           | /* empty */                 {$$ = gc0(mkInt(DEF_PREC));}
781           ;
782 ops       : ops ',' op                  {$$ = gc3(cons($3,$1));}
783           | op                          {$$ = gc1(singleton($1));}
784           ;
785 vars      : vars ',' var                {$$ = gc3(cons($3,$1));}
786           | var                         {$$ = gc1(singleton($1));}
787           ;
788 decls     : '{' decls0 end              {$$ = gc3($2);}
789           | '{' decls1 end              {$$ = gc3($2);}
790           ;
791 decls0    : /* empty */                 {$$ = gc0(NIL);}
792           | decls0 ';'                  {$$ = gc2($1);}
793           | decls1 ';'                  {$$ = gc2($1);}
794           ;
795 decls1    : decls0 decl                 {$$ = gc2(cons($2,$1));}
796           ;
797 decl      : gendecl                     {$$ = $1;}
798           | funlhs rhs                  {$$ = gc2(ap(FUNBIND,pair($1,$2)));}
799           | funlhs COCO type rhs        {$$ = gc4(ap(FUNBIND,
800                                                      pair($1,ap(RSIGN,
801                                                                 ap($4,$3)))));}
802           | pat0 rhs                    {$$ = gc2(ap(PATBIND,pair($1,$2)));}
803           ;
804 funlhs    : funlhs0                     {$$ = $1;}
805           | funlhs1                     {$$ = $1;}
806           | npk                         {$$ = $1;}
807           ;
808 funlhs0   : pat10_vI varop    pat0      {$$ = gc3(ap2($2,$1,$3));}
809           | infixPat varop    pat0      {$$ = gc3(ap2($2,$1,$3));}
810           | NUMLIT   varop    pat0      {$$ = gc3(ap2($2,$1,$3));}
811           | var      varop_pl pat0      {$$ = gc3(ap2($2,$1,$3));}
812           | var      '+'      pat0_INT  {$$ = gc3(ap2(varPlus,$1,$3));}
813           ;
814 funlhs1   : '(' funlhs0 ')' apat        {$$ = gc4(ap($2,$4));}
815           | '(' funlhs1 ')' apat        {$$ = gc4(ap($2,$4));}
816           | '(' npk     ')' apat        {$$ = gc4(ap($2,$4));}
817           | var     apat                {$$ = gc2(ap($1,$2));}
818           | funlhs1 apat                {$$ = gc2(ap($1,$2));}
819           ;
820 rhs       : rhs1 wherePart              {$$ = gc2(letrec($2,$1));}
821           | error                       {syntaxError("declaration");}
822           ;
823 rhs1      : '=' exp                     {$$ = gc2(pair($1,$2));}
824           | gdrhs                       {$$ = gc1(grded(rev($1)));}
825           ;
826 gdrhs     : gdrhs gddef                 {$$ = gc2(cons($2,$1));}
827           | gddef                       {$$ = gc1(singleton($1));}
828           ;
829 gddef     : '|' exp0 '=' exp            {$$ = gc4(pair($3,pair($2,$4)));}
830           ;
831 wherePart : /* empty */                 {$$ = gc0(NIL);}
832           | WHERE decls                 {$$ = gc2($2);}
833           ;
834
835 /*- Patterns: -------------------------------------------------------------*/
836
837 pat       : npk                         {$$ = $1;}
838           | pat_npk                     {$$ = $1;}
839           ;
840 pat_npk   : pat0 COCO type              {$$ = gc3(ap(ESIGN,pair($1,$3)));}
841           | pat0                        {$$ = $1;}
842           ;
843 npk       : var '+' NUMLIT              {$$ = gc3(ap2(varPlus,$1,$3));}
844           ;
845 pat0      : var                         {$$ = $1;}
846           | NUMLIT                      {$$ = $1;}
847           | pat0_vI                     {$$ = $1;}
848           ;
849 pat0_INT  : var                         {$$ = $1;}
850           | pat0_vI                     {$$ = $1;}
851           ;
852 pat0_vI   : pat10_vI                    {$$ = $1;}
853           | infixPat                    {$$ = gc1(ap(INFIX,$1));}
854           ;
855 infixPat  : '-' pat10                   {$$ = gc2(ap(NEG,only($2)));}
856           | var qconop pat10            {$$ = gc3(ap(ap($2,only($1)),$3));}
857           | var qconop '-' pat10        {$$ = gc4(ap(NEG,ap2($2,only($1),$4)));}
858           | NUMLIT qconop pat10         {$$ = gc3(ap(ap($2,only($1)),$3));}
859           | NUMLIT qconop '-' pat10     {$$ = gc4(ap(NEG,ap2($2,only($1),$4)));}
860           | pat10_vI qconop pat10       {$$ = gc3(ap(ap($2,only($1)),$3));}
861           | pat10_vI qconop '-' pat10   {$$ = gc4(ap(NEG,ap2($2,only($1),$4)));}
862           | infixPat qconop pat10       {$$ = gc3(ap(ap($2,$1),$3));}
863           | infixPat qconop '-' pat10   {$$ = gc4(ap(NEG,ap(ap($2,$1),$4)));}
864           ;
865 pat10     : fpat                        {$$ = $1;}
866           | apat                        {$$ = $1;}
867           ;
868 pat10_vI  : fpat                        {$$ = $1;}
869           | apat_vI                     {$$ = $1;}
870           ;
871 fpat      : fpat apat                   {$$ = gc2(ap($1,$2));}
872           | gcon apat                   {$$ = gc2(ap($1,$2));}
873           ;
874 apat      : NUMLIT                      {$$ = $1;}
875           | var                         {$$ = $1;}
876           | apat_vI                     {$$ = $1;}
877           ;
878 apat_vI   : var '@' apat                {$$ = gc3(ap(ASPAT,pair($1,$3)));}
879           | gcon                        {$$ = $1;}
880           | qcon '{' patbinds '}'       {$$ = gc4(ap(CONFLDS,pair($1,$3)));}
881           | CHARLIT                     {$$ = $1;}
882           | STRINGLIT                   {$$ = $1;}
883           | '_'                         {$$ = gc1(WILDCARD);}
884           | '(' pat_npk ')'             {$$ = gc3($2);}
885           | '(' npk ')'                 {$$ = gc3($2);}
886           | '(' pats2 ')'               {$$ = gc3(buildTuple($2));}
887           | '[' pats1 ']'               {$$ = gc3(ap(FINLIST,rev($2)));}
888           | '~' apat                    {$$ = gc2(ap(LAZYPAT,$2));}
889 /*#if TREX*/
890           | '(' patfields ')'           {
891 #if TREX
892                                          $$ = gc3(revOnto($2,nameNoRec));
893 #else
894                                          $$ = gc3(NIL);
895 #endif
896                                         }
897           | '(' patfields '|' pat ')'   {$$ = gc5(revOnto($2,$4));}
898 /*#endif TREX*/
899           ;
900 pats2     : pats2 ',' pat               {$$ = gc3(cons($3,$1));}
901           | pat ',' pat                 {$$ = gc3(cons($3,singleton($1)));}
902           ;
903 pats1     : pats1 ',' pat               {$$ = gc3(cons($3,$1));}
904           | pat                         {$$ = gc1(singleton($1));}
905           ;
906 patbinds  : /* empty */                 {$$ = gc0(NIL);}
907           | patbinds1                   {$$ = gc1(rev($1));}
908           ;
909 patbinds1 : patbinds1 ',' patbind       {$$ = gc3(cons($3,$1));}
910           | patbind                     {$$ = gc1(singleton($1));}
911           ;
912 patbind   : qvar '=' pat                {$$ = gc3(pair($1,$3));}
913           | var                         {$$ = $1;}
914           ;
915 /*#if TREX*/
916 patfields : patfields ',' patfield      {$$ = gc3(cons($3,$1));}
917           | patfield                    {$$ = gc1(singleton($1));}
918           ;
919 patfield  : varid '=' pat               {
920 #if TREX
921                                          $$ = gc3(ap(mkExt(textOf($1)),$3));
922 #else
923                                          noTREX("a pattern");
924 #endif
925                                         }
926           ;
927 /*#endif TREX*/
928
929 /*- Expressions: ----------------------------------------------------------*/
930
931 exp       : exp_err                     {$$ = $1;}
932           | error                       {syntaxError("expression");}
933           ;
934 exp_err   : exp0a COCO sigType          {$$ = gc3(ap(ESIGN,pair($1,$3)));}
935           | exp0                        {$$ = $1;}
936           ;
937 exp0      : exp0a                       {$$ = $1;}
938           | exp0b                       {$$ = $1;}
939           ;
940 exp0a     : infixExpa                   {$$ = gc1(ap(INFIX,$1));}
941           | exp10a                      {$$ = $1;}
942           ;
943 exp0b     : infixExpb                   {$$ = gc1(ap(INFIX,$1));}
944           | exp10b                      {$$ = $1;}
945           ;
946 infixExpa : infixExpa qop '-' exp10a    {$$ = gc4(ap(NEG,ap(ap($2,$1),$4)));}
947           | infixExpa qop exp10a        {$$ = gc3(ap(ap($2,$1),$3));}
948           | '-' exp10a                  {$$ = gc2(ap(NEG,only($2)));}
949           | exp10a qop '-' exp10a       {$$ = gc4(ap(NEG,
950                                                      ap(ap($2,only($1)),$4)));}
951           | exp10a qop exp10a           {$$ = gc3(ap(ap($2,only($1)),$3));}
952           ;
953 infixExpb : infixExpa qop '-' exp10b    {$$ = gc4(ap(NEG,ap(ap($2,$1),$4)));}
954           | infixExpa qop exp10b        {$$ = gc3(ap(ap($2,$1),$3));}
955           | '-' exp10b                  {$$ = gc2(ap(NEG,only($2)));}
956           | exp10a qop '-' exp10b       {$$ = gc4(ap(NEG,
957                                                      ap(ap($2,only($1)),$4)));}
958           | exp10a qop exp10b           {$$ = gc3(ap(ap($2,only($1)),$3));}
959           ;
960 exp10a    : CASEXP exp OF '{' alts end  {$$ = gc6(ap(CASE,pair($2,rev($5))));}
961           | DO '{' stmts end            {$$ = gc4(ap(DOCOMP,checkDo($3)));}
962           | appExp                      {$$ = $1;}
963           ;
964 exp10b    : '\\' pats ARROW exp         {$$ = gc4(ap(LAMBDA,      
965                                                      pair(rev($2),
966                                                           pair($3,$4))));}
967           | LET decls IN exp            {$$ = gc4(letrec($2,$4));}
968           | IF exp THEN exp ELSE exp    {$$ = gc6(ap(COND,triple($2,$4,$6)));}
969           ;
970 pats      : pats apat                   {$$ = gc2(cons($2,$1));}
971           | apat                        {$$ = gc1(cons($1,NIL));}
972           ;
973 appExp    : appExp aexp                 {$$ = gc2(ap($1,$2));}
974           | aexp                        {$$ = $1;}
975           ;
976 aexp      : qvar                        {$$ = $1;}
977           | qvar '@' aexp               {$$ = gc3(ap(ASPAT,pair($1,$3)));}
978           | '~' aexp                    {$$ = gc2(ap(LAZYPAT,$2));}
979           | '_'                         {$$ = gc1(WILDCARD);}
980           | gcon                        {$$ = $1;}
981           | qcon '{' fbinds '}'         {$$ = gc4(ap(CONFLDS,pair($1,$3)));}
982           | aexp '{' fbinds '}'         {$$ = gc4(ap(UPDFLDS,
983                                                      triple($1,NIL,$3)));}
984           | NUMLIT                      {$$ = $1;}
985           | CHARLIT                     {$$ = $1;}
986           | STRINGLIT                   {$$ = $1;}
987           | REPEAT                      {$$ = $1;}
988           | '(' exp ')'                 {$$ = gc3($2);}
989           | '(' exps2 ')'               {$$ = gc3(buildTuple($2));}
990 /*#if TREX*/
991           | '(' vfields ')'             {
992 #if TREX
993                                          $$ = gc3(revOnto($2,nameNoRec));
994 #else
995                                          $$ = gc3(NIL);
996 #endif
997                                         }
998           | '(' vfields '|' exp ')'     {$$ = gc5(revOnto($2,$4));}
999           | RECSELID                    {$$ = $1;}
1000 /*#endif*/
1001           | '[' list ']'                {$$ = gc3($2);}
1002           | '(' exp10a qop ')'          {$$ = gc4(ap($3,$2));}
1003           | '(' qvarop_mi exp0 ')'      {$$ = gc4(ap(ap(nameFlip,$2),$3));}
1004           | '(' qconop exp0 ')'         {$$ = gc4(ap(ap(nameFlip,$2),$3));}
1005           ;
1006 exps2     : exps2 ',' exp               {$$ = gc3(cons($3,$1));}
1007           | exp ',' exp                 {$$ = gc3(cons($3,cons($1,NIL)));}
1008           ;
1009 /*#if TREX*/
1010 vfields   : vfields ',' vfield          {$$ = gc3(cons($3,$1));}
1011           | vfield                      {$$ = gc1(singleton($1));}
1012           ;
1013 vfield    : varid '=' exp               {
1014 #if TREX
1015                                          $$ = gc3(ap(mkExt(textOf($1)),$3));
1016 #else
1017                                          noTREX("an expression");
1018 #endif
1019                                         }
1020           ;
1021 /*#endif*/
1022 alts      : alts1                       {$$ = $1;}
1023           | alts1 ';'                   {$$ = gc2($1);}
1024           ;
1025 alts1     : alts1 ';' alt               {$$ = gc3(cons($3,$1));}
1026           | alt                         {$$ = gc1(cons($1,NIL));}
1027           ;
1028 alt       : pat altRhs wherePart        {$$ = gc3(pair($1,letrec($3,$2)));}
1029           ;
1030 altRhs    : guardAlts                   {$$ = gc1(grded(rev($1)));}
1031           | ARROW exp                   {$$ = gc2(pair($1,$2));}
1032           | error                       {syntaxError("case expression");}
1033           ;
1034 guardAlts : guardAlts guardAlt          {$$ = gc2(cons($2,$1));}
1035           | guardAlt                    {$$ = gc1(cons($1,NIL));}
1036           ;
1037 guardAlt  : '|' exp0 ARROW exp          {$$ = gc4(pair($3,pair($2,$4)));}
1038           ;
1039 stmts     : stmts1 ';'                  {$$ = gc2($1);}
1040           | stmts1                      {$$ = $1;}
1041           ;
1042 stmts1    : stmts1 ';' stmt             {$$ = gc3(cons($3,$1));}
1043           | stmt                        {$$ = gc1(cons($1,NIL));}
1044           ;
1045 stmt      : exp_err FROM exp            {$$ = gc3(ap(FROMQUAL,pair($1,$3)));}
1046           | LET decls                   {$$ = gc2(ap(QWHERE,$2));}
1047 /*        | IF exp                      {$$ = gc2(ap(BOOLQUAL,$2));}*/
1048           | exp_err                     {$$ = gc1(ap(DOQUAL,$1));}
1049           ;
1050 fbinds    : /* empty */                 {$$ = gc0(NIL);}
1051           | fbinds1                     {$$ = gc1(rev($1));}
1052           ;
1053 fbinds1   : fbinds1 ',' fbind           {$$ = gc3(cons($3,$1));}
1054           | fbind                       {$$ = gc1(singleton($1));}
1055           ;
1056 fbind     : var                         {$$ = $1;}
1057           | qvar '=' exp                {$$ = gc3(pair($1,$3));}
1058           ;
1059
1060 /*- List Expressions: -------------------------------------------------------*/
1061
1062 list      : exp                         {$$ = gc1(ap(FINLIST,cons($1,NIL)));}
1063           | exps2                       {$$ = gc1(ap(FINLIST,rev($1)));}
1064           | exp '|' quals               {$$ = gc3(ap(COMP,pair($1,rev($3))));}
1065           | exp         UPTO exp        {$$ = gc3(ap(ap(nameFromTo,$1),$3));}
1066           | exp ',' exp UPTO            {$$ = gc4(ap(ap(nameFromThen,$1),$3));}
1067           | exp         UPTO            {$$ = gc2(ap(nameFrom,$1));}
1068           | exp ',' exp UPTO exp        {$$ = gc5(ap(ap(ap(nameFromThenTo,
1069                                                                 $1),$3),$5));}
1070           ;
1071 quals     : quals ',' qual              {$$ = gc3(cons($3,$1));}
1072           | qual                        {$$ = gc1(cons($1,NIL));}
1073           ;
1074 qual      : exp FROM exp                {$$ = gc3(ap(FROMQUAL,pair($1,$3)));}
1075           | exp                         {$$ = gc1(ap(BOOLQUAL,$1));}
1076           | LET decls                   {$$ = gc2(ap(QWHERE,$2));}
1077           ;
1078
1079 /*- Identifiers and symbols: ----------------------------------------------*/
1080
1081 gcon      : qcon                        {$$ = $1;}
1082           | '(' ')'                     {$$ = gc2(nameUnit);}
1083           | '[' ']'                     {$$ = gc2(nameNil);}
1084           | '(' tupCommas ')'           {$$ = gc3($2);}
1085           ;
1086 tupCommas : tupCommas ','               {$$ = gc2(mkTuple(tupleOf($1)+1));}
1087           | ','                         {$$ = gc1(mkTuple(2));}
1088           ;
1089 varid     : VARID                       {$$ = $1;}
1090           | HIDING                      {$$ = gc1(varHiding);}
1091           | QUALIFIED                   {$$ = gc1(varQualified);}
1092           | ASMOD                       {$$ = gc1(varAsMod);}
1093           ;
1094 qconid    : QCONID                      {$$ = $1;}
1095           | CONID                       {$$ = $1;}
1096           ;
1097 var       : varid                       {$$ = $1;}
1098           | '(' VAROP ')'               {$$ = gc3($2);}
1099           | '(' '+' ')'                 {$$ = gc3(varPlus);}
1100           | '(' '-' ')'                 {$$ = gc3(varMinus);}
1101           | '(' '!' ')'                 {$$ = gc3(varBang);}
1102           | '(' '.' ')'                 {$$ = gc3(varDot);}
1103           ;
1104 qvar      : QVARID                      {$$ = $1;}
1105           | '(' QVAROP ')'              {$$ = gc3($2);}
1106           | var                         {$$ = $1;}
1107           ;
1108 con       : CONID                       {$$ = $1;}
1109           | '(' CONOP ')'               {$$ = gc3($2);}
1110           ;
1111 qcon      : QCONID                      {$$ = $1;}
1112           | '(' QCONOP ')'              {$$ = gc3($2);}
1113           | con                         {$$ = $1;}
1114           ;
1115 varop     : '+'                         {$$ = gc1(varPlus);}
1116           | '-'                         {$$ = gc1(varMinus);}
1117           | varop_mipl                  {$$ = $1;}
1118           ;
1119 varop_mi  : '+'                         {$$ = gc1(varPlus);}
1120           | varop_mipl                  {$$ = $1;}
1121           ;
1122 varop_pl  : '-'                         {$$ = gc1(varMinus);}
1123           | varop_mipl                  {$$ = $1;}
1124           ;
1125 varop_mipl: VAROP                       {$$ = $1;}
1126           | '`' varid '`'               {$$ = gc3($2);}
1127           | '!'                         {$$ = gc1(varBang);}
1128           | '.'                         {$$ = gc1(varDot);}
1129           ;
1130 qvarop    : '-'                         {$$ = gc1(varMinus);}
1131           | qvarop_mi                   {$$ = $1;}
1132           ;
1133 qvarop_mi : QVAROP                      {$$ = $1;}
1134           | '`' QVARID '`'              {$$ = gc3($2);}
1135           | varop_mi                    {$$ = $1;}
1136           ;
1137
1138 conop     : CONOP                       {$$ = $1;}
1139           | '`' CONID  '`'              {$$ = gc3($2);}
1140           ;
1141 qconop    : QCONOP                      {$$ = $1;}
1142           | '`' QCONID '`'              {$$ = gc3($2);}
1143           | conop                       {$$ = $1;}
1144           ;
1145 op        : varop                       {$$ = $1;}
1146           | conop                       {$$ = $1;}
1147           ;
1148 qop       : qvarop                      {$$ = $1;}
1149           | qconop                      {$$ = $1;}
1150           ;
1151
1152 /*- Stuff from STG hugs ---------------------------------------------------*/
1153
1154 qvarid    : varid1                      {$$ = gc1($1);}
1155           | QVARID                      {$$ = gc1($1);}
1156
1157 varid1    : VARID                       {$$ = gc1($1);}
1158           | HIDING                      {$$ = gc1(varHiding);}
1159           | QUALIFIED                   {$$ = gc1(varQualified);}
1160           | ASMOD                       {$$ = gc1(varAsMod);}
1161           ;
1162
1163 /*- Tricks to force insertion of leading and closing braces ---------------*/
1164
1165 begin     : error                       {yyerrok; 
1166                                          if (offsideON) goOffside(startColumn);}
1167           ;
1168                                         /* deal with trailing semicolon    */
1169 end       : '}'                         {$$ = $1;}
1170           | error                       {yyerrok; 
1171                                          if (offsideON && canUnOffside()) {
1172                                              unOffside();
1173                                              /* insert extra token on stack*/
1174                                              push(NIL);
1175                                              pushed(0) = pushed(1);
1176                                              pushed(1) = mkInt(column);
1177                                          }
1178                                          else
1179                                              syntaxError("definition");
1180                                         }
1181           ;
1182
1183 /*-------------------------------------------------------------------------*/
1184
1185 %%
1186
1187 static Cell local gcShadow(n,e)         /* keep parsed fragments on stack  */
1188 Int  n;
1189 Cell e; {
1190     /* If a look ahead token is held then the required stack transformation
1191      * is:
1192      *   pushed: n               1     0          1     0
1193      *           x1  |  ...  |  xn  |  la   ===>  e  |  la
1194      *                                top()            top()
1195      *
1196      * Otherwise, the transformation is:
1197      *   pushed: n-1             0        0
1198      *           x1  |  ...  |  xn  ===>  e
1199      *                         top()     top()
1200      */
1201     if (yychar>=0) {
1202         pushed(n-1) = top();
1203         pushed(n)   = e;
1204     }
1205     else
1206         pushed(n-1) = e;
1207     sp -= (n-1);
1208     return e;
1209 }
1210
1211 static Void local syntaxError(s)        /* report on syntax error          */
1212 String s; {
1213     ERRMSG(row) "Syntax error in %s (unexpected %s)", s, unexpected()
1214     EEND;
1215 }
1216
1217 static String local unexpected() {     /* find name for unexpected token   */
1218     static char buffer[100];
1219     static char *fmt = "%s \"%s\"";
1220     static char *kwd = "keyword";
1221
1222     switch (yychar) {
1223         case 0         : return "end of input";
1224
1225 #define keyword(kw) sprintf(buffer,fmt,kwd,kw); return buffer;
1226         case INFIXL    : keyword("infixl");
1227         case INFIXR    : keyword("infixr");
1228         case INFIXN    : keyword("infix");
1229         case FOREIGN   : keyword("foreign");
1230         case UNSAFE    : keyword("unsafe");
1231         case TINSTANCE : keyword("instance");
1232         case TCLASS    : keyword("class");
1233         case CASEXP    : keyword("case");
1234         case OF        : keyword("of");
1235         case IF        : keyword("if");
1236         case THEN      : keyword("then");
1237         case ELSE      : keyword("else");
1238         case WHERE     : keyword("where");
1239         case TYPE      : keyword("type");
1240         case DATA      : keyword("data");
1241         case TNEWTYPE  : keyword("newtype");
1242         case LET       : keyword("let");
1243         case IN        : keyword("in");
1244         case DERIVING  : keyword("deriving");
1245         case DEFAULT   : keyword("default");
1246         case IMPORT    : keyword("import");
1247         case TMODULE   : keyword("module");
1248         case ALL       : keyword("__forall");
1249 #undef keyword
1250
1251         case ARROW     : return "`->'";
1252         case '='       : return "`='";
1253         case COCO      : return "`::'";
1254         case '-'       : return "`-'";
1255         case '!'       : return "`!'";
1256         case ','       : return "comma";
1257         case '@'       : return "`@'";
1258         case '('       : return "`('";
1259         case ')'       : return "`)'";
1260         case '{'       : return "`{'";
1261         case '}'       : return "`}'";
1262         case '_'       : return "`_'";
1263         case '|'       : return "`|'";
1264         case '.'       : return "`.'";
1265         case ';'       : return "`;'";
1266         case UPTO      : return "`..'";
1267         case '['       : return "`['";
1268         case ']'       : return "`]'";
1269         case FROM      : return "`<-'";
1270         case '\\'      : return "backslash (lambda)";
1271         case '~'       : return "tilde";
1272         case '`'       : return "backquote";
1273 #if TREX
1274         case RECSELID  : sprintf(buffer,"selector \"#%s\"",
1275                                  textToStr(extText(snd(yylval))));
1276                          return buffer;
1277 #endif
1278         case VAROP     :
1279         case VARID     :
1280         case CONOP     :
1281         case CONID     : sprintf(buffer,"symbol \"%s\"",
1282                                  textToStr(textOf(yylval)));
1283                          return buffer;
1284         case QVAROP    :
1285         case QVARID    :
1286         case QCONOP    : 
1287         case QCONID    : sprintf(buffer,"symbol \"%s\"",
1288                                  identToStr(yylval));
1289                          return buffer;
1290         case HIDING    : return "symbol \"hiding\"";
1291         case QUALIFIED : return "symbol \"qualified\"";
1292         case ASMOD     : return "symbol \"as\"";
1293         case NUMLIT    : return "numeric literal";
1294         case CHARLIT   : return "character literal";
1295         case STRINGLIT : return "string literal";
1296         case IMPLIES   : return "`=>'";
1297         default        : return "token";
1298     }
1299 }
1300
1301 static Cell local checkPrec(p)          /* Check for valid precedence value*/
1302 Cell p; {
1303     if (!isInt(p) || intOf(p)<MIN_PREC || intOf(p)>MAX_PREC) {
1304         ERRMSG(row) "Precedence value must be an integer in the range [%d..%d]",
1305                     MIN_PREC, MAX_PREC
1306         EEND;
1307     }
1308     return p;
1309 }
1310
1311 static Cell local buildTuple(tup)       /* build tuple (x1,...,xn) from    */
1312 List tup; {                             /* list [xn,...,x1]                */
1313     Int  n = 0;
1314     Cell t = tup;
1315     Cell x;
1316
1317     do {                                /*    .                    .       */
1318         x      = fst(t);                /*   / \                  / \      */
1319         fst(t) = snd(t);                /*  xn  .                .   xn    */
1320         snd(t) = x;                     /*       .    ===>      .          */
1321         x      = t;                     /*        .            .           */
1322         t      = fun(x);                /*         .          .            */
1323         n++;                            /*        / \        / \           */
1324     } while (nonNull(t));               /*       x1  NIL   (n)  x1         */
1325     fst(x) = mkTuple(n);
1326     return tup;
1327 }
1328
1329 static List local checkContext(con)     /* validate context                */
1330 Type con; {
1331     mapOver(checkPred, con);
1332     return con;
1333 }
1334
1335 static Cell local checkPred(c)          /* check that type expr is a valid */
1336 Cell c; {                               /* constraint                      */
1337     Cell cn = getHead(c);
1338 #if TREX
1339     if (isExt(cn) && argCount==1)
1340         return c;
1341 #endif
1342     if (!isQCon(cn) || argCount==0)
1343         syntaxError("class expression");
1344     return c;
1345 }
1346
1347 static Pair local checkDo(dqs)          /* convert reversed list of dquals */
1348 List dqs; {                             /* to an (expr,quals) pair         */
1349     if (isNull(dqs) || whatIs(hd(dqs))!=DOQUAL) {
1350         ERRMSG(row) "Last generator in do {...} must be an expression"
1351         EEND;
1352     }
1353     fst(dqs) = snd(fst(dqs));           /* put expression in fst of pair   */
1354     snd(dqs) = rev(snd(dqs));           /* & reversed list of quals in snd */
1355     return dqs;
1356 }
1357
1358 static Cell local checkTyLhs(c)         /* check that lhs is of the form   */
1359 Cell c; {                               /* T a1 ... a                      */
1360     Cell tlhs = c;
1361     while (isAp(tlhs) && whatIs(arg(tlhs))==VARIDCELL)
1362         tlhs = fun(tlhs);
1363     switch (whatIs(tlhs)) {
1364         case CONIDCELL  : return c;
1365
1366         default :
1367             ERRMSG(row) "Illegal left hand side in datatype definition"
1368             EEND;
1369     }
1370     return 0; /* NOTREACHED */
1371 }
1372
1373 #if !TREX
1374 static Void local noTREX(where)
1375 String where; {
1376     ERRMSG(row) "Attempt to use TREX records while parsing %s.\n", where ETHEN
1377     ERRTEXT     "(TREX is disabled in this build of Hugs)"
1378     EEND;
1379 }
1380 #endif
1381
1382 /*-------------------------------------------------------------------------*/