我正在用 Haskell 编写一个编译器,所以我们有一个lot (或者至少对我来说似乎很多) of data
s 和构造函数,如下所示:
data DataType
= Int | Float | Bool | Char | Range | Type
| String Width
| Record (Lexeme Identifier) (Seq Field) Width
| Union (Lexeme Identifier) (Seq Field) Width
| Array (Lexeme DataType) (Lexeme Expression) Width
| UserDef (Lexeme Identifier)
| Void | TypeError -- For compiler use
data Statement
-- Language
= StNoop
| StAssign (Lexeme Access) (Lexeme Expression)
-- Definitions
| StDeclaration (Lexeme Declaration)
| StDeclarationList (DeclarationList Expression)
| StStructDefinition (Lexeme DataType)
-- Functions
| StReturn (Lexeme Expression)
| StFunctionDef (Lexeme Declaration) (Seq (Lexeme DataType))
| StFunctionImp (Lexeme Identifier) (Seq (Lexeme Identifier)) StBlock
| StProcedureCall (Lexeme Identifier) (Seq (Lexeme Expression))
-- I/O
| StRead (Seq (Lexeme Access))
| StPrint (Seq (Lexeme Expression))
-- Conditional
| StIf (Lexeme Expression) StBlock StBlock
| StCase (Lexeme Expression) (Seq (Lexeme When)) StBlock
-- Loops
| StLoop StBlock (Lexeme Expression) StBlock
| StFor (Lexeme Identifier) (Lexeme Expression) StBlock
| StBreak
| StContinue
还有很多。您可能已经注意到重复的Lexeme a
在许多构造函数中。
Lexeme 如下data
type Position = (Int, Int)
data Lexeme a = Lex
{ lexInfo :: a
, lexPosn :: Position
}
所以它的作用是保存信息Position
中的一个元素的程序的文件,用于报告错误和警告。
有没有更简单的方法来处理保存信息的Position
问题?
我习惯于看到另一个可以选择性地用来保存词汇信息的构造函数:
data Expression = ... all the old Exprs
| ExprPos Position Expression
data Declaration = ... decls ...
| DeclPos Position Declaration
现在在你的Statement
和其他数据类型而不是:
| StFor (Lexeme Identifier) (Lexeme Expression) StBlock
你有:
| StFor Identifier Expression StBlock
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)