]> git.sur5r.net Git - cc65/blob - src/cc65/stmt.c
Removed unused modules
[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
277     NextToken ();
278     if (CurTok.Tok != TOK_SEMI) {
279
280         /* Check if the function has a return value declared */
281         if (F_HasVoidReturn (CurrentFunc)) {
282             Error ("Returning a value in function with return type void");
283         }
284
285         /* Evaluate the return expression */
286         hie0 (InitExprDesc (&Expr));
287
288         /* Ignore the return expression if the function returns void */
289         if (!F_HasVoidReturn (CurrentFunc)) {
290
291             /* Convert the return value to the type of the function result */
292             TypeConversion (&Expr, F_GetReturnType (CurrentFunc));
293
294             /* Load the value into the primary */
295             ExprLoad (CF_NONE, &Expr);
296         }
297
298     } else if (!F_HasVoidReturn (CurrentFunc) && !F_HasOldStyleIntRet (CurrentFunc)) {
299         Error ("Function `%s' must return a value", F_GetFuncName (CurrentFunc));
300     }
301
302     /* Cleanup the stack in case we're inside a block with locals */
303     g_space (oursp - F_GetTopLevelSP (CurrentFunc));
304
305     /* Output a jump to the function exit code */
306     g_jump (F_GetRetLab (CurrentFunc));
307 }
308
309
310
311 static void BreakStatement (void)
312 /* Handle the 'break' statement */
313 {
314     LoopDesc* L;
315
316     /* Skip the break */
317     NextToken ();
318
319     /* Get the current loop descriptor */
320     L = CurrentLoop ();
321
322     /* Check if we are inside a loop */
323     if (L == 0) {
324         /* Error: No current loop */
325         Error ("`break' statement not within loop or switch");
326         return;
327     }
328
329     /* Correct the stack pointer if needed */
330     g_space (oursp - L->StackPtr);
331
332     /* Jump to the exit label of the loop */
333     g_jump (L->BreakLabel);
334 }
335
336
337
338 static void ContinueStatement (void)
339 /* Handle the 'continue' statement */
340 {
341     LoopDesc* L;
342
343     /* Skip the continue */
344     NextToken ();
345
346     /* Get the current loop descriptor */
347     L = CurrentLoop ();
348     if (L) {
349         /* Search for a loop that has a continue label. */
350         do {
351             if (L->ContinueLabel) {
352                 break;
353             }
354             L = L->Next;
355         } while (L);
356     }
357
358     /* Did we find it? */
359     if (L == 0) {
360         Error ("`continue' statement not within a loop");
361         return;
362     }
363
364     /* Correct the stackpointer if needed */
365     g_space (oursp - L->StackPtr);
366
367     /* Jump to next loop iteration */
368     g_jump (L->ContinueLabel);
369 }
370
371
372
373 static void ForStatement (void)
374 /* Handle a 'for' statement */
375 {
376     ExprDesc lval1;
377     ExprDesc lval3;
378     int HaveIncExpr;
379     CodeMark IncExprStart;
380     CodeMark IncExprEnd;
381     int PendingToken;
382
383     /* Get several local labels needed later */
384     unsigned TestLabel    = GetLocalLabel ();
385     unsigned BreakLabel   = GetLocalLabel ();
386     unsigned IncLabel     = GetLocalLabel ();
387     unsigned BodyLabel    = GetLocalLabel ();
388
389     /* Skip the FOR token */
390     NextToken ();
391
392     /* Add the loop to the loop stack. A continue jumps to the start of the
393      * the increment condition.
394      */
395     AddLoop (oursp, BreakLabel, IncLabel);
396
397     /* Skip the opening paren */
398     ConsumeLParen ();
399
400     /* Parse the initializer expression */
401     if (CurTok.Tok != TOK_SEMI) {
402         expression0 (&lval1);
403     }
404     ConsumeSemi ();
405
406     /* Label for the test expressions */
407     g_defcodelabel (TestLabel);
408
409     /* Parse the test expression */
410     if (CurTok.Tok != TOK_SEMI) {
411         Test (BodyLabel, 1);
412         g_jump (BreakLabel);
413     } else {
414         g_jump (BodyLabel);
415     }
416     ConsumeSemi ();
417
418     /* Remember the start of the increment expression */
419     IncExprStart = GetCodePos();
420
421     /* Label for the increment expression */
422     g_defcodelabel (IncLabel);
423
424     /* Parse the increment expression */
425     HaveIncExpr = (CurTok.Tok != TOK_RPAREN);
426     if (HaveIncExpr) {
427         expression0 (&lval3);
428     }
429
430     /* Jump to the test */
431     g_jump (TestLabel);
432
433     /* Remember the end of the increment expression */
434     IncExprEnd = GetCodePos();
435
436     /* Skip the closing paren */
437     ConsumeRParen ();
438
439     /* Loop body */
440     g_defcodelabel (BodyLabel);
441     Statement (&PendingToken);
442
443     /* If we had an increment expression, move the code to the bottom of
444      * the loop. In this case we don't need to jump there at the end of
445      * the loop body.
446      */
447     if (HaveIncExpr) {
448         MoveCode (IncExprStart, IncExprEnd, GetCodePos());
449     } else {
450         /* Jump back to the increment expression */
451         g_jump (IncLabel);
452     }
453
454     /* Skip a pending token if we have one */
455     SkipPending (PendingToken);
456
457     /* Declare the break label */
458     g_defcodelabel (BreakLabel);
459
460     /* Remove the loop from the loop stack */
461     DelLoop ();
462 }
463
464
465
466 static int CompoundStatement (void)
467 /* Compound statement. Allow any number of statements inside braces. The
468  * function returns true if the last statement was a break or return.
469  */
470 {
471     int GotBreak;
472
473     /* Remember the stack at block entry */
474     int OldStack = oursp;
475
476     /* Enter a new lexical level */
477     EnterBlockLevel ();
478
479     /* Parse local variable declarations if any */
480     DeclareLocals ();
481
482     /* Now process statements in this block */
483     GotBreak = 0;
484     while (CurTok.Tok != TOK_RCURLY) {
485         if (CurTok.Tok != TOK_CEOF) {
486             GotBreak = Statement (0);
487         } else {
488             break;
489         }
490     }
491
492     /* Clean up the stack. */
493     if (!GotBreak) {
494         g_space (oursp - OldStack);
495     }
496     oursp = OldStack;
497
498     /* Emit references to imports/exports for this block */
499     EmitExternals ();
500
501     /* Leave the lexical level */
502     LeaveBlockLevel ();
503
504     return GotBreak;
505 }
506
507
508
509 int Statement (int* PendingToken)
510 /* Statement parser. Returns 1 if the statement does a return/break, returns
511  * 0 otherwise. If the PendingToken pointer is not NULL, the function will
512  * not skip the terminating token of the statement (closing brace or
513  * semicolon), but store true if there is a pending token, and false if there
514  * is none. The token is always checked, so there is no need for the caller to
515  * check this token, it must be skipped, however. If the argument pointer is
516  * NULL, the function will skip the token.
517  */
518 {
519     ExprDesc lval;
520     int GotBreak;
521
522     /* Assume no pending token */
523     if (PendingToken) {
524         *PendingToken = 0;
525     }
526
527     /* Check for a label */
528     if (CurTok.Tok == TOK_IDENT && NextTok.Tok == TOK_COLON) {
529
530         /* Special handling for a label */
531         DoLabel ();
532
533     } else {
534
535         switch (CurTok.Tok) {
536
537             case TOK_LCURLY:
538                 NextToken ();
539                 GotBreak = CompoundStatement ();
540                 CheckTok (TOK_RCURLY, "`{' expected", PendingToken);
541                 return GotBreak;
542
543             case TOK_IF:
544                 return IfStatement ();
545
546             case TOK_WHILE:
547                 WhileStatement ();
548                 break;
549
550             case TOK_DO:
551                 DoStatement ();
552                 break;
553
554             case TOK_SWITCH:
555                 SwitchStatement ();
556                 break;
557
558             case TOK_RETURN:
559                 ReturnStatement ();
560                 CheckSemi (PendingToken);
561                 return 1;
562
563             case TOK_BREAK:
564                 BreakStatement ();
565                 CheckSemi (PendingToken);
566                 return 1;
567
568             case TOK_CONTINUE:
569                 ContinueStatement ();
570                 CheckSemi (PendingToken);
571                 return 1;
572
573             case TOK_FOR:
574                 ForStatement ();
575                 break;
576
577             case TOK_GOTO:
578                 GotoStatement ();
579                 CheckSemi (PendingToken);
580                 return 1;
581
582             case TOK_SEMI:
583                 /* Ignore it */
584                 CheckSemi (PendingToken);
585                 break;
586
587             case TOK_PRAGMA:
588                 DoPragma ();
589                 break;
590
591             default:
592                 /* Actual statement */
593                 expression0 (&lval);
594                 CheckSemi (PendingToken);
595         }
596     }
597     return 0;
598 }
599
600
601
602