{- Copyright 2010 Dominique Devriese This file is part of the grammar-combinators library. The grammar-combinators library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Foobar is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Foobar. If not, see . -} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE TypeFamilies #-} import Text.GrammarCombinators.Parser.RecursiveDescent import Text.GrammarCombinators.Parser.Packrat import Text.GrammarCombinators.Base import Generics.MultiRec.FoldAlg import Text.GrammarCombinators.Test.Grammar data family NodeResult ix data instance NodeResult AdditiveExpr = NRA (IO ()) data instance NodeResult MultiplicativeExpr = NRM (IO ()) data instance NodeResult PrimaryExpr = NRP (IO ()) data instance NodeResult Decimal = NRD (IO ()) printOpEx :: Char -> IO () -> IO () -> IO () printOpEx op a b = do putChar '('; a; putChar op; b; putChar ')' printAlg :: Algebra ASTNode NodeResult printAlg = const ( (\(NRM a) (NRA b) -> NRA $ printOpEx '+' a b) & (\(NRM a) -> NRA a) & (\(NRP a) (NRM b) -> NRM $ printOpEx '*' a b) & (\(NRP a) -> NRM a) & (\(NRA a) -> NRP a) & (\(NRD a) -> NRP a) & (\c -> NRD $ putChar '(' >> putChar c >> putChar ')')) printer = alg . printAlg printgram :: ProcessingContextFreeGrammar ASTNode Char NodeResult printgram = applyProcessor grammar printer test1 = "((2+1)*2)+3*4" prTest1 = parsePackrat printgram AdditiveExpr test1 prTest1Result = case prTest1 of Parsed (NRA r) _ -> r rdTest1 = parseRecDec printgram AdditiveExpr test1 rdTest1Result = case rdTest1 of Just (NRA r) -> r