]> git.sur5r.net Git - cc65/blob - src/cc65/pragma.c
Allow push/pop arguments for segment name #pragmas
[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     ident       Ident;
159     StrBuf      S;
160     const char* Name;
161
162     /* Try to read an identifier */
163     int Push = 0;
164     if (SB_GetSym (B, Ident)) {
165
166         /* Check if we have a first argument named "pop" */
167         if (strcmp (Ident, "pop") == 0) {
168
169             /* Pop the old value */
170             PopSegName (Seg);
171
172             /* Set the segment name */
173             g_segname (Seg);
174
175             /* Done */
176             return;
177
178         /* Check if we have a first argument named "push" */
179         } else if (strcmp (Ident, "push") == 0) {
180
181             Push = 1;
182             SB_SkipWhite (B);
183             if (SB_Get (B) != ',') {
184                 Error ("Comma expected");
185                 return;
186             }
187             SB_SkipWhite (B);
188
189         } else {
190             Error ("Invalid pragma arguments");
191             return;
192         }
193     }
194
195     /* A string argument must follow */
196     if (!SB_GetString (B, &S)) {
197         Error ("String literal expected");
198         return;
199     }
200
201     /* Get the string */
202     Name = SB_GetConstBuf (&S);
203
204     /* Check if the name is valid */
205     if (!ValidSegName (Name)) {
206         /* Segment name is invalid */
207         Error ("Illegal segment name: `%s'", Name);
208         return;
209     }
210
211     /* Set the new name */
212     if (Push) {
213         PushSegName (Seg, Name);
214     } else {
215         SetSegName (Seg, Name);
216     }
217     g_segname (Seg);          
218
219     /* Call the string buf destructor */
220     DoneStrBuf (&S);
221 }
222
223
224
225 static void CharMapPragma (StrBuf* B)
226 /* Change the character map */
227 {
228     long Index, C;
229
230     /* Read the character index */
231     if (!SB_GetNumber (B, &Index)) {
232         return;
233     }
234     if (Index < 1 || Index > 255) {
235         Error ("Character index out of range");
236         return;
237     }
238
239     /* Comma follows */
240     SB_SkipWhite (B);
241     if (SB_Get (B) != ',') {
242         Error ("Comma expected");
243         return;
244     }
245     SB_SkipWhite (B);
246
247     /* Read the character code */
248     if (!SB_GetNumber (B, &C)) {
249         return;
250     }
251     if (C < 1 || C > 255) {
252         Error ("Character code out of range");
253         return;
254     }
255
256     /* Remap the character */
257     TgtTranslateSet ((unsigned) Index, (unsigned char) C);
258 }
259
260
261
262 static void FlagPragma (StrBuf* B, IntStack* Stack)
263 /* Handle a pragma that expects a boolean paramater */
264 {
265     ident Ident;
266     long  Val;
267     int   Push;
268
269     /* Try to read an identifier */
270     int IsIdent = SB_GetSym (B, Ident);
271
272     /* Check if we have a first argument named "pop" */
273     if (IsIdent && strcmp (Ident, "pop") == 0) {
274         if (IS_GetCount (Stack) < 2) {
275             Error ("Cannot pop, stack is empty");
276         } else {
277             IS_Drop (Stack);
278         }
279         /* No other arguments allowed */
280         return;
281     }
282
283     /* Check if we have a first argument named "push" */
284     if (IsIdent && strcmp (Ident, "push") == 0) {
285         Push = 1;
286         SB_SkipWhite (B);
287         if (SB_Get (B) != ',') {
288             Error ("Comma expected");
289             return;
290         }
291         SB_SkipWhite (B);
292         IsIdent = SB_GetSym (B, Ident);
293     } else {
294         Push = 0;
295     }
296
297     /* Boolean argument follows */
298     if (IsIdent) {
299         if (strcmp (Ident, "true") == 0 || strcmp (Ident, "on") == 0) {
300             Val = 1;
301         } else if (strcmp (Ident, "false") == 0 || strcmp (Ident, "off") == 0) {
302             Val = 0;
303         } else {
304             Error ("Pragma argument must be one of `on', `off', `true' or `false'");
305         }
306     } else if (!SB_GetNumber (B, &Val)) {
307         Error ("Invalid pragma argument");
308         return;
309     }
310
311     /* Set/push the new value */
312     if (Push) {
313         if (IS_IsFull (Stack)) {
314             Error ("Cannot push: stack overflow");
315         } else {
316             IS_Push (Stack, Val);
317         }
318     } else {
319         IS_Set (Stack, Val);
320     }
321 }
322
323
324
325 static void ParsePragma (void)
326 /* Parse the contents of the _Pragma statement */
327 {
328     pragma_t Pragma;
329     ident    Ident;
330
331     /* Create a string buffer from the string literal */
332     StrBuf B = AUTO_STRBUF_INITIALIZER;
333     GetLiteralStrBuf (&B, CurTok.IVal);
334
335     /* Reset the string pointer, effectivly clearing the string from the
336      * string table. Since we're working with one token lookahead, this
337      * will fail if the next token is also a string token, but that's a
338      * syntax error anyway, because we expect a right paren.
339      */
340     ResetLiteralPoolOffs (CurTok.IVal);
341
342     /* Skip the string token */
343     NextToken ();
344
345     /* Get the pragma name from the string */
346     SB_SkipWhite (&B);
347     if (!SB_GetSym (&B, Ident)) {
348         Error ("Invalid pragma");
349         return;
350     }
351
352     /* Search for the name */
353     Pragma = FindPragma (Ident);
354
355     /* Do we know this pragma? */
356     if (Pragma == PR_ILLEGAL) {
357         /* According to the ANSI standard, we're not allowed to generate errors
358          * for unknown pragmas, however, we're allowed to warn - and we will
359          * do so. Otherwise one typo may give you hours of bug hunting...
360          */
361         Warning ("Unknown pragma `%s'", Ident);
362         return;
363     }
364
365     /* Check for an open paren */
366     SB_SkipWhite (&B);
367     if (SB_Get (&B) != '(') {
368         Error ("'(' expected");
369         return;
370     }
371
372     /* Skip white space before the argument */
373     SB_SkipWhite (&B);
374
375     /* Switch for the different pragmas */
376     switch (Pragma) {
377
378         case PR_BSSSEG:
379             SegNamePragma (&B, SEG_BSS);
380             break;
381
382         case PR_CHARMAP:
383             CharMapPragma (&B);
384             break;
385
386         case PR_CHECKSTACK:
387             FlagPragma (&B, &CheckStack);
388             break;
389
390         case PR_CODESEG:
391             SegNamePragma (&B, SEG_CODE);
392             break;
393
394         case PR_DATASEG:
395             SegNamePragma (&B, SEG_DATA);
396             break;
397
398         case PR_REGVARADDR:
399             FlagPragma (&B, &AllowRegVarAddr);
400             break;
401
402         case PR_REGVARS:
403             FlagPragma (&B, &EnableRegVars);
404             break;
405
406         case PR_RODATASEG:
407             SegNamePragma (&B, SEG_RODATA);
408             break;
409
410         case PR_SIGNEDCHARS:
411             FlagPragma (&B, &SignedChars);
412             break;
413
414         case PR_STATICLOCALS:
415             FlagPragma (&B, &StaticLocals);
416             break;
417
418         case PR_ZPSYM:
419             StringPragma (&B, MakeZPSym);
420             break;
421
422         default:
423             Internal ("Invalid pragma");
424     }
425
426     /* Closing paren expected */
427     SB_SkipWhite (&B);
428     if (SB_Get (&B) != ')') {
429         Error ("')' expected");
430         return;
431     }
432     SB_SkipWhite (&B);
433
434     /* Allow an optional semicolon to be compatible with the old syntax */
435     if (SB_Peek (&B) == ';') {
436         SB_Skip (&B);
437         SB_SkipWhite (&B);
438     }
439
440     /* Make sure nothing follows */
441     if (SB_Peek (&B) != '\0') {
442         Error ("Unexpected input following pragma directive");
443     }
444
445     /* Release the StrBuf */
446     DoneStrBuf (&B);
447 }
448
449
450
451 void DoPragma (void)
452 /* Handle pragmas. These come always in form of the new C99 _Pragma() operator. */
453 {
454     /* Skip the token itself */
455     NextToken ();
456
457     /* We expect an opening paren */
458     if (!ConsumeLParen ()) {
459         return;
460     }
461
462     /* String literal */
463     if (CurTok.Tok != TOK_SCONST) {
464
465         /* Print a diagnostic */
466         Error ("String literal expected");
467
468         /* Try some smart error recovery: Skip tokens until we reach the
469          * enclosing paren, or a semicolon.
470          */
471         PragmaErrorSkip ();
472
473     } else {
474
475         /* Parse the _Pragma statement */
476         ParsePragma ();
477     }
478
479     /* Closing paren needed */
480     ConsumeRParen ();
481 }
482
483
484