]> git.sur5r.net Git - cc65/blob - src/cc65/pragma.c
Add dummy return value to avoid a wcc warning
[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-2004 Ullrich von Bassewitz                                       */
10 /*               Römerstraße 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     DoneStrBuf (&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     DoneStrBuf (&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         Error ("Character index out of range");
242         return;
243     }
244
245     /* Comma follows */
246     SB_SkipWhite (B);
247     if (SB_Get (B) != ',') {
248         Error ("Comma expected");
249         return;
250     }
251     SB_SkipWhite (B);
252
253     /* Read the character code */
254     if (!SB_GetNumber (B, &C)) {
255         return;
256     }
257     if (C < 1 || C > 255) {
258         Error ("Character code out of range");
259         return;
260     }
261
262     /* Remap the character */
263     TgtTranslateSet ((unsigned) Index, (unsigned char) C);
264 }
265
266
267
268 static void FlagPragma (StrBuf* B, IntStack* Stack)
269 /* Handle a pragma that expects a boolean paramater */
270 {
271     ident Ident;
272     long  Val;
273     int   Push;
274
275     /* Try to read an identifier */
276     int IsIdent = SB_GetSym (B, Ident);
277
278     /* Check if we have a first argument named "pop" */
279     if (IsIdent && strcmp (Ident, "pop") == 0) {
280         if (IS_GetCount (Stack) < 2) {
281             Error ("Cannot pop, stack is empty");
282         } else {
283             IS_Drop (Stack);
284         }
285         /* No other arguments allowed */
286         return;
287     }
288
289     /* Check if we have a first argument named "push" */
290     if (IsIdent && strcmp (Ident, "push") == 0) {
291         Push = 1;
292         SB_SkipWhite (B);
293         if (SB_Get (B) != ',') {
294             Error ("Comma expected");
295             return;
296         }
297         SB_SkipWhite (B);
298         IsIdent = SB_GetSym (B, Ident);
299     } else {
300         Push = 0;
301     }
302
303     /* Boolean argument follows */
304     if (IsIdent) {
305         if (strcmp (Ident, "true") == 0 || strcmp (Ident, "on") == 0) {
306             Val = 1;
307         } else if (strcmp (Ident, "false") == 0 || strcmp (Ident, "off") == 0) {
308             Val = 0;
309         } else {
310             Error ("Pragma argument must be one of `on', `off', `true' or `false'");
311         }
312     } else if (!SB_GetNumber (B, &Val)) {
313         Error ("Invalid pragma argument");
314         return;
315     }
316
317     /* Set/push the new value */
318     if (Push) {
319         if (IS_IsFull (Stack)) {
320             Error ("Cannot push: stack overflow");
321         } else {
322             IS_Push (Stack, Val);
323         }
324     } else {
325         IS_Set (Stack, Val);
326     }
327 }
328
329
330
331 static void IntPragma (StrBuf* B, IntStack* Stack, long Low, long High)
332 /* Handle a pragma that expects an int paramater */
333 {
334     ident Ident;
335     long  Val;
336     int   Push;
337
338     /* Try to read an identifier */
339     int IsIdent = SB_GetSym (B, Ident);
340
341     /* Check if we have a first argument named "pop" */
342     if (IsIdent && strcmp (Ident, "pop") == 0) {
343         if (IS_GetCount (Stack) < 2) {
344             Error ("Cannot pop, stack is empty");
345         } else {
346             IS_Drop (Stack);
347         }
348         /* No other arguments allowed */
349         return;
350     }
351
352     /* Check if we have a first argument named "push" */
353     if (IsIdent && strcmp (Ident, "push") == 0) {
354         Push = 1;
355         SB_SkipWhite (B);
356         if (SB_Get (B) != ',') {
357             Error ("Comma expected");
358             return;
359         }
360         SB_SkipWhite (B);
361         IsIdent = 0;
362     } else {
363         Push = 0;
364     }
365
366     /* Integer argument follows */
367     if (IsIdent || !SB_GetNumber (B, &Val)) {
368         Error ("Pragma argument must be numeric");
369         return;
370     }
371
372     /* Check the argument */
373     if (Val < Low || Val > High) {
374         Error ("Pragma argument out of bounds (%ld-%ld)", Low, High);
375         return;
376     }
377
378     /* Set/push the new value */
379     if (Push) {
380         if (IS_IsFull (Stack)) {
381             Error ("Cannot push: stack overflow");
382         } else {
383             IS_Push (Stack, Val);
384         }
385     } else {
386         IS_Set (Stack, Val);
387     }
388 }
389
390
391
392 static void ParsePragma (void)
393 /* Parse the contents of the _Pragma statement */
394 {
395     pragma_t Pragma;
396     ident    Ident;
397
398     /* Create a string buffer from the string literal */
399     StrBuf B = AUTO_STRBUF_INITIALIZER;
400     GetLiteralStrBuf (&B, CurTok.IVal);
401
402     /* Reset the string pointer, effectivly clearing the string from the
403      * string table. Since we're working with one token lookahead, this
404      * will fail if the next token is also a string token, but that's a
405      * syntax error anyway, because we expect a right paren.
406      */
407     ResetLiteralPoolOffs (CurTok.IVal);
408
409     /* Skip the string token */
410     NextToken ();
411
412     /* Get the pragma name from the string */
413     SB_SkipWhite (&B);
414     if (!SB_GetSym (&B, Ident)) {
415         Error ("Invalid pragma");
416         return;
417     }
418
419     /* Search for the name */
420     Pragma = FindPragma (Ident);
421
422     /* Do we know this pragma? */
423     if (Pragma == PR_ILLEGAL) {
424         /* According to the ANSI standard, we're not allowed to generate errors
425          * for unknown pragmas, however, we're allowed to warn - and we will
426          * do so. Otherwise one typo may give you hours of bug hunting...
427          */
428         Warning ("Unknown pragma `%s'", Ident);
429         return;
430     }
431
432     /* Check for an open paren */
433     SB_SkipWhite (&B);
434     if (SB_Get (&B) != '(') {
435         Error ("'(' expected");
436         return;
437     }
438
439     /* Skip white space before the argument */
440     SB_SkipWhite (&B);
441
442     /* Switch for the different pragmas */
443     switch (Pragma) {
444
445         case PR_BSSSEG:
446             SegNamePragma (&B, SEG_BSS);
447             break;
448
449         case PR_CHARMAP:
450             CharMapPragma (&B);
451             break;
452
453         case PR_CHECKSTACK:
454             FlagPragma (&B, &CheckStack);
455             break;
456
457         case PR_CODESEG:
458             SegNamePragma (&B, SEG_CODE);
459             break;
460
461         case PR_CODESIZE:
462             IntPragma (&B, &CodeSizeFactor, 10, 1000);
463             break;
464
465         case PR_DATASEG:
466             SegNamePragma (&B, SEG_DATA);
467             break;
468
469         case PR_OPTIMIZE:
470             FlagPragma (&B, &Optimize);
471             break;
472
473         case PR_REGVARADDR:
474             FlagPragma (&B, &AllowRegVarAddr);
475             break;
476
477         case PR_REGVARS:
478             FlagPragma (&B, &EnableRegVars);
479             break;
480
481         case PR_RODATASEG:
482             SegNamePragma (&B, SEG_RODATA);
483             break;
484
485         case PR_SIGNEDCHARS:
486             FlagPragma (&B, &SignedChars);
487             break;
488
489         case PR_STATICLOCALS:
490             FlagPragma (&B, &StaticLocals);
491             break;
492
493         case PR_WARN:
494             FlagPragma (&B, &WarnDisable);
495             break;
496
497         case PR_ZPSYM:                    
498             StringPragma (&B, MakeZPSym);
499             break;
500
501         default:
502             Internal ("Invalid pragma");
503     }
504
505     /* Closing paren expected */
506     SB_SkipWhite (&B);
507     if (SB_Get (&B) != ')') {
508         Error ("')' expected");
509         return;
510     }
511     SB_SkipWhite (&B);
512
513     /* Allow an optional semicolon to be compatible with the old syntax */
514     if (SB_Peek (&B) == ';') {
515         SB_Skip (&B);
516         SB_SkipWhite (&B);
517     }
518
519     /* Make sure nothing follows */
520     if (SB_Peek (&B) != '\0') {
521         Error ("Unexpected input following pragma directive");
522     }
523
524     /* Release the StrBuf */
525     DoneStrBuf (&B);
526 }
527
528
529
530 void DoPragma (void)
531 /* Handle pragmas. These come always in form of the new C99 _Pragma() operator. */
532 {
533     /* Skip the token itself */
534     NextToken ();
535
536     /* We expect an opening paren */
537     if (!ConsumeLParen ()) {
538         return;
539     }
540
541     /* String literal */
542     if (CurTok.Tok != TOK_SCONST) {
543
544         /* Print a diagnostic */
545         Error ("String literal expected");
546
547         /* Try some smart error recovery: Skip tokens until we reach the
548          * enclosing paren, or a semicolon.
549          */
550         PragmaErrorSkip ();
551
552     } else {
553
554         /* Parse the _Pragma statement */
555         ParsePragma ();
556     }
557
558     /* Closing paren needed */
559     ConsumeRParen ();
560 }
561
562
563