I am writing a Delphi code parser using Parsec, my current AST data structures look like this:
module Text.DelphiParser.Ast where
data TypeName = TypeName String [String] deriving (Show)
type UnitName = String
data ArgumentKind = Const | Var | Out | Normal deriving (Show)
data Argument = Argument ArgumentKind String TypeName deriving (Show)
data MethodFlag = Overload | Override | Reintroduce | Static | StdCall deriving (Show)
data ClassMember =
ConstField String TypeName
| VarField String TypeName
| Property String TypeName String (Maybe String)
| ConstructorMethod String [Argument] [MethodFlag]
| DestructorMethod String [Argument] [MethodFlag]
| ProcMethod String [Argument] [MethodFlag]
| FunMethod String [Argument] TypeName [MethodFlag]
| ClassProcMethod String [Argument] [MethodFlag]
| ClassFunMethod String [Argument] TypeName [MethodFlag]
deriving (Show)
data Visibility = Private | Protected | Public | Published deriving (Show)
data ClassSection = ClassSection Visibility [ClassMember] deriving (Show)
data Class = Class String [ClassSection] deriving (Show)
data Type = ClassType Class deriving (Show)
data Interface = Interface [UnitName] [Type] deriving (Show)
data Implementation = Implementation [UnitName] deriving (Show)
data Unit = Unit String Interface Implementation deriving (Show)
I want to preserve comments in my AST data structures and I'm currently trying to figure out how to do this.
My parser is split into a lexer and a parser (both written with Parsec) and I have already implemented lexing of comment tokens.
unit SomeUnit;
interface
uses
OtherUnit1, OtherUnit2;
type
// This is my class that does blabla
TMyClass = class
var
FMyAttribute: Integer;
public
procedure SomeProcedure;
{ The constructor takes an argument ... }
constructor Create(const Arg1: Integer);
end;
implementation
end.
The token stream looks like this:
[..., Type, LineComment " This is my class that does blabla", Identifier "TMyClass", Equals, Class, ...]
The parser translates this into:
Class "TMyClass" ...
The Class
data type doesn't have any way to attach comments and since comments (especially block comments) could appear almost anywhere in the token stream I would have to add an optional comment to all data types in the AST?
How can I deal with comments in my AST?