]> git.sur5r.net Git - cc65/blob - src/cc65/symtab.c
87fad111b33b98ef37312b7786c96e5d3f5f65ba
[cc65] / src / cc65 / symtab.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 symtab.c                                  */
4 /*                                                                           */
5 /*              Symbol table management for the cc65 C compiler              */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000-2013, Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 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 <stdlib.h>
38 #include <stdarg.h>
39 #include <string.h>
40
41 /* common */
42 #include "check.h"
43 #include "debugflag.h"
44 #include "hashfunc.h"
45 #include "xmalloc.h"
46
47 /* cc65 */
48 #include "asmcode.h"
49 #include "asmlabel.h"
50 #include "codegen.h"
51 #include "datatype.h"
52 #include "declare.h"
53 #include "error.h"
54 #include "funcdesc.h"
55 #include "global.h"
56 #include "stackptr.h"
57 #include "symentry.h"
58 #include "typecmp.h"
59 #include "symtab.h"
60 #include "function.h"
61 #include "input.h"
62
63
64
65 /*****************************************************************************/
66 /*                                   Data                                    */
67 /*****************************************************************************/
68
69
70
71 /* An empty symbol table */
72 SymTable        EmptySymTab = {
73     0,          /* PrevTab */
74     0,          /* SymHead */
75     0,          /* SymTail */
76     0,          /* SymCount */
77     1,          /* Size */
78     { 0 }       /* Tab[1] */
79 };
80
81 /* Symbol table sizes */
82 #define SYMTAB_SIZE_GLOBAL      211U
83 #define SYMTAB_SIZE_FUNCTION     29U
84 #define SYMTAB_SIZE_BLOCK        13U
85 #define SYMTAB_SIZE_STRUCT       19U
86 #define SYMTAB_SIZE_LABEL         7U
87
88 /* The current and root symbol tables */
89 static unsigned         LexicalLevel    = 0;    /* For safety checks */
90 static SymTable*        SymTab0         = 0;
91 static SymTable*        SymTab          = 0;
92 static SymTable*        TagTab0         = 0;
93 static SymTable*        TagTab          = 0;
94 static SymTable*        LabelTab        = 0;
95
96
97
98 /*****************************************************************************/
99 /*                              struct SymTable                              */
100 /*****************************************************************************/
101
102
103
104 static SymTable* NewSymTable (unsigned Size)
105 /* Create and return a symbol table for the given lexical level */
106 {
107     unsigned I;
108
109     /* Allocate memory for the table */
110     SymTable* S = xmalloc (sizeof (SymTable) + (Size-1) * sizeof (SymEntry*));
111
112     /* Initialize the symbol table structure */
113     S->PrevTab  = 0;
114     S->SymHead  = 0;
115     S->SymTail  = 0;
116     S->SymCount = 0;
117     S->Size     = Size;
118     for (I = 0; I < Size; ++I) {
119         S->Tab[I] = 0;
120     }
121
122     /* Return the symbol table */
123     return S;
124 }
125
126
127
128 static void FreeSymTable (SymTable* S)
129 /* Free the given symbo table including all symbols */
130 {
131     /* Free all symbols */
132     SymEntry* Sym = S->SymHead;
133     while (Sym) {
134         SymEntry* NextSym = Sym->NextSym;
135         FreeSymEntry (Sym);
136         Sym = NextSym;
137     }
138
139     /* Free the table itself */
140     xfree (S);
141 }
142
143
144
145 /*****************************************************************************/
146 /*                         Check symbols in a table                          */
147 /*****************************************************************************/
148
149
150
151 static void CheckSymTable (SymTable* Tab)
152 /* Check a symbol table for open references, unused symbols ... */
153 {
154     SymEntry* Entry = Tab->SymHead;
155     while (Entry) {
156
157         /* Get the storage flags for tne entry */
158         unsigned Flags = Entry->Flags;
159
160         /* Ignore typedef entries */
161         if (!SymIsTypeDef (Entry)) {
162
163             /* Check if the symbol is one with storage, and it if it was
164             ** defined but not used.
165             */
166             if (((Flags & SC_AUTO) || (Flags & SC_STATIC)) && (Flags & SC_EXTERN) == 0) {
167                 if (SymIsDef (Entry) && !SymIsRef (Entry) &&
168                     !SymHasAttr (Entry, atUnused)) {
169                     if (Flags & SC_PARAM) {
170                         if (IS_Get (&WarnUnusedParam)) {
171                             Warning ("Parameter `%s' is never used", Entry->Name);
172                         }
173                     } else {
174                         if (IS_Get (&WarnUnusedVar)) {
175                             Warning ("`%s' is defined but never used", Entry->Name);
176                         }
177                     }
178                 }
179             }
180
181             /* If the entry is a label, check if it was defined in the function */
182             if (Flags & SC_LABEL) {
183                 if (!SymIsDef (Entry)) {
184                     /* Undefined label */
185                     Error ("Undefined label: `%s'", Entry->Name);
186                 } else if (!SymIsRef (Entry)) {
187                     /* Defined but not used */
188                     if (IS_Get (&WarnUnusedLabel)) {
189                         Warning ("`%s' is defined but never used", Entry->Name);
190                     }
191                 }
192             }
193
194         }
195
196         /* Next entry */
197         Entry = Entry->NextSym;
198     }
199 }
200
201
202
203 /*****************************************************************************/
204 /*                        Handling of lexical levels                         */
205 /*****************************************************************************/
206
207
208
209 unsigned GetLexicalLevel (void)
210 /* Return the current lexical level */
211 {
212     return LexicalLevel;
213 }
214
215
216
217 void EnterGlobalLevel (void)
218 /* Enter the program global lexical level */
219 {
220     /* Safety */
221     PRECONDITION (++LexicalLevel == LEX_LEVEL_GLOBAL);
222
223     /* Create and assign the symbol table */
224     SymTab0 = SymTab = NewSymTable (SYMTAB_SIZE_GLOBAL);
225
226     /* Create and assign the tag table */
227     TagTab0 = TagTab = NewSymTable (SYMTAB_SIZE_GLOBAL);
228 }
229
230
231
232 void LeaveGlobalLevel (void)
233 /* Leave the program global lexical level */
234 {
235     /* Safety */
236     PRECONDITION (LexicalLevel-- == LEX_LEVEL_GLOBAL);
237
238     /* Check the tables */
239     CheckSymTable (SymTab0);
240
241     /* Dump the tables if requested */
242     if (Debug) {
243         PrintSymTable (SymTab0, stdout, "Global symbol table");
244         PrintSymTable (TagTab0, stdout, "Global tag table");
245     }
246
247     /* Don't delete the symbol and struct tables! */
248     SymTab = 0;
249     TagTab = 0;
250 }
251
252
253
254 void EnterFunctionLevel (void)
255 /* Enter function lexical level */
256 {
257     SymTable* S;
258
259     /* New lexical level */
260     ++LexicalLevel;
261
262     /* Get a new symbol table and make it current */
263     S = NewSymTable (SYMTAB_SIZE_FUNCTION);
264     S->PrevTab = SymTab;
265     SymTab     = S;
266
267     /* Get a new tag table and make it current */
268     S = NewSymTable (SYMTAB_SIZE_FUNCTION);
269     S->PrevTab = TagTab;
270     TagTab  = S;
271
272     /* Create and assign a new label table */
273     S = NewSymTable (SYMTAB_SIZE_LABEL);
274     S->PrevTab = LabelTab;
275     LabelTab = S;
276 }
277
278
279
280 void RememberFunctionLevel (struct FuncDesc* F)
281 /* Remember the symbol tables for the level and leave the level without checks */
282 {
283     /* Leave the lexical level */
284     --LexicalLevel;
285
286     /* Remember the tables */
287     F->SymTab = SymTab;
288     F->TagTab = TagTab;
289
290     /* Don't delete the tables */
291     SymTab = SymTab->PrevTab;
292     TagTab = TagTab->PrevTab;
293     LabelTab = LabelTab->PrevTab;
294 }
295
296
297
298 void ReenterFunctionLevel (struct FuncDesc* F)
299 /* Reenter the function lexical level using the existing tables from F */
300 {
301     /* New lexical level */
302     ++LexicalLevel;
303
304     /* Make the tables current again */
305     F->SymTab->PrevTab = SymTab;
306     SymTab = F->SymTab;
307
308     F->TagTab->PrevTab = TagTab;
309     TagTab = F->TagTab;
310
311     /* Create and assign a new label table */
312     LabelTab = NewSymTable (SYMTAB_SIZE_LABEL);
313 }
314
315
316
317 void LeaveFunctionLevel (void)
318 /* Leave function lexical level */
319 {
320     /* Leave the lexical level */
321     --LexicalLevel;
322
323     /* Check the tables */
324     CheckSymTable (SymTab);
325     CheckSymTable (LabelTab);
326
327     /* Drop the label table if it is empty */
328     if (LabelTab->SymCount == 0) {
329         FreeSymTable (LabelTab);
330     }
331
332     /* Don't delete the tables */
333     SymTab = SymTab->PrevTab;
334     TagTab = TagTab->PrevTab;
335     LabelTab  = 0;
336 }
337
338
339
340 void EnterBlockLevel (void)
341 /* Enter a nested block in a function */
342 {
343     SymTable* S;
344
345     /* New lexical level */
346     ++LexicalLevel;
347
348     /* Get a new symbol table and make it current */
349     S = NewSymTable (SYMTAB_SIZE_BLOCK);
350     S->PrevTab  = SymTab;
351     SymTab      = S;
352
353     /* Get a new tag table and make it current */
354     S = NewSymTable (SYMTAB_SIZE_BLOCK);
355     S->PrevTab = TagTab;
356     TagTab     = S;
357 }
358
359
360
361 void LeaveBlockLevel (void)
362 /* Leave a nested block in a function */
363 {
364     /* Leave the lexical level */
365     --LexicalLevel;
366
367     /* Check the tables */
368     CheckSymTable (SymTab);
369
370     /* Don't delete the tables */
371     SymTab = SymTab->PrevTab;
372     TagTab = TagTab->PrevTab;
373 }
374
375
376
377 void EnterStructLevel (void)
378 /* Enter a nested block for a struct definition */
379 {
380     SymTable* S;
381
382     /* Get a new symbol table and make it current. Note: Structs and enums
383     ** nested in struct scope are NOT local to the struct but visible in the
384     ** outside scope. So we will NOT create a new struct or enum table.
385     */
386     S = NewSymTable (SYMTAB_SIZE_BLOCK);
387     S->PrevTab  = SymTab;
388     SymTab      = S;
389 }
390
391
392
393 void LeaveStructLevel (void)
394 /* Leave a nested block for a struct definition */
395 {
396     /* Don't delete the table */
397     SymTab = SymTab->PrevTab;
398 }
399
400
401
402 /*****************************************************************************/
403 /*                              Find functions                               */
404 /*****************************************************************************/
405
406
407
408 static SymEntry* FindSymInTable (const SymTable* T, const char* Name, unsigned Hash)
409 /* Search for an entry in one table */
410 {
411     /* Get the start of the hash chain */
412     SymEntry* E = T->Tab [Hash % T->Size];
413     while (E) {
414         /* Compare the name */
415         if (strcmp (E->Name, Name) == 0) {
416             /* Found */
417             return E;
418         }
419         /* Not found, next entry in hash chain */
420         E = E->NextHash;
421     }
422
423     /* Not found */
424     return 0;
425 }
426
427
428
429 static SymEntry* FindSymInTree (const SymTable* Tab, const char* Name)
430 /* Find the symbol with the given name in the table tree that starts with T */
431 {
432     /* Get the hash over the name */
433     unsigned Hash = HashStr (Name);
434
435     /* Check all symbol tables for the symbol */
436     while (Tab) {
437         /* Try to find the symbol in this table */
438         SymEntry* E = FindSymInTable (Tab, Name, Hash);
439
440         /* Bail out if we found it */
441         if (E != 0) {
442             return E;
443         }
444
445         /* Repeat the search in the next higher lexical level */
446         Tab = Tab->PrevTab;
447     }
448
449     /* Not found */
450     return 0;
451 }
452
453
454
455 SymEntry* FindSym (const char* Name)
456 /* Find the symbol with the given name */
457 {
458     return FindSymInTree (SymTab, Name);
459 }
460
461
462
463 SymEntry* FindGlobalSym (const char* Name)
464 /* Find the symbol with the given name in the global symbol table only */
465 {
466     return FindSymInTable (SymTab0, Name, HashStr (Name));
467 }
468
469
470
471 SymEntry* FindLocalSym (const char* Name)
472 /* Find the symbol with the given name in the current symbol table only */
473 {
474     return FindSymInTable (SymTab, Name, HashStr (Name));
475 }
476
477
478
479 SymEntry* FindTagSym (const char* Name)
480 /* Find the symbol with the given name in the tag table */
481 {
482     return FindSymInTree (TagTab, Name);
483 }
484
485
486
487 SymEntry* FindStructField (const Type* T, const char* Name)
488 /* Find a struct field in the fields list */
489 {
490     SymEntry* Field = 0;
491
492     /* The given type may actually be a pointer to struct */
493     if (IsTypePtr (T)) {
494         ++T;
495     }
496
497     /* Non-structs do not have any struct fields... */
498     if (IsClassStruct (T)) {
499
500         /* Get a pointer to the struct/union type */
501         const SymEntry* Struct = GetSymEntry (T);
502         CHECK (Struct != 0);
503
504         /* Now search in the struct symbol table. Beware: The table may not
505         ** exist.
506         */
507         if (Struct->V.S.SymTab) {
508             Field = FindSymInTable (Struct->V.S.SymTab, Name, HashStr (Name));
509         }
510     }
511
512     return Field;
513 }
514
515
516
517 /*****************************************************************************/
518 /*                       Add stuff to the symbol table                       */
519 /*****************************************************************************/
520
521
522
523 static void AddSymEntry (SymTable* T, SymEntry* S)
524 /* Add a symbol to a symbol table */
525 {
526     /* Get the hash value for the name */
527     unsigned Hash = HashStr (S->Name) % T->Size;
528
529     /* Insert the symbol into the list of all symbols in this level */
530     if (T->SymTail) {
531         T->SymTail->NextSym = S;
532     }
533     S->PrevSym = T->SymTail;
534     T->SymTail = S;
535     if (T->SymHead == 0) {
536         /* First symbol */
537         T->SymHead = S;
538     }
539     ++T->SymCount;
540
541     /* Insert the symbol into the hash chain */
542     S->NextHash  = T->Tab[Hash];
543     T->Tab[Hash] = S;
544
545     /* Tell the symbol in which table it is */
546     S->Owner = T;
547 }
548
549
550
551 SymEntry* AddStructSym (const char* Name, unsigned Type, unsigned Size, SymTable* Tab)
552 /* Add a struct/union entry and return it */
553 {
554     SymEntry* Entry;
555
556     /* Type must be struct or union */
557     PRECONDITION (Type == SC_STRUCT || Type == SC_UNION);
558
559     /* Do we have an entry with this name already? */
560     Entry = FindSymInTable (TagTab, Name, HashStr (Name));
561     if (Entry) {
562
563         /* We do have an entry. This may be a forward, so check it. */
564         if ((Entry->Flags & SC_TYPEMASK) != Type) {
565             /* Existing symbol is not a struct */
566             Error ("Symbol `%s' is already different kind", Name);
567         } else if (Size > 0 && Entry->V.S.Size > 0) {
568             /* Both structs are definitions. */
569             Error ("Multiple definition for `%s'", Name);
570         } else {
571             /* Define the struct size if it is given */
572             if (Size > 0) {
573                 Entry->V.S.SymTab = Tab;
574                 Entry->V.S.Size   = Size;
575             }
576         }
577
578     } else {
579
580         /* Create a new entry */
581         Entry = NewSymEntry (Name, Type);
582
583         /* Set the struct data */
584         Entry->V.S.SymTab = Tab;
585         Entry->V.S.Size   = Size;
586
587         /* Add it to the current table */
588         AddSymEntry (TagTab, Entry);
589     }
590
591     /* Return the entry */
592     return Entry;
593 }
594
595
596
597 SymEntry* AddBitField (const char* Name, unsigned Offs, unsigned BitOffs, unsigned Width)
598 /* Add a bit field to the local symbol table and return the symbol entry */
599 {
600     /* Do we have an entry with this name already? */
601     SymEntry* Entry = FindSymInTable (SymTab, Name, HashStr (Name));
602     if (Entry) {
603
604         /* We have a symbol with this name already */
605         Error ("Multiple definition for `%s'", Name);
606
607     } else {
608
609         /* Create a new entry */
610         Entry = NewSymEntry (Name, SC_BITFIELD);
611
612         /* Set the symbol attributes. Bit-fields are always of type unsigned */
613         Entry->Type         = type_uint;
614         Entry->V.B.Offs     = Offs;
615         Entry->V.B.BitOffs  = BitOffs;
616         Entry->V.B.BitWidth = Width;
617
618         /* Add the entry to the symbol table */
619         AddSymEntry (SymTab, Entry);
620
621     }
622
623     /* Return the entry */
624     return Entry;
625 }
626
627
628
629 SymEntry* AddConstSym (const char* Name, const Type* T, unsigned Flags, long Val)
630 /* Add an constant symbol to the symbol table and return it */
631 {
632     /* Enums must be inserted in the global symbol table */
633     SymTable* Tab = ((Flags & SC_ENUM) == SC_ENUM)? SymTab0 : SymTab;
634
635     /* Do we have an entry with this name already? */
636     SymEntry* Entry = FindSymInTable (Tab, Name, HashStr (Name));
637     if (Entry) {
638         if ((Entry->Flags & SC_CONST) != SC_CONST) {
639             Error ("Symbol `%s' is already different kind", Name);
640         } else {
641             Error ("Multiple definition for `%s'", Name);
642         }
643         return Entry;
644     }
645
646     /* Create a new entry */
647     Entry = NewSymEntry (Name, Flags);
648
649     /* Enum values are ints */
650     Entry->Type = TypeDup (T);
651
652     /* Set the enum data */
653     Entry->V.ConstVal = Val;
654
655     /* Add the entry to the symbol table */
656     AddSymEntry (Tab, Entry);
657
658     /* Return the entry */
659     return Entry;
660 }
661
662
663 DefOrRef* AddDefOrRef(SymEntry* E, unsigned Flags)
664 /* Add definition or reference to the SymEntry and preserve its attributes */
665 {
666     DefOrRef *DOR;
667
668     DOR = xmalloc (sizeof (DefOrRef));
669     CollAppend (E->V.L.DefsOrRefs, DOR);
670     DOR->Line = GetCurrentLine ();
671     DOR->LocalsBlockId = (long)CollLast (&CurrentFunc->LocalsBlockStack);
672     DOR->Flags = Flags;
673     DOR->StackPtr = StackPtr;
674     DOR->Depth = CollCount (&CurrentFunc->LocalsBlockStack);
675     DOR->LateSP_Label = GetLocalLabel ();
676
677     return DOR;
678 }
679
680 SymEntry* AddLabelSym (const char* Name, unsigned Flags)
681 /* Add a goto label to the label table */
682 {
683     unsigned i;
684     DefOrRef *DOR, *NewDOR;
685     /* We juggle it so much that a shortcut will help with clarity */
686     Collection *AIC = &CurrentFunc->LocalsBlockStack;
687
688     /* Do we have an entry with this name already? */
689     SymEntry* Entry = FindSymInTable (LabelTab, Name, HashStr (Name));
690     if (Entry) {
691
692         if (SymIsDef (Entry) && (Flags & SC_DEF) != 0) {
693             /* Trying to define the label more than once */
694             Error ("Label `%s' is defined more than once", Name);
695         }
696
697         NewDOR = AddDefOrRef (Entry, Flags);
698
699         /* Walk through all occurrences of the label so far and evaluate
700         ** their relationship with the one passed to the function.
701         */
702         for (i = 0; i < CollCount (Entry->V.L.DefsOrRefs); i++) {
703             DOR = CollAt (Entry->V.L.DefsOrRefs, i);
704
705             if ((DOR->Flags & SC_DEF) && (Flags & SC_REF) && (Flags & SC_GOTO)) {
706                 /* We're processing a goto and here is its destination label.
707                 ** This means the difference between SP values is already known,
708                 ** so we simply emit the SP adjustment code.
709                 */
710                 if (StackPtr != DOR->StackPtr) {
711                     g_space (StackPtr - DOR->StackPtr);
712                 }
713
714                 /* Are we jumping into a block with initalization of an object that
715                 ** has automatic storage duration? Let's emit a warning.
716                 */
717                 if ((long)CollLast (AIC) != DOR->LocalsBlockId &&
718                     (CollCount (AIC) < DOR->Depth ||
719                     (long)CollAt (AIC, DOR->Depth - 1) != DOR->LocalsBlockId)) {
720                     Warning ("Goto at line %d to label %s jumps into a block with "
721                     "initialization of an object that has automatic storage duration",
722                     GetCurrentLine (), Name);
723                 }
724             }
725
726
727             if ((DOR->Flags & SC_REF) && (DOR->Flags & SC_GOTO) && (Flags & SC_DEF)) {
728                 /* We're processing a label, let's update all gotos encountered
729                 ** so far
730                 */
731                 g_userodata();
732                 g_defdatalabel (DOR->LateSP_Label);
733                 g_defdata (CF_CONST | CF_INT, StackPtr - DOR->StackPtr, 0);
734
735                 /* Are we jumping into a block with initalization of an object that
736                 ** has automatic storage duration? Let's emit a warning.
737                 */
738                 if ((long)CollLast (AIC) != DOR->LocalsBlockId &&
739                     (CollCount (AIC) >= DOR->Depth ||
740                     (long)CollLast (AIC) >= (long)DOR->Line))
741                     Warning ("Goto at line %d to label %s jumps into a block with "
742                     "initialization of an object that has automatic storage duration",
743                     DOR->Line, Name);
744              }
745
746         }
747
748         Entry->Flags |= Flags;
749
750     } else {
751
752         /* Create a new entry */
753         Entry = NewSymEntry (Name, SC_LABEL | Flags);
754
755         /* Set a new label number */
756         Entry->V.L.Label = GetLocalLabel ();
757
758         /* Create Collection for label definition and references */
759         Entry->V.L.DefsOrRefs = NewCollection ();
760         NewDOR = AddDefOrRef (Entry, Flags);
761
762         /* Generate the assembler name of the label */
763         Entry->AsmName = xstrdup (LocalLabelName (Entry->V.L.Label));
764
765         /* Add the entry to the label table */
766         AddSymEntry (LabelTab, Entry);
767
768     }
769
770     /* We are processing a goto, but the label has not yet been defined */
771     if (!SymIsDef (Entry) && (Flags & SC_REF) && (Flags & SC_GOTO)) {
772         g_lateadjustSP (NewDOR->LateSP_Label);
773     }
774
775     /* Return the entry */
776     return Entry;
777 }
778
779
780
781 SymEntry* AddLocalSym (const char* Name, const Type* T, unsigned Flags, int Offs)
782 /* Add a local symbol and return the symbol entry */
783 {
784     /* Do we have an entry with this name already? */
785     SymEntry* Entry = FindSymInTable (SymTab, Name, HashStr (Name));
786     if (Entry) {
787
788         /* We have a symbol with this name already */
789         Error ("Multiple definition for `%s'", Name);
790
791     } else {
792
793         /* Create a new entry */
794         Entry = NewSymEntry (Name, Flags);
795
796         /* Set the symbol attributes */
797         Entry->Type = TypeDup (T);
798         if ((Flags & SC_AUTO) == SC_AUTO) {
799             Entry->V.Offs = Offs;
800         } else if ((Flags & SC_REGISTER) == SC_REGISTER) {
801             Entry->V.R.RegOffs  = Offs;
802             Entry->V.R.SaveOffs = StackPtr;
803         } else if ((Flags & SC_EXTERN) == SC_EXTERN) {
804             Entry->V.L.Label = Offs;
805             SymSetAsmName (Entry);
806         } else if ((Flags & SC_STATIC) == SC_STATIC) {
807             /* Generate the assembler name from the label number */
808             Entry->V.L.Label = Offs;
809             Entry->AsmName = xstrdup (LocalLabelName (Entry->V.L.Label));
810         } else if ((Flags & SC_STRUCTFIELD) == SC_STRUCTFIELD) {
811             Entry->V.Offs = Offs;
812         } else {
813             Internal ("Invalid flags in AddLocalSym: %04X", Flags);
814         }
815
816         /* Add the entry to the symbol table */
817         AddSymEntry (SymTab, Entry);
818
819     }
820
821     /* Return the entry */
822     return Entry;
823 }
824
825
826
827 SymEntry* AddGlobalSym (const char* Name, const Type* T, unsigned Flags)
828 /* Add an external or global symbol to the symbol table and return the entry */
829 {
830     /* There is some special handling for functions, so check if it is one */
831     int IsFunc = IsTypeFunc (T);
832
833     /* Functions must be inserted in the global symbol table */
834     SymTable* Tab = IsFunc? SymTab0 : SymTab;
835
836     /* Do we have an entry with this name already? */
837     SymEntry* Entry = FindSymInTable (Tab, Name, HashStr (Name));
838     if (Entry) {
839
840         Type* EType;
841
842         /* We have a symbol with this name already */
843         if (Entry->Flags & SC_TYPE) {
844             Error ("Multiple definition for `%s'", Name);
845             return Entry;
846         }
847
848         /* Get the type string of the existing symbol */
849         EType = Entry->Type;
850
851         /* If we are handling arrays, the old entry or the new entry may be an
852         ** incomplete declaration. Accept this, and if the exsting entry is
853         ** incomplete, complete it.
854         */
855         if (IsTypeArray (T) && IsTypeArray (EType)) {
856
857             /* Get the array sizes */
858             long Size  = GetElementCount (T);
859             long ESize = GetElementCount (EType);
860
861             if ((Size != UNSPECIFIED && ESize != UNSPECIFIED && Size != ESize) ||
862                 TypeCmp (T + 1, EType + 1) < TC_EQUAL) {
863                 /* Types not identical: Conflicting types */
864                 Error ("Conflicting types for `%s'", Name);
865                 return Entry;
866             } else {
867                 /* Check if we have a size in the existing definition */
868                 if (ESize == UNSPECIFIED) {
869                     /* Existing, size not given, use size from new def */
870                     SetElementCount (EType, Size);
871                 }
872             }
873
874         } else {
875             /* New type must be identical */
876             if (TypeCmp (EType, T) < TC_EQUAL) {
877                 Error ("Conflicting types for `%s'", Name);
878                 return Entry;
879             }
880
881             /* In case of a function, use the new type descriptor, since it
882             ** contains pointers to the new symbol tables that are needed if
883             ** an actual function definition follows. Be sure not to use the
884             ** new descriptor if it contains a function declaration with an
885             ** empty parameter list.
886             */
887             if (IsFunc) {
888                 /* Get the function descriptor from the new type */
889                 FuncDesc* F = GetFuncDesc (T);
890                 /* Use this new function descriptor if it doesn't contain
891                 ** an empty parameter list.
892                 */
893                 if ((F->Flags & FD_EMPTY) == 0) {
894                     Entry->V.F.Func = F;
895                     SetFuncDesc (EType, F);
896                 }
897             }
898         }
899
900         /* If a static declaration follows a non-static declaration, then
901         ** warn about the conflict.  (It will compile a public declaration.)
902         */
903         if ((Flags & SC_EXTERN) == 0 && (Entry->Flags & SC_EXTERN) != 0) {
904             Warning ("static declaration follows non-static declaration of `%s'.", Name);
905         }
906
907         /* An extern declaration must not change the current linkage. */
908         if (IsFunc || (Flags & (SC_EXTERN | SC_STORAGE)) == SC_EXTERN) {
909             Flags &= ~SC_EXTERN;
910         }
911
912         /* If a public declaration follows a static declaration, then
913         ** warn about the conflict.  (It will compile a public declaration.)
914         */
915         if ((Flags & SC_EXTERN) != 0 && (Entry->Flags & SC_EXTERN) == 0) {
916             Warning ("public declaration follows static declaration of `%s'.", Name);
917         }
918
919         /* Add the new flags */
920         Entry->Flags |= Flags;
921
922     } else {
923
924         /* Create a new entry */
925         Entry = NewSymEntry (Name, Flags);
926
927         /* Set the symbol attributes */
928         Entry->Type = TypeDup (T);
929
930         /* If this is a function, set the function descriptor and clear
931         ** additional fields.
932         */
933         if (IsFunc) {
934             Entry->V.F.Func = GetFuncDesc (Entry->Type);
935             Entry->V.F.Seg  = 0;
936         }
937
938         /* Add the assembler name of the symbol */
939         SymSetAsmName (Entry);
940
941         /* Add the entry to the symbol table */
942         AddSymEntry (Tab, Entry);
943     }
944
945     /* Return the entry */
946     return Entry;
947 }
948
949
950
951 /*****************************************************************************/
952 /*                                   Code                                    */
953 /*****************************************************************************/
954
955
956
957 SymTable* GetSymTab (void)
958 /* Return the current symbol table */
959 {
960     return SymTab;
961 }
962
963
964
965 SymTable* GetGlobalSymTab (void)
966 /* Return the global symbol table */
967 {
968     return SymTab0;
969 }
970
971
972
973 int SymIsLocal (SymEntry* Sym)
974 /* Return true if the symbol is defined in the highest lexical level */
975 {
976     return (Sym->Owner == SymTab || Sym->Owner == TagTab);
977 }
978
979
980
981 void MakeZPSym (const char* Name)
982 /* Mark the given symbol as zero page symbol */
983 {
984     /* Get the symbol table entry */
985     SymEntry* Entry = FindSymInTable (SymTab, Name, HashStr (Name));
986
987     /* Mark the symbol as zeropage */
988     if (Entry) {
989         Entry->Flags |= SC_ZEROPAGE;
990     } else {
991         Error ("Undefined symbol: `%s'", Name);
992     }
993 }
994
995
996
997 void PrintSymTable (const SymTable* Tab, FILE* F, const char* Header, ...)
998 /* Write the symbol table to the given file */
999 {
1000     unsigned Len;
1001     const SymEntry* Entry;
1002
1003     /* Print the header */
1004     va_list ap;
1005     va_start (ap, Header);
1006     fputc ('\n', F);
1007     Len = vfprintf (F, Header, ap);
1008     va_end (ap);
1009     fputc ('\n', F);
1010
1011     /* Underline the header */
1012     while (Len--) {
1013         fputc ('=', F);
1014     }
1015     fputc ('\n', F);
1016
1017     /* Dump the table */
1018     Entry = Tab->SymHead;
1019     if (Entry == 0) {
1020         fprintf (F, "(empty)\n");
1021     } else {
1022         while (Entry) {
1023             DumpSymEntry (F, Entry);
1024             Entry = Entry->NextSym;
1025         }
1026     }
1027     fprintf (F, "\n\n\n");
1028 }
1029
1030
1031
1032 void EmitExternals (void)
1033 /* Write import/export statements for external symbols */
1034 {
1035     SymEntry* Entry;
1036
1037     Entry = SymTab->SymHead;
1038     while (Entry) {
1039         unsigned Flags = Entry->Flags;
1040         if (Flags & SC_EXTERN) {
1041             /* Only defined or referenced externs */
1042             if (SymIsRef (Entry) && !SymIsDef (Entry)) {
1043                 /* An import */
1044                 g_defimport (Entry->Name, Flags & SC_ZEROPAGE);
1045             } else if (SymIsDef (Entry)) {
1046                 /* An export */
1047                 g_defexport (Entry->Name, Flags & SC_ZEROPAGE);
1048             }
1049         }
1050         Entry = Entry->NextSym;
1051     }
1052 }
1053
1054
1055
1056 void EmitDebugInfo (void)
1057 /* Emit debug infos for the locals of the current scope */
1058 {
1059     const char* Head;
1060     const SymEntry* Sym;
1061
1062     /* Output info for locals if enabled */
1063     if (DebugInfo) {
1064         /* For cosmetic reasons in the output file, we will insert two tabs
1065         ** on global level and just one on local level.
1066         */
1067         if (LexicalLevel == LEX_LEVEL_GLOBAL) {
1068             Head = "\t.dbg\t\tsym";
1069         } else {
1070             Head = "\t.dbg\tsym";
1071         }
1072         Sym = SymTab->SymHead;
1073         while (Sym) {
1074             if ((Sym->Flags & (SC_CONST|SC_TYPE)) == 0) {
1075                 if (Sym->Flags & SC_AUTO) {
1076                     AddTextLine ("%s, \"%s\", \"00\", auto, %d",
1077                                  Head, Sym->Name, Sym->V.Offs);
1078                 } else if (Sym->Flags & SC_REGISTER) {
1079                     AddTextLine ("%s, \"%s\", \"00\", register, \"regbank\", %d",
1080                                  Head, Sym->Name, Sym->V.R.RegOffs);
1081
1082                 } else if (SymIsRef (Sym) && !SymIsDef (Sym)) {
1083                     AddTextLine ("%s, \"%s\", \"00\", %s, \"%s\"",
1084                                  Head, Sym->Name,
1085                                  (Sym->Flags & SC_EXTERN)? "extern" : "static",
1086                                  Sym->AsmName);
1087                 }
1088             }
1089             Sym = Sym->NextSym;
1090         }
1091     }
1092 }