]> git.sur5r.net Git - cc65/blob - src/ca65html/ca65html
Fixed a problem with MagerValps changes.
[cc65] / src / ca65html / ca65html
1 #!/usr/bin/perl
2 ###############################################################################
3 #                                                                             #
4 #                                   main.c                                    #
5 #                                                                             #
6 #                      Convert a ca65 source into HTML                        #
7 #                                                                             #
8 #                                                                             #
9 #                                                                             #
10 #  (C) 2000-2007 Ullrich von Bassewitz                                        #
11 #                RĂ·merstrasse 52                                              #
12 #                D-70794 Filderstadt                                          #
13 #  EMail:        uz@cc65.org                                                  #
14 #                                                                             #
15 #                                                                             #
16 #  This software is provided 'as-is', without any expressed or implied        #
17 #  warranty.  In no event will the authors be held liable for any damages     #
18 #  arising from the use of this software.                                     #
19 #                                                                             #
20 #  Permission is granted to anyone to use this software for any purpose,      #
21 #  including commercial applications, and to alter it and redistribute it     #
22 #  freely, subject to the following restrictions:                             #
23 #                                                                             #
24 #  1. The origin of this software must not be misrepresented; you must not    #
25 #     claim that you wrote the original software. If you use this software    #
26 #     in a product, an acknowledgment in the product documentation would be   #
27 #     appreciated but is not required.                                        #
28 #  2. Altered source versions must be plainly marked as such, and must not    #
29 #     be misrepresented as being the original software.                       #
30 #  3. This notice may not be removed or altered from any source               #
31 #     distribution.                                                           #
32 #                                                                             #
33 ###############################################################################
34
35
36
37 # Things currently missing:
38 #
39 #   - Scoping with .proc/.endproc
40 #   - .global is ignored
41 #   - .constructor/.destructor/.condes dito
42 #   - .ignorecase is ignored, labels are always case sensitive
43 #   - .include handling (difficult)
44 #   - The global namespace operator ::
45 #
46
47
48
49 use strict 'vars';
50 use warnings;
51
52 # Modules
53 use Getopt::Long;
54
55
56
57 #-----------------------------------------------------------------------------#
58 #                                  Variables                                  #
59 # ----------------------------------------------------------------------------#
60
61
62
63 # Global variables
64 my %Files           = ();           # List of all files.
65 my $FileCount       = 0;            # Number of input files
66 my %Exports         = ();           # List of exported symbols.
67 my %Imports         = ();           # List of imported symbols.
68 my %Labels          = ();           # List of all labels
69 my $LabelNum        = 0;            # Counter to generate unique labels
70
71 # Command line options
72 my $BGColor         = "#FFFFFF";    # Background color
73 my $Colorize        = 0;            # Colorize the output
74 my $CommentColor    = "#B22222";    # Color for comments
75 my $CRefs           = 0;            # Add references to the C file
76 my $CtrlColor       = "#228B22";    # Color for control directives
77 my $CvtTabs         = 0;            # Convert tabs to spaces
78 my $Debug           = 0;            # No debugging
79 my $Help            = 0;            # Help flag
80 my $HTMLDir         = "";           # Directory in which to create the files
81 my $IndexCols       = 6;            # Columns in the file listing
82 my $IndexTitle      = "Index";      # Title of index page
83 my $IndexName       = "index.html"; # Name of index page
84 my $IndexPage       = 0;            # Create an index page
85 my $KeywordColor    = "#A020F0";    # Color for keywords
86 my $LineLabels      = 0;            # Add a HTML label to each line
87 my $LineNumbers     = 0;            # Add line numbers to the output
88 my $LinkStyle       = 0;            # Default link style
89 my $ReplaceExt      = 0;            # Replace extension instead of appending
90 my $StringColor     = "#6169C1";    # Color for strings
91 my $TextColor       = "#000000";    # Text color
92 my $Verbose         = 0;            # Be quiet
93
94 # Table used to convert the label number into names
95 my @NameTab         = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
96                        "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
97                        "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6",
98                        "7", "8", "9");
99
100
101
102 #-----------------------------------------------------------------------------#
103 #                              Helper functions                               #
104 # ----------------------------------------------------------------------------#
105
106
107
108 # Terminate with an error
109 sub Abort {
110     print STDERR "ca65html: @_\n";
111     exit 1;
112 }
113
114 # Print a message if verbose is true
115 sub Gabble {
116     if ($Verbose) {
117         print "ca65html: @_\n";
118     }
119 }
120
121 # Generate a label and return it
122 sub GenLabel {
123
124     my $I;
125     my $L = "";;
126     my $Num = $LabelNum++;
127
128     # Generate the label
129     for ($I = 0; $I < 4; $I++) {
130         $L = $NameTab[$Num % 36] . $L;
131         $Num /= 36;
132     }
133     return $L;
134 }
135
136 # Make an output file name from an input file name
137 sub GetOutName {
138
139     # Input name is parameter
140     my $InName = $_[0];
141
142     # Create the output file name from the input file name
143     if ($ReplaceExt && $InName =~ /^(.+)\.([^\.\/]*)$/) {
144         return "$1.html";
145     } else {
146         return "$InName.html";
147     }
148 }
149
150 # Remove illegal characters from a string
151 sub Cleanup {
152     my $S = shift (@_);
153     $S =~ s/&/&amp;/g;
154     $S =~ s/</&lt;/g;
155     $S =~ s/>/&gt;/g;
156     $S =~ s/\"/&quot;/g;
157     return $S;
158 }
159
160 # Strip a path from a filename and return just the name
161 sub StripPath {
162
163     # Filename is argument
164     my $FileName = $_[0];
165
166     # Remove a path name if we have one
167     $FileName =~ /^(.*?)([^\/]*)$/;
168     return $2;
169 }
170
171
172
173 #-----------------------------------------------------------------------------#
174 #                         Document header and footer                          #
175 # ----------------------------------------------------------------------------#
176
177
178
179 # Print the document header
180 sub DocHeader {
181     my $OUT = shift (@_);
182     my $Asm = shift (@_);
183     if (not $Colorize) {
184         # Colorization generates invalid HTML. Common browsers display it
185         # correctly, but we don't claim it adheres to some standard ...
186         print $OUT "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n";
187     }
188     print $OUT <<"EOF";
189 <html>
190 <head>
191 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
192 <meta name="GENERATOR" content="ca65html">
193 <title>$Asm</title>
194 </head>
195 <body bgcolor="$BGColor" text="$TextColor" link="#0000d0" vlink="#000060" alink="#00d0d0">
196 <p><br><p>
197 <center><h1>$Asm</h1></center>
198 <hr size="1" noshade><p><br><p>
199 EOF
200 }
201
202 # Print the document footer
203 sub DocFooter {
204     my $OUT  = shift (@_);
205     my $Name = shift (@_);
206
207     # Get the current date and time
208     my $Today = localtime;
209
210     # Print
211     print $OUT "<p><br><p>\n";
212     print $OUT "<hr size=\"1\" noshade>\n";
213     print $OUT "<address>\n";
214     if (not $Colorize) {
215         print $OUT "<a href=\"http://validator.w3.org/check/referer\"><img border=\"0\" src=\"http://www.w3.org/Icons/valid-html401\" alt=\"Valid HTML 4.01!\" height=\"31\" width=\"88\" align=\"right\"></a>\n";
216     }
217     print $OUT "$Name; generated on $Today by ca65html<br>\n";
218     print $OUT "<a href=\"mailto:uz&#64;cc65.org\">uz&#64;cc65.org</a>\n";
219     print $OUT "</address>\n";
220     print $OUT "</body>\n";
221     print $OUT "</html>\n";
222 }
223
224
225
226 #-----------------------------------------------------------------------------#
227 #                                Colorization                                 #
228 #-----------------------------------------------------------------------------#
229
230
231
232 sub ColorizeComment {
233     if ($Colorize && $_[0] ne "") {
234         return "<font color=\"$CommentColor\">$_[0]</font>";
235     } else {
236         return $_[0];
237     }
238 }
239
240
241
242 sub ColorizeCtrl {
243     if ($Colorize) {
244         return "<font color=\"$CtrlColor\">$_[0]</font>";
245     } else {
246         return $_[0];
247     }
248 }
249
250
251
252 sub ColorizeKeyword {
253     if ($Colorize) {
254         return "<font color=\"$KeywordColor\">$_[0]</font>";
255     } else {
256         return $_[0];
257     }
258 }
259
260
261
262 sub ColorizeString {
263     if ($Colorize) {
264         return "<font color=\"$StringColor\">$_[0]</font>";
265     } else {
266         return $_[0];
267     }
268 }
269
270
271
272 #-----------------------------------------------------------------------------#
273 #                            File list management                             #
274 #-----------------------------------------------------------------------------#
275
276
277
278 sub AddFile {
279
280     # Argument is file to add
281     my $FileName = $_[0];
282
283     # Get just the name (remove a path if there is one)
284     my $Name = StripPath ($FileName);
285
286     # Check if we have the file already
287     if (exists ($Files{$Name})) {
288         Gabble ("File \"$FileName\" already known");
289         return;
290     }
291
292     # Check with the full pathname. If we don't find it, search in the current
293     # directory
294     if (-f $FileName && -r _) {
295         $Files{$Name} = $FileName;
296         $FileCount++;
297     } elsif (-f $Name && -r _) {
298         $Files{$Name} = $Name;
299         $FileCount++;
300     } else {
301         Abort ("$FileName not found or not readable");
302     }
303 }
304
305
306
307 #-----------------------------------------------------------------------------#
308 #                       Referencing and defining labels                       #
309 #-----------------------------------------------------------------------------#
310
311
312
313 # Get a label reference
314 sub RefLabel {
315
316     # Arguments are: Filename, identifier, item that should be tagged
317     my $FileName = $_[0];
318     my $Id       = $_[1];
319     my $Item     = $_[2];
320
321     # Search for the identifier in the list of labels
322     if (exists ($Labels{$FileName}{$Id})) {
323         # It is a label (in this file)
324         return sprintf ("<a href=\"#%s\">%s</a>", $Labels{$FileName}{$Id}, $Item);
325     } elsif (exists ($Imports{$FileName}{$Id})) {
326         # It is an import. If LinkStyle is 1, or if the file exporting the
327         # identifier is not visible, we link to the .import statement in the
328         # current file. Otherwise we link directly to the referenced symbol
329         # in the file that exports it.
330         if ($LinkStyle == 1 or not exists ($Exports{$Id})) {
331             return sprintf ("<a href=\"#%s\">%s</a>", $Imports{$FileName}{$Id}, $Item);
332         } else {
333             # Get the filename from the export
334             my $Label;
335             ($FileName, $Label) = split (/#/, $Exports{$Id});
336             if (not defined ($Labels{$FileName}{$Id})) {
337                 # This may currently happen because we don't see .include
338                 # statements, so we may have an export but no definition.
339                 # Link to the .export statement instead
340                 $Label = $Exports{$Id};
341             } else {
342                 # Link to the definition in the file
343                 $Label = sprintf ("%s#%s", $FileName, $Labels{$FileName}{$Id});
344             }
345             return sprintf ("<a href=\"%s\">%s</a>", $Label, $Item);
346         }
347     } else {
348         # The symbol is unknown, return as is
349         return $Item;
350     }
351 }
352
353
354
355 #-----------------------------------------------------------------------------#
356 #                                   Pass 1                                    #
357 # ----------------------------------------------------------------------------#
358
359
360
361 # Process1: Read one file for the first time.
362 sub Process1 {
363
364     # Variables
365     my $Line;
366     my $Id;
367
368     # Filename is parameter
369     my $InName = shift(@_);
370
371     # Create the output file name from the input file name
372     my $OutName = GetOutName ($InName);
373
374     # Current cheap local label prefix is empty
375     my $CheapPrefix = "";
376
377     # Open a the input file
378     my $FileName = $Files{$InName};     # Includes path if needed
379     open (INPUT, "<$FileName") or Abort ("Cannot open $FileName: $!");
380
381     # Keep the user happy
382     Gabble ("$FileName => $OutName");
383
384     # Read and process all lines from the file
385     while ($Line = <INPUT>) {
386
387         # Remove the newline
388         chop ($Line);
389
390         # Check for a label
391         if ($Line =~ /^\s*(\@?)([_a-zA-Z]\w*)(:(?!=)|\s*:?=)/) {
392
393             # Is this a local label?
394             if ($1 eq "\@") {
395                 # Use the prefix
396                 $Id = "$CheapPrefix$1$2";
397             } else {
398                 # Use as is
399                 $Id = $2;
400                 # Remember the id as new cheap local prefix
401                 $CheapPrefix = $Id;
402             }
403
404             # Remember the label
405             $Labels{$OutName}{$Id} = GenLabel();
406
407         # Check for an import statement
408         } elsif ($Line =~ /^\s*(\.import|\.importzp)\s+(.*?)(\s*)(;.*$|$)/) {
409
410             # Split into a list of identifiers
411             my @Ids = split (/\s*,\s*/, $2);
412             for $Id (@Ids) {
413                 $Imports{$OutName}{$Id} = GenLabel();
414             }
415
416         # Check for an export statement
417         } elsif ($Line =~ /^\s*(\.export|\.exportzp)\s+(.*?)(\s*)(;.*$|$)/) {
418
419             # Split into a list of identifiers
420             my @Ids = split (/\s*,\s*/, $2);
421             for $Id (@Ids) {
422                 $Exports{$Id} = sprintf ("%s#%s", $OutName, GenLabel());
423             }
424
425         # Check for a .proc statement
426         } elsif ($Line =~ /^\s*\.proc\s+([_a-zA-Z]\w*)?.*$/) {
427
428             # Do we have an id?
429             $Id = $1;
430             if ($Id ne "") {
431                 $Labels{$OutName}{$Id} = GenLabel();
432             }
433
434         }
435     }
436
437     # Close the input file
438     close (INPUT);
439 }
440
441
442
443 # Pass1: Read all files for the first time.
444 sub Pass1 () {
445
446     # Keep the user happy
447     Gabble ("Pass 1");
448
449     # Walk over the files
450     for my $InName (keys (%Files)) {
451         # Process one file
452         Process1 ($InName);
453     }
454 }
455
456
457
458 #-----------------------------------------------------------------------------#
459 #                                   Pass 2                                    #
460 # ----------------------------------------------------------------------------#
461
462
463
464 # Process2: Read one file the second time.
465 sub Process2 {
466
467     # Variables
468     my $Base;
469     my $Ext;
470     my $Line;
471     my $OutLine;
472     my $Id;
473     my $Label;
474     my $Operand;
475     my $Comment;
476     my $Trailer;
477
478     # Input file is parameter
479     my $InName = shift(@_);
480
481     # Create the output file name from the input file name
482     my $OutName = GetOutName ($InName);
483
484     # Current cheap local label prefix is empty
485     my $CheapPrefix = "";
486
487     # Open a the input file
488     my $FileName = $Files{$InName};     # Includes path if needed
489     open (INPUT, "<$FileName") or Abort ("Cannot open $FileName: $!");
490
491     # Open the output file and print the HTML header
492     open (OUTPUT, ">$HTMLDir$OutName") or Abort ("Cannot open $OutName: $!");
493     DocHeader (OUTPUT, $InName);
494     print OUTPUT "<pre>\n";
495
496     # Keep the user happy
497     Gabble ("$FileName => $OutName");
498
499     # The instructions that will have hyperlinks if a label is used
500     my $LabelIns = "adc|add|and|asl|bcc|bcs|beq|bit|bmi|bne|bpl|bra|bvc|bvs|".
501                    "cmp|cpx|cpy|dec|eor|inc|jmp|jsr|lda|ldx|ldy|lsr|ora|rol|".
502                    "ror|sbc|sta|stx|sty|stz|sub|";
503
504     # The instructions that will have hyperlinks if a label is used
505     my $AllIns = "adc|add|and|asl|bcc|bcs|beq|bge|bit|blt|bmi|bne|bpl|bvc|".
506                  "bra|brk|brl|bvs|clc|cld|cli|clv|cmp|cop|cpa|cpx|cpy|dea|".
507                  "dec|dex|dey|eor|ina|inc|inx|iny|jml|jmp|jsl|jsr|lda|ldx|".
508                  "ldy|lsr|mvn|mvp|nop|ora|pea|pei|per|pha|phb|phd|phk|php|".
509                  "phx|phy|pla|plb|pld|plp|plx|ply|rep|rol|ror|rti|rtl|rts|".
510                  "sbc|sec|sed|sei|sep|sta|stx|sty|stz|sub|swa|tad|tax|tay|".
511                  "tcd|tcs|tda|tdc|trb|tsa|tsb|tsc|tsx|txa|txs|txy|tya|tyx|".
512                  "wai|xba|xce";
513
514     # Read the input file, replacing references by hyperlinks and mark
515     # labels as link targets.
516     my $LineNo = 0;
517     while ($Line = <INPUT>) {
518
519         # Count input lines
520         $LineNo++;
521
522         # Remove the newline
523         chop ($Line);
524
525         # If requested, convert tabs to spaces
526         if ($CvtTabs) {
527             # Don't ask me - this is from the perl manual page
528             1 while ($Line =~ s/\t+/' ' x (length($&)*8 - length($`)%8)/e) ;
529         }
530
531         # Clear the output line
532         $OutLine = "";
533
534         # If requested, add a html label to each line with a name "linexxx",
535         # so it can be referenced from the outside (this is the same convention
536         # that is used by c2html). If we have line numbers enabled, add them.
537         if ($LineLabels && $LineNumbers) {
538             $OutLine .= sprintf ("<a name=\"line%d\">%6d</a>:  ", $LineNo, $LineNo);
539         } elsif ($LineLabels) {
540             $OutLine .= sprintf ("<a name=\"line%d\"></a>", $LineNo);
541         } elsif ($LineNumbers) {
542             $OutLine .= sprintf ("%6d:  ", $LineNo);
543         }
544
545         # Cut off a comment from the input line. Beware: We have to check for
546         # strings, since these may contain a semicolon that is no comment
547         # start.
548         ($Line, $Comment) = $Line =~ /^((?:[^"';]+|".*?"|'.*?')*)(.*)$/;
549         if ($Comment =~ /^["']/) {
550             # Line with invalid syntax - there's a string start but
551             # no string end.
552             Abort (sprintf ("Invalid input at %s(%d)", $FileName, $LineNo));
553         }
554
555         # Remove trailing whitespace and move it together with the comment
556         # into the $Trailer variable.
557         $Line =~ s/\s*$//;
558         $Trailer = $& . ColorizeComment (Cleanup ($Comment));
559
560         # Check for a label at the start of the line. If we have one, process
561         # it and remove it from the line
562         if ($Line =~ s/^\s*?(\@?)([_a-zA-Z]\w*)(:(?!=)|\s*:?=)//) {
563
564             # Is this a local label?
565             if ($1 eq "\@") {
566                 # Use the prefix
567                 $Id = "$CheapPrefix$1$2";
568             } else {
569                 # Use as is
570                 $Id = $2;
571                 # Remember the id as new cheap local prefix
572                 $CheapPrefix = $Id;
573             }
574
575             # Get the label for the id
576             $Label = $Labels{$OutName}{$Id};
577
578             # Print the label with a tag
579             $OutLine .= sprintf ("<a name=\"%s\">%s%s</a>%s", $Label, $1, $2, $3);
580         }
581
582         # Print any leading whitespace and remove it, so we don't have to
583         # care about whitespace below.
584         if ($Line =~ s/^\s+//) {
585             $OutLine .= $&;
586         }
587
588         # Handle the import statements
589         if ($Line =~ s/^(\.import|\.importzp)\s+//) {
590
591             # Print any fixed stuff from the line and remove it
592             $OutLine .= $&;
593
594             # Print all identifiers if there are any
595             while ($Line =~ s/^[_a-zA-Z]\w*//) {
596
597                 # Remember the identifier
598                 my $Id = $&;
599
600                 # Variable to assemble HTML representation
601                 my $Contents = "";
602
603                 # Make this import a link target
604                 if (exists ($Imports{$OutName}{$Id})) {
605                     $Label = $Imports{$OutName}{$Id};
606                     $Contents .= sprintf (" name=\"%s\"", $Label);
607                 }
608
609                 # If we have an export for this import, add a link to this
610                 # export definition
611                 if (exists ($Exports{$Id})) {
612                     $Label = $Exports{$Id};
613                     $Contents .= sprintf (" href=\"%s\"", $Label);
614                 }
615
616                 # Add the HTML stuff to the output line
617                 if ($Contents ne "") {
618                     $OutLine .= sprintf ("<a%s>%s</a>", $Contents, $Id);
619                 } else {
620                     $OutLine .= $Id;
621                 }
622
623                 # Check if another identifier follows
624                 if ($Line =~ s/^\s*,\s*//) {
625                     $OutLine .= $&;
626                 } else {
627                     last;
628                 }
629             }
630
631             # Add an remainder if there is one
632             $OutLine .= Cleanup ($Line);
633
634         # Handle export statements
635         } elsif ($Line =~ s/^(\.export|\.exportzp)\s+//) {
636
637             # Print the command the and white space
638             $OutLine .= $&;
639
640             # Print all identifiers if there are any
641             while ($Line =~ s/^[_a-zA-Z]\w*//) {
642
643                 # Remember the identifier
644                 my $Id = $&;
645
646                 # Variable to assemble HTML representation
647                 my $Contents = "";
648
649                 # If we have a definition for this export in this file, add
650                 # a link to the definition.
651                 if (exists ($Labels{$OutName}{$Id})) {
652                     $Label = $Labels{$OutName}{$Id};
653                     $Contents = sprintf (" href=\"#%s\"", $Label);
654                 }
655
656                 # If we have this identifier in the list of exports, add a
657                 # jump target for the export.
658                 if (exists ($Exports{$Id})) {
659                     $Label = $Exports{$Id};
660                     # Be sure to use only the label part
661                     $Label =~ s/^.*#//;
662                     $Contents .= sprintf (" name=\"%s\"", $Label);
663                 }
664
665                 # Add the HTML stuff to the output line
666                 if ($Contents ne "") {
667                     $OutLine .= sprintf ("<a%s>%s</a>", $Contents, $Id);
668                 } else {
669                     $OutLine .= $Id;
670                 }
671
672                 # Check if another identifier follows
673                 if ($Line =~ s/^\s*,\s*//) {
674                     $OutLine .= $&;
675                 } else {
676                     last;
677                 }
678             }
679
680             # Add an remainder if there is one
681             $OutLine .= Cleanup ($Line);
682
683         # Check for .addr and .word
684         } elsif ($Line =~ s/^(\.addr|\.word)\s+//) {
685
686             # Print the command and the white space
687             $OutLine .= $&;
688
689             # Print all identifiers if there are any
690             while ($Line =~ /^([^_a-zA-Z]*)([_a-zA-Z]\w*)(.*)$/) {
691                 # Add the non label stuff
692                 $OutLine .= Cleanup ($1);
693
694                 # If the identifier is a known label, add a link
695                 if (exists ($Labels{$OutName}{$2})) {
696                     $Label = $Labels{$OutName}{$2};
697                     $OutLine .= sprintf ("<a href=\"#%s\">%s</a>", $Label, $2);
698                 } else {
699                     $OutLine .= $2;
700                 }
701
702                 # Proceed with the remainder of the line
703                 $Line = $3;
704             }
705
706             # Add an remainder if there is one
707             $OutLine .= Cleanup ($Line);
708
709         # Handle .proc
710         } elsif ($Line =~ /^(\.proc)(\s+)([_a-zA-Z]\w*)?(.*)$/) {
711
712             # Do we have an identifier?
713             if ($3 ne "") {
714                 # Get the label for the id
715                 $Label = $Labels{$OutName}{$3};
716
717                 # Print the label with a tag
718                 $OutLine .= "$1$2<a name=\"$Label\">$3</a>";
719
720             } else {
721
722                 # Print the label
723                 $OutLine .= "$1$2$3";
724
725             }
726
727             # Add the remainder
728             $OutLine .= Cleanup ($4);
729
730         # Handle .include
731         } elsif ($Line =~ /^(\.include)(\s+)\"((?:[^\"]+?|\\\")+)(\".*)$/) {
732
733             # Add the fixed stuff to the output line
734             $OutLine .= "$1$2&quot;";
735
736             # Get the filename into a named variable
737             my $FileName = Cleanup ($3);
738
739             # Get the name without a path
740             my $Name = StripPath ($3);
741
742             # If the include file is among the list of our files, add a link,
743             # otherwise just add the name as is.
744             if (exists ($Files{$Name})) {
745                 $OutLine .= sprintf ("<a href=\"%s\">%s</a>", GetOutName ($Name), $FileName);
746             } else {
747                 $OutLine .= $FileName;
748             }
749
750             # Add the remainder
751             $OutLine .= Cleanup ($4);
752
753         # Handle .dbg line
754         } elsif ($CRefs && $Line =~ s/^\.dbg\s+//) {
755
756             # Add the fixed stuff to the output line
757             $OutLine .= $&;
758
759             # Check for the type of the .dbg directive
760             if ($Line =~ /^(line,\s*)\"((?:[^\"]+?|\\\")+)\"(,\s*)(\d+)(.*)$/) {
761
762                 # Add the fixed stuff to the output line
763                 $OutLine .= "$1&quot;";
764
765                 # Get the filename and line number into named variables
766                 my $DbgFile = $2;
767                 my $DbgLine = $4;
768
769                 # Remember the remainder
770                 $Line = "\"$3$4$5";
771
772                 # Get the name without a path
773                 my $Name = StripPath ($DbgFile);
774
775                 # We don't need FileName any longer as is, so clean it up
776                 $DbgFile = Cleanup ($DbgFile);
777
778                 # Add a link to the source file
779                 $OutLine .= sprintf ("<a href=\"%s.html#line%d\">%s</a>", $Name, $DbgLine, $DbgFile);
780
781                 # Add the remainder
782                 $OutLine .= Cleanup ($Line);
783
784             } elsif ($Line =~ /^(file,\s*)\"((?:[^\"]+?|\\\")+)\"(.*)$/) { #pf FIXME: doesn't handle \" correctly!
785
786                 # Get the filename into a named variables
787                 my $DbgFile = Cleanup ($2);
788
789                 # Get the name without a path
790                 my $Name = Cleanup (StripPath ($2));
791
792                 # Add the fixed stuff to the output line
793                 $OutLine .= sprintf ("%s\"<a href=\"%s.html\">%s</a>\"%s",
794                                      $1, $Name, $DbgFile, $3);
795
796             } else {
797
798                 # Add the remainder
799                 $OutLine .= Cleanup ($Line);
800
801             }
802
803         } elsif ($CRefs && $Line =~ /^(\.dbg)(\s+line,\s*)\"((?:[^\"]+?|\\\")+)\"(,\s*)(\d+)(.*$)/) {
804
805             # Add the fixed stuff to the output line
806             $OutLine .= "$1$2&quot;";
807
808             # Get the filename and line number into named variables
809             my $FileName = $3;
810             my $LineNo   = $5;
811
812             # Remember the remainder
813             $Line = "\"$4$5$6";
814
815             # Get the name without a path
816             my $Name = StripPath ($FileName);
817
818             # We don't need FileName any longer as is, so clean it up
819             $FileName = Cleanup ($FileName);
820
821             # Add a link to the source file
822             $OutLine .= sprintf ("<a href=\"%s.html#line%d\">%s</a>", $Name, $LineNo, $FileName);
823
824             # Add the remainder
825             $OutLine .= Cleanup ($Line);
826
827         # Check for instructions with labels
828         } elsif ($Line =~ /^($LabelIns)\b(\s+)(.*)$/) {
829
830             # Print the instruction and white space
831             $OutLine .= ColorizeKeyword ($1) . $2;
832
833             # Remember the remaining parts
834             $Operand = $3;
835
836             # Check for the first identifier in the operand and replace it
837             # by a hyperlink
838             if ($Operand =~ /^([^_a-zA-Z]*?)(\@?)([_a-zA-Z]\w*)(.*)$/) {
839
840                 # Is this a local label?
841                 if ($2 eq "\@") {
842                     # Use the prefix
843                     $Id = "$CheapPrefix$2$3";
844                 } else {
845                     # Use as is
846                     $Id = $3;
847                 }
848
849                 # Get the reference to this label if we find it
850                 $Operand = Cleanup($1) . RefLabel($OutName, $Id, $2 . $3) . Cleanup($4);
851             }
852
853             # Reassemble and print the line
854             $OutLine .= $Operand;
855
856         # Check for all other instructions
857         } elsif ($Line =~ /^($AllIns)\b(.*)$/) {
858
859             # Colorize and print
860             $OutLine .= ColorizeKeyword ($1) . Cleanup ($2);
861
862         } else {
863
864             # Nothing known - print the line
865             $OutLine .= Cleanup ($Line);
866
867         }
868
869         # Colorize all keywords
870         $OutLine =~ s/(?<![\w;])\.[_a-zA-Z]\w*/ColorizeCtrl ($&)/ge;
871
872         # Add the trailer
873         $OutLine .= $Trailer;
874
875         # Print the result
876         print OUTPUT "$OutLine\n";
877     }
878
879     # Print the HTML footer
880     print OUTPUT "</pre>\n";
881     DocFooter (OUTPUT, $OutName);
882
883     # Close the files
884     close (INPUT);
885     close (OUTPUT);
886 }
887
888
889
890 # Pass2: Read all files the second time.
891 sub Pass2 () {
892
893     # Keep the user happy
894     Gabble ("Pass 2");
895
896     # Walk over the files
897     for my $InName (keys (%Files)) {
898         # Process one file
899         Process2 ($InName);
900     }
901 }
902
903
904
905 #-----------------------------------------------------------------------------#
906 #                            Create an index page                             #
907 # ----------------------------------------------------------------------------#
908
909
910
911 # Print a list of all files
912 sub FileIndex {
913
914     # File is argument
915     my $INDEX = $_[0];
916
917     # Print the file list in a table
918     print $INDEX "<h2>Files</h2><p>\n";
919     print $INDEX "<table border=\"0\" width=\"100%\">\n";
920     my $Count = 0;
921     for my $File (sort (keys (%Files))) {
922
923         #
924         if (($Count % $IndexCols) == 0) {
925             print $INDEX "<tr>\n";
926         }
927         printf $INDEX "<td><a href=\"%s\">%s</a></td>\n", GetOutName ($File), $File;
928         if (($Count % $IndexCols) == $IndexCols-1) {
929             print $INDEX "</tr>\n";
930         }
931         $Count++;
932     }
933     if (($Count % $IndexCols) != 0) {
934         print $INDEX "</tr>\n";
935     }
936     print $INDEX "</table><p><br><p>\n";
937 }
938
939
940
941 # Print a list of all exports
942 sub ExportIndex {
943
944     # File is argument
945     my $INDEX = $_[0];
946
947     # Print the file list in a table
948     print $INDEX "<h2>Exports</h2><p>\n";
949     print $INDEX "<table border=\"0\" width=\"100%\">\n";
950     my $Count = 0;
951     for my $Export (sort (keys (%Exports))) {
952
953         # Get the export
954         my $File;
955         my $Label;
956         ($File, $Label) = split (/#/, $Exports{$Export});
957
958         # The label is the label of the export statement. If we can find the
959         # actual label, use this instead.
960         if (exists ($Labels{$File}{$Export})) {
961             $Label = $Labels{$File}{$Export};
962         }
963
964         #
965         if (($Count % $IndexCols) == 0) {
966             print $INDEX "<tr>\n";
967         }
968         printf $INDEX "<td><a href=\"%s#%s\">%s</a></td>\n", $File, $Label, $Export;
969         if (($Count % $IndexCols) == $IndexCols-1) {
970             print $INDEX "</tr>\n";
971         }
972         $Count++;
973     }
974     if (($Count % $IndexCols) != 0) {
975         print $INDEX "</tr>\n";
976     }
977     print $INDEX "</table><p><br><p>\n";
978 }
979
980
981
982 sub CreateIndex {
983
984     # Open the index page file
985     open (INDEX, ">$HTMLDir$IndexName") or Abort ("Cannot open $IndexName: $!");
986
987     # Print the header
988     DocHeader (INDEX, $IndexTitle, 0);
989
990     # Print the file list in a table
991     FileIndex (INDEX);
992     ExportIndex (INDEX);
993
994     # Print the document footer
995     DocFooter (INDEX, $IndexName);
996
997     # Close the index file
998     close (INDEX);
999 }
1000
1001
1002
1003 #-----------------------------------------------------------------------------#
1004 #                           Print usage information                           #
1005 # ----------------------------------------------------------------------------#
1006
1007
1008
1009 sub Usage {
1010     print "Usage: ca65html [options] file ...\n";
1011     print "Options:\n";
1012     print "  --bgcolor c        Use background color c instead of $BGColor\n";
1013     print "  --colorize         Colorize the output (generates non standard HTML)\n";
1014     print "  --commentcolor c   Use color c for comments instead of $CommentColor\n";
1015     print "  --crefs            Generate references to the C source file(s)\n";
1016     print "  --ctrlcolor c      Use color c for directives instead of $CtrlColor\n";
1017     print "  --cvttabs          Convert tabs to spaces in the output\n";
1018     print "  --help             This text\n";
1019     print "  --htmldir dir      Specify directory for HTML files\n";
1020     print "  --indexcols n      Use n columns on index page (default $IndexCols)\n";
1021     print "  --indexname file   Use file for the index file instead of $IndexName\n";
1022     print "  --indexpage        Create an index page\n";
1023     print "  --indextitle title Use title as the index title instead of $IndexTitle\n";
1024     print "  --keywordcolor c   Use color c for keywords instead of $KeywordColor\n";
1025     print "  --linelabels       Generate a linexxx HTML label for each line\n";
1026     print "  --linenumbers      Add line numbers to the output\n";
1027     print "  --linkstyle style  Use the given link style\n";
1028     print "  --replaceext       Replace source extension instead of appending .html\n";
1029     print "  --textcolor c      Use text color c instead of $TextColor\n";
1030     print "  --verbose          Be more verbose\n";
1031 }
1032
1033
1034
1035 #-----------------------------------------------------------------------------#
1036 #                                    Main                                     #
1037 # ----------------------------------------------------------------------------#
1038
1039
1040
1041 # Get program options
1042 GetOptions ("bgcolor=s"         => \$BGColor,
1043             "colorize"          => \$Colorize,
1044             "commentcolor=s"    => \$CommentColor,
1045             "crefs"             => \$CRefs,
1046             "ctrlcolor=s"       => \$CtrlColor,
1047             "cvttabs"           => \$CvtTabs,
1048             "debug!"            => \$Debug,
1049             "help"              => \$Help,
1050             "htmldir=s"         => \$HTMLDir,
1051             "indexcols=i"       => \$IndexCols,
1052             "indexname=s"       => \$IndexName,
1053             "indexpage"         => \$IndexPage,
1054             "indextitle=s"      => \$IndexTitle,
1055             "keywordcolor=s"    => \$KeywordColor,
1056             "linelabels"        => \$LineLabels,
1057             "linenumbers"       => \$LineNumbers,
1058             "linkstyle=i"       => \$LinkStyle,
1059             "replaceext"        => \$ReplaceExt,
1060             "textcolor=s"       => \$TextColor,
1061             "verbose!"          => \$Verbose,
1062             "<>"                => \&AddFile);
1063
1064 # Check some arguments
1065 if ($IndexCols <= 0 || $IndexCols >= 20) {
1066     Abort ("Invalid value for --indexcols option");
1067 }
1068 if ($HTMLDir ne "" && $HTMLDir =~ /[^\/]$/) {
1069     # Add a trailing path separator
1070     $HTMLDir .= "/";
1071 }
1072
1073
1074
1075 # Print help if requested
1076 if ($Help) {
1077     Usage ();
1078 }
1079
1080 # Check if we have input files given
1081 if ($FileCount == 0) {
1082     Abort ("No input files");
1083 }
1084
1085 # Convert the documents
1086 Pass1 ();
1087 Pass2 ();
1088
1089 # Generate an index page if requested
1090 if ($IndexPage) {
1091     CreateIndex ();
1092 }
1093
1094 # Done
1095 exit 0;
1096