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