1 /*****************************************************************************/
5 /* Pragma handling for the cc65 C compiler */
9 /* (C) 1998-2011, 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"
54 #include "wrappedcall.h"
58 /*****************************************************************************/
60 /*****************************************************************************/
64 /* Tokens for the #pragmas */
68 PRAGMA_ALLOW_EAGER_INLINE,
70 PRAGMA_BSSSEG, /* obsolete */
73 PRAGMA_CHECKSTACK, /* obsolete */
75 PRAGMA_CODESEG, /* obsolete */
78 PRAGMA_DATASEG, /* obsolete */
79 PRAGMA_INLINE_STDFUNCS,
85 PRAGMA_REGVARS, /* obsolete */
87 PRAGMA_RODATASEG, /* obsolete */
89 PRAGMA_SIGNEDCHARS, /* obsolete */
91 PRAGMA_STATICLOCALS, /* obsolete */
94 PRAGMA_WRITABLE_STRINGS,
100 static const struct Pragma {
101 const char* Key; /* Keyword */
102 pragma_t Tok; /* Token */
103 } Pragmas[PRAGMA_COUNT] = {
104 { "align", PRAGMA_ALIGN },
105 { "allow-eager-inline", PRAGMA_ALLOW_EAGER_INLINE },
106 { "bss-name", PRAGMA_BSS_NAME },
107 { "bssseg", PRAGMA_BSSSEG }, /* obsolete */
108 { "charmap", PRAGMA_CHARMAP },
109 { "check-stack", PRAGMA_CHECK_STACK },
110 { "checkstack", PRAGMA_CHECKSTACK }, /* obsolete */
111 { "code-name", PRAGMA_CODE_NAME },
112 { "codeseg", PRAGMA_CODESEG }, /* obsolete */
113 { "codesize", PRAGMA_CODESIZE },
114 { "data-name", PRAGMA_DATA_NAME },
115 { "dataseg", PRAGMA_DATASEG }, /* obsolete */
116 { "inline-stdfuncs", PRAGMA_INLINE_STDFUNCS },
117 { "local-strings", PRAGMA_LOCAL_STRINGS },
118 { "message", PRAGMA_MESSAGE },
119 { "optimize", PRAGMA_OPTIMIZE },
120 { "register-vars", PRAGMA_REGISTER_VARS },
121 { "regvaraddr", PRAGMA_REGVARADDR },
122 { "regvars", PRAGMA_REGVARS }, /* obsolete */
123 { "rodata-name", PRAGMA_RODATA_NAME },
124 { "rodataseg", PRAGMA_RODATASEG }, /* obsolete */
125 { "signed-chars", PRAGMA_SIGNED_CHARS },
126 { "signedchars", PRAGMA_SIGNEDCHARS }, /* obsolete */
127 { "static-locals", PRAGMA_STATIC_LOCALS },
128 { "staticlocals", PRAGMA_STATICLOCALS }, /* obsolete */
129 { "warn", PRAGMA_WARN },
130 { "wrapped-call", PRAGMA_WRAPPED_CALL },
131 { "writable-strings", PRAGMA_WRITABLE_STRINGS },
132 { "zpsym", PRAGMA_ZPSYM },
135 /* Result of ParsePushPop */
145 /*****************************************************************************/
146 /* Helper functions */
147 /*****************************************************************************/
151 static void PragmaErrorSkip (void)
152 /* Called in case of an error, skips tokens until the closing paren or a
153 ** semicolon is reached.
156 static const token_t TokenList[] = { TOK_RPAREN, TOK_SEMI };
157 SkipTokens (TokenList, sizeof(TokenList) / sizeof(TokenList[0]));
162 static int CmpKey (const void* Key, const void* Elem)
163 /* Compare function for bsearch */
165 return strcmp ((const char*) Key, ((const struct Pragma*) Elem)->Key);
170 static pragma_t FindPragma (const StrBuf* Key)
171 /* Find a pragma and return the token. Return PRAGMA_ILLEGAL if the keyword is
172 ** not a valid pragma.
176 P = bsearch (SB_GetConstBuf (Key), Pragmas, PRAGMA_COUNT, sizeof (Pragmas[0]), CmpKey);
177 return P? P->Tok : PRAGMA_ILLEGAL;
182 static int GetComma (StrBuf* B)
183 /* Expects and skips a comma in B. Prints an error and returns zero if no
184 ** comma is found. Return a value <> 0 otherwise.
188 if (SB_Get (B) != ',') {
189 Error ("Comma expected");
198 static int GetString (StrBuf* B, StrBuf* S)
199 /* Expects and skips a string in B. Prints an error and returns zero if no
200 ** string is found. Returns a value <> 0 otherwise.
203 if (!SB_GetString (B, S)) {
204 Error ("String literal expected");
212 static int GetNumber (StrBuf* B, long* Val)
213 /* Expects and skips a number in B. Prints an eror and returns zero if no
214 ** number is found. Returns a value <> 0 otherwise.
217 if (!SB_GetNumber (B, Val)) {
218 Error ("Constant integer expected");
226 static IntStack* GetWarning (StrBuf* B)
227 /* Get a warning name from the string buffer. Returns a pointer to the intstack
228 ** that holds the state of the warning, and NULL in case of errors. The
229 ** function will output error messages in case of problems.
233 StrBuf W = AUTO_STRBUF_INITIALIZER;
235 /* The warning name is a symbol but the '-' char is allowed within */
236 if (SB_GetSym (B, &W, "-")) {
238 /* Map the warning name to an IntStack that contains its state */
239 S = FindWarning (SB_GetConstBuf (&W));
243 Error ("Pragma expects a warning name as first argument");
247 /* Deallocate the string */
256 static int HasStr (StrBuf* B, const char* E)
257 /* Checks if E follows in B. If so, skips it and returns true */
259 unsigned Len = strlen (E);
260 if (SB_GetLen (B) - SB_GetIndex (B) >= Len) {
261 if (strncmp (SB_GetConstBuf (B) + SB_GetIndex (B), E, Len) == 0) {
263 SB_SkipMultiple (B, Len);
272 static PushPopResult ParsePushPop (StrBuf* B)
273 /* Check for and parse the "push" and "pop" keywords. In case of "push", a
274 ** following comma is expected and skipped.
277 StrBuf Ident = AUTO_STRBUF_INITIALIZER;
278 PushPopResult Res = PP_NONE;
280 /* Remember the current string index, so we can go back in case of errors */
281 unsigned Index = SB_GetIndex (B);
283 /* Try to read an identifier */
284 if (SB_GetSym (B, &Ident, 0)) {
286 /* Check if we have a first argument named "pop" */
287 if (SB_CompareStr (&Ident, "pop") == 0) {
291 /* Check if we have a first argument named "push" */
292 } else if (SB_CompareStr (&Ident, "push") == 0) {
296 /* Skip the following comma */
298 /* Error already flagged by GetComma */
304 /* Unknown keyword, roll back */
305 SB_SetIndex (B, Index);
309 /* Free the string buffer and return the result */
316 static void PopInt (IntStack* S)
317 /* Pops an integer from an IntStack. Prints an error if the stack is empty */
319 if (IS_GetCount (S) < 2) {
320 Error ("Cannot pop, stack is empty");
328 static void PushInt (IntStack* S, long Val)
329 /* Pushes an integer onto an IntStack. Prints an error if the stack is full */
332 Error ("Cannot push: stack overflow");
340 static int BoolKeyword (StrBuf* Ident)
341 /* Check if the identifier in Ident is a keyword for a boolean value. Currently
342 ** accepted are true/false/on/off.
345 if (SB_CompareStr (Ident, "true") == 0) {
348 if (SB_CompareStr (Ident, "on") == 0) {
351 if (SB_CompareStr (Ident, "false") == 0) {
354 if (SB_CompareStr (Ident, "off") == 0) {
359 Error ("Pragma argument must be one of 'on', 'off', 'true' or 'false'");
365 /*****************************************************************************/
366 /* Pragma handling functions */
367 /*****************************************************************************/
371 static void StringPragma (StrBuf* B, void (*Func) (const char*))
372 /* Handle a pragma that expects a string parameter */
374 StrBuf S = AUTO_STRBUF_INITIALIZER;
376 /* We expect a string here */
377 if (GetString (B, &S)) {
378 /* Call the given function with the string argument */
379 Func (SB_GetConstBuf (&S));
382 /* Call the string buf destructor */
388 static void SegNamePragma (StrBuf* B, segment_t Seg)
389 /* Handle a pragma that expects a segment name parameter */
392 StrBuf S = AUTO_STRBUF_INITIALIZER;
395 /* Check for the "push" or "pop" keywords */
396 switch (ParsePushPop (B)) {
406 /* Pop the old value and output it */
409 /* BSS variables are output at the end of the compilation. Don't
410 ** bother to change their segment, now.
412 if (Seg != SEG_BSS) {
424 Internal ("Invalid result from ParsePushPop");
428 /* A string argument must follow */
429 if (!GetString (B, &S)) {
434 Name = SB_GetConstBuf (&S);
436 /* Check if the name is valid */
437 if (ValidSegName (Name)) {
439 /* Set the new name */
441 PushSegName (Seg, Name);
443 SetSegName (Seg, Name);
446 /* BSS variables are output at the end of the compilation. Don't
447 ** bother to change their segment, now.
449 if (Seg != SEG_BSS) {
455 /* Segment name is invalid */
456 Error ("Illegal segment name: '%s'", Name);
461 /* Call the string buf destructor */
466 static void WrappedCallPragma (StrBuf* B)
467 /* Handle the wrapped-call pragma */
469 StrBuf S = AUTO_STRBUF_INITIALIZER;
474 /* Check for the "push" or "pop" keywords */
475 switch (ParsePushPop (B)) {
478 Error ("Push or pop required");
495 Internal ("Invalid result from ParsePushPop");
499 /* A symbol argument must follow */
500 if (!SB_GetSym (B, &S, NULL)) {
504 /* Skip the following comma */
506 /* Error already flagged by GetComma */
507 Error ("Value required for wrapped-call identifier");
511 if (!GetNumber (B, &Val)) {
512 Error ("Value required for wrapped-call identifier");
516 if (Val < 0 || Val > 255) {
517 Error ("Identifier must be between 0-255");
522 Name = SB_GetConstBuf (&S);
523 Entry = FindSym(Name);
525 /* Check if the name is valid */
526 if (Entry && Entry->Flags & SC_FUNC) {
528 PushWrappedCall(Entry, (unsigned char) Val);
529 Entry->Flags |= SC_REF;
530 Entry->V.F.Func->Flags |= FD_CALL_WRAPPER;
534 /* Segment name is invalid */
535 Error ("Wrapped-call target does not exist or is not a function");
540 /* Call the string buf destructor */
546 static void CharMapPragma (StrBuf* B)
547 /* Change the character map */
551 /* Read the character index */
552 if (!GetNumber (B, &Index)) {
555 if (Index < 0 || Index > 255) {
556 Error ("Character index out of range");
565 /* Read the character code */
566 if (!GetNumber (B, &C)) {
569 if (C < 0 || C > 255) {
570 Error ("Character code out of range");
574 /* Warn about remapping character code 0x00
575 ** (except when remapping it back to itself).
577 if (Index + C != 0 && IS_Get (&WarnRemapZero)) {
579 Warning ("Remapping from 0 is dangerous with string functions");
582 Warning ("Remapping to 0 can make string functions stop unexpectedly");
586 /* Remap the character */
587 TgtTranslateSet ((unsigned) Index, (unsigned char) C);
592 static void WarnPragma (StrBuf* B)
593 /* Enable/disable warnings */
598 /* A warning name must follow */
599 IntStack* S = GetWarning (B);
609 /* Check for the "push" or "pop" keywords */
610 switch (ParsePushPop (B)) {
621 /* Pop the old value and bail out */
630 Internal ("Invalid result from ParsePushPop");
633 /* Boolean argument follows */
634 if (HasStr (B, "true") || HasStr (B, "on")) {
636 } else if (HasStr (B, "false") || HasStr (B, "off")) {
638 } else if (!SB_GetNumber (B, &Val)) {
639 Error ("Invalid pragma argument");
643 /* Set/push the new value */
653 static void FlagPragma (StrBuf* B, IntStack* Stack)
654 /* Handle a pragma that expects a boolean paramater */
656 StrBuf Ident = AUTO_STRBUF_INITIALIZER;
661 /* Try to read an identifier */
662 int IsIdent = SB_GetSym (B, &Ident, 0);
664 /* Check if we have a first argument named "pop" */
665 if (IsIdent && SB_CompareStr (&Ident, "pop") == 0) {
667 /* No other arguments allowed */
671 /* Check if we have a first argument named "push" */
672 if (IsIdent && SB_CompareStr (&Ident, "push") == 0) {
677 IsIdent = SB_GetSym (B, &Ident, 0);
682 /* Boolean argument follows */
684 Val = BoolKeyword (&Ident);
685 } else if (!GetNumber (B, &Val)) {
689 /* Set/push the new value */
691 PushInt (Stack, Val);
697 /* Free the identifier */
703 static void IntPragma (StrBuf* B, IntStack* Stack, long Low, long High)
704 /* Handle a pragma that expects an int paramater */
709 /* Check for the "push" or "pop" keywords */
710 switch (ParsePushPop (B)) {
721 /* Pop the old value and bail out */
730 Internal ("Invalid result from ParsePushPop");
734 /* Integer argument follows */
735 if (!GetNumber (B, &Val)) {
739 /* Check the argument */
740 if (Val < Low || Val > High) {
741 Error ("Pragma argument out of bounds (%ld-%ld)", Low, High);
745 /* Set/push the new value */
747 PushInt (Stack, Val);
755 static void MakeMessage (const char* Message)
757 fprintf (stderr, "%s(%u): Note: %s\n", GetInputName (CurTok.LI), GetInputLine (CurTok.LI), Message);
762 static void ParsePragma (void)
763 /* Parse the contents of the _Pragma statement */
766 StrBuf Ident = AUTO_STRBUF_INITIALIZER;
768 /* Create a string buffer from the string literal */
769 StrBuf B = AUTO_STRBUF_INITIALIZER;
770 SB_Append (&B, GetLiteralStrBuf (CurTok.SVal));
772 /* Skip the string token */
775 /* Get the pragma name from the string */
777 if (!SB_GetSym (&B, &Ident, "-")) {
778 Error ("Invalid pragma");
782 /* Search for the name */
783 Pragma = FindPragma (&Ident);
785 /* Do we know this pragma? */
786 if (Pragma == PRAGMA_ILLEGAL) {
787 /* According to the ANSI standard, we're not allowed to generate errors
788 ** for unknown pragmas, but warn about them if enabled (the default).
790 if (IS_Get (&WarnUnknownPragma)) {
791 Warning ("Unknown pragma '%s'", SB_GetConstBuf (&Ident));
796 /* Check for an open paren */
798 if (SB_Get (&B) != '(') {
799 Error ("'(' expected");
803 /* Skip white space before the argument */
806 /* Switch for the different pragmas */
810 IntPragma (&B, &DataAlignment, 1, 4096);
813 case PRAGMA_ALLOW_EAGER_INLINE:
814 FlagPragma (&B, &EagerlyInlineFuncs);
818 Warning ("#pragma bssseg is obsolete, please use #pragma bss-name instead");
820 case PRAGMA_BSS_NAME:
821 SegNamePragma (&B, SEG_BSS);
828 case PRAGMA_CHECKSTACK:
829 Warning ("#pragma checkstack is obsolete, please use #pragma check-stack instead");
831 case PRAGMA_CHECK_STACK:
832 FlagPragma (&B, &CheckStack);
836 Warning ("#pragma codeseg is obsolete, please use #pragma code-name instead");
838 case PRAGMA_CODE_NAME:
839 SegNamePragma (&B, SEG_CODE);
842 case PRAGMA_CODESIZE:
843 IntPragma (&B, &CodeSizeFactor, 10, 1000);
847 Warning ("#pragma dataseg is obsolete, please use #pragma data-name instead");
849 case PRAGMA_DATA_NAME:
850 SegNamePragma (&B, SEG_DATA);
853 case PRAGMA_INLINE_STDFUNCS:
854 FlagPragma (&B, &InlineStdFuncs);
857 case PRAGMA_LOCAL_STRINGS:
858 FlagPragma (&B, &LocalStrings);
862 StringPragma (&B, MakeMessage);
865 case PRAGMA_OPTIMIZE:
866 FlagPragma (&B, &Optimize);
869 case PRAGMA_REGVARADDR:
870 FlagPragma (&B, &AllowRegVarAddr);
874 Warning ("#pragma regvars is obsolete, please use #pragma register-vars instead");
876 case PRAGMA_REGISTER_VARS:
877 FlagPragma (&B, &EnableRegVars);
880 case PRAGMA_RODATASEG:
881 Warning ("#pragma rodataseg is obsolete, please use #pragma rodata-name instead");
883 case PRAGMA_RODATA_NAME:
884 SegNamePragma (&B, SEG_RODATA);
887 case PRAGMA_SIGNEDCHARS:
888 Warning ("#pragma signedchars is obsolete, please use #pragma signed-chars instead");
890 case PRAGMA_SIGNED_CHARS:
891 FlagPragma (&B, &SignedChars);
894 case PRAGMA_STATICLOCALS:
895 Warning ("#pragma staticlocals is obsolete, please use #pragma static-locals instead");
897 case PRAGMA_STATIC_LOCALS:
898 FlagPragma (&B, &StaticLocals);
901 case PRAGMA_WRAPPED_CALL:
902 WrappedCallPragma(&B);
909 case PRAGMA_WRITABLE_STRINGS:
910 FlagPragma (&B, &WritableStrings);
914 StringPragma (&B, MakeZPSym);
918 Internal ("Invalid pragma");
921 /* Closing paren expected */
923 if (SB_Get (&B) != ')') {
924 Error ("')' expected");
929 /* Allow an optional semicolon to be compatible with the old syntax */
930 if (SB_Peek (&B) == ';') {
935 /* Make sure nothing follows */
936 if (SB_Peek (&B) != '\0') {
937 Error ("Unexpected input following pragma directive");
941 /* Release the string buffers */
949 /* Handle pragmas. These come always in form of the new C99 _Pragma() operator. */
951 /* Skip the token itself */
954 /* We expect an opening paren */
955 if (!ConsumeLParen ()) {
960 if (CurTok.Tok != TOK_SCONST) {
962 /* Print a diagnostic */
963 Error ("String literal expected");
965 /* Try some smart error recovery: Skip tokens until we reach the
966 ** enclosing paren, or a semicolon.
972 /* Parse the _Pragma statement */
976 /* Closing paren needed */