3 ms·
Some crude snippets from a Pascal-C (I never could decide) self-educational compiler/toy I wrote a while ago (in Haskell): -- a parser function that matche
by retrac 3y ago
Some crude snippets from a Pascal-C (I never could decide) self-educational compiler/toy I wrote a while ago (in Haskell):
-- a parser function that matches on { ... } returning ...
-- can be combined with other parsers
braces = (symbol "{") `between` (symbol "}")
...
-- a statement is a controlFlow or a declaration or an assignment
statement = controlFlow <|> declaration <|> assignment
-- a block is either 1 or more statements surrounded by { ... }
-- or a single statement.
block = (braces $ many statement) <|> statement
...
-- An expression is a number, or a variable, or a binary operation
-- derive functionality to print and test equality of these values.
data Expr =
Num Int
| Var Variable
| DualOp Op Expr Expr
...
deriving (Show, Eq)
...
foldConstants (DualOp Add (Num a) (Num b)) = Num (a + b)
...
Parser combinators (parser functions that take other parser functions and return more complex combined parser functions) with enough syntactic sugar can express BNF-like grammars directly as code. And ML-style list and pattern matching operations are very expressive for operating on the intermediate representation.