]> git.sur5r.net Git - cc65/blob - src/cc65/stmt.c
Fix the check for constant static local data, which was wrong when the data
[cc65] / src / cc65 / stmt.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  stmt.c                                   */
4 /*                                                                           */
5 /*                             Parse a statement                             */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2009, Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 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 <stdio.h>
37 #include <string.h>
38
39 /* common */
40 #include "coll.h"
41 #include "xmalloc.h"
42
43 /* cc65 */
44 #include "asmcode.h"
45 #include "asmlabel.h"
46 #include "codegen.h"
47 #include "datatype.h"
48 #include "error.h"
49 #include "expr.h"
50 #include "function.h"
51 #include "global.h"
52 #include "goto.h"
53 #include "litpool.h"
54 #include "loadexpr.h"
55 #include "locals.h"
56 #include "loop.h"
57 #include "pragma.h"
58 #include "scanner.h"
59 #include "stackptr.h"
60 #include "stmt.h"
61 #include "swstmt.h"
62 #include "symtab.h"
63 #include "testexpr.h"
64 #include "typeconv.h"
65
66
67
68 /*****************************************************************************/
69 /*                             Helper functions                              */
70 /*****************************************************************************/
71
72
73
74 static void CheckLabelWithoutStatement (void)
75 /* Called from Statement() after a label definition. Will check for a
76  * following closing curly brace. This means that a label is not followed
77  * by a statement which is required by the standard. Output an error if so.
78  */
79 {
80     if (CurTok.Tok == TOK_RCURLY) {
81         Error ("Label at end of compound statement");
82     }
83 }
84
85
86
87 static void CheckTok (token_t Tok, const char* Msg, int* PendingToken)
88 /* Helper function for Statement. Will check for Tok and print Msg if not
89  * found. If PendingToken is NULL, it will the skip the token, otherwise
90  * it will store one to PendingToken.
91  */
92 {
93     if (CurTok.Tok != Tok) {
94         Error ("%s", Msg);
95     } else if (PendingToken) {
96         *PendingToken = 1;
97     } else {
98         NextToken ();
99     }
100 }
101
102
103
104 static void CheckSemi (int* PendingToken)
105 /* Helper function for Statement. Will check for a semicolon and print an
106  * error message if not found (plus some error recovery). If PendingToken is
107  * NULL, it will the skip the token, otherwise it will store one to
108  * PendingToken.
109  * This function is a special version of CheckTok with the addition of the
110  * error recovery.
111  */
112 {
113     int HaveToken = (CurTok.Tok == TOK_SEMI);
114     if (!HaveToken) {
115         Error ("`;' expected");
116         /* Try to be smart about errors */
117         if (CurTok.Tok == TOK_COLON || CurTok.Tok == TOK_COMMA) {
118             HaveToken = 1;
119         }
120     }
121     if (HaveToken) {
122         if (PendingToken) {
123             *PendingToken = 1;
124         } else {
125             NextToken ();
126         }
127     }
128 }
129
130
131
132 static void SkipPending (int PendingToken)
133 /* Skip the pending token if we have one */
134 {
135     if (PendingToken) {
136         NextToken ();
137     }
138 }
139
140
141
142 /*****************************************************************************/
143 /*                                   Code                                    */
144 /*****************************************************************************/
145
146
147
148 static int IfStatement (void)
149 /* Handle an 'if' statement */
150 {
151     unsigned Label1;
152     unsigned TestResult;
153     int GotBreak;
154
155     /* Skip the if */
156     NextToken ();
157
158     /* Generate a jump label and parse the condition */
159     Label1 = GetLocalLabel ();
160     TestResult = TestInParens (Label1, 0);
161
162     /* Parse the if body */
163     GotBreak = Statement (0);
164
165     /* Else clause present? */
166     if (CurTok.Tok != TOK_ELSE) {
167
168         g_defcodelabel (Label1);
169
170         /* Since there's no else clause, we're not sure, if the a break
171          * statement is really executed.
172          */
173         return 0;
174
175     } else {
176
177         /* Generate a jump around the else branch */
178         unsigned Label2 = GetLocalLabel ();
179         g_jump (Label2);
180
181         /* Skip the else */
182         NextToken ();
183
184         /* If the if expression was always true, the code in the else branch
185          * is never executed. Output a warning if this is the case.
186          */
187         if (TestResult == TESTEXPR_TRUE) {
188             Warning ("Unreachable code");
189         }
190
191         /* Define the target for the first test */
192         g_defcodelabel (Label1);
193
194         /* Total break only if both branches had a break. */
195         GotBreak &= Statement (0);
196
197         /* Generate the label for the else clause */
198         g_defcodelabel (Label2);
199
200         /* Done */
201         return GotBreak;
202     }
203 }
204
205
206
207 static void DoStatement (void)
208 /* Handle the 'do' statement */
209 {
210     /* Get the loop control labels */
211     unsigned LoopLabel      = GetLocalLabel ();
212     unsigned BreakLabel     = GetLocalLabel ();
213     unsigned ContinueLabel  = GetLocalLabel ();
214
215     /* Skip the while token */
216     NextToken ();
217
218     /* Add the loop to the loop stack */
219     AddLoop (BreakLabel, ContinueLabel);
220
221     /* Define the loop label */
222     g_defcodelabel (LoopLabel);
223
224     /* Parse the loop body */
225     Statement (0);
226
227     /* Output the label for a continue */
228     g_defcodelabel (ContinueLabel);
229
230     /* Parse the end condition */
231     Consume (TOK_WHILE, "`while' expected");
232     TestInParens (LoopLabel, 1);
233     ConsumeSemi ();
234
235     /* Define the break label */
236     g_defcodelabel (BreakLabel);
237
238     /* Remove the loop from the loop stack */
239     DelLoop ();
240 }
241
242
243
244 static void WhileStatement (void)
245 /* Handle the 'while' statement */
246 {
247     int         PendingToken;
248     CodeMark    CondCodeStart;  /* Start of condition evaluation code */
249     CodeMark    CondCodeEnd;    /* End of condition evaluation code */
250     CodeMark    Here;           /* "Here" location of code */
251
252     /* Get the loop control labels */
253     unsigned LoopLabel  = GetLocalLabel ();
254     unsigned BreakLabel = GetLocalLabel ();
255     unsigned CondLabel  = GetLocalLabel ();
256
257     /* Skip the while token */
258     NextToken ();
259
260     /* Add the loop to the loop stack. In case of a while loop, the condition
261      * label is used for continue statements.
262      */
263     AddLoop (BreakLabel, CondLabel);
264
265     /* We will move the code that evaluates the while condition to the end of
266      * the loop, so generate a jump here.
267      */
268     g_jump (CondLabel);
269
270     /* Remember the current position */
271     GetCodePos (&CondCodeStart);
272
273     /* Emit the code position label */
274     g_defcodelabel (CondLabel);
275
276     /* Test the loop condition */
277     TestInParens (LoopLabel, 1);
278
279     /* Remember the end of the condition evaluation code */
280     GetCodePos (&CondCodeEnd);
281
282     /* Define the head label */
283     g_defcodelabel (LoopLabel);
284
285     /* Loop body */
286     Statement (&PendingToken);
287
288     /* Move the test code here */
289     GetCodePos (&Here);
290     MoveCode (&CondCodeStart, &CondCodeEnd, &Here);
291
292     /* Exit label */
293     g_defcodelabel (BreakLabel);
294
295     /* Eat remaining tokens that were delayed because of line info
296      * correctness
297      */
298     SkipPending (PendingToken);
299
300     /* Remove the loop from the loop stack */
301     DelLoop ();
302 }
303
304
305
306 static void ReturnStatement (void)
307 /* Handle the 'return' statement */
308 {
309     ExprDesc Expr;
310
311     NextToken ();
312     if (CurTok.Tok != TOK_SEMI) {
313
314         /* Evaluate the return expression */
315         hie0 (&Expr);
316
317         /* If we return something in a void function, print an error and
318          * ignore the value. Otherwise convert the value to the type of the
319          * return.
320          */
321         if (F_HasVoidReturn (CurrentFunc)) {
322             Error ("Returning a value in function with return type void");
323         } else {
324             /* Convert the return value to the type of the function result */
325             TypeConversion (&Expr, F_GetReturnType (CurrentFunc));
326
327             /* Load the value into the primary */
328             LoadExpr (CF_NONE, &Expr);
329         }
330
331     } else if (!F_HasVoidReturn (CurrentFunc) && !F_HasOldStyleIntRet (CurrentFunc)) {
332         Error ("Function `%s' must return a value", F_GetFuncName (CurrentFunc));
333     }
334
335     /* Mark the function as having a return statement */
336     F_ReturnFound (CurrentFunc);
337
338     /* Cleanup the stack in case we're inside a block with locals */
339     g_space (StackPtr - F_GetTopLevelSP (CurrentFunc));
340
341     /* Output a jump to the function exit code */
342     g_jump (F_GetRetLab (CurrentFunc));
343 }
344
345
346
347 static void BreakStatement (void)
348 /* Handle the 'break' statement */
349 {
350     LoopDesc* L;
351
352     /* Skip the break */
353     NextToken ();
354
355     /* Get the current loop descriptor */
356     L = CurrentLoop ();
357
358     /* Check if we are inside a loop */
359     if (L == 0) {
360         /* Error: No current loop */
361         Error ("`break' statement not within loop or switch");
362         return;
363     }
364
365     /* Correct the stack pointer if needed */
366     g_space (StackPtr - L->StackPtr);
367
368     /* Jump to the exit label of the loop */
369     g_jump (L->BreakLabel);
370 }
371
372
373
374 static void ContinueStatement (void)
375 /* Handle the 'continue' statement */
376 {
377     LoopDesc* L;
378
379     /* Skip the continue */
380     NextToken ();
381
382     /* Get the current loop descriptor */
383     L = CurrentLoop ();
384     if (L) {
385         /* Search for a loop that has a continue label. */
386         do {
387             if (L->ContinueLabel) {
388                 break;
389             }
390             L = L->Next;
391         } while (L);
392     }
393
394     /* Did we find it? */
395     if (L == 0) {
396         Error ("`continue' statement not within a loop");
397         return;
398     }
399
400     /* Correct the stackpointer if needed */
401     g_space (StackPtr - L->StackPtr);
402
403     /* Jump to next loop iteration */
404     g_jump (L->ContinueLabel);
405 }
406
407
408
409 static void ForStatement (void)
410 /* Handle a 'for' statement */
411 {
412     ExprDesc lval1;
413     ExprDesc lval3;
414     int HaveIncExpr;
415     CodeMark IncExprStart;
416     CodeMark IncExprEnd;
417     int PendingToken;
418
419     /* Get several local labels needed later */
420     unsigned TestLabel    = GetLocalLabel ();
421     unsigned BreakLabel   = GetLocalLabel ();
422     unsigned IncLabel     = GetLocalLabel ();
423     unsigned BodyLabel    = GetLocalLabel ();
424
425     /* Skip the FOR token */
426     NextToken ();
427
428     /* Add the loop to the loop stack. A continue jumps to the start of the
429      * the increment condition.
430      */
431     AddLoop (BreakLabel, IncLabel);
432
433     /* Skip the opening paren */
434     ConsumeLParen ();
435
436     /* Parse the initializer expression */
437     if (CurTok.Tok != TOK_SEMI) {
438         Expression0 (&lval1);
439     }
440     ConsumeSemi ();
441
442     /* Label for the test expressions */
443     g_defcodelabel (TestLabel);
444
445     /* Parse the test expression */
446     if (CurTok.Tok != TOK_SEMI) {
447         Test (BodyLabel, 1);
448         g_jump (BreakLabel);
449     } else {
450         g_jump (BodyLabel);
451     }
452     ConsumeSemi ();
453
454     /* Remember the start of the increment expression */
455     GetCodePos (&IncExprStart);
456
457     /* Label for the increment expression */
458     g_defcodelabel (IncLabel);
459
460     /* Parse the increment expression */
461     HaveIncExpr = (CurTok.Tok != TOK_RPAREN);
462     if (HaveIncExpr) {
463         Expression0 (&lval3);
464     }
465
466     /* Jump to the test */
467     g_jump (TestLabel);
468
469     /* Remember the end of the increment expression */
470     GetCodePos (&IncExprEnd);
471
472     /* Skip the closing paren */
473     ConsumeRParen ();
474
475     /* Loop body */
476     g_defcodelabel (BodyLabel);
477     Statement (&PendingToken);
478
479     /* If we had an increment expression, move the code to the bottom of
480      * the loop. In this case we don't need to jump there at the end of
481      * the loop body.
482      */
483     if (HaveIncExpr) {
484         CodeMark Here;
485         GetCodePos (&Here);
486         MoveCode (&IncExprStart, &IncExprEnd, &Here);
487     } else {
488         /* Jump back to the increment expression */
489         g_jump (IncLabel);
490     }
491
492     /* Skip a pending token if we have one */
493     SkipPending (PendingToken);
494
495     /* Declare the break label */
496     g_defcodelabel (BreakLabel);
497
498     /* Remove the loop from the loop stack */
499     DelLoop ();
500 }
501
502
503
504 static int CompoundStatement (void)
505 /* Compound statement. Allow any number of statements inside braces. The
506  * function returns true if the last statement was a break or return.
507  */
508 {
509     int GotBreak;
510
511     /* Remember the stack at block entry */
512     int OldStack = StackPtr;
513
514     /* Enter a new lexical level */
515     EnterBlockLevel ();
516
517     /* Parse local variable declarations if any */
518     DeclareLocals ();
519
520     /* Now process statements in this block */
521     GotBreak = 0;
522     while (CurTok.Tok != TOK_RCURLY) {
523         if (CurTok.Tok != TOK_CEOF) {
524             GotBreak = Statement (0);
525         } else {
526             break;
527         }
528     }
529
530     /* Clean up the stack. */
531     if (!GotBreak) {
532         g_space (StackPtr - OldStack);
533     }
534     StackPtr = OldStack;
535
536     /* Emit references to imports/exports for this block */
537     EmitExternals ();
538
539     /* Leave the lexical level */
540     LeaveBlockLevel ();
541
542     return GotBreak;
543 }
544
545
546
547 int Statement (int* PendingToken)
548 /* Statement parser. Returns 1 if the statement does a return/break, returns
549  * 0 otherwise. If the PendingToken pointer is not NULL, the function will
550  * not skip the terminating token of the statement (closing brace or
551  * semicolon), but store true if there is a pending token, and false if there
552  * is none. The token is always checked, so there is no need for the caller to
553  * check this token, it must be skipped, however. If the argument pointer is
554  * NULL, the function will skip the token.
555  */
556 {
557     ExprDesc Expr;
558     int GotBreak;
559     CodeMark Start, End;
560
561     /* Assume no pending token */
562     if (PendingToken) {
563         *PendingToken = 0;
564     }
565
566     /* Check for a label. A label is always part of a statement, it does not
567      * replace one.
568      */
569     while (CurTok.Tok == TOK_IDENT && NextTok.Tok == TOK_COLON) {
570         /* Handle the label */
571         DoLabel ();
572         CheckLabelWithoutStatement ();
573     }
574
575     switch (CurTok.Tok) {
576
577         case TOK_LCURLY:
578             NextToken ();
579             GotBreak = CompoundStatement ();
580             CheckTok (TOK_RCURLY, "`{' expected", PendingToken);
581             return GotBreak;
582
583         case TOK_IF:
584             return IfStatement ();
585
586         case TOK_WHILE:
587             WhileStatement ();
588             break;
589
590         case TOK_DO:
591             DoStatement ();
592             break;
593
594         case TOK_SWITCH:
595             SwitchStatement ();
596             break;
597
598         case TOK_RETURN:
599             ReturnStatement ();
600             CheckSemi (PendingToken);
601             return 1;
602
603         case TOK_BREAK:
604             BreakStatement ();
605             CheckSemi (PendingToken);
606             return 1;
607
608         case TOK_CONTINUE:
609             ContinueStatement ();
610             CheckSemi (PendingToken);
611             return 1;
612
613         case TOK_FOR:
614             ForStatement ();
615             break;
616
617         case TOK_GOTO:
618             GotoStatement ();
619             CheckSemi (PendingToken);
620             return 1;
621
622         case TOK_SEMI:
623             /* Ignore it */
624             CheckSemi (PendingToken);
625             break;
626
627         case TOK_PRAGMA:
628             DoPragma ();
629             break;
630
631         case TOK_CASE:
632             CaseLabel ();
633             CheckLabelWithoutStatement ();
634             break;
635
636         case TOK_DEFAULT:
637             DefaultLabel ();
638             CheckLabelWithoutStatement ();
639             break;
640
641         default:
642             /* Remember the current code position */
643             GetCodePos (&Start);
644             /* Actual statement */
645             ExprWithCheck (hie0, &Expr);
646             /* Load the result only if it is an lvalue and the type is
647              * marked as volatile. Otherwise the load is useless.
648              */
649             if (ED_IsLVal (&Expr) && IsQualVolatile (Expr.Type)) {
650                 LoadExpr (CF_NONE, &Expr);
651             }
652             /* If the statement didn't generate code, and is not of type
653              * void, emit a warning.
654              */
655             GetCodePos (&End);
656             if (CodeRangeIsEmpty (&Start, &End) && !IsTypeVoid (Expr.Type)) {
657                 Warning ("Statement has no effect");
658             }
659             CheckSemi (PendingToken);
660     }
661     return 0;
662 }
663
664
665
666