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