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 */
92 static const struct Pragma {
93 const char* Key; /* Keyword */
94 pragma_t Tok; /* Token */
95 } Pragmas[PRAGMA_COUNT] = {
96 { "bss-name", PRAGMA_BSS_NAME },
97 { "bssseg", PRAGMA_BSSSEG }, /* obsolete */
98 { "charmap", PRAGMA_CHARMAP },
99 { "check-stack", PRAGMA_CHECK_STACK },
100 { "checkstack", PRAGMA_CHECKSTACK }, /* obsolete */
101 { "code-name", PRAGMA_CODE_NAME },
102 { "codeseg", PRAGMA_CODESEG }, /* obsolete */
103 { "codesize", PRAGMA_CODESIZE },
104 { "data-name", PRAGMA_DATA_NAME },
105 { "dataseg", PRAGMA_DATASEG }, /* obsolete */
106 { "optimize", PRAGMA_OPTIMIZE },
107 { "register-vars", PRAGMA_REGISTER_VARS },
108 { "regvaraddr", PRAGMA_REGVARADDR },
109 { "regvars", PRAGMA_REGVARS }, /* obsolete */
110 { "rodata-name", PRAGMA_RODATA_NAME },
111 { "rodataseg", PRAGMA_RODATASEG }, /* obsolete */
112 { "signed-chars", PRAGMA_SIGNED_CHARS },
113 { "signedchars", PRAGMA_SIGNEDCHARS }, /* obsolete */
114 { "static-locals", PRAGMA_STATIC_LOCALS },
115 { "staticlocals", PRAGMA_STATICLOCALS }, /* obsolete */
116 { "warn", PRAGMA_WARN },
117 { "zpsym", PRAGMA_ZPSYM },
120 /* Result of ParsePushPop */
130 /*****************************************************************************/
131 /* Helper functions */
132 /*****************************************************************************/
136 static void PragmaErrorSkip (void)
137 /* Called in case of an error, skips tokens until the closing paren or a
138 * semicolon is reached.
141 static const token_t TokenList[] = { TOK_RPAREN, TOK_SEMI };
142 SkipTokens (TokenList, sizeof(TokenList) / sizeof(TokenList[0]));
147 static int CmpKey (const void* Key, const void* Elem)
148 /* Compare function for bsearch */
150 return strcmp ((const char*) Key, ((const struct Pragma*) Elem)->Key);
155 static pragma_t FindPragma (const StrBuf* Key)
156 /* Find a pragma and return the token. Return PRAGMA_ILLEGAL if the keyword is
157 * not a valid pragma.
161 P = bsearch (SB_GetConstBuf (Key), Pragmas, PRAGMA_COUNT, sizeof (Pragmas[0]), CmpKey);
162 return P? P->Tok : PRAGMA_ILLEGAL;
167 static int GetComma (StrBuf* B)
168 /* Expects and skips a comma in B. Prints an error and returns zero if no
169 * comma is found. Return a value <> 0 otherwise.
173 if (SB_Get (B) != ',') {
174 Error ("Comma expected");
183 static int GetString (StrBuf* B, StrBuf* S)
184 /* Expects and skips a string in B. Prints an error and returns zero if no
185 * string is found. Returns a value <> 0 otherwise.
188 if (!SB_GetString (B, S)) {
189 Error ("String literal expected");
197 static int GetNumber (StrBuf* B, long* Val)
198 /* Expects and skips a number in B. Prints an eror and returns zero if no
199 * number is found. Returns a value <> 0 otherwise.
202 if (!SB_GetNumber (B, Val)) {
203 Error ("Constant integer expected");
211 static IntStack* GetWarning (StrBuf* B)
212 /* Get a warning name from the string buffer. Returns a pointer to the intstack
213 * that holds the state of the warning, and NULL in case of errors. The
214 * function will output error messages in case of problems.
218 StrBuf W = AUTO_STRBUF_INITIALIZER;
220 /* The warning name is a symbol but the '-' char is allowed within */
221 if (SB_GetSym (B, &W, "-")) {
223 /* Map the warning name to an IntStack that contains its state */
224 S = FindWarning (SB_GetConstBuf (&W));
228 Error ("Pragma expects a warning name as first argument");
232 /* Deallocate the string */
241 static int HasStr (StrBuf* B, const char* E)
242 /* Checks if E follows in B. If so, skips it and returns true */
244 unsigned Len = strlen (E);
245 if (SB_GetLen (B) - SB_GetIndex (B) >= Len) {
246 if (strncmp (SB_GetConstBuf (B) + SB_GetIndex (B), E, Len) == 0) {
248 SB_SkipMultiple (B, Len);
257 static PushPopResult ParsePushPop (StrBuf* B)
258 /* Check for and parse the "push" and "pop" keywords. In case of "push", a
259 * following comma is expected and skipped.
262 StrBuf Ident = AUTO_STRBUF_INITIALIZER;
263 PushPopResult Res = PP_NONE;
266 /* Try to read an identifier */
267 if (SB_GetSym (B, &Ident, 0)) {
269 /* Check if we have a first argument named "pop" */
270 if (SB_CompareStr (&Ident, "pop") == 0) {
274 /* Check if we have a first argument named "push" */
275 } else if (SB_CompareStr (&Ident, "push") == 0) {
279 /* Skip the following comma */
286 /* Unknown keyword */
287 Error ("Invalid pragma arguments");
292 /* Free the string buffer and return the result */
299 static void PopInt (IntStack* S)
300 /* Pops an integer from an IntStack. Prints an error if the stack is empty */
302 if (IS_GetCount (S) < 2) {
303 Error ("Cannot pop, stack is empty");
311 static void PushInt (IntStack* S, long Val)
312 /* Pushes an integer onto an IntStack. Prints an error if the stack is full */
315 Error ("Cannot push: stack overflow");
323 static int BoolKeyword (StrBuf* Ident)
324 /* Check if the identifier in Ident is a keyword for a boolean value. Currently
325 * accepted are true/false/on/off.
328 if (SB_CompareStr (Ident, "true") == 0) {
331 if (SB_CompareStr (Ident, "on") == 0) {
334 if (SB_CompareStr (Ident, "false") == 0) {
337 if (SB_CompareStr (Ident, "off") == 0) {
342 Error ("Pragma argument must be one of `on', `off', `true' or `false'");
348 /*****************************************************************************/
349 /* Pragma handling functions */
350 /*****************************************************************************/
354 static void StringPragma (StrBuf* B, void (*Func) (const char*))
355 /* Handle a pragma that expects a string parameter */
357 StrBuf S = AUTO_STRBUF_INITIALIZER;
359 /* We expect a string here */
360 if (GetString (B, &S)) {
361 /* Call the given function with the string argument */
362 Func (SB_GetConstBuf (&S));
365 /* Call the string buf destructor */
371 static void SegNamePragma (StrBuf* B, segment_t Seg)
372 /* Handle a pragma that expects a segment name parameter */
374 StrBuf S = AUTO_STRBUF_INITIALIZER;
377 /* Check for the "push" or "pop" keywords */
379 switch (ParsePushPop (B)) {
389 /* Pop the old value and output it */
401 Internal ("Invalid result from ParsePushPop");
405 /* A string argument must follow */
406 if (!GetString (B, &S)) {
411 Name = SB_GetConstBuf (&S);
413 /* Check if the name is valid */
414 if (ValidSegName (Name)) {
416 /* Set the new name */
418 PushSegName (Seg, Name);
420 SetSegName (Seg, Name);
426 /* Segment name is invalid */
427 Error ("Illegal segment name: `%s'", Name);
432 /* Call the string buf destructor */
438 static void CharMapPragma (StrBuf* B)
439 /* Change the character map */
443 /* Read the character index */
444 if (!GetNumber (B, &Index)) {
447 if (Index < 1 || Index > 255) {
450 Error ("Remapping 0 is not allowed");
452 Error ("Character index out of range");
462 /* Read the character code */
463 if (!GetNumber (B, &C)) {
466 if (C < 1 || C > 255) {
469 Error ("Remapping 0 is not allowed");
471 Error ("Character code out of range");
476 /* Remap the character */
477 TgtTranslateSet ((unsigned) Index, (unsigned char) C);
482 static void WarnPragma (StrBuf* B)
483 /* Enable/disable warnings */
488 /* A warning name must follow */
489 IntStack* S =GetWarning (B);
499 /* Check for the "push" or "pop" keywords */
500 switch (ParsePushPop (B)) {
511 /* Pop the old value and bail out */
520 Internal ("Invalid result from ParsePushPop");
523 /* Boolean argument follows */
524 if (HasStr (B, "true") || HasStr (B, "on")) {
526 } else if (HasStr (B, "false") || HasStr (B, "off")) {
528 } else if (!SB_GetNumber (B, &Val)) {
529 Error ("Invalid pragma argument");
533 /* Set/push the new value */
543 static void FlagPragma (StrBuf* B, IntStack* Stack)
544 /* Handle a pragma that expects a boolean paramater */
546 StrBuf Ident = AUTO_STRBUF_INITIALIZER;
551 /* Try to read an identifier */
552 int IsIdent = SB_GetSym (B, &Ident, 0);
554 /* Check if we have a first argument named "pop" */
555 if (IsIdent && SB_CompareStr (&Ident, "pop") == 0) {
557 /* No other arguments allowed */
561 /* Check if we have a first argument named "push" */
562 if (IsIdent && SB_CompareStr (&Ident, "push") == 0) {
567 IsIdent = SB_GetSym (B, &Ident, 0);
572 /* Boolean argument follows */
574 Val = BoolKeyword (&Ident);
575 } else if (!GetNumber (B, &Val)) {
579 /* Set/push the new value */
581 PushInt (Stack, Val);
587 /* Free the identifier */
593 static void IntPragma (StrBuf* B, IntStack* Stack, long Low, long High)
594 /* Handle a pragma that expects an int paramater */
599 /* Check for the "push" or "pop" keywords */
600 switch (ParsePushPop (B)) {
611 /* Pop the old value and bail out */
620 Internal ("Invalid result from ParsePushPop");
624 /* Integer argument follows */
625 if (!GetNumber (B, &Val)) {
629 /* Check the argument */
630 if (Val < Low || Val > High) {
631 Error ("Pragma argument out of bounds (%ld-%ld)", Low, High);
635 /* Set/push the new value */
637 PushInt (Stack, Val);
645 static void ParsePragma (void)
646 /* Parse the contents of the _Pragma statement */
649 StrBuf Ident = AUTO_STRBUF_INITIALIZER;
651 /* Create a string buffer from the string literal */
652 StrBuf B = AUTO_STRBUF_INITIALIZER;
653 GetLiteralStrBuf (&B, CurTok.IVal);
655 /* Reset the string pointer, effectivly clearing the string from the
656 * string table. Since we're working with one token lookahead, this
657 * will fail if the next token is also a string token, but that's a
658 * syntax error anyway, because we expect a right paren.
660 ResetLiteralPoolOffs (CurTok.IVal);
662 /* Skip the string token */
665 /* Get the pragma name from the string */
667 if (!SB_GetSym (&B, &Ident, "-")) {
668 Error ("Invalid pragma");
672 /* Search for the name */
673 Pragma = FindPragma (&Ident);
675 /* Do we know this pragma? */
676 if (Pragma == PRAGMA_ILLEGAL) {
677 /* According to the ANSI standard, we're not allowed to generate errors
678 * for unknown pragmas, however, we're allowed to warn - and we will
679 * do so. Otherwise one typo may give you hours of bug hunting...
681 Warning ("Unknown pragma `%s'", SB_GetConstBuf (&Ident));
685 /* Check for an open paren */
687 if (SB_Get (&B) != '(') {
688 Error ("'(' expected");
692 /* Skip white space before the argument */
695 /* Switch for the different pragmas */
699 Warning ("#pragma bssseg is obsolete, please use #pragma bss-name instead");
701 case PRAGMA_BSS_NAME:
702 SegNamePragma (&B, SEG_BSS);
709 case PRAGMA_CHECKSTACK:
710 Warning ("#pragma checkstack is obsolete, please use #pragma check-stack instead");
712 case PRAGMA_CHECK_STACK:
713 FlagPragma (&B, &CheckStack);
717 Warning ("#pragma codeseg is obsolete, please use #pragma code-name instead");
719 case PRAGMA_CODE_NAME:
720 SegNamePragma (&B, SEG_CODE);
723 case PRAGMA_CODESIZE:
724 IntPragma (&B, &CodeSizeFactor, 10, 1000);
728 Warning ("#pragma dataseg is obsolete, please use #pragma data-name instead");
730 case PRAGMA_DATA_NAME:
731 SegNamePragma (&B, SEG_DATA);
734 case PRAGMA_OPTIMIZE:
735 FlagPragma (&B, &Optimize);
738 case PRAGMA_REGVARADDR:
739 FlagPragma (&B, &AllowRegVarAddr);
743 Warning ("#pragma regvars is obsolete, please use #pragma register-vars instead");
745 case PRAGMA_REGISTER_VARS:
746 FlagPragma (&B, &EnableRegVars);
749 case PRAGMA_RODATASEG:
750 Warning ("#pragma rodataseg is obsolete, please use #pragma rodata-name instead");
752 case PRAGMA_RODATA_NAME:
753 SegNamePragma (&B, SEG_RODATA);
756 case PRAGMA_SIGNEDCHARS:
757 Warning ("#pragma signedchars is obsolete, please use #pragma signed-chars instead");
759 case PRAGMA_SIGNED_CHARS:
760 FlagPragma (&B, &SignedChars);
763 case PRAGMA_STATICLOCALS:
764 Warning ("#pragma staticlocals is obsolete, please use #pragma static-locals instead");
766 case PRAGMA_STATIC_LOCALS:
767 FlagPragma (&B, &StaticLocals);
775 StringPragma (&B, MakeZPSym);
779 Internal ("Invalid pragma");
782 /* Closing paren expected */
784 if (SB_Get (&B) != ')') {
785 Error ("')' expected");
790 /* Allow an optional semicolon to be compatible with the old syntax */
791 if (SB_Peek (&B) == ';') {
796 /* Make sure nothing follows */
797 if (SB_Peek (&B) != '\0') {
798 Error ("Unexpected input following pragma directive");
802 /* Release the string buffers */
810 /* Handle pragmas. These come always in form of the new C99 _Pragma() operator. */
812 /* Skip the token itself */
815 /* We expect an opening paren */
816 if (!ConsumeLParen ()) {
821 if (CurTok.Tok != TOK_SCONST) {
823 /* Print a diagnostic */
824 Error ("String literal expected");
826 /* Try some smart error recovery: Skip tokens until we reach the
827 * enclosing paren, or a semicolon.
833 /* Parse the _Pragma statement */
837 /* Closing paren needed */