]> git.sur5r.net Git - cc65/blob - src/cc65/pragma.c
Made several options that can be changed by #pragmas stackable.
[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_DATASEG,
70     PR_REGVARADDR,
71     PR_REGVARS,
72     PR_RODATASEG,
73     PR_SIGNEDCHARS,
74     PR_STATICLOCALS,
75     PR_ZPSYM,
76     PR_COUNT
77 } pragma_t;
78
79 /* Pragma table */
80 static const struct Pragma {
81     const char* Key;            /* Keyword */
82     pragma_t    Tok;            /* Token */
83 } Pragmas[PR_COUNT] = {
84     {   "bssseg",       PR_BSSSEG       },
85     {   "charmap",      PR_CHARMAP      },
86     {   "checkstack",   PR_CHECKSTACK   },
87     {   "codeseg",      PR_CODESEG      },
88     {   "dataseg",      PR_DATASEG      },
89     {   "regvaraddr",   PR_REGVARADDR   },
90     {   "regvars",      PR_REGVARS      },
91     {   "rodataseg",    PR_RODATASEG    },
92     {   "signedchars",  PR_SIGNEDCHARS  },
93     {   "staticlocals", PR_STATICLOCALS },
94     {   "zpsym",        PR_ZPSYM        },
95 };
96
97
98
99 /*****************************************************************************/
100 /*                                   Code                                    */
101 /*****************************************************************************/
102
103
104
105 static void PragmaErrorSkip (void)
106 /* Called in case of an error, skips tokens until the closing paren or a
107  * semicolon is reached.
108  */
109 {
110     static const token_t TokenList[] = { TOK_RPAREN, TOK_SEMI };
111     SkipTokens (TokenList, sizeof(TokenList) / sizeof(TokenList[0]));
112 }
113
114
115
116 static int CmpKey (const void* Key, const void* Elem)
117 /* Compare function for bsearch */
118 {
119     return strcmp ((const char*) Key, ((const struct Pragma*) Elem)->Key);
120 }
121
122
123
124 static pragma_t FindPragma (const char* Key)
125 /* Find a pragma and return the token. Return PR_ILLEGAL if the keyword is
126  * not a valid pragma.
127  */
128 {
129     struct Pragma* P;
130     P = bsearch (Key, Pragmas, PR_COUNT, sizeof (Pragmas[0]), CmpKey);
131     return P? P->Tok : PR_ILLEGAL;
132 }
133
134
135
136 static void StringPragma (StrBuf* B, void (*Func) (const char*))
137 /* Handle a pragma that expects a string parameter */
138 {
139     StrBuf S;
140
141     /* We expect a string here */
142     if (SB_GetString (B, &S)) {
143         /* Call the given function with the string argument */
144         Func (SB_GetConstBuf (&S));
145     } else {
146         Error ("String literal expected");
147     }
148
149     /* Call the string buf destructor */
150     DoneStrBuf (&S);
151 }
152
153
154
155 static void SegNamePragma (StrBuf* B, segment_t Seg)
156 /* Handle a pragma that expects a segment name parameter */
157 {
158     StrBuf S;
159
160     if (SB_GetString (B, &S)) {
161
162         /* Get the string */
163         const char* Name = SB_GetConstBuf (&S);
164
165         /* Check if the name is valid */
166         if (ValidSegName (Name)) {
167
168             /* Set the new name */
169             g_segname (Seg, Name);
170
171         } else {
172
173             /* Segment name is invalid */
174             Error ("Illegal segment name: `%s'", Name);
175
176         }
177
178     } else {
179         Error ("String literal expected");
180     }
181
182     /* Call the string buf destructor */
183     DoneStrBuf (&S);
184 }
185
186
187
188 static void CharMapPragma (StrBuf* B)
189 /* Change the character map */
190 {
191     long Index, C;
192
193     /* Read the character index */
194     if (!SB_GetNumber (B, &Index)) {
195         return;
196     }
197     if (Index < 1 || Index > 255) {
198         Error ("Character index out of range");
199         return;
200     }
201
202     /* Comma follows */
203     SB_SkipWhite (B);
204     if (SB_Get (B) != ',') {
205         Error ("Comma expected");
206         return;
207     }
208     SB_SkipWhite (B);
209
210     /* Read the character code */
211     if (!SB_GetNumber (B, &C)) {
212         return;
213     }
214     if (C < 1 || C > 255) {
215         Error ("Character code out of range");
216         return;
217     }
218
219     /* Remap the character */
220     TgtTranslateSet ((unsigned) Index, (unsigned char) C);
221 }
222
223
224
225 static void FlagPragma (StrBuf* B, IntStack* Stack)
226 /* Handle a pragma that expects a boolean paramater */
227 {
228     ident Ident;
229     long  Val;
230     int   Push;
231
232     /* Try to read an identifier */
233     int IsIdent = SB_GetSym (B, Ident);
234
235     /* Check if we have a first argument named "pop" */
236     if (IsIdent && strcmp (Ident, "pop") == 0) {
237         if (IS_GetCount (Stack) < 2) {
238             Error ("Cannot pop, stack is empty");
239         } else {
240             (void) IS_Pop (Stack);
241         }
242         /* No other arguments allowed */
243         return;
244     }
245
246     /* Check if we have a first argument named "push" */
247     if (IsIdent && strcmp (Ident, "push") == 0) {
248         Push = 1;
249         SB_SkipWhite (B);
250         if (SB_Get (B) != ',') {
251             Error ("Comma expected");
252             return;
253         }
254         SB_SkipWhite (B);
255         IsIdent = SB_GetSym (B, Ident);
256     } else {
257         Push = 0;
258     }
259
260     /* Boolean argument follows */
261     if (IsIdent) {
262         if (strcmp (Ident, "true") == 0 || strcmp (Ident, "on") == 0) {
263             Val = 1;
264         } else if (strcmp (Ident, "false") == 0 || strcmp (Ident, "off") == 0) {
265             Val = 0;
266         } else {
267             Error ("Pragma argument must be one of `on', `off', `true' or `false'");
268         }
269     } else if (!SB_GetNumber (B, &Val)) {
270         Error ("Invalid pragma argument");
271         return;
272     }
273
274     /* Set/push the new value */
275     if (Push) {
276         if (IS_IsFull (Stack)) {
277             Error ("Cannot push: stack overflow");
278         } else {
279             IS_Push (Stack, Val);
280         }
281     } else {
282         IS_Set (Stack, Val);
283     }
284 }
285
286
287
288 static void ParsePragma (void)
289 /* Parse the contents of the _Pragma statement */
290 {
291     pragma_t Pragma;
292     ident    Ident;
293
294     /* Create a string buffer from the string literal */
295     StrBuf B = AUTO_STRBUF_INITIALIZER;
296     GetLiteralStrBuf (&B, CurTok.IVal);
297
298     /* Reset the string pointer, effectivly clearing the string from the
299      * string table. Since we're working with one token lookahead, this
300      * will fail if the next token is also a string token, but that's a
301      * syntax error anyway, because we expect a right paren.
302      */
303     ResetLiteralPoolOffs (CurTok.IVal);
304
305     /* Skip the string token */
306     NextToken ();
307
308     /* Get the pragma name from the string */
309     SB_SkipWhite (&B);
310     if (!SB_GetSym (&B, Ident)) {
311         Error ("Invalid pragma");
312         return;
313     }
314
315     /* Search for the name */
316     Pragma = FindPragma (Ident);
317
318     /* Do we know this pragma? */
319     if (Pragma == PR_ILLEGAL) {
320         /* According to the ANSI standard, we're not allowed to generate errors
321          * for unknown pragmas, however, we're allowed to warn - and we will
322          * do so. Otherwise one typo may give you hours of bug hunting...
323          */
324         Warning ("Unknown pragma `%s'", Ident);
325         return;
326     }
327
328     /* Check for an open paren */
329     SB_SkipWhite (&B);
330     if (SB_Get (&B) != '(') {
331         Error ("'(' expected");
332         return;
333     }
334
335     /* Skip white space before the argument */
336     SB_SkipWhite (&B);
337
338     /* Switch for the different pragmas */
339     switch (Pragma) {
340
341         case PR_BSSSEG:
342             SegNamePragma (&B, SEG_BSS);
343             break;
344
345         case PR_CHARMAP:
346             CharMapPragma (&B);
347             break;
348
349         case PR_CHECKSTACK:
350             FlagPragma (&B, &CheckStack);
351             break;
352
353         case PR_CODESEG:
354             SegNamePragma (&B, SEG_CODE);
355             break;
356
357         case PR_DATASEG:
358             SegNamePragma (&B, SEG_DATA);
359             break;
360
361         case PR_REGVARADDR:
362             FlagPragma (&B, &AllowRegVarAddr);
363             break;
364
365         case PR_REGVARS:
366             FlagPragma (&B, &EnableRegVars);
367             break;
368
369         case PR_RODATASEG:
370             SegNamePragma (&B, SEG_RODATA);
371             break;
372
373         case PR_SIGNEDCHARS:
374             FlagPragma (&B, &SignedChars);
375             break;
376
377         case PR_STATICLOCALS:
378             FlagPragma (&B, &StaticLocals);
379             break;
380
381         case PR_ZPSYM:
382             StringPragma (&B, MakeZPSym);
383             break;
384
385         default:
386             Internal ("Invalid pragma");
387     }
388
389     /* Closing paren expected */
390     SB_SkipWhite (&B);
391     if (SB_Get (&B) != ')') {
392         Error ("')' expected");
393         return;
394     }
395     SB_SkipWhite (&B);
396
397     /* Allow an optional semicolon to be compatible with the old syntax */
398     if (SB_Peek (&B) == ';') {
399         SB_Skip (&B);
400         SB_SkipWhite (&B);
401     }
402
403     /* Make sure nothing follows */
404     if (SB_Peek (&B) != '\0') {
405         Error ("Unexpected input following pragma directive");
406     }
407
408     /* Release the StrBuf */
409     DoneStrBuf (&B);
410 }
411
412
413
414 void DoPragma (void)
415 /* Handle pragmas. These come always in form of the new C99 _Pragma() operator. */
416 {
417     /* Skip the token itself */
418     NextToken ();
419
420     /* We expect an opening paren */
421     if (!ConsumeLParen ()) {
422         return;
423     }
424
425     /* String literal */
426     if (CurTok.Tok != TOK_SCONST) {
427
428         /* Print a diagnostic */
429         Error ("String literal expected");
430
431         /* Try some smart error recovery: Skip tokens until we reach the
432          * enclosing paren, or a semicolon.
433          */
434         PragmaErrorSkip ();
435
436     } else {
437
438         /* Parse the _Pragma statement */
439         ParsePragma ();
440     }
441
442     /* Closing paren needed */
443     ConsumeRParen ();
444 }
445
446
447