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