]> git.sur5r.net Git - cc65/blob - src/cc65/symtab.c
Make __fixargs__ an actual symbol table entry. Add a new pseudo variable
[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     Ullrich von Bassewitz                                        */
10 /*              Wacholderweg 14                                              */
11 /*              D-70597 Stuttgart                                            */
12 /* EMail:       uz@musoftware.de                                             */
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 "hashstr.h"
44 #include "xmalloc.h"
45
46 /* cc65 */
47 #include "asmcode.h"
48 #include "asmlabel.h"
49 #include "codegen.h"
50 #include "datatype.h"
51 #include "declare.h"
52 #include "error.h"
53 #include "funcdesc.h"
54 #include "global.h"
55 #include "symentry.h"
56 #include "typecmp.h"
57 #include "symtab.h"
58
59
60
61 /*****************************************************************************/
62 /*                                   Data                                    */
63 /*****************************************************************************/
64
65
66
67 /* An empty symbol table */
68 SymTable        EmptySymTab = {
69     0,          /* PrevTab */
70     0,          /* SymHead */
71     0,          /* SymTail */
72     0,          /* SymCount */
73     1,          /* Size */
74     { 0 }       /* Tab[1] */
75 };
76
77 /* Symbol table sizes */
78 #define SYMTAB_SIZE_GLOBAL      211U
79 #define SYMTAB_SIZE_FUNCTION     29U
80 #define SYMTAB_SIZE_BLOCK        13U
81 #define SYMTAB_SIZE_STRUCT       19U
82 #define SYMTAB_SIZE_LABEL         7U
83
84 /* Predefined lexical levels */
85 #define LEX_LEVEL_GLOBAL        1U
86
87 /* The current and root symbol tables */
88 static unsigned         LexicalLevel    = 0;    /* For safety checks */
89 static SymTable*        SymTab0         = 0;
90 static SymTable*        SymTab          = 0;
91 static SymTable*        TagTab0         = 0;
92 static SymTable*        TagTab          = 0;
93 static SymTable*        LabelTab        = 0;
94
95
96
97 /*****************************************************************************/
98 /*                              struct SymTable                              */
99 /*****************************************************************************/
100
101
102
103 static SymTable* NewSymTable (unsigned Size)
104 /* Create and return a symbol table for the given lexical level */
105 {
106     unsigned I;
107
108     /* Allocate memory for the table */
109     SymTable* S = xmalloc (sizeof (SymTable) + (Size-1) * sizeof (SymEntry*));
110
111     /* Initialize the symbol table structure */
112     S->PrevTab  = 0;
113     S->SymHead  = 0;
114     S->SymTail  = 0;
115     S->SymCount = 0;
116     S->Size     = Size;
117     for (I = 0; I < Size; ++I) {
118         S->Tab[I] = 0;
119     }
120
121     /* Return the symbol table */
122     return S;
123 }
124
125
126
127 static void FreeSymTable (SymTable* S)
128 /* Free the given symbo table including all symbols */
129 {
130     /* Free all symbols */
131     SymEntry* Sym = S->SymHead;
132     while (Sym) {
133         SymEntry* NextSym = Sym->NextSym;
134         FreeSymEntry (Sym);
135         Sym = NextSym;
136     }
137
138     /* Free the table itself */
139     xfree (S);
140 }
141
142
143
144 /*****************************************************************************/
145 /*                         Check symbols in a table                          */
146 /*****************************************************************************/
147
148
149
150 static void CheckSymTable (SymTable* Tab)
151 /* Check a symbol table for open references, unused symbols ... */
152 {
153     SymEntry* Entry = Tab->SymHead;
154     while (Entry) {
155
156         /* Get the storage flags for tne entry */
157         unsigned Flags = Entry->Flags;
158
159         /* Ignore typedef entries */
160         if ((Flags & SC_TYPEDEF) != SC_TYPEDEF) {
161
162             /* Check if the symbol is one with storage, and it if it was
163              * defined but not used.
164              */
165             if (((Flags & SC_AUTO) || (Flags & SC_STATIC)) && (Flags & SC_EXTERN) == 0) {
166                 if ((Flags & SC_DEF) && !(Flags & SC_REF)) {
167                     if (Flags & SC_PARAM) {
168                         Warning ("Parameter `%s' is never used", Entry->Name);
169                     } else {
170                         Warning ("`%s' is defined but never used", Entry->Name);
171                     }
172                 }
173             }
174
175             /* If the entry is a label, check if it was defined in the function */
176             if (Flags & SC_LABEL) {
177                 if ((Flags & SC_DEF) == 0) {
178                     /* Undefined label */
179                     Error ("Undefined label: `%s'", Entry->Name);
180                 } else if ((Flags & SC_REF) == 0) {
181                     /* Defined but not used */
182                     Warning ("`%s' is defined but never used", Entry->Name);
183                 }
184             }
185
186         }
187
188         /* Next entry */
189         Entry = Entry->NextSym;
190     }
191 }
192
193
194
195 /*****************************************************************************/
196 /*                        Handling of lexical levels                         */
197 /*****************************************************************************/
198
199
200
201 void EnterGlobalLevel (void)
202 /* Enter the program global lexical level */
203 {
204     /* Safety */
205     PRECONDITION (++LexicalLevel == LEX_LEVEL_GLOBAL);
206
207     /* Create and assign the symbol table */
208     SymTab0 = SymTab = NewSymTable (SYMTAB_SIZE_GLOBAL);
209
210     /* Create and assign the tag table */
211     TagTab0 = TagTab = NewSymTable (SYMTAB_SIZE_GLOBAL);
212 }
213
214
215
216 void LeaveGlobalLevel (void)
217 /* Leave the program global lexical level */
218 {
219     /* Safety */
220     PRECONDITION (LexicalLevel-- == LEX_LEVEL_GLOBAL);
221
222     /* Check the tables */
223     CheckSymTable (SymTab0);
224
225     /* Dump the tables if requested */
226     if (Debug) {
227         PrintSymTable (SymTab0, stdout, "Global symbol table");
228         PrintSymTable (TagTab0, stdout, "Global tag table");
229     }
230
231     /* Don't delete the symbol and struct tables! */
232     SymTab0 = SymTab = 0;
233     TagTab0 = TagTab = 0;
234 }
235
236
237
238 void EnterFunctionLevel (void)
239 /* Enter function lexical level */
240 {
241     SymTable* S;
242
243     /* New lexical level */
244     ++LexicalLevel;
245
246     /* Get a new symbol table and make it current */
247     S = NewSymTable (SYMTAB_SIZE_FUNCTION);
248     S->PrevTab = SymTab;
249     SymTab     = S;
250
251     /* Get a new tag table and make it current */
252     S = NewSymTable (SYMTAB_SIZE_FUNCTION);
253     S->PrevTab = TagTab;
254     TagTab  = S;
255
256     /* Create and assign a new label table */
257     LabelTab = NewSymTable (SYMTAB_SIZE_LABEL);
258 }
259
260
261
262 void RememberFunctionLevel (struct FuncDesc* F)
263 /* Remember the symbol tables for the level and leave the level without checks */
264 {
265     /* Leave the lexical level */
266     --LexicalLevel;
267
268     /* Remember the tables */
269     F->SymTab = SymTab;
270     F->TagTab = TagTab;
271
272     /* Don't delete the tables */
273     SymTab = SymTab->PrevTab;
274     TagTab = TagTab->PrevTab;
275 }
276
277
278
279 void ReenterFunctionLevel (struct FuncDesc* F)
280 /* Reenter the function lexical level using the existing tables from F */
281 {
282     /* New lexical level */
283     ++LexicalLevel;
284
285     /* Make the tables current again */
286     F->SymTab->PrevTab = SymTab;
287     SymTab = F->SymTab;
288
289     F->TagTab->PrevTab = TagTab;
290     TagTab = F->TagTab;
291
292     /* Create and assign a new label table */
293     LabelTab = NewSymTable (SYMTAB_SIZE_LABEL);
294 }
295
296
297
298 void LeaveFunctionLevel (void)
299 /* Leave function lexical level */
300 {
301     /* Leave the lexical level */
302     --LexicalLevel;
303
304     /* Check the tables */
305     CheckSymTable (SymTab);
306     CheckSymTable (LabelTab);
307
308     /* Drop the label table if it is empty */
309     if (LabelTab->SymCount == 0) {
310         FreeSymTable (LabelTab);
311     }
312
313     /* Don't delete the tables */
314     SymTab = SymTab->PrevTab;
315     TagTab = TagTab->PrevTab;
316     LabelTab  = 0;
317 }
318
319
320
321 void EnterBlockLevel (void)
322 /* Enter a nested block in a function */
323 {
324     SymTable* S;
325
326     /* New lexical level */
327     ++LexicalLevel;
328
329     /* Get a new symbol table and make it current */
330     S = NewSymTable (SYMTAB_SIZE_BLOCK);
331     S->PrevTab  = SymTab;
332     SymTab      = S;
333
334     /* Get a new tag table and make it current */
335     S = NewSymTable (SYMTAB_SIZE_BLOCK);
336     S->PrevTab = TagTab;
337     TagTab     = S;
338 }
339
340
341
342 void LeaveBlockLevel (void)
343 /* Leave a nested block in a function */
344 {
345     /* Leave the lexical level */
346     --LexicalLevel;
347
348     /* Check the tables */
349     CheckSymTable (SymTab);
350
351     /* Don't delete the tables */
352     SymTab = SymTab->PrevTab;
353     TagTab = TagTab->PrevTab;
354 }
355
356
357
358 void EnterStructLevel (void)
359 /* Enter a nested block for a struct definition */
360 {
361     SymTable* S;
362
363     /* Get a new symbol table and make it current. Note: Structs and enums
364      * nested in struct scope are NOT local to the struct but visible in the
365      * outside scope. So we will NOT create a new struct or enum table.
366      */
367     S = NewSymTable (SYMTAB_SIZE_BLOCK);
368     S->PrevTab  = SymTab;
369     SymTab      = S;
370 }
371
372
373
374 void LeaveStructLevel (void)
375 /* Leave a nested block for a struct definition */
376 {
377     /* Don't delete the table */
378     SymTab = SymTab->PrevTab;
379 }
380
381
382
383 /*****************************************************************************/
384 /*                              Find functions                               */
385 /*****************************************************************************/
386
387
388
389 static SymEntry* FindSymInTable (const SymTable* T, const char* Name, unsigned Hash)
390 /* Search for an entry in one table */
391 {
392     /* Get the start of the hash chain */
393     SymEntry* E = T->Tab [Hash % T->Size];
394     while (E) {
395         /* Compare the name */
396         if (strcmp (E->Name, Name) == 0) {
397             /* Found */
398             return E;
399         }
400         /* Not found, next entry in hash chain */
401         E = E->NextHash;
402     }
403
404     /* Not found */
405     return 0;
406 }
407
408
409
410 static SymEntry* FindSymInTree (const SymTable* Tab, const char* Name)
411 /* Find the symbol with the given name in the table tree that starts with T */
412 {
413     /* Get the hash over the name */
414     unsigned Hash = HashStr (Name);
415
416     /* Check all symbol tables for the symbol */
417     while (Tab) {
418         /* Try to find the symbol in this table */
419         SymEntry* E = FindSymInTable (Tab, Name, Hash);
420
421         /* Bail out if we found it */
422         if (E != 0) {
423             return E;
424         }
425
426         /* Repeat the search in the next higher lexical level */
427         Tab = Tab->PrevTab;
428     }
429
430     /* Not found */
431     return 0;
432 }
433
434
435
436 SymEntry* FindSym (const char* Name)
437 /* Find the symbol with the given name */
438 {
439     return FindSymInTree (SymTab, Name);
440 }
441
442
443
444 SymEntry* FindLocalSym (const char* Name)
445 /* Find the symbol with the given name in the current symbol table only */
446 {
447     return FindSymInTable (SymTab, Name, HashStr (Name));
448 }
449
450
451
452 SymEntry* FindTagSym (const char* Name)
453 /* Find the symbol with the given name in the tag table */
454 {
455     return FindSymInTree (TagTab, Name);
456 }
457
458
459
460 SymEntry* FindStructField (const type* Type, const char* Name)
461 /* Find a struct field in the fields list */
462 {
463     SymEntry* Field = 0;
464
465     /* The given type may actually be a pointer to struct */
466     if (Type[0] == T_PTR) {
467         ++Type;
468     }
469
470     /* Non-structs do not have any struct fields... */
471     if (IsClassStruct (Type)) {
472
473         const SymTable* Tab;
474
475         /* Get a pointer to the struct/union type */
476         const SymEntry* Struct = (const SymEntry*) Decode (Type+1);
477         CHECK (Struct != 0);
478
479         /* Get the field symbol table from the struct entry.
480          * Beware: The table may not exist.
481          */
482         Tab = Struct->V.S.SymTab;
483
484         /* Now search in the struct symbol table */
485         if (Tab) {
486             Field = FindSymInTable (Struct->V.S.SymTab, Name, HashStr (Name));
487         }
488     }
489
490     return Field;
491 }
492
493
494
495 /*****************************************************************************/
496 /*                       Add stuff to the symbol table                       */
497 /*****************************************************************************/
498
499
500
501 static void AddSymEntry (SymTable* T, SymEntry* S)
502 /* Add a symbol to a symbol table */
503 {
504     /* Get the hash value for the name */
505     unsigned Hash = HashStr (S->Name) % T->Size;
506
507     /* Insert the symbol into the list of all symbols in this level */
508     if (T->SymTail) {
509         T->SymTail->NextSym = S;
510     }
511     S->PrevSym = T->SymTail;
512     T->SymTail = S;
513     if (T->SymHead == 0) {
514         /* First symbol */
515         T->SymHead = S;
516     }
517     T->SymCount++;
518
519     /* Insert the symbol into the hash chain */
520     S->NextHash  = T->Tab[Hash];
521     T->Tab[Hash] = S;
522
523     /* Tell the symbol in which table it is */
524     S->Owner = T;
525 }
526
527
528
529 SymEntry* AddStructSym (const char* Name, unsigned Size, SymTable* Tab)
530 /* Add a struct/union entry and return it */
531 {
532     /* Do we have an entry with this name already? */
533     SymEntry* Entry = FindSymInTable (TagTab, Name, HashStr (Name));
534     if (Entry) {
535
536         /* We do have an entry. This may be a forward, so check it. */
537         if ((Entry->Flags & SC_STRUCT) == 0) {
538             /* Existing symbol is not a struct */
539             Error ("Symbol `%s' is already different kind", Name);
540         } else if (Size > 0 && Entry->V.S.Size > 0) {
541             /* Both structs are definitions. */
542             Error ("Multiple definition for `%s'", Name);
543         } else {
544             /* Define the struct size if it is given */
545             if (Size > 0) {
546                 Entry->V.S.SymTab = Tab;
547                 Entry->V.S.Size   = Size;
548             }
549         }
550
551     } else {
552
553         /* Create a new entry */
554         Entry = NewSymEntry (Name, SC_STRUCT);
555
556         /* Set the struct data */
557         Entry->V.S.SymTab = Tab;
558         Entry->V.S.Size   = Size;
559
560         /* Add it to the current table */
561         AddSymEntry (TagTab, Entry);
562     }
563
564     /* Return the entry */
565     return Entry;
566 }
567
568
569
570 SymEntry* AddEnumSym (const char* Name, int Val)
571 /* Add an enum symbol to the symbol table and return it */
572 {
573     /* Do we have an entry with this name already? */
574     SymEntry* Entry = FindSymInTable (SymTab, Name, HashStr (Name));
575     if (Entry) {
576         if (Entry->Flags != SC_ENUM) {
577             Error ("Symbol `%s' is already different kind", Name);
578         } else {
579             Error ("Multiple definition for `%s'", Name);
580         }
581         return Entry;
582     }
583
584     /* Create a new entry */
585     Entry = NewSymEntry (Name, SC_ENUM);
586
587     /* Enum values are ints */
588     Entry->Type = TypeDup (type_int);
589
590     /* Set the enum data */
591     Entry->V.EnumVal = Val;
592
593     /* Add the entry to the symbol table */
594     AddSymEntry (SymTab, Entry);
595
596     /* Return the entry */
597     return Entry;
598 }
599
600
601
602 SymEntry* AddLabelSym (const char* Name, unsigned Flags)
603 /* Add a goto label to the label table */
604 {
605     /* Do we have an entry with this name already? */
606     SymEntry* Entry = FindSymInTable (LabelTab, Name, HashStr (Name));
607     if (Entry) {
608
609         if ((Entry->Flags & SC_DEF) != 0 && (Flags & SC_DEF) != 0) {
610             /* Trying to define the label more than once */
611             Error ("Label `%s' is defined more than once", Name);
612         }
613         Entry->Flags |= Flags;
614
615     } else {
616
617         /* Create a new entry */
618         Entry = NewSymEntry (Name, SC_LABEL | Flags);
619
620         /* Set a new label number */
621         Entry->V.Label = GetLabel ();
622
623         /* Add the entry to the label table */
624         AddSymEntry (LabelTab, Entry);
625
626     }
627
628     /* Return the entry */
629     return Entry;
630 }
631
632
633
634 SymEntry* AddLocalSym (const char* Name, const type* Type, unsigned Flags, int Offs)
635 /* Add a local symbol and return the symbol entry */
636 {
637     /* Do we have an entry with this name already? */
638     SymEntry* Entry = FindSymInTable (SymTab, Name, HashStr (Name));
639     if (Entry) {
640
641         /* We have a symbol with this name already */
642         Error ("Multiple definition for `%s'", Name);
643
644     } else {
645
646         /* Create a new entry */
647         Entry = NewSymEntry (Name, Flags);
648
649         /* Set the symbol attributes */
650         Entry->Type   = TypeDup (Type);
651         Entry->V.Offs = Offs;
652
653         /* Add the entry to the symbol table */
654         AddSymEntry (SymTab, Entry);
655
656     }
657
658     /* Return the entry */
659     return Entry;
660 }
661
662
663
664 SymEntry* AddGlobalSym (const char* Name, const type* Type, unsigned Flags)
665 /* Add an external or global symbol to the symbol table and return the entry */
666 {
667     /* Functions must be inserted in the global symbol table */
668     SymTable* Tab = IsTypeFunc (Type)? SymTab0 : SymTab;
669
670     /* Do we have an entry with this name already? */
671     SymEntry* Entry = FindSymInTable (Tab, Name, HashStr (Name));
672     if (Entry) {
673
674         type* EType;
675
676         /* We have a symbol with this name already */
677         if (Entry->Flags & SC_TYPE) {
678             Error ("Multiple definition for `%s'", Name);
679             return Entry;
680         }
681
682         /* Get the type string of the existing symbol */
683         EType = Entry->Type;
684
685         /* If we are handling arrays, the old entry or the new entry may be an
686          * incomplete declaration. Accept this, and if the exsting entry is
687          * incomplete, complete it.
688          */
689         if (IsTypeArray (Type) && IsTypeArray (EType)) {
690
691             /* Get the array sizes */
692             unsigned Size  = Decode (Type + 1);
693             unsigned ESize = Decode (EType + 1);
694
695             if ((Size != 0 && ESize != 0) ||
696                 TypeCmp (Type+DECODE_SIZE+1, EType+DECODE_SIZE+1) < TC_EQUAL) {
697                 /* Types not identical: Conflicting types */
698                 Error ("Conflicting types for `%s'", Name);
699                 return Entry;
700             } else {
701                 /* Check if we have a size in the existing definition */
702                 if (ESize == 0) {
703                     /* Existing, size not given, use size from new def */
704                     Encode (EType + 1, Size);
705                 }
706             }
707
708         } else {
709             /* New type must be identical */
710             if (TypeCmp (EType, Type) < TC_EQUAL) {
711                 Error ("Conflicting types for `%s'", Name);
712                 return Entry;
713             }
714
715             /* In case of a function, use the new type descriptor, since it
716              * contains pointers to the new symbol tables that are needed if
717              * an actual function definition follows.
718              */
719             if (IsTypeFunc (Type)) {
720                 CopyEncode (Type+1, EType+1);
721             }
722         }
723
724         /* Add the new flags */
725         Entry->Flags |= Flags;
726
727     } else {
728
729         /* Create a new entry */
730         Entry = NewSymEntry (Name, Flags);
731
732         /* Set the symbol attributes */         
733         Entry->Type = TypeDup (Type);
734
735         /* Add the entry to the symbol table */
736         AddSymEntry (Tab, Entry);
737     }
738
739     /* Return the entry */
740     return Entry;
741 }
742
743
744
745 /*****************************************************************************/
746 /*                                   Code                                    */
747 /*****************************************************************************/
748
749
750
751 SymTable* GetSymTab (void)
752 /* Return the current symbol table */
753 {
754     return SymTab;
755 }
756
757
758
759 int SymIsLocal (SymEntry* Sym)
760 /* Return true if the symbol is defined in the highest lexical level */
761 {
762     return (Sym->Owner == SymTab || Sym->Owner == TagTab);
763 }
764
765
766
767 void MakeZPSym (const char* Name)
768 /* Mark the given symbol as zero page symbol */
769 {
770     /* Get the symbol table entry */
771     SymEntry* Entry = FindSymInTable (SymTab, Name, HashStr (Name));
772
773     /* Mark the symbol as zeropage */
774     if (Entry) {
775         Entry->Flags |= SC_ZEROPAGE;
776     } else {
777         Error ("Undefined symbol: `%s'", Name);
778     }
779 }
780
781
782
783 void PrintSymTable (const SymTable* Tab, FILE* F, const char* Header, ...)
784 /* Write the symbol table to the given file */
785 {
786     unsigned Len;
787     const SymEntry* Entry;
788
789     /* Print the header */
790     va_list ap;
791     va_start (ap, Header);
792     fputc ('\n', F);
793     Len = vfprintf (F, Header, ap);
794     va_end (ap);
795     fputc ('\n', F);
796
797     /* Underline the header */
798     while (Len--) {
799         fputc ('=', F);
800     }
801     fputc ('\n', F);
802
803     /* Dump the table */
804     Entry = Tab->SymHead;
805     if (Entry == 0) {
806         fprintf (F, "(empty)\n");
807     } else {
808         while (Entry) {
809             DumpSymEntry (F, Entry);
810             Entry = Entry->NextSym;
811         }
812     }
813     fprintf (F, "\n\n\n");
814 }
815
816
817
818 void EmitExternals (void)
819 /* Write import/export statements for external symbols */
820 {
821     SymEntry* Entry;
822
823     AddEmptyLine ();
824
825     Entry = SymTab->SymHead;
826     while (Entry) {
827         unsigned Flags = Entry->Flags;
828         if (Flags & SC_EXTERN) {
829             /* Only defined or referenced externs */
830             if ((Flags & SC_REF) != 0 && (Flags & SC_DEF) == 0) {
831                 /* An import */
832                 g_defimport (Entry->Name, Flags & SC_ZEROPAGE);
833             } else if (Flags & SC_DEF) {
834                 /* An export */
835                 g_defexport (Entry->Name, Flags & SC_ZEROPAGE);
836             }
837         }
838         Entry = Entry->NextSym;
839     }
840 }
841
842
843