1 /*****************************************************************************/
5 /* Pragma handling for the cc65 C compiler */
9 /* (C) 1998-2009, Ullrich von Bassewitz */
10 /* Roemerstrasse 52 */
11 /* D-70794 Filderstadt */
12 /* EMail: uz@cc65.org */
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. */
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: */
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 */
32 /*****************************************************************************/
51 #include "scanstrbuf.h"
57 /*****************************************************************************/
59 /*****************************************************************************/
63 /* Tokens for the #pragmas */
67 PRAGMA_BSSSEG, /* obsolete */
70 PRAGMA_CHECKSTACK, /* obsolete */
72 PRAGMA_CODESEG, /* obsolete */
75 PRAGMA_DATASEG, /* obsolete */
79 PRAGMA_REGVARS, /* obsolete */
81 PRAGMA_RODATASEG, /* obsolete */
83 PRAGMA_SIGNEDCHARS, /* obsolete */
85 PRAGMA_STATICLOCALS, /* obsolete */
87 PRAGMA_WRITABLE_STRINGS,
93 static const struct Pragma {
94 const char* Key; /* Keyword */
95 pragma_t Tok; /* Token */
96 } Pragmas[PRAGMA_COUNT] = {
97 { "bss-name", PRAGMA_BSS_NAME },
98 { "bssseg", PRAGMA_BSSSEG }, /* obsolete */
99 { "charmap", PRAGMA_CHARMAP },
100 { "check-stack", PRAGMA_CHECK_STACK },
101 { "checkstack", PRAGMA_CHECKSTACK }, /* obsolete */
102 { "code-name", PRAGMA_CODE_NAME },
103 { "codeseg", PRAGMA_CODESEG }, /* obsolete */
104 { "codesize", PRAGMA_CODESIZE },
105 { "data-name", PRAGMA_DATA_NAME },
106 { "dataseg", PRAGMA_DATASEG }, /* obsolete */
107 { "optimize", PRAGMA_OPTIMIZE },
108 { "register-vars", PRAGMA_REGISTER_VARS },
109 { "regvaraddr", PRAGMA_REGVARADDR },
110 { "regvars", PRAGMA_REGVARS }, /* obsolete */
111 { "rodata-name", PRAGMA_RODATA_NAME },
112 { "rodataseg", PRAGMA_RODATASEG }, /* obsolete */
113 { "signed-chars", PRAGMA_SIGNED_CHARS },
114 { "signedchars", PRAGMA_SIGNEDCHARS }, /* obsolete */
115 { "static-locals", PRAGMA_STATIC_LOCALS },
116 { "staticlocals", PRAGMA_STATICLOCALS }, /* obsolete */
117 { "warn", PRAGMA_WARN },
118 { "writable-strings", PRAGMA_WRITABLE_STRINGS },
119 { "zpsym", PRAGMA_ZPSYM },
122 /* Result of ParsePushPop */
132 /*****************************************************************************/
133 /* Helper functions */
134 /*****************************************************************************/
138 static void PragmaErrorSkip (void)
139 /* Called in case of an error, skips tokens until the closing paren or a
140 * semicolon is reached.
143 static const token_t TokenList[] = { TOK_RPAREN, TOK_SEMI };
144 SkipTokens (TokenList, sizeof(TokenList) / sizeof(TokenList[0]));
149 static int CmpKey (const void* Key, const void* Elem)
150 /* Compare function for bsearch */
152 return strcmp ((const char*) Key, ((const struct Pragma*) Elem)->Key);
157 static pragma_t FindPragma (const StrBuf* Key)
158 /* Find a pragma and return the token. Return PRAGMA_ILLEGAL if the keyword is
159 * not a valid pragma.
163 P = bsearch (SB_GetConstBuf (Key), Pragmas, PRAGMA_COUNT, sizeof (Pragmas[0]), CmpKey);
164 return P? P->Tok : PRAGMA_ILLEGAL;
169 static int GetComma (StrBuf* B)
170 /* Expects and skips a comma in B. Prints an error and returns zero if no
171 * comma is found. Return a value <> 0 otherwise.
175 if (SB_Get (B) != ',') {
176 Error ("Comma expected");
185 static int GetString (StrBuf* B, StrBuf* S)
186 /* Expects and skips a string in B. Prints an error and returns zero if no
187 * string is found. Returns a value <> 0 otherwise.
190 if (!SB_GetString (B, S)) {
191 Error ("String literal expected");
199 static int GetNumber (StrBuf* B, long* Val)
200 /* Expects and skips a number in B. Prints an eror and returns zero if no
201 * number is found. Returns a value <> 0 otherwise.
204 if (!SB_GetNumber (B, Val)) {
205 Error ("Constant integer expected");
213 static IntStack* GetWarning (StrBuf* B)
214 /* Get a warning name from the string buffer. Returns a pointer to the intstack
215 * that holds the state of the warning, and NULL in case of errors. The
216 * function will output error messages in case of problems.
220 StrBuf W = AUTO_STRBUF_INITIALIZER;
222 /* The warning name is a symbol but the '-' char is allowed within */
223 if (SB_GetSym (B, &W, "-")) {
225 /* Map the warning name to an IntStack that contains its state */
226 S = FindWarning (SB_GetConstBuf (&W));
230 Error ("Pragma expects a warning name as first argument");
234 /* Deallocate the string */
243 static int HasStr (StrBuf* B, const char* E)
244 /* Checks if E follows in B. If so, skips it and returns true */
246 unsigned Len = strlen (E);
247 if (SB_GetLen (B) - SB_GetIndex (B) >= Len) {
248 if (strncmp (SB_GetConstBuf (B) + SB_GetIndex (B), E, Len) == 0) {
250 SB_SkipMultiple (B, Len);
259 static PushPopResult ParsePushPop (StrBuf* B)
260 /* Check for and parse the "push" and "pop" keywords. In case of "push", a
261 * following comma is expected and skipped.
264 StrBuf Ident = AUTO_STRBUF_INITIALIZER;
265 PushPopResult Res = PP_NONE;
268 /* Try to read an identifier */
269 if (SB_GetSym (B, &Ident, 0)) {
271 /* Check if we have a first argument named "pop" */
272 if (SB_CompareStr (&Ident, "pop") == 0) {
276 /* Check if we have a first argument named "push" */
277 } else if (SB_CompareStr (&Ident, "push") == 0) {
281 /* Skip the following comma */
288 /* Unknown keyword */
289 Error ("Invalid pragma arguments");
294 /* Free the string buffer and return the result */
301 static void PopInt (IntStack* S)
302 /* Pops an integer from an IntStack. Prints an error if the stack is empty */
304 if (IS_GetCount (S) < 2) {
305 Error ("Cannot pop, stack is empty");
313 static void PushInt (IntStack* S, long Val)
314 /* Pushes an integer onto an IntStack. Prints an error if the stack is full */
317 Error ("Cannot push: stack overflow");
325 static int BoolKeyword (StrBuf* Ident)
326 /* Check if the identifier in Ident is a keyword for a boolean value. Currently
327 * accepted are true/false/on/off.
330 if (SB_CompareStr (Ident, "true") == 0) {
333 if (SB_CompareStr (Ident, "on") == 0) {
336 if (SB_CompareStr (Ident, "false") == 0) {
339 if (SB_CompareStr (Ident, "off") == 0) {
344 Error ("Pragma argument must be one of `on', `off', `true' or `false'");
350 /*****************************************************************************/
351 /* Pragma handling functions */
352 /*****************************************************************************/
356 static void StringPragma (StrBuf* B, void (*Func) (const char*))
357 /* Handle a pragma that expects a string parameter */
359 StrBuf S = AUTO_STRBUF_INITIALIZER;
361 /* We expect a string here */
362 if (GetString (B, &S)) {
363 /* Call the given function with the string argument */
364 Func (SB_GetConstBuf (&S));
367 /* Call the string buf destructor */
373 static void SegNamePragma (StrBuf* B, segment_t Seg)
374 /* Handle a pragma that expects a segment name parameter */
376 StrBuf S = AUTO_STRBUF_INITIALIZER;
379 /* Check for the "push" or "pop" keywords */
381 switch (ParsePushPop (B)) {
391 /* Pop the old value and output it */
403 Internal ("Invalid result from ParsePushPop");
407 /* A string argument must follow */
408 if (!GetString (B, &S)) {
413 Name = SB_GetConstBuf (&S);
415 /* Check if the name is valid */
416 if (ValidSegName (Name)) {
418 /* Set the new name */
420 PushSegName (Seg, Name);
422 SetSegName (Seg, Name);
428 /* Segment name is invalid */
429 Error ("Illegal segment name: `%s'", Name);
434 /* Call the string buf destructor */
440 static void CharMapPragma (StrBuf* B)
441 /* Change the character map */
445 /* Read the character index */
446 if (!GetNumber (B, &Index)) {
449 if (Index < 1 || Index > 255) {
452 Error ("Remapping 0 is not allowed");
454 Error ("Character index out of range");
464 /* Read the character code */
465 if (!GetNumber (B, &C)) {
468 if (C < 1 || C > 255) {
471 Error ("Remapping 0 is not allowed");
473 Error ("Character code out of range");
478 /* Remap the character */
479 TgtTranslateSet ((unsigned) Index, (unsigned char) C);
484 static void WarnPragma (StrBuf* B)
485 /* Enable/disable warnings */
490 /* A warning name must follow */
491 IntStack* S =GetWarning (B);
501 /* Check for the "push" or "pop" keywords */
502 switch (ParsePushPop (B)) {
513 /* Pop the old value and bail out */
522 Internal ("Invalid result from ParsePushPop");
525 /* Boolean argument follows */
526 if (HasStr (B, "true") || HasStr (B, "on")) {
528 } else if (HasStr (B, "false") || HasStr (B, "off")) {
530 } else if (!SB_GetNumber (B, &Val)) {
531 Error ("Invalid pragma argument");
535 /* Set/push the new value */
545 static void FlagPragma (StrBuf* B, IntStack* Stack)
546 /* Handle a pragma that expects a boolean paramater */
548 StrBuf Ident = AUTO_STRBUF_INITIALIZER;
553 /* Try to read an identifier */
554 int IsIdent = SB_GetSym (B, &Ident, 0);
556 /* Check if we have a first argument named "pop" */
557 if (IsIdent && SB_CompareStr (&Ident, "pop") == 0) {
559 /* No other arguments allowed */
563 /* Check if we have a first argument named "push" */
564 if (IsIdent && SB_CompareStr (&Ident, "push") == 0) {
569 IsIdent = SB_GetSym (B, &Ident, 0);
574 /* Boolean argument follows */
576 Val = BoolKeyword (&Ident);
577 } else if (!GetNumber (B, &Val)) {
581 /* Set/push the new value */
583 PushInt (Stack, Val);
589 /* Free the identifier */
595 static void IntPragma (StrBuf* B, IntStack* Stack, long Low, long High)
596 /* Handle a pragma that expects an int paramater */
601 /* Check for the "push" or "pop" keywords */
602 switch (ParsePushPop (B)) {
613 /* Pop the old value and bail out */
622 Internal ("Invalid result from ParsePushPop");
626 /* Integer argument follows */
627 if (!GetNumber (B, &Val)) {
631 /* Check the argument */
632 if (Val < Low || Val > High) {
633 Error ("Pragma argument out of bounds (%ld-%ld)", Low, High);
637 /* Set/push the new value */
639 PushInt (Stack, Val);
647 static void ParsePragma (void)
648 /* Parse the contents of the _Pragma statement */
651 StrBuf Ident = AUTO_STRBUF_INITIALIZER;
653 /* Create a string buffer from the string literal */
654 StrBuf B = AUTO_STRBUF_INITIALIZER;
655 GetLiteralStrBuf (&B, CurTok.IVal);
657 /* Reset the string pointer, effectivly clearing the string from the
658 * string table. Since we're working with one token lookahead, this
659 * will fail if the next token is also a string token, but that's a
660 * syntax error anyway, because we expect a right paren.
662 ResetLiteralPoolOffs (CurTok.IVal);
664 /* Skip the string token */
667 /* Get the pragma name from the string */
669 if (!SB_GetSym (&B, &Ident, "-")) {
670 Error ("Invalid pragma");
674 /* Search for the name */
675 Pragma = FindPragma (&Ident);
677 /* Do we know this pragma? */
678 if (Pragma == PRAGMA_ILLEGAL) {
679 /* According to the ANSI standard, we're not allowed to generate errors
680 * for unknown pragmas, but warn about them if enabled (the default).
682 if (IS_Get (&WarnUnknownPragma)) {
683 Warning ("Unknown pragma `%s'", SB_GetConstBuf (&Ident));
688 /* Check for an open paren */
690 if (SB_Get (&B) != '(') {
691 Error ("'(' expected");
695 /* Skip white space before the argument */
698 /* Switch for the different pragmas */
702 Warning ("#pragma bssseg is obsolete, please use #pragma bss-name instead");
704 case PRAGMA_BSS_NAME:
705 SegNamePragma (&B, SEG_BSS);
712 case PRAGMA_CHECKSTACK:
713 Warning ("#pragma checkstack is obsolete, please use #pragma check-stack instead");
715 case PRAGMA_CHECK_STACK:
716 FlagPragma (&B, &CheckStack);
720 Warning ("#pragma codeseg is obsolete, please use #pragma code-name instead");
722 case PRAGMA_CODE_NAME:
723 SegNamePragma (&B, SEG_CODE);
726 case PRAGMA_CODESIZE:
727 IntPragma (&B, &CodeSizeFactor, 10, 1000);
731 Warning ("#pragma dataseg is obsolete, please use #pragma data-name instead");
733 case PRAGMA_DATA_NAME:
734 SegNamePragma (&B, SEG_DATA);
737 case PRAGMA_OPTIMIZE:
738 FlagPragma (&B, &Optimize);
741 case PRAGMA_REGVARADDR:
742 FlagPragma (&B, &AllowRegVarAddr);
746 Warning ("#pragma regvars is obsolete, please use #pragma register-vars instead");
748 case PRAGMA_REGISTER_VARS:
749 FlagPragma (&B, &EnableRegVars);
752 case PRAGMA_RODATASEG:
753 Warning ("#pragma rodataseg is obsolete, please use #pragma rodata-name instead");
755 case PRAGMA_RODATA_NAME:
756 SegNamePragma (&B, SEG_RODATA);
759 case PRAGMA_SIGNEDCHARS:
760 Warning ("#pragma signedchars is obsolete, please use #pragma signed-chars instead");
762 case PRAGMA_SIGNED_CHARS:
763 FlagPragma (&B, &SignedChars);
766 case PRAGMA_STATICLOCALS:
767 Warning ("#pragma staticlocals is obsolete, please use #pragma static-locals instead");
769 case PRAGMA_STATIC_LOCALS:
770 FlagPragma (&B, &StaticLocals);
777 case PRAGMA_WRITABLE_STRINGS:
778 FlagPragma (&B, &WritableStrings);
782 StringPragma (&B, MakeZPSym);
786 Internal ("Invalid pragma");
789 /* Closing paren expected */
791 if (SB_Get (&B) != ')') {
792 Error ("')' expected");
797 /* Allow an optional semicolon to be compatible with the old syntax */
798 if (SB_Peek (&B) == ';') {
803 /* Make sure nothing follows */
804 if (SB_Peek (&B) != '\0') {
805 Error ("Unexpected input following pragma directive");
809 /* Release the string buffers */
817 /* Handle pragmas. These come always in form of the new C99 _Pragma() operator. */
819 /* Skip the token itself */
822 /* We expect an opening paren */
823 if (!ConsumeLParen ()) {
828 if (CurTok.Tok != TOK_SCONST) {
830 /* Print a diagnostic */
831 Error ("String literal expected");
833 /* Try some smart error recovery: Skip tokens until we reach the
834 * enclosing paren, or a semicolon.
840 /* Parse the _Pragma statement */
844 /* Closing paren needed */