]> git.sur5r.net Git - cc65/blob - src/cc65/stmt.c
Fixed a bug
[cc65] / src / cc65 / stmt.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  stmt.c                                   */
4 /*                                                                           */
5 /*                             Parse a statement                             */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2003 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 "swstmt.h"
59 #include "symtab.h"
60 #include "stmt.h"
61 #include "testexpr.h"
62 #include "typeconv.h"
63
64
65
66 /*****************************************************************************/
67 /*                             Helper functions                              */
68 /*****************************************************************************/
69
70
71
72 static void CheckTok (token_t Tok, const char* Msg, int* PendingToken)
73 /* Helper function for Statement. Will check for Tok and print Msg if not
74  * found. If PendingToken is NULL, it will the skip the token, otherwise
75  * it will store one to PendingToken.
76  */
77 {
78     if (CurTok.Tok != Tok) {
79         Error (Msg);
80     } else if (PendingToken) {
81         *PendingToken = 1;
82     } else {
83         NextToken ();
84     }
85 }
86
87
88
89 static void CheckSemi (int* PendingToken)
90 /* Helper function for Statement. Will check for a semicolon and print an
91  * error message if not found (plus some error recovery). If PendingToken is
92  * NULL, it will the skip the token, otherwise it will store one to
93  * PendingToken.
94  * This function is a special version of CheckTok with the addition of the
95  * error recovery.
96  */
97 {
98     int HaveToken = (CurTok.Tok == TOK_SEMI);
99     if (!HaveToken) {
100         Error ("`;' expected");
101         /* Try to be smart about errors */
102         if (CurTok.Tok == TOK_COLON || CurTok.Tok == TOK_COMMA) {
103             HaveToken = 1;
104         }
105     }
106     if (HaveToken) {
107         if (PendingToken) {
108             *PendingToken = 1;
109         } else {
110             NextToken ();
111         }
112     }
113 }
114
115
116
117 static void SkipPending (int PendingToken)
118 /* Skip the pending token if we have one */
119 {
120     if (PendingToken) {
121         NextToken ();
122     }
123 }
124
125
126
127 /*****************************************************************************/
128 /*                                   Code                                    */
129 /*****************************************************************************/
130
131
132
133 static int IfStatement (void)
134 /* Handle an 'if' statement */
135 {
136     unsigned Label1;
137     unsigned TestResult;
138     int GotBreak;
139
140     /* Skip the if */
141     NextToken ();
142
143     /* Generate a jump label and parse the condition */
144     Label1 = GetLocalLabel ();
145     TestResult = TestInParens (Label1, 0);
146
147     /* Parse the if body */
148     GotBreak = Statement (0);
149
150     /* Else clause present? */
151     if (CurTok.Tok != TOK_ELSE) {
152
153         g_defcodelabel (Label1);
154
155         /* Since there's no else clause, we're not sure, if the a break
156          * statement is really executed.
157          */
158         return 0;
159
160     } else {
161
162         /* Generate a jump around the else branch */
163         unsigned Label2 = GetLocalLabel ();
164         g_jump (Label2);
165
166         /* Skip the else */
167         NextToken ();
168
169         /* If the if expression was always true, the code in the else branch
170          * is never executed. Output a warning if this is the case.
171          */
172         if (TestResult == TESTEXPR_TRUE) {
173             Warning ("Unreachable code");
174         }
175
176         /* Define the target for the first test */
177         g_defcodelabel (Label1);
178
179         /* Total break only if both branches had a break. */
180         GotBreak &= Statement (0);
181
182         /* Generate the label for the else clause */
183         g_defcodelabel (Label2);
184
185         /* Done */
186         return GotBreak;
187     }
188 }
189
190
191
192 static void DoStatement (void)
193 /* Handle the 'do' statement */
194 {
195     /* Get the loop control labels */
196     unsigned LoopLabel      = GetLocalLabel ();
197     unsigned BreakLabel     = GetLocalLabel ();
198     unsigned ContinueLabel  = GetLocalLabel ();
199
200     /* Skip the while token */
201     NextToken ();
202
203     /* Add the loop to the loop stack */
204     AddLoop (oursp, BreakLabel, ContinueLabel);
205
206     /* Define the loop label */
207     g_defcodelabel (LoopLabel);
208
209     /* Parse the loop body */
210     Statement (0);
211
212     /* Output the label for a continue */
213     g_defcodelabel (ContinueLabel);
214
215     /* Parse the end condition */
216     Consume (TOK_WHILE, "`while' expected");
217     TestInParens (LoopLabel, 1);
218     ConsumeSemi ();
219
220     /* Define the break label */
221     g_defcodelabel (BreakLabel);
222
223     /* Remove the loop from the loop stack */
224     DelLoop ();
225 }
226
227
228
229 static void WhileStatement (void)
230 /* Handle the 'while' statement */
231 {
232     int PendingToken;
233
234     /* Get the loop control labels */
235     unsigned LoopLabel  = GetLocalLabel ();
236     unsigned BreakLabel = GetLocalLabel ();
237
238     /* Skip the while token */
239     NextToken ();
240
241     /* Add the loop to the loop stack. In case of a while loop, the loop head
242      * label is used for continue statements.
243      */
244     AddLoop (oursp, BreakLabel, LoopLabel);
245
246     /* Define the head label */
247     g_defcodelabel (LoopLabel);
248
249     /* Test the loop condition */
250     TestInParens (BreakLabel, 0);
251
252     /* Loop body */
253     Statement (&PendingToken);
254
255     /* Jump back to loop top */
256     g_jump (LoopLabel);
257
258     /* Exit label */
259     g_defcodelabel (BreakLabel);
260
261     /* Eat remaining tokens that were delayed because of line info
262      * correctness
263      */
264     SkipPending (PendingToken);
265
266     /* Remove the loop from the loop stack */
267     DelLoop ();
268 }
269
270
271
272 static void ReturnStatement (void)
273 /* Handle the 'return' statement */
274 {
275     ExprDesc Expr;
276     int k;
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         k = hie0 (InitExprDesc (&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             k = TypeConversion (&Expr, k, F_GetReturnType (CurrentFunc));
294
295             /* Load the value into the primary */
296             ExprLoad (CF_NONE, k, &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 (oursp - 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 (oursp - 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 (oursp - 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 (oursp, BreakLabel, IncLabel);
397
398     /* Skip the opening paren */
399     ConsumeLParen ();
400
401     /* Parse the initializer expression */
402     if (CurTok.Tok != TOK_SEMI) {
403         expression (&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         expression (&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 = oursp;
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 (oursp - OldStack);
496     }
497     oursp = 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 lval;
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                 expression (&lval);
595                 CheckSemi (PendingToken);
596         }
597     }
598     return 0;
599 }
600
601
602
603