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