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