]> git.sur5r.net Git - cc65/blob - src/cc65/pragma.c
Rewrote handling of the -W command line option. It is now used to enable or
[cc65] / src / cc65 / pragma.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 pragma.c                                  */
4 /*                                                                           */
5 /*                  Pragma handling for the cc65 C compiler                  */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2009, Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 52                                           */
11 /*                D-70794 Filderstadt                                        */
12 /* EMail:         uz@cc65.org                                                */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <stdlib.h>
37 #include <string.h>
38
39 /* common */
40 #include "segnames.h"
41 #include "tgttrans.h"
42
43 /* cc65 */
44 #include "codegen.h"
45 #include "error.h"
46 #include "expr.h"
47 #include "global.h"
48 #include "litpool.h"
49 #include "scanner.h"
50 #include "scanstrbuf.h"
51 #include "symtab.h"
52 #include "pragma.h"
53
54
55
56 /*****************************************************************************/
57 /*                                   data                                    */
58 /*****************************************************************************/
59
60
61
62 /* Tokens for the #pragmas */
63 typedef enum {
64     PR_ILLEGAL = -1,
65     PR_BSSSEG,
66     PR_CHARMAP,
67     PR_CHECKSTACK,
68     PR_CODESEG,
69     PR_CODESIZE,
70     PR_DATASEG,
71     PR_OPTIMIZE,
72     PR_REGVARADDR,
73     PR_REGVARS,
74     PR_RODATASEG,
75     PR_SIGNEDCHARS,
76     PR_STATICLOCALS,
77     PR_WARN,
78     PR_ZPSYM,
79     PR_COUNT
80 } pragma_t;
81
82 /* Pragma table */
83 static const struct Pragma {
84     const char* Key;            /* Keyword */
85     pragma_t    Tok;            /* Token */
86 } Pragmas[PR_COUNT] = {
87     {   "bssseg",       PR_BSSSEG       },
88     {   "charmap",      PR_CHARMAP      },
89     {   "checkstack",   PR_CHECKSTACK   },
90     {   "codeseg",      PR_CODESEG      },
91     {   "codesize",     PR_CODESIZE     },
92     {   "dataseg",      PR_DATASEG      },
93     {   "optimize",     PR_OPTIMIZE     },
94     {   "regvaraddr",   PR_REGVARADDR   },
95     {   "regvars",      PR_REGVARS      },
96     {   "rodataseg",    PR_RODATASEG    },
97     {   "signedchars",  PR_SIGNEDCHARS  },
98     {   "staticlocals", PR_STATICLOCALS },
99     {   "warn",         PR_WARN         },
100     {   "zpsym",        PR_ZPSYM        },
101 };
102
103
104
105 /*****************************************************************************/
106 /*                                   Code                                    */
107 /*****************************************************************************/
108
109
110
111 static void PragmaErrorSkip (void)
112 /* Called in case of an error, skips tokens until the closing paren or a
113  * semicolon is reached.
114  */
115 {
116     static const token_t TokenList[] = { TOK_RPAREN, TOK_SEMI };
117     SkipTokens (TokenList, sizeof(TokenList) / sizeof(TokenList[0]));
118 }
119
120
121
122 static int CmpKey (const void* Key, const void* Elem)
123 /* Compare function for bsearch */
124 {
125     return strcmp ((const char*) Key, ((const struct Pragma*) Elem)->Key);
126 }
127
128
129
130 static pragma_t FindPragma (const char* Key)
131 /* Find a pragma and return the token. Return PR_ILLEGAL if the keyword is
132  * not a valid pragma.
133  */
134 {
135     struct Pragma* P;
136     P = bsearch (Key, Pragmas, PR_COUNT, sizeof (Pragmas[0]), CmpKey);
137     return P? P->Tok : PR_ILLEGAL;
138 }
139
140
141
142 static void StringPragma (StrBuf* B, void (*Func) (const char*))
143 /* Handle a pragma that expects a string parameter */
144 {
145     StrBuf S;
146
147     /* We expect a string here */
148     if (SB_GetString (B, &S)) {
149         /* Call the given function with the string argument */
150         Func (SB_GetConstBuf (&S));
151     } else {
152         Error ("String literal expected");
153     }
154
155     /* Call the string buf destructor */
156     SB_Done (&S);
157 }
158
159
160
161 static void SegNamePragma (StrBuf* B, segment_t Seg)
162 /* Handle a pragma that expects a segment name parameter */
163 {
164     ident       Ident;
165     StrBuf      S;
166     const char* Name;
167
168     /* Try to read an identifier */
169     int Push = 0;
170     if (SB_GetSym (B, Ident)) {
171
172         /* Check if we have a first argument named "pop" */
173         if (strcmp (Ident, "pop") == 0) {
174
175             /* Pop the old value */
176             PopSegName (Seg);
177
178             /* Set the segment name */
179             g_segname (Seg);
180
181             /* Done */
182             return;
183
184         /* Check if we have a first argument named "push" */
185         } else if (strcmp (Ident, "push") == 0) {
186
187             Push = 1;
188             SB_SkipWhite (B);
189             if (SB_Get (B) != ',') {
190                 Error ("Comma expected");
191                 return;
192             }
193             SB_SkipWhite (B);
194
195         } else {
196             Error ("Invalid pragma arguments");
197             return;
198         }
199     }
200
201     /* A string argument must follow */
202     if (!SB_GetString (B, &S)) {
203         Error ("String literal expected");
204         return;
205     }
206
207     /* Get the string */
208     Name = SB_GetConstBuf (&S);
209
210     /* Check if the name is valid */
211     if (!ValidSegName (Name)) {
212         /* Segment name is invalid */
213         Error ("Illegal segment name: `%s'", Name);
214         return;
215     }
216
217     /* Set the new name */
218     if (Push) {
219         PushSegName (Seg, Name);
220     } else {
221         SetSegName (Seg, Name);
222     }
223     g_segname (Seg);
224
225     /* Call the string buf destructor */
226     SB_Done (&S);
227 }
228
229
230
231 static void CharMapPragma (StrBuf* B)
232 /* Change the character map */
233 {
234     long Index, C;
235
236     /* Read the character index */
237     if (!SB_GetNumber (B, &Index)) {
238         return;
239     }
240     if (Index < 1 || Index > 255) {
241         if (Index == 0) {
242             /* For groepaz */
243             Error ("Remapping 0 is not allowed");
244         } else {
245             Error ("Character index out of range");
246         }
247         return;
248     }
249
250     /* Comma follows */
251     SB_SkipWhite (B);
252     if (SB_Get (B) != ',') {
253         Error ("Comma expected");
254         return;
255     }
256     SB_SkipWhite (B);
257
258     /* Read the character code */
259     if (!SB_GetNumber (B, &C)) {
260         return;
261     }
262     if (C < 1 || C > 255) {
263         if (C == 0) {
264             /* For groepaz */
265             Error ("Remapping 0 is not allowed");
266         } else {
267             Error ("Character code out of range");
268         }
269         return;
270     }
271
272     /* Remap the character */
273     TgtTranslateSet ((unsigned) Index, (unsigned char) C);
274 }
275
276
277
278 static void FlagPragma (StrBuf* B, IntStack* Stack)
279 /* Handle a pragma that expects a boolean paramater */
280 {
281     ident Ident;
282     long  Val;
283     int   Push;
284
285     /* Try to read an identifier */
286     int IsIdent = SB_GetSym (B, Ident);
287
288     /* Check if we have a first argument named "pop" */
289     if (IsIdent && strcmp (Ident, "pop") == 0) {
290         if (IS_GetCount (Stack) < 2) {
291             Error ("Cannot pop, stack is empty");
292         } else {
293             IS_Drop (Stack);
294         }
295         /* No other arguments allowed */
296         return;
297     }
298
299     /* Check if we have a first argument named "push" */
300     if (IsIdent && strcmp (Ident, "push") == 0) {
301         Push = 1;
302         SB_SkipWhite (B);
303         if (SB_Get (B) != ',') {
304             Error ("Comma expected");
305             return;
306         }
307         SB_SkipWhite (B);
308         IsIdent = SB_GetSym (B, Ident);
309     } else {
310         Push = 0;
311     }
312
313     /* Boolean argument follows */
314     if (IsIdent) {
315         if (strcmp (Ident, "true") == 0 || strcmp (Ident, "on") == 0) {
316             Val = 1;
317         } else if (strcmp (Ident, "false") == 0 || strcmp (Ident, "off") == 0) {
318             Val = 0;
319         } else {
320             Error ("Pragma argument must be one of `on', `off', `true' or `false'");
321         }
322     } else if (!SB_GetNumber (B, &Val)) {
323         Error ("Invalid pragma argument");
324         return;
325     }
326
327     /* Set/push the new value */
328     if (Push) {
329         if (IS_IsFull (Stack)) {
330             Error ("Cannot push: stack overflow");
331         } else {
332             IS_Push (Stack, Val);
333         }
334     } else {
335         IS_Set (Stack, Val);
336     }
337 }
338
339
340
341 static void IntPragma (StrBuf* B, IntStack* Stack, long Low, long High)
342 /* Handle a pragma that expects an int paramater */
343 {
344     ident Ident;
345     long  Val;
346     int   Push;
347
348     /* Try to read an identifier */
349     int IsIdent = SB_GetSym (B, Ident);
350
351     /* Check if we have a first argument named "pop" */
352     if (IsIdent && strcmp (Ident, "pop") == 0) {
353         if (IS_GetCount (Stack) < 2) {
354             Error ("Cannot pop, stack is empty");
355         } else {
356             IS_Drop (Stack);
357         }
358         /* No other arguments allowed */
359         return;
360     }
361
362     /* Check if we have a first argument named "push" */
363     if (IsIdent && strcmp (Ident, "push") == 0) {
364         Push = 1;
365         SB_SkipWhite (B);
366         if (SB_Get (B) != ',') {
367             Error ("Comma expected");
368             return;
369         }
370         SB_SkipWhite (B);
371         IsIdent = 0;
372     } else {
373         Push = 0;
374     }
375
376     /* Integer argument follows */
377     if (IsIdent || !SB_GetNumber (B, &Val)) {
378         Error ("Pragma argument must be numeric");
379         return;
380     }
381
382     /* Check the argument */
383     if (Val < Low || Val > High) {
384         Error ("Pragma argument out of bounds (%ld-%ld)", Low, High);
385         return;
386     }
387
388     /* Set/push the new value */
389     if (Push) {
390         if (IS_IsFull (Stack)) {
391             Error ("Cannot push: stack overflow");
392         } else {
393             IS_Push (Stack, Val);
394         }
395     } else {
396         IS_Set (Stack, Val);
397     }
398 }
399
400
401
402 static void ParsePragma (void)
403 /* Parse the contents of the _Pragma statement */
404 {
405     pragma_t Pragma;
406     ident    Ident;
407
408     /* Create a string buffer from the string literal */
409     StrBuf B = AUTO_STRBUF_INITIALIZER;
410     GetLiteralStrBuf (&B, CurTok.IVal);
411
412     /* Reset the string pointer, effectivly clearing the string from the
413      * string table. Since we're working with one token lookahead, this
414      * will fail if the next token is also a string token, but that's a
415      * syntax error anyway, because we expect a right paren.
416      */
417     ResetLiteralPoolOffs (CurTok.IVal);
418
419     /* Skip the string token */
420     NextToken ();
421
422     /* Get the pragma name from the string */
423     SB_SkipWhite (&B);
424     if (!SB_GetSym (&B, Ident)) {
425         Error ("Invalid pragma");
426         return;
427     }
428
429     /* Search for the name */
430     Pragma = FindPragma (Ident);
431
432     /* Do we know this pragma? */
433     if (Pragma == PR_ILLEGAL) {
434         /* According to the ANSI standard, we're not allowed to generate errors
435          * for unknown pragmas, however, we're allowed to warn - and we will
436          * do so. Otherwise one typo may give you hours of bug hunting...
437          */
438         Warning ("Unknown pragma `%s'", Ident);
439         return;
440     }
441
442     /* Check for an open paren */
443     SB_SkipWhite (&B);
444     if (SB_Get (&B) != '(') {
445         Error ("'(' expected");
446         return;
447     }
448
449     /* Skip white space before the argument */
450     SB_SkipWhite (&B);
451
452     /* Switch for the different pragmas */
453     switch (Pragma) {
454
455         case PR_BSSSEG:
456             SegNamePragma (&B, SEG_BSS);
457             break;
458
459         case PR_CHARMAP:
460             CharMapPragma (&B);
461             break;
462
463         case PR_CHECKSTACK:
464             FlagPragma (&B, &CheckStack);
465             break;
466
467         case PR_CODESEG:
468             SegNamePragma (&B, SEG_CODE);
469             break;
470
471         case PR_CODESIZE:
472             IntPragma (&B, &CodeSizeFactor, 10, 1000);
473             break;
474
475         case PR_DATASEG:
476             SegNamePragma (&B, SEG_DATA);
477             break;
478
479         case PR_OPTIMIZE:
480             FlagPragma (&B, &Optimize);
481             break;
482
483         case PR_REGVARADDR:
484             FlagPragma (&B, &AllowRegVarAddr);
485             break;
486
487         case PR_REGVARS:
488             FlagPragma (&B, &EnableRegVars);
489             break;
490
491         case PR_RODATASEG:
492             SegNamePragma (&B, SEG_RODATA);
493             break;
494
495         case PR_SIGNEDCHARS:
496             FlagPragma (&B, &SignedChars);
497             break;
498
499         case PR_STATICLOCALS:
500             FlagPragma (&B, &StaticLocals);
501             break;
502
503         case PR_WARN:
504             FlagPragma (&B, &WarnEnable);
505             break;
506
507         case PR_ZPSYM:
508             StringPragma (&B, MakeZPSym);
509             break;
510
511         default:
512             Internal ("Invalid pragma");
513     }
514
515     /* Closing paren expected */
516     SB_SkipWhite (&B);
517     if (SB_Get (&B) != ')') {
518         Error ("')' expected");
519         return;
520     }
521     SB_SkipWhite (&B);
522
523     /* Allow an optional semicolon to be compatible with the old syntax */
524     if (SB_Peek (&B) == ';') {
525         SB_Skip (&B);
526         SB_SkipWhite (&B);
527     }
528
529     /* Make sure nothing follows */
530     if (SB_Peek (&B) != '\0') {
531         Error ("Unexpected input following pragma directive");
532     }
533
534     /* Release the StrBuf */
535     SB_Done (&B);
536 }
537
538
539
540 void DoPragma (void)
541 /* Handle pragmas. These come always in form of the new C99 _Pragma() operator. */
542 {
543     /* Skip the token itself */
544     NextToken ();
545
546     /* We expect an opening paren */
547     if (!ConsumeLParen ()) {
548         return;
549     }
550
551     /* String literal */
552     if (CurTok.Tok != TOK_SCONST) {
553
554         /* Print a diagnostic */
555         Error ("String literal expected");
556
557         /* Try some smart error recovery: Skip tokens until we reach the
558          * enclosing paren, or a semicolon.
559          */
560         PragmaErrorSkip ();
561
562     } else {
563
564         /* Parse the _Pragma statement */
565         ParsePragma ();
566     }
567
568     /* Closing paren needed */
569     ConsumeRParen ();
570 }
571
572
573