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