diff --git a/LayeredHaskell-make/src-exe/Main.hs b/LayeredHaskell-make/src-exe/Main.hs index 12554a1..5402e6b 100644 --- a/LayeredHaskell-make/src-exe/Main.hs +++ b/LayeredHaskell-make/src-exe/Main.hs @@ -7,7 +7,7 @@ import System.FilePath (()) import qualified Paths_LayeredHaskell_make as LHMake (version) import LHMake.Data.Feature - (superimpose, + (superimpose, superimposeUpp, list, listAll, listDeps, generate) import LHMake.Text.Label (infoLabel, hintLabel, warnLabel, errLabel) @@ -17,8 +17,8 @@ features :: FilePath features = "LayeredHaskell-make" "src" "LHMake" "Feature" "Features" -- | The destination directory for generated source files. -dir :: FilePath -dir = "src" "LH" "Feature" +src :: FilePath +src = "src" -- | The @LayeredHaskell-make@ executable facilitates superimposition. -- If @info@ is passed in as a command-line argument, @@ -30,7 +30,8 @@ main = do case args of [] -> do names <- getNames - superimpose names dir + superimpose names src + superimposeUpp src -- General information ["help"] -> help ["version"] -> version @@ -46,7 +47,7 @@ main = do "set":names | null names -> do putStrLn $ errLabel "One or more features must be enabled." - putStrLn $ hintLabel "For information on 'set', pass 'help' as an argument to LayeredHaskell-make." + putStrLn $ hintLabel "For information on `set', pass `help' as an argument to LayeredHaskell-make." | otherwise -> do writeFile features (unlines names) putStrLn $ infoLabel "Enabled just now: " ++ unwords names @@ -55,8 +56,9 @@ main = do putStrLn $ warnLabel "One or more command-line arguments were given, but they are not recognized." putStrLn $ warnLabel "Proceeding as if there were none..." names <- getNames - superimpose names dir - putStrLn $ hintLabel "For a list of all commands, pass 'help' as an argument to LayeredHaskell-make." + superimpose names src + superimposeUpp src + putStrLn $ hintLabel "For a list of all commands, pass `help' as an argument to LayeredHaskell-make." where getNames = do args <- readFile features @@ -73,7 +75,7 @@ help = do putStrLn " ... = c : ...all non-redundant feature combinations" putStrLn " ... = d : ...all feature dependencies and implications" putStrLn "set : Enable a set of features" - putStrLn " .... = Any feature combination from 'ls c', separated by spaces" + putStrLn " .... = Any feature combination from `ls c', separated by spaces" putStrLn "show : The set of currently enabled features" putStrLn "version : The version" diff --git a/LayeredHaskell-make/src/LHMake/Control/Superimposition.hs b/LayeredHaskell-make/src/LHMake/Control/Superimposition.hs index 94acf2f..e47ba49 100644 --- a/LayeredHaskell-make/src/LHMake/Control/Superimposition.hs +++ b/LayeredHaskell-make/src/LHMake/Control/Superimposition.hs @@ -10,39 +10,48 @@ Maintainer : kimhang@oregonstate.edu Stability : experimental This module provides a superimposition operator @'(-->)'@ on Haskell and Happy abstract syntax trees. -The following example illustrates its use on two Haskell files. -> -- A.hs -> module LH.Feature.A.Basic where +Superimposition retains definition components that occur in only one AST. +When components in both ASTs are associated with the same 'Identifier', +the component from the AST being superimposed takes precedence. + +The following (somewhat contrived) example illustrates its use on two Haskell files. + +> -- F1/Basic.hs +> module LH.Feature.Basic where > > data Expr = Lit Int +> | Neg Expr > > eval :: Expr -> Int > eval (Lit n) = n +> eval (Neg e) = negate (eval e) > -> -- B.hs -> module LH.Feature.B.Basic where +> -- F2/Basic.hs +> module LH.Feature.Basic where > > data Expr = Add Expr Expr > > eval :: Expr -> Int +> eval (Neg e) = eval (Add (Lit 0) e) > eval (Add e1 e2) = eval e1 + eval e2 > -> -- B.hs --> A.hs -> module LH.Feature.BA.Basic where +> -- F2/Basic.hs --> F1/Basic.hs +> module LH.Feature.Basic where > > data Expr = Lit Int | Add Expr Expr > > eval :: Expr -> Int -> eval (Lit n) = n -> eval (Add e1 e2) = eval e1 + eval e2 +> eval (Lit n) = n -- from F1 +> eval (Neg e) = eval (Add (Lit 0) e) -- from F2, taking precedence over F1 +> eval (Add e1 e2) = eval e1 + eval e2 -- from F2 -} {-# LANGUAGE FlexibleContexts, FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module LHMake.Control.Superimposition ( -- * Superimposition - Superimposable (..), Identifiable (..), + Superimposable (..), Identifiable (..), Ann (..), -- ** Parsing parseMode, -- ** Identifiers @@ -75,7 +84,7 @@ infixl 6 --> -- \(L\) and \(R\) are assumed to have the same 'Identifier', as defined by the 'Identifiable' typeclass. -- -- By default, \(L\) overrides the contents of \(R\). --- Specific instances replace this behavior with a merging semantics. +-- Specific instances replace this behavior with a more nuanced merging semantics. class Superimposable a where -- | Superimposes two values. -- @@ -118,30 +127,33 @@ instance (Identifiable a, Eq (Identifier a), Superimposable a) => Superimposable parseMode :: H.ParseMode parseMode = H.defaultParseMode { H.fixities = Nothing } --- All Haskell syntax trees here carry the annotation (), since the source --- positions the parser records would otherwise make equal values compare as different. +-- | A wrapper for enabling equality checks between 'H.Annotated' AST nodes (via 'H.=~='). +newtype Ann a ann = Ann (a ann) + +instance (H.Annotated a, Eq (a ())) => Eq (Ann a ann) where + Ann x == Ann y = x H.=~= y -instance Superimposable (H.CName ()) -instance Superimposable (H.QualConDecl ()) -instance Superimposable (H.InstRule ()) -instance Superimposable (H.Match ()) +instance Superimposable (H.CName ann) +instance Superimposable (H.QualConDecl ann) +instance Superimposable (H.InstRule ann) +instance Superimposable (H.Match ann) -instance Identifiable (H.CName ()) where - type Identifier (H.CName ()) = H.Name () - identify (H.VarName _ name) = Right name - identify (H.ConName _ name) = Right name +instance Identifiable (H.CName ann) where + type Identifier (H.CName ann) = Ann H.Name ann + identify (H.VarName _ name) = Right (Ann name) + identify (H.ConName _ name) = Right (Ann name) -- | A constructor is identified by its name. -instance Identifiable (H.QualConDecl ()) where - type Identifier (H.QualConDecl ()) = H.Name () +instance Identifiable (H.QualConDecl ann) where + type Identifier (H.QualConDecl ann) = Ann H.Name ann identify (H.QualConDecl _ _ _ con) = case con of - H.ConDecl _ name _ -> Right name - H.InfixConDecl _ _ name _ -> Right name - H.RecDecl _ name _ -> Right name + H.ConDecl _ name _ -> Right (Ann name) + H.InfixConDecl _ _ name _ -> Right (Ann name) + H.RecDecl _ name _ -> Right (Ann name) -instance Identifiable (H.InstRule ()) where - type Identifier (H.InstRule ()) = H.InstRule () - identify = Right +instance Identifiable (H.InstRule ann) where + type Identifier (H.InstRule ann) = Ann H.InstRule ann + identify = Right . Ann -- | Splits a function clause into its name and patterns. -- An infix definition such as @x ++ y = e@ is treated like @(++) x y = e@. @@ -150,35 +162,35 @@ clause (H.Match _ name pats _ _) = (name, pats) clause (H.InfixMatch _ pat name pats _ _) = (name, pat : pats) -- | A function is identified by its patterns. -instance Identifiable (H.Match ()) where - type Identifier (H.Match ()) = [H.Pat ()] - identify = Right . snd . clause +instance Identifiable (H.Match ann) where + type Identifier (H.Match ann) = [Ann H.Pat ann] + identify = Right . map Ann . snd . clause -- Pragmas -------------------------------------------------------------------- -- | Identifiers for module pragmas. -data PragmaId - = Extension (H.Name ()) -- ^ A @LANGUAGE@ pragma. - | Options (Maybe H.Tool) [String] -- ^ An @OPTIONS@ pragma, such as @OPTIONS_GHC@. - | Annotated (H.ModulePragma ()) -- ^ An @ANN@ pragma, identified by its contents. +data PragmaId ann + = Extension (Ann H.Name ann) -- ^ A @LANGUAGE@ pragma. + | Options (Maybe H.Tool) [String] -- ^ An @OPTIONS@ pragma, such as @OPTIONS_GHC@. + | Annotated (Ann H.ModulePragma ann) -- ^ An @ANN@ pragma, identified by its contents. deriving Eq -- | Splits a @LANGUAGE@ pragma holding several extensions into one pragma per extension. -- -- For instance, @{-# LANGUAGE A, B #-}@ is flattened into @{-# LANGUAGE A #-}@ and @{-# LANGUAGE B #-}@. -- All other pragmas are left as is. -flattenPragmas :: H.ModulePragma () -> [H.ModulePragma ()] -flattenPragmas (H.LanguagePragma _ names) = [H.LanguagePragma () [name] | name <- names] +flattenPragmas :: H.ModulePragma ann -> [H.ModulePragma ann] +flattenPragmas (H.LanguagePragma l names) = [H.LanguagePragma l [name] | name <- names] flattenPragmas pragma = [pragma] -instance Superimposable (H.ModulePragma ()) +instance Superimposable (H.ModulePragma ann) -instance Identifiable (H.ModulePragma ()) where - type Identifier (H.ModulePragma ()) = PragmaId - identify (H.LanguagePragma _ [name]) = Right (Extension name) +instance Identifiable (H.ModulePragma ann) where + type Identifier (H.ModulePragma ann) = PragmaId ann + identify (H.LanguagePragma _ [name]) = Right (Extension (Ann name)) identify (H.LanguagePragma _ _) = Left "Cannot merge a LANGUAGE pragma that holds several extensions" identify (H.OptionsPragma _ tool opt) = Right (Options tool (words opt)) - identify pragma@(H.AnnModulePragma _ _) = Right (Annotated pragma) + identify pragma@(H.AnnModulePragma _ _) = Right (Annotated (Ann pragma)) -- Modules -------------------------------------------------------------------- @@ -188,13 +200,13 @@ instance Identifiable (H.ModulePragma ()) where -- For instance, the Haskell type signature @f g :: A@ is flattened into @f :: A@ and @g :: A@. -- -- Note that pragmas attached to declarations (such as @WARNING@) are dropped by 'flattenDecls'. -flattenDecls :: H.Decl () -> [H.Decl ()] -flattenDecls (H.TypeSig _ names ty) = [H.TypeSig () [name] ty | name <- names] -flattenDecls (H.InfixDecl _ assoc prec ops) = [H.InfixDecl () assoc prec [op] | op <- ops] -flattenDecls (H.PatBind _ (H.PVar _ name) rhs wheres) - = [H.FunBind () [H.Match () name [] rhs wheres]] -flattenDecls (H.InstDecl _ overlap rule decls) - = [H.InstDecl () overlap rule (fmap (concatMap flattenInstDecl) decls)] +flattenDecls :: H.Decl ann -> [H.Decl ann] +flattenDecls (H.TypeSig l names ty) = [H.TypeSig l [name] ty | name <- names] +flattenDecls (H.InfixDecl l assoc prec ops) = [H.InfixDecl l assoc prec [op] | op <- ops] +flattenDecls (H.PatBind l (H.PVar _ name) rhs wheres) + = [H.FunBind l [H.Match l name [] rhs wheres]] +flattenDecls (H.InstDecl l overlap rule decls) + = [H.InstDecl l overlap rule (fmap (concatMap flattenInstDecl) decls)] flattenDecls H.InlineSig {} = [] flattenDecls H.InlineConlikeSig {} = [] flattenDecls H.SpecSig {} = [] @@ -208,15 +220,15 @@ flattenDecls H.MinimalPragma {} = [] flattenDecls decl = [decl] -- | Flattens the declarations inside of an instance declaration. -flattenInstDecl :: H.InstDecl () -> [H.InstDecl ()] -flattenInstDecl (H.InsDecl _ decl) = map (H.InsDecl ()) (flattenDecls decl) +flattenInstDecl :: H.InstDecl ann -> [H.InstDecl ann] +flattenInstDecl (H.InsDecl l decl) = map (H.InsDecl l) (flattenDecls decl) flattenInstDecl decl = [decl] -- | To superimpose two Haskell modules, they must have the same name. -- Then, their pragmas, exports, and imports are merged. -- Pragmas and declarations are flattened before they are merged. See 'flattenPragmas' and 'flattenDecls'. -instance Superimposable (H.Module ()) where - H.Module _ head1 pragmas1 imps1 decls1 --> H.Module _ head2 pragmas2 imps2 decls2 = do +instance Superimposable (H.Module ann) where + H.Module l head1 pragmas1 imps1 decls1 --> H.Module _ head2 pragmas2 imps2 decls2 = do hd <- case (head1, head2) of (Just h1, Just h2) -> fmap Just (h1 --> h2) (Nothing, Nothing) -> Right Nothing @@ -224,89 +236,89 @@ instance Superimposable (H.Module ()) where pragmas <- concatMap flattenPragmas pragmas1 --> concatMap flattenPragmas pragmas2 imps <- imps1 --> imps2 decls <- concatMap flattenDecls decls1 --> concatMap flattenDecls decls2 - return (H.Module () hd pragmas imps decls) + return (H.Module l hd pragmas imps decls) _ --> _ = Left "Cannot merge modules that are not plain Haskell modules" -- | A module header holds the module name and its exports. -- The names must be the same, and then the exports are merged. -instance Superimposable (H.ModuleHead ()) where - H.ModuleHead _ mod1 warn1 exps1 --> H.ModuleHead _ mod2 _ exps2 - | mod1 == mod2 = do +instance Superimposable (H.ModuleHead ann) where + H.ModuleHead l mod1 warn1 exps1 --> H.ModuleHead _ mod2 _ exps2 + | mod1 H.=~= mod2 = do exps <- sequenceA (liftA2 (-->) exps1 exps2) - return (H.ModuleHead () mod1 warn1 exps) - | otherwise = Left ("Cannot merge differing modules: " ++ H.prettyPrint mod1 ++ " and " ++ H.prettyPrint mod2) + return (H.ModuleHead l mod1 warn1 exps) + | otherwise = Left ("Cannot merge differing modules: " ++ H.prettyPrint (void mod1) ++ " and " ++ H.prettyPrint (void mod2)) -- Exports -------------------------------------------------------------------- -instance Superimposable (H.ExportSpecList ()) where - H.ExportSpecList _ xs --> H.ExportSpecList _ ys = fmap (H.ExportSpecList ()) (xs --> ys) +instance Superimposable (H.ExportSpecList ann) where + H.ExportSpecList l xs --> H.ExportSpecList _ ys = fmap (H.ExportSpecList l) (xs --> ys) -instance Superimposable (H.ExportSpec ()) where +instance Superimposable (H.ExportSpec ann) where x@(H.EThingWith _ (H.EWildcard {}) _ _) --> _ = Right x _ --> y@(H.EThingWith _ (H.EWildcard {}) _ _) = Right y - H.EThingWith _ wild name xs --> H.EThingWith _ _ _ ys - = fmap (H.EThingWith () wild name) (xs --> ys) + H.EThingWith l wild name xs --> H.EThingWith _ _ _ ys + = fmap (H.EThingWith l wild name) (xs --> ys) H.EAbs _ _ _ --> y@(H.EThingWith _ _ _ _) = Right y x --> _ = Right x -instance Identifiable (H.ExportSpec ()) where +instance Identifiable (H.ExportSpec ann) where -- An export spec is identified by an entity or a whole module. - type Identifier (H.ExportSpec ()) = Either (H.QName ()) (H.ModuleName ()) - identify (H.EVar _ name) = Right (Left name) - identify (H.EAbs _ _ name) = Right (Left name) - identify (H.EThingWith _ _ name _) = Right (Left name) - identify (H.EModuleContents _ modl) = Right (Right modl) + type Identifier (H.ExportSpec ann) = Either (Ann H.QName ann) (Ann H.ModuleName ann) + identify (H.EVar _ name) = Right (Left (Ann name)) + identify (H.EAbs _ _ name) = Right (Left (Ann name)) + identify (H.EThingWith _ _ name _) = Right (Left (Ann name)) + identify (H.EModuleContents _ modl) = Right (Right (Ann modl)) -- Imports -------------------------------------------------------------------- -instance Superimposable (H.ImportDecl ()) where +instance Superimposable (H.ImportDecl ann) where x --> y = do specs <- sequenceA (liftA2 (-->) (H.importSpecs x) (H.importSpecs y)) return (x { H.importSpecs = specs }) -instance Identifiable (H.ImportDecl ()) where - type Identifier (H.ImportDecl ()) = (H.ModuleName (), Bool, Maybe (H.ModuleName ())) - identify imp = Right (H.importModule imp, H.importQualified imp, H.importAs imp) +instance Identifiable (H.ImportDecl ann) where + type Identifier (H.ImportDecl ann) = (Ann H.ModuleName ann, Bool, Maybe (Ann H.ModuleName ann)) + identify imp = Right (Ann (H.importModule imp), H.importQualified imp, fmap Ann (H.importAs imp)) -- Note that @ImportSpecList _ False xs@ imports only @xs@, -- and @ImportSpecList _ True xs@ imports everything except @xs@. -instance Superimposable (H.ImportSpecList ()) where - H.ImportSpecList _ False xs --> H.ImportSpecList _ False ys = fmap (H.ImportSpecList () False) (xs --> ys) - H.ImportSpecList _ True xs --> H.ImportSpecList _ True ys = do +instance Superimposable (H.ImportSpecList ann) where + H.ImportSpecList l False xs --> H.ImportSpecList _ False ys = fmap (H.ImportSpecList l False) (xs --> ys) + H.ImportSpecList l True xs --> H.ImportSpecList _ True ys = do xids <- traverse identify xs yids <- traverse identify ys - return (H.ImportSpecList () True [x | (x, xid) <- zip xs xids, xid `elem` yids]) - H.ImportSpecList _ False xs --> H.ImportSpecList _ True ys = do + return (H.ImportSpecList l True [x | (x, xid) <- zip xs xids, xid `elem` yids]) + H.ImportSpecList l False xs --> H.ImportSpecList _ True ys = do xids <- traverse identify xs yids <- traverse identify ys - return (H.ImportSpecList () True [y | (y, yid) <- zip ys yids, yid `notElem` xids]) - H.ImportSpecList _ True xs --> H.ImportSpecList _ False ys = do + return (H.ImportSpecList l True [y | (y, yid) <- zip ys yids, yid `notElem` xids]) + H.ImportSpecList l True xs --> H.ImportSpecList _ False ys = do xids <- traverse identify xs yids <- traverse identify ys - return (H.ImportSpecList () True [x | (x, xid) <- zip xs xids, xid `notElem` yids]) + return (H.ImportSpecList l True [x | (x, xid) <- zip xs xids, xid `notElem` yids]) -instance Superimposable (H.ImportSpec ()) where +instance Superimposable (H.ImportSpec ann) where x@(H.IThingAll _ _) --> _ = Right x _ --> y@(H.IThingAll _ _) = Right y - H.IThingWith _ name xs --> H.IThingWith _ _ ys - = fmap (H.IThingWith () name) (xs --> ys) + H.IThingWith l name xs --> H.IThingWith _ _ ys + = fmap (H.IThingWith l name) (xs --> ys) H.IAbs _ _ _ --> y@(H.IThingWith _ _ _) = Right y x --> _ = Right x -instance Identifiable (H.ImportSpec ()) where - type Identifier (H.ImportSpec ()) = H.Name () - identify (H.IVar _ name) = Right name - identify (H.IAbs _ _ name) = Right name - identify (H.IThingAll _ name) = Right name - identify (H.IThingWith _ name _) = Right name +instance Identifiable (H.ImportSpec ann) where + type Identifier (H.ImportSpec ann) = Ann H.Name ann + identify (H.IVar _ name) = Right (Ann name) + identify (H.IAbs _ _ name) = Right (Ann name) + identify (H.IThingAll _ name) = Right (Ann name) + identify (H.IThingWith _ name _) = Right (Ann name) -- Declarations --------------------------------------------------------------- @@ -314,13 +326,12 @@ instance Identifiable (H.ImportSpec ()) where -- -- Only these declarations can be merged. Everything else (classes, default -- declarations, foreign declarations, pattern bindings) is rejected by 'identify'. -data DeclId - = Value (H.Name ()) -- ^ Functions and variables. - | Sig (H.Name ()) -- ^ Type signatures. - | Type (H.Name ()) -- ^ Type synonyms, datatype declarations, and @newtype@s. - | Fixity (H.Name ()) -- ^ Fixity declarations. - | Instance (H.InstHead ()) - -- ^ Typeclass instance declarations. +data DeclId ann + = Value (Ann H.Name ann) -- ^ Functions and variables. + | Sig (Ann H.Name ann) -- ^ Type signatures. + | Type (Ann H.Name ann) -- ^ Type synonyms, datatype declarations, and @newtype@s. + | Fixity (Ann H.Name ann) -- ^ Fixity declarations. + | Instance (Ann H.InstHead ann) -- ^ Typeclass instance declarations. deriving Eq -- | Finds the name that a declaration head (such as @T a b@) declares. @@ -339,7 +350,7 @@ instHead (H.IParen _ rule) = instHead rule -- These are as follows. -- -- * Type synonyms --- * Datatype declarations +-- * Datatype declarations (including GADTs) -- * Newtype declarations -- * Function bindings -- * Type signatures @@ -347,53 +358,54 @@ instHead (H.IParen _ rule) = instHead rule -- * Typeclass instance declarations. -- -- See 'DeclId'. -instance Identifiable (H.Decl ()) where - type Identifier (H.Decl ()) = DeclId - identify (H.TypeDecl _ hd _) = Right (Type (headName hd)) - identify (H.DataDecl _ _ _ hd _ _) = Right (Type (headName hd)) - identify (H.FunBind _ (m : _)) = Right (Value (fst (clause m))) - identify (H.TypeSig _ [name] _) = Right (Sig name) - identify (H.InfixDecl _ _ _ [H.VarOp _ name]) = Right (Fixity name) - identify (H.InfixDecl _ _ _ [H.ConOp _ name]) = Right (Fixity name) - identify (H.InstDecl _ _ rule _) = Right (Instance (instHead rule)) +instance Identifiable (H.Decl ann) where + type Identifier (H.Decl ann) = DeclId ann + identify (H.TypeDecl _ hd _) = Right (Type (Ann (headName hd))) + identify (H.DataDecl _ _ _ hd _ _) = Right (Type (Ann (headName hd))) + identify (H.GDataDecl _ _ _ hd _ _ _) = Right (Type (Ann (headName hd))) + identify (H.FunBind _ (m : _)) = Right (Value (Ann (fst (clause m)))) + identify (H.TypeSig _ [name] _) = Right (Sig (Ann name)) + identify (H.InfixDecl _ _ _ [H.VarOp _ name]) = Right (Fixity (Ann name)) + identify (H.InfixDecl _ _ _ [H.ConOp _ name]) = Right (Fixity (Ann name)) + identify (H.InstDecl _ _ rule _) = Right (Instance (Ann (instHead rule))) identify decl = Left ("Cannot merge this declaration: " - ++ takeWhile (/= '\n') (dropWhile isSpace (H.prettyPrint decl))) + ++ takeWhile (/= '\n') (dropWhile isSpace (H.prettyPrint (void decl)))) -- | Datatype declarations, functions, and typeclass instance declarations are merged. -- Type synonyms, @newtype@s, type signatures, and fixity declarations are overridden from the left. -instance Superimposable (H.Decl ()) where - H.DataDecl _ dn@(H.DataType _) ctx hd cons1 derivs1 --> H.DataDecl _ (H.DataType _) _ _ cons2 derivs2 = do +instance Superimposable (H.Decl ann) where + H.DataDecl l dn@(H.DataType _) ctx hd cons1 derivs1 --> H.DataDecl _ (H.DataType _) _ _ cons2 derivs2 = do cons <- cons1 --> cons2 derivs <- derivs1 --> derivs2 - return (H.DataDecl () dn ctx hd cons derivs) - H.FunBind _ ms1 --> H.FunBind _ ms2 + return (H.DataDecl l dn ctx hd cons derivs) + H.FunBind l ms1 --> H.FunBind _ ms2 | length (nub [length (snd (clause m)) | m <- ms1 ++ ms2]) == 1 - = fmap (H.FunBind ()) (ms1 --> ms2) - H.InstDecl _ overlap rule decls1 --> H.InstDecl _ _ _ decls2 = do + = fmap (H.FunBind l) (ms1 --> ms2) + H.InstDecl l overlap rule decls1 --> H.InstDecl _ _ _ decls2 = do decls <- fromMaybe [] decls1 --> fromMaybe [] decls2 - return (H.InstDecl () overlap rule (if null decls then Nothing else Just decls)) + return (H.InstDecl l overlap rule (if null decls then Nothing else Just decls)) x --> _ = Right x -instance Superimposable (H.InstDecl ()) where - H.InsDecl _ x --> H.InsDecl _ y = fmap (H.InsDecl ()) (x --> y) +instance Superimposable (H.InstDecl ann) where + H.InsDecl l x --> H.InsDecl _ y = fmap (H.InsDecl l) (x --> y) x --> _ = Right x -instance Identifiable (H.InstDecl ()) where - type Identifier (H.InstDecl ()) = DeclId +instance Identifiable (H.InstDecl ann) where + type Identifier (H.InstDecl ann) = DeclId ann identify (H.InsDecl _ decl) = identify decl identify decl = Left ("Cannot merge this instance declaration: " ++ - takeWhile (/= '\n') (dropWhile isSpace (H.prettyPrint decl))) + takeWhile (/= '\n') (dropWhile isSpace (H.prettyPrint (void decl)))) -- | A @deriving@ clause is identified by its strategy (e.g., 'H.DerivStock'). -- Clauses with the same strategy are merged, and the classes they derive are merged by their names. -instance Superimposable (H.Deriving ()) where - H.Deriving _ strat rules1 --> H.Deriving _ _ rules2 - = fmap (H.Deriving () strat) (rules1 --> rules2) +instance Superimposable (H.Deriving ann) where + H.Deriving l strat rules1 --> H.Deriving _ _ rules2 + = fmap (H.Deriving l strat) (rules1 --> rules2) -instance Identifiable (H.Deriving ()) where - type Identifier (H.Deriving ()) = Maybe (H.DerivStrategy ()) - identify (H.Deriving _ strat _) = Right strat +instance Identifiable (H.Deriving ann) where + type Identifier (H.Deriving ann) = Maybe (Ann H.DerivStrategy ann) + identify (H.Deriving _ strat _) = Right (fmap Ann strat) ------------------------------------------------------------------------------- -- Happy @@ -417,7 +429,7 @@ instance Identifiable (Y.Rule String) where type Identifier (Y.Rule String) = String identify (Y.Rule name _ _ _) = Right name --- | @%token@ directives are merged and @%name@ directives are overridden from the left. +-- | @%token@ directives are merged, whereas @%name@ and @%partial@ directives are overridden from the left. -- Other differing directives are simply rejected. instance Superimposable (Y.Directive String) where x@(Y.TokenSpec _) --> _ = Right x @@ -429,7 +441,7 @@ instance Superimposable (Y.Directive String) where -- | Identifiers for Happy directives. data DirectiveId = Token String -- ^ A @%token@ directive, one per token. - | Name String -- ^ The @%name@ directive. + | Name String -- ^ A @%name@ or @%partial@ directive. | Attribute String -- ^ The @%attribute@ directive. | Prec String -- ^ A @%left@, @%right@, or @%nonassoc@ directive, one per token. | Other String -- ^ Any other directive. @@ -438,7 +450,6 @@ data DirectiveId instance Identifiable (Y.Directive String) where type Identifier (Y.Directive String) = DirectiveId identify (Y.TokenSpec [(name, _)]) = Right (Token name) - identify (Y.TokenName _ _ True) = Left "Cannot merge %partial directives" identify (Y.TokenName name _ _) = Right (Name name) identify (Y.TokenAttribute name _) = Right (Attribute name) identify (Y.TokenLeft [name]) = Right (Prec name) @@ -538,17 +549,17 @@ instance Superimposable Y.BookendedAbsSyn where modl1 <- parse head1 foot1 modl2 <- parse head2 foot2 merged <- modl1 --> modl2 - (shell, decls) <- case merged of - H.Module _ hd pragmas imps ds -> Right (H.Module () hd pragmas imps [], ds) + (sh, decls) <- case merged of + H.Module l hd pragmas imps ds -> Right (H.Module l hd pragmas imps [], ds) _ -> Left "Invalid Happy header or footer: not a plain Haskell module" syn <- syn1 --> syn2 return (Y.BookendedAbsSyn (opts1 <|> opts2) -- The header contains the pragmas, the Haskell module declaration and imports. - (Just (H.prettyPrint shell)) + (Just (H.prettyPrint (void sh))) syn -- The footer contains Haskell declarations. - (Just (unlines (map H.prettyPrint decls)))) + (Just (unlines (map (H.prettyPrint . void) decls)))) where parse header footer = case H.parseModuleWithMode parseMode (unlines (catMaybes [header, footer])) of - H.ParseOk modl -> Right (void modl) + H.ParseOk modl -> Right modl H.ParseFailed _ msg -> Left ("Invalid Happy header or footer: " ++ msg) \ No newline at end of file diff --git a/LayeredHaskell-make/src/LHMake/Data/Feature.hs b/LayeredHaskell-make/src/LHMake/Data/Feature.hs index f0d53fb..72fd49f 100644 --- a/LayeredHaskell-make/src/LHMake/Data/Feature.hs +++ b/LayeredHaskell-make/src/LHMake/Data/Feature.hs @@ -17,13 +17,13 @@ module LHMake.Data.Feature ( -- * Features FeatureName, ModuleName, Feature (..), feature, -- ** Registries - Registry, registry, + Registry, registry, resolve, -- ** Superimposing features - FeatureSet, resolve, superimpose, + Layer, Layer', superimpose, superimposeUpp, -- ** Listing features list, listAll, listDeps, - -- ** Listing feature combinations - combos, generate, generateCombos, + -- ** Listing layers + layers, generate, generateLayers, -- * Dependencies Dependency (..), -- ** Convenient synonyms @@ -35,13 +35,13 @@ module LHMake.Data.Feature ( import Control.Monad (forM, forM_, unless, when) import Data.Bifunctor (first) import Data.Functor (void) -import Data.List (intercalate) +import Data.List (intercalate, sortOn) import Data.Map (Map) import Data.Maybe (maybeToList) import Data.Set (Set) import System.Directory (createDirectoryIfMissing, doesFileExist) import System.Exit (die) -import System.FilePath (takeDirectory, (), (<.>)) +import System.FilePath (pathSeparator, takeDirectory, (), (<.>)) import System.IO (readFile') import Happy.Frontend (parseYFileContents) @@ -51,11 +51,12 @@ import qualified Language.Haskell.Exts as H import qualified Data.Graph as Graph import qualified Data.Map as Map import qualified Data.Set as Set +import qualified Data.Text as Text import LHMake.Control.Superimposition ((-->), parseMode) import LHMake.Data.Error (LHsMakeError) import LHMake.Text.Happy.Pretty (pprHappy) -import LHMake.Text.Label (infoLabel, errLabel) +import LHMake.Text.Label (infoLabel, hintLabel, warnLabel, errLabel) ------------------------------------------------------------------------------- -- Features @@ -66,7 +67,7 @@ type FeatureName = String -- | The name of a Haskell module or Happy grammar (which itself denotes a Haskell module). type ModuleName = String --- | A language feature \(f\) is represented using four components: the files holding its Haskell modules, +-- | A language feature \(f\) is represented using four primary components: a set of Haskell source files, -- at most one Happy grammar file, and two nested sets of feature names that represent what \(f\) depends on, -- and in what cases \(f\) is automatically enabled. -- @@ -76,7 +77,11 @@ type ModuleName = String -- ['dependsOn']: ...denotes /all/ conditions holding. -- ['impliedBy']: ...denotes /some/ condition holding. -- --- See 'feature'. +-- The two remaining components are a description of \(f\) ('descrip') and whether +-- \(f\) can be enabled manually ('hidden'). +-- +-- 'feature' is a smart constructor for 'Feature' values that might be more preferable for use, as it uses +-- a helper datatype 'Dependency' to more idiomatically express dependencies and implications. data Feature = Feature { descrip :: String -- ^ A short description of \(f\). , modules :: [FilePath] -- ^ Haskell source files. @@ -91,14 +96,14 @@ data Feature = Feature -- @{{A}, {B, C}}@ means @A@ or (@B@ and @C@). See 'dnf'. , hidden :: Bool -- ^ If 'True', \(f\) may only be enabled automatically. + -- + -- 'hidden' prevents features that might produce partial or invalid files from being enabled at will. } -- | Builds a 'Feature' \(f\) specified in terms of values of type 'Dependency'. -- The two 'Dependency' arguments are automatically converted into the respective normal forms. See 'cnf' and 'dnf'. -- --- The filepaths 'feature' expects should be written relative to @LayeredHaskell-make\/src\/LH\/Feature\/@. --- --- Note that since 'feature' takes 'Dependency' arguments, it's easier to construct features using this over the original constructor 'Feature'. +-- The filepaths 'feature' expects are relative to @LayeredHaskell-make\/src\/LH\/Feature\/@. feature :: String -- ^ A short description of \(f\). See 'descrip'. -> [FilePath] -- ^ Haskell source files (specified /relatively/, e.g. @E/AbsSyn.hs@). See 'modules'. @@ -119,25 +124,28 @@ type Registry = Map FeatureName Feature -- | The set of /all/ features. -- --- ==== __Features__ +-- Features that are 'hidden' are marked with an asterisk (*). -- --- Layered Haskell defines the following features. --- Hidden features are /italicized/. +-- +------+-----------------------------------+------------------+------------------+ +-- | Name | 'descrip' | 'dependsOn' | 'impliedBy' | +-- +======+===================================+==================+==================+ +-- | @E@* | Expressions | /none/ | /none/ | +-- +------+-----------------------------------+------------------+------------------+ +-- | @B@ | Basic types (@Int@ and @Bool@) | @E@ | /none/ | +-- +------+-----------------------------------+------------------+------------------+ +-- | @D@ | (Monomorphic) algebraic datatypes | @E@ | /none/ | +-- +------+-----------------------------------+------------------+------------------+ +-- | @F@ | Functions and patterns | @B@ or @D@ | /none/ | +-- +------+-----------------------------------+------------------+------------------+ +-- | @C@* | Case expressions | /none/ | @F@ and @D@ | +-- +------+-----------------------------------+------------------+------------------+ +-- | @L@ | List and tuple syntax | @F@ and @D@ | /none/ | +-- +------+-----------------------------------+------------------+------------------+ +-- | @P@ | (Prenex) polymorphism | @D@ | /none/ | +-- +------+-----------------------------------+------------------+------------------+ -- --- [@E@]: /Expressions/. --- All other features, whether it be directly or indirectly, depends on @E@. --- [@B@]: Basic types, namely @Int@ and @Bool@. --- Depends on @E@. --- [@D@]: (Monomorphic) algebraic datatypes. --- Depends on @E@. --- [@F@]: Functions and basic pattern matching. --- Depends on @B@ or @D@. --- [@C@]: /Case expressions/. --- Implied by @F@ and @D@. --- [@P@]: Prenex polymorphism (with implicit @forall@s). --- Depends on @D@. --- [@L@]: List and tuple syntax. --- Depends on @F@ and @D@. +-- As mentioned in the description of 'superimposeUpp', +-- all feature-related modules are expected to begin with @LH.Feature.*@. registry :: Registry registry = Map.fromList [ ("E", feature "Expressions" @@ -187,11 +195,15 @@ registry = Map.fromList ------------------------------------------------------------------------------- -- Merging features --- | A feature set is a set of features, which we simply identify by their names. -type FeatureSet = Set FeatureName +-- | A layer is a collection of features. +type Layer = [FeatureName] + +-- | An intermediate representation of layers as a 'Set'. +-- 'Layer'' is used internally just for the sake of efficiency. +type Layer' = Set FeatureName -- | Repeatedly adds to a set of feature names until nothing new gets added. -select :: Registry -> FeatureSet -> FeatureSet +select :: Registry -> Layer' -> Layer' select reg names | Set.size added == Set.size names = names | otherwise = select reg added @@ -201,9 +213,9 @@ select reg names (Map.restrictKeys reg names) implications = Map.keysSet (Map.filter (any (`Set.isSubsetOf` names) . impliedBy) reg) --- | Attempt to produce the features in a valid order. +-- | Attempts to produce the features in a valid order. -- Specifically, every feature should occur before the features the 'dependsOn' and 'impliedBy' fields refer to. -order :: Registry -> FeatureSet -> LHsMakeError [FeatureName] +order :: Registry -> Layer' -> LHsMakeError Layer order reg names = fmap reverse (traverse acyclic (Graph.stronglyConnComp nodes)) where nodes = [ (name, name, Set.toList (Set.unions (dependsOn feat <> impliedBy feat))) @@ -212,14 +224,14 @@ order reg names = fmap reverse (traverse acyclic (Graph.stronglyConnComp nodes)) acyclic (Graph.CyclicSCC members) = Left ("These features have cyclic dependencies: " ++ unwords members) -- | Lists every unknown feature name. -unknown :: Registry -> FeatureSet -> [String] +unknown :: Registry -> Layer' -> [String] unknown reg names = [ "Unknown feature: " ++ name | name <- Set.toList (Set.filter (`Map.notMember` reg) names) ] -- | Lists every problem with a set of feature names. -- An empty result means that there are no problems with the set. -check :: Registry -> FeatureSet -> [String] +check :: Registry -> Layer' -> [String] check reg names = unknown reg names ++ [ "Can't automatically resolve dependencies of " ++ name ++ ", explicitly enable one of: " ++ unwords (Set.toList clause) @@ -227,17 +239,19 @@ check reg names = , clause <- Set.toList (dependsOn feat) , Set.disjoint clause names ] --- | Decides which features are really needed for a selection. +-- | With respect to a 'Registry', resolves all dependencies and implications within the input 'Layer''. +-- For instance, if the input 'Registry' is 'registry' and the input 'Layer'' is @{B}@ (taking some liberties with the notation), +-- @'resolve' 'registry' {B, F, D} == 'Right' [B, F, D, C, E]@. -- --- 'resolve' generates an error if any of the following are true. +-- 'resolve' emits an error if any of the following are true. -- -- * One or more 'hidden' features were manually enabled. --- * The 'registry' is ill-formed in that it contains unknown features. +-- * The input 'Registry' is ill-formed in that it contains unknown features. -- * The enabled features have dependencies that cannot be unambiguously resolved. -- -- The last case occurs when, say, a feature @A@ depends on features @B@ or @C@, but only @A@ was manually enabled. -- To avoid an arbitrary choice between @B@ and @C@, an error is emitted. -resolve :: Registry -> FeatureSet -> LHsMakeError [FeatureName] +resolve :: Registry -> Layer' -> LHsMakeError Layer resolve reg names = do let hide = Map.keys (Map.filter hidden (Map.restrictKeys reg names)) selected = select reg names @@ -282,9 +296,9 @@ load feat = do moduleName _ (H.Module _ (Just (H.ModuleHead _ (H.ModuleName _ name) _ _)) _ _ _) = Right name moduleName file _ = Left (file ++ ": The module has no header, so I can't identify it") --- | Resolves the dependencies inherent to a 'FeatureSet', then superimposes modules and grammars +-- | Resolves the dependencies inherent to a 'Layer'', then superimposes modules and grammars -- such that a single set of Haskell modules and at most one Happy grammar is produced. -merge :: Registry -> FeatureSet -> IO (LHsMakeError (Map ModuleName (H.Module ()), Map ModuleName BookendedAbsSyn)) +merge :: Registry -> Layer' -> IO (LHsMakeError (Map ModuleName (H.Module ()), Map ModuleName BookendedAbsSyn)) merge reg names = case resolve reg names of Left err -> return (Left (errLabel err)) Right enabled -> do @@ -303,25 +317,65 @@ merge reg names = case resolve reg names of (,) <$> mergeAll modls <*> mergeAll grams -- | Superimposes features (and implicit dependencies), and outputs files to a specified directory. --- The directory should written in the format of, say, @src\/LH\/Feature@, --- since 'superimpose' simply appends it to the front of the filepath using '()'. +-- +-- The directory should be the root of the module hierarchy (for example, @src@), +-- since each module is written to a filepath corresponding to its name. +-- For instance, the module @LH.Feature.AbsSyn@ with the argument @src@ produces the +-- path @src\/LH\/Feature\/AbsSyn.hs@. -- -- Note that 'superimpose' will write to a file /only/ if its contents have changed. -superimpose :: [FeatureName] -> FilePath -> IO () -superimpose names dir = do +superimpose :: Layer -> FilePath -> IO () +superimpose = superimposeWith id + +-- | Invokes 'superimpose' with the most expressive (i.e., /uppermost/) layer, +-- which is a layer maximal in the sense that it ends up enabling +-- the most features in total. +-- +-- The maximal layer is always unique, since combining two valid layers +-- always produces another valid one (as 'Dependency' doesn't have negations). +-- +-- The result of 'superimposeUpp' produces modules with the prefix @LH.Feature.Upp.*@. +-- Hence, all feature-related modules are expected to begin with @LH.Feature.*@. +superimposeUpp :: FilePath -> IO () +superimposeUpp dir = do + allLayers <- generateLayers + let total = Set.size . select registry . Set.fromList + maximal = case sortOn (negate . total) allLayers of + (most:_) -> most + [] -> [] + putStrLn $ hintLabel $ "LayeredHaskell-make identified the maximal layer: " + ++ if null maximal then "[]" else unwords maximal + when (null maximal) (putStrLn $ warnLabel "The maximal layer contains no features.") + superimposeWith upp maximal dir + where + -- Replaces all instances of `LH.Feature.' with `LH.Feature.Upp.' + -- while also keeping existing instances of `LH.Feature.Upp.' the same. + upp = Text.unpack + . replaceWith "LH.Feature." "LH.Feature.Upp." + . replaceWith "LH.Feature.Upp." "LH.Feature." + . Text.pack + -- Replaces all instances of a with b. + replaceWith a b = Text.replace (Text.pack a) (Text.pack b) + +-- | A helper for 'superimpose' and 'superimposeUpp'. +superimposeWith :: (String -> String) -- ^ A renaming function for module names. + -> Layer + -> FilePath + -> IO () +superimposeWith rename names dir = do putStrLn $ infoLabel "LayeredHaskell-make is starting up..." (haskell, happy) <- merge registry (Set.fromList names) >>= either die return forM_ (Map.toList haskell) $ \(name, modl) -> writeIfChanged - (dir end name <.> "hs") - (H.prettyPrint modl) + (dir toPath (rename name) <.> "hs") + (rename (H.prettyPrint modl)) forM_ (Map.toList happy) $ \(name, gram) -> writeIfChanged - (dir end name <.> "y") - (pprHappy gram) + (dir toPath (rename name) <.> "y") + (rename (pprHappy gram)) putStrLn $ infoLabel "Done!" where - end = reverse . takeWhile (/= '.') . reverse + toPath = map (\ch -> if ch == '.' then pathSeparator else ch) -- | Writes to a file only if its content differs. -- This way, we don't need to recompile everything on every build. @@ -360,7 +414,7 @@ list = printFeatures "Listing features..." (Map.filter (not . hidden) registry) listAll :: IO () listAll = printFeatures "Listing all features..." registry descrip --- | Lists all feature dependencies and implications. +-- | Lists all dependencies and implications between features in the 'registry'. listDeps :: IO () listDeps = printFeatures "Listing all dependencies and joint implications..." registry detail where @@ -377,13 +431,13 @@ listDeps = printFeatures "Listing all dependencies and joint implications..." re | not (Set.null xss) ] ------------------------------------------------------------------------------- --- Listing feature combinations +-- Listing layers --- | Generates a list of all feature combinations. +-- | Generates a list of all layers generatable from the features in the 'registry'. -- -- The Boolean paired with a 'FeatureName' is 'True' when the feature must be enabled manually. -combos :: LHsMakeError [[(FeatureName, Bool)]] -combos = do +layers :: LHsMakeError [[(FeatureName, Bool)]] +layers = do mapM_ Left (unknown registry (foldMap (Set.unions . dependsOn) registry)) fmap (filter (not . null)) $ forM (filter (null . check registry) @@ -397,29 +451,27 @@ combos = do -- False means that the feature can be automatically enabled as a dependency. manual names name = not (name `Set.member` select registry (Set.delete name names)) --- | Generates and prints a list of all possible (non-redundant) feature combinations, +-- | Generates and prints a list of all possible (non-redundant) layers from the features in the 'registry', -- with dependencies and implications automatically resolved. -- Dependencies that must be manually enabled are printed in color. generate :: IO () generate = do - putStrLn $ infoLabel "Listing all (non-redundant) feature combinations..." + putStrLn $ infoLabel "Listing all (non-redundant) layers..." putStrLn $ infoLabel ("Note that only " ++ colored "colored" ++ " features need to be enabled manually. ") ++ "The rest can be automatically resolved." - either (putStrLn . errLabel) report combos + either (putStrLn . errLabel) report layers where report entries = do mapM_ (putStrLn . infoLabel . unwords . map paint) entries - putStrLn $ infoLabel (show (length entries)) ++ " feature combinations found!" + putStrLn $ infoLabel (show (length entries)) ++ " layers found!" paint (name, manual) = if manual then colored name else name --- | Produces the feature combinations colored by 'generate'. --- --- One can interpret 'generateCombos' as a filtering of 'combos' lifted into the 'IO' monad. -generateCombos :: IO [[FeatureName]] -generateCombos = +-- | Extracts the layers colored by 'generate'. +generateLayers :: IO [Layer] +generateLayers = either (die . errLabel) (return . filter (not . null) . map (map fst . filter snd)) - combos + layers ------------------------------------------------------------------------------- -- Dependencies @@ -454,7 +506,7 @@ combine :: Ord a => Set (Set a) -> Set (Set a) -> Set (Set a) combine xs ys = Set.map (uncurry Set.union) (Set.cartesianProduct xs ys) -- | Computes the conjunctive normal form (CNF) of a 'Dependency'. --- See 'LH.Data.Feature.dependsOn'. +-- See 'dependsOn'. -- -- CNF denotes a set of requirements, each a set of features that must /all/ be enabled. cnf :: Dependency -> Set (Set FeatureName) @@ -464,7 +516,7 @@ cnf (Any deps) = foldr (combine . cnf) (Set.singleton Set.empty) deps cnf (All deps) = foldMap cnf deps -- | Computes the disjunctive normal form (DNF) of a 'Dependency'. --- See 'LH.Data.Feature.impliedBy'. +-- See 'impliedBy'. -- -- DNF denotes a set of alternatives, each a set of features that of which /one/ must be enabled. dnf :: Dependency -> Set (Set FeatureName) diff --git a/LayeredHaskell-make/src/LHMake/Feature/B/Parser.y b/LayeredHaskell-make/src/LHMake/Feature/B/Parser.y index 10b88c8..47efba9 100644 --- a/LayeredHaskell-make/src/LHMake/Feature/B/Parser.y +++ b/LayeredHaskell-make/src/LHMake/Feature/B/Parser.y @@ -12,19 +12,10 @@ Stability : experimental This module provides a parser for Layered Haskell programs with B enabled. -} -{-# LANGUAGE OverloadedStrings #-} module LH.Feature.Parser ( -- * Parsing - parseProgram + parseProgram, parsePartialProgram ) where - -import Data.Sequence (Seq) - -import LH.Data.SrcLoc -import LH.Feature.AbsSyn -import LH.Text.Lexer -import LH.Text.Parser.Monad -import LH.Text.Token } %name program Block @@ -33,6 +24,7 @@ import LH.Text.Token %monad { LHsParser } %lexer { lexer } { LHsLexeme _ LHsTkEOF } %error { parseError } +%error.expected -- There must be no shift/reduce conflicts. %expect 0 diff --git a/LayeredHaskell-make/src/LHMake/Feature/C/Parser.y b/LayeredHaskell-make/src/LHMake/Feature/C/Parser.y index 9ddfbd7..80d3dc0 100644 --- a/LayeredHaskell-make/src/LHMake/Feature/C/Parser.y +++ b/LayeredHaskell-make/src/LHMake/Feature/C/Parser.y @@ -14,18 +14,8 @@ This module provides a parser for Layered Haskell programs with C enabled. -} module LH.Feature.Parser ( -- * Parsing - parseProgram + parseProgram, parsePartialProgram ) where - -import Control.Monad.Except (throwError) - -import Data.Sequence (Seq, (<|)) - -import LH.Data.SrcLoc -import LH.Feature.AbsSyn -import LH.Text.Lexer -import LH.Text.Parser.Monad -import LH.Text.Token } %name program Block @@ -34,6 +24,7 @@ import LH.Text.Token %monad { LHsParser } %lexer { lexer } { LHsLexeme _ LHsTkEOF } %error { parseError } +%error.expected -- There must be no shift/reduce conflicts. %expect 0 @@ -55,8 +46,8 @@ Expr :: { L LHsExpr } { let alts = $5 <| $6 in L ($1 ><* fmap snd alts) (LHsCase $2 alts) } CaseAlts :: { Seq LHsAlt } - : SEMI CaseAlt CaseAlts { $2 <| $3 } - | {- ε -} { Seq.empty } + : SEMI CaseAlt CaseAlts { $2 <| $3 } + | {- ε -} { Seq.empty } CaseAlt :: { LHsAlt } - : Pat '->' Expr { ($1, $3) } + : Pat '->' Expr { ($1, $3) } diff --git a/LayeredHaskell-make/src/LHMake/Feature/D/Parser.y b/LayeredHaskell-make/src/LHMake/Feature/D/Parser.y index cb4bcf6..b327b6a 100644 --- a/LayeredHaskell-make/src/LHMake/Feature/D/Parser.y +++ b/LayeredHaskell-make/src/LHMake/Feature/D/Parser.y @@ -14,20 +14,8 @@ This module provides a parser for Layered Haskell programs with D enabled. -} module LH.Feature.Parser ( -- * Parsing - parseProgram + parseProgram, parsePartialProgram ) where - -import Control.Monad.Except (throwError) - -import Data.Sequence (Seq, (|>)) - -import qualified Data.Sequence as Seq - -import LH.Data.SrcLoc -import LH.Feature.AbsSyn -import LH.Text.Lexer -import LH.Text.Parser.Monad -import LH.Text.Token } %name program Block @@ -36,6 +24,7 @@ import LH.Text.Token %monad { LHsParser } %lexer { lexer } { LHsLexeme _ LHsTkEOF } %error { parseError } +%error.expected -- There must be no shift/reduce conflicts. %expect 0 @@ -61,8 +50,7 @@ import LH.Text.Token -- A sequence of constructor declarations (separated by pipes). Cons :: { Seq (L (Id, Seq (L LHsType))) } - : {- ε -} { Seq.empty } - | Con { Seq.singleton $1 } + : Con { Seq.singleton $1 } | Cons '|' Con { $1 |> $3 } -- A constructor declaration. diff --git a/LayeredHaskell-make/src/LHMake/Feature/E/AbsSyn.hs b/LayeredHaskell-make/src/LHMake/Feature/E/AbsSyn.hs index 2aac9f9..abfe73a 100644 --- a/LayeredHaskell-make/src/LHMake/Feature/E/AbsSyn.hs +++ b/LayeredHaskell-make/src/LHMake/Feature/E/AbsSyn.hs @@ -23,8 +23,8 @@ module LH.Feature.AbsSyn ( LHsPat (..), -- ** Types LHsType, - -- ** Environments - LHsEnv + -- * Environments + LHsEnv, LHsTEnv ) where import Data.Map (Map) @@ -69,5 +69,8 @@ data LHsPat -- -- | A type. -- data LHsType --- | An environment of variable-value bindings. +-- | Environments map variables to values. type LHsEnv = Map Id LHsVal + +-- | Type environments map variables to types. +type LHsTEnv = Map Id LHsType \ No newline at end of file diff --git a/LayeredHaskell-make/src/LHMake/Feature/E/Parser.y b/LayeredHaskell-make/src/LHMake/Feature/E/Parser.y index c2411ad..993e86f 100644 --- a/LayeredHaskell-make/src/LHMake/Feature/E/Parser.y +++ b/LayeredHaskell-make/src/LHMake/Feature/E/Parser.y @@ -12,23 +12,31 @@ Stability : experimental This module provides a parser for Layered Haskell programs with E enabled. -} +{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_HADDOCK hide #-} module LH.Feature.Parser ( -- * Parsing - parseProgram + parseProgram, parsePartialProgram ) where import Control.Monad.Except (throwError) +import Control.Monad.State.Strict (get) +import Data.Char (isSpace) import Data.Sequence (Seq, (|>), (<|)) import Data.Text (Text) import qualified Data.Sequence as Seq +import qualified Data.Text as Text +import LH.Data.Error (Label) import LH.Data.SrcLoc import LH.Feature.AbsSyn import LH.Text.Lexer +import LH.Text.Parser.Error (LHsTextError(ParseError, PossibleEq), prevLabel) +import LH.Text.Parser.ExpList (HappyExpList, toPhrases) import LH.Text.Parser.Monad +import LH.Text.Pretty ((<+>), quotes) import LH.Text.Token } @@ -38,6 +46,7 @@ import LH.Text.Token %monad { LHsParser } %lexer { lexer } { LHsLexeme _ LHsTkEOF } %error { parseError } +%error.expected -- There must be no shift/reduce conflicts. %expect 0 @@ -64,44 +73,59 @@ import LH.Text.Token -- A block of declarations, which also serves as a program. Block :: { Seq (L LHsDecl) } - : OPEN Decls End { $2 } + : OPEN Decls End { $2 } + +-- A block of declarations in let expressions. +LetBlock :: { Seq (L LHsDecl) } + : OPEN LetDecls End { $2 } -- The end of a block. -- Outside of a virtual closing brace, a parse error can also end a block! End :: { () } - : CLOSE { () } - | error {% popLayout } + : CLOSE { () } + | error {% popLayout } ------------------------------------------------------------------------------- -- Declarations -- A sequence of declarations (separated by virtual semicolons). Decls :: { Seq (L LHsDecl) } - : {- ε -} { Seq.empty } - | Decl { Seq.singleton $1 } - | Decls SEMI { $1 } - | Decls SEMI Decl { $1 |> $3 } + : {- ε -} { Seq.empty } + | Decl { Seq.singleton $1 } + | Decls SEMI { $1 } + | Decls SEMI Decl { $1 |> $3 } + +-- A non-empty sequence of function declarations or type signatures (separated by virtual semicolons). +-- As one could surmise from the name of the nonterminal, these are used only in let expressions. +LetDecls :: { Seq (L LHsDecl) } + : FunSig { Seq.singleton $1 } + | LetDecls SEMI { $1 } + | LetDecls SEMI FunSig { $1 |> $3 } -- A single declaration. Decl :: { L LHsDecl } - : var Pats '=' Expr { L ($1><$4) (LHsEqn (ident $1) $2 $4) } - | var '::' Type { L ($1><$3) (LHsSig (ident $1) $3) } + : FunSig { $1 } + +-- A function declaration or a type signature. +FunSig :: { L LHsDecl } + : var Pats '=' Expr { L ($1><$4) (LHsEqn (ident $1) $2 $4) } + | var '::' Type { L ($1><$3) (LHsSig (ident $1) $3) } ------------------------------------------------------------------------------- -- Expressions Expr :: { L LHsExpr } - : 'let' Block 'in' Expr { L ($1><$4) (LHsLet $2 $4) } - | App { $1 } + : 'let' LetBlock 'in' Expr { L ($1><$4) (LHsLet $2 $4) } + | App { $1 } App :: { L LHsExpr } - : App Atom { L ($1><$2) (LHsApp $1 $2) } - | Atom { $1 } + : App Atom { L ($1><$2) (LHsApp $1 $2) } + | Atom { $1 } Atom :: { L LHsExpr } - : var { L (toSpan $1) (LHsVar (ident $1)) } - | con { L (toSpan $1) (LHsCon (ident $1)) } - | '(' Expr ')' { L ($1><$3) (un $2) } + : var { L (toSpan $1) (LHsVar (ident $1)) } + | con { L (toSpan $1) (LHsCon (ident $1)) } + | '(' Expr ')' { L ($1><$3) (un $2) } ------------------------------------------------------------------------------- -- Patterns @@ -109,19 +133,19 @@ Atom :: { L LHsExpr } -- A sequence of patterns (separated by juxtaposition). -- E contains no patterns, so this rule is empty. Pats :: { Seq (L LHsPat) } - : {- ε -} { Seq.empty } + : {- ε -} { Seq.empty } Pat :: { L LHsPat } - : PatCon { $1 } + : PatCon { $1 } PatCon :: { L LHsPat } - : PatAtom { $1 } + : PatAtom { $1 } PatApp :: { L (Seq (L LHsPat)) } - : PatAtom Pats { L ($1 ><* $2) ($1 <| $2) } + : PatAtom Pats { L ($1 ><* $2) ($1 <| $2) } PatAtom :: { L LHsPat } - : '(' Pat ')' { L ($1 >< $3) (un $2) } + : '(' Pat ')' { L ($1 >< $3) (un $2) } ------------------------------------------------------------------------------- -- Types @@ -129,13 +153,13 @@ PatAtom :: { L LHsPat } -- The following rules are intentionally non-terminating, since E has no meaningful types. Type :: { L LHsType } - : TyApp { $1 } + : TyApp { $1 } TyApp :: { L LHsType } - : TyAtom { $1 } + : TyAtom { $1 } TyAtom :: { L LHsType } - : '(' Type ')' { L ($1 >< $3) (un $2) } + : '(' Type ')' { L ($1 >< $3) (un $2) } { -- | Gives the parser the next token. @@ -146,10 +170,43 @@ lexer f = scanToken >>= f parseProgram :: Text -> Either LHsTextError (Seq (L LHsDecl)) parseProgram = runLHsParser (beginProgram >> program) --- | Reports a token that the parser did not expect. -parseError :: LHsLexeme -> LHsParser a -parseError (LHsLexeme sp tok) = do - throwError (ParseError sp tok) +-- | Parses a partial program, producing a prefix of syntactically correct declarations ('LHsDecl'). +parsePartialProgram :: Text -> Seq (L LHsDecl) +parsePartialProgram src = + case parseProgram src of + -- If the parser succeeds, we can produce the program in its entirety. + Right decls -> decls + -- If the parser emits a syntax error, we can pick out the troublesome line and remove everything after it. + Left (ParseError (LHsSpan (LHsPos l _) _) _ _ _) -> + let lns = Text.lines src + -- The line where the erroneous declaration begins. + -- We'll drop everything that follows it. + rmv = last (0 : [ i | (i, ln) <- zip [0..] (take l lns) + , not (Text.null ln) + , not (isSpace (Text.head ln)) ]) + in if rmv == 0 then Seq.empty else parsePartialProgram (Text.unlines (take rmv lns)) + -- We perform a recursive call in case removing lines leads to another parse error. + -- This would happen in a case like the following. + -- + -- > g = let x = y + -- > in x + -- + -- rmv would drop `in x', but the remaining portion of `g' is syntactically incorrect. + -- So, we invoke parsePartialProgram again to drop the definition of `g' as well! + -- Otherwise, we produce the empty sequence. + Left _ -> Seq.empty + +-- | Reports a token that the parser didn't expect. +parseError :: LHsLexeme -> HappyExpList -> LHsParser a +parseError (LHsLexeme sp tok) exs = do + st <- get + let brs = stBrack st + let nv = stNVirt st + -- If the unexpected token is an equals, and '==' is possible as an alternative, + -- we emit PossibleEq instead of ParseError. + if tok == LHsTkEq && "'=='" `elem` exs + then throwError (PossibleEq sp (toPhrases tok exs)) + else throwError (ParseError sp tok (prevLabel tok brs nv) (toPhrases tok exs)) -- | Parses an identifier. ident :: LHsLexeme -> Id diff --git a/LayeredHaskell-make/src/LHMake/Feature/F/Parser.y b/LayeredHaskell-make/src/LHMake/Feature/F/Parser.y index bfee94b..3929430 100644 --- a/LayeredHaskell-make/src/LHMake/Feature/F/Parser.y +++ b/LayeredHaskell-make/src/LHMake/Feature/F/Parser.y @@ -14,16 +14,8 @@ This module provides a parser for Layered Haskell programs with F enabled. -} module LH.Feature.Parser ( -- * Parsing - parseProgram + parseProgram, parsePartialProgram ) where - -import Data.Sequence (Seq, (<|), (|>)) - -import LH.Data.SrcLoc -import LH.Feature.AbsSyn -import LH.Text.Lexer -import LH.Text.Parser.Monad -import LH.Text.Token } %name program Block @@ -32,6 +24,7 @@ import LH.Text.Token %monad { LHsParser } %lexer { lexer } { LHsLexeme _ LHsTkEOF } %error { parseError } +%error.expected -- There must be no shift/reduce conflicts. %expect 0 diff --git a/LayeredHaskell-make/src/LHMake/Feature/L/Parser.y b/LayeredHaskell-make/src/LHMake/Feature/L/Parser.y index e95cd26..688fe7d 100644 --- a/LayeredHaskell-make/src/LHMake/Feature/L/Parser.y +++ b/LayeredHaskell-make/src/LHMake/Feature/L/Parser.y @@ -14,18 +14,8 @@ This module provides a parser for Layered Haskell programs with L enabled. -} module LH.Feature.Parser ( -- * Parsing - parseProgram + parseProgram, parsePartialProgram ) where - -import Control.Monad.Except (throwError) - -import Data.Sequence (Seq, (<|)) - -import LH.Data.SrcLoc -import LH.Feature.AbsSyn -import LH.Text.Lexer -import LH.Text.Parser.Monad -import LH.Text.Token } %name program Block @@ -34,6 +24,7 @@ import LH.Text.Token %monad { LHsParser } %lexer { lexer } { LHsLexeme _ LHsTkEOF } %error { parseError } +%error.expected -- There must be no shift/reduce conflicts. %expect 0 @@ -58,9 +49,7 @@ import LH.Text.Token -- Expressions Expr :: { L LHsExpr } - : '[' ListExpr ']' { L ($1 >< $3) (LHsList $2) } - | '(' Expr ',' Expr CommaExprs ')' { L ($1 >< $6) (LHsTuple ($2 <| ($4 <| $5))) } - | Expr ':' Expr { L ($1 >< $3) (LHsBin LHsListCons $1 $3) } + : Expr ':' Expr { L ($1 >< $3) (LHsBin LHsListCons $1 $3) } | Expr '++' Expr { L ($1 >< $3) (LHsBin LHsListAppend $1 $3) } | Expr '!!' Expr { L ($1 >< $3) (LHsBin LHsListIndex $1 $3) } @@ -69,6 +58,10 @@ Bin :: { LHsBin } | '++' { LHsListAppend } | '!!' { LHsListIndex } +Atom :: { L LHsExpr } + : '[' ListExpr ']' { L ($1 >< $3) (LHsList $2) } + | '(' Expr ',' Expr CommaExprs ')' { L ($1 >< $6) (LHsTuple ($2 <| ($4 <| $5))) } + ListExpr :: { Seq (L LHsExpr) } : Expr CommaExprs { $1 <| $2 } | {- ε -} { Seq.empty } diff --git a/LayeredHaskell-make/src/LHMake/Feature/P/Parser.y b/LayeredHaskell-make/src/LHMake/Feature/P/Parser.y index b4f6ed7..6a44d35 100644 --- a/LayeredHaskell-make/src/LHMake/Feature/P/Parser.y +++ b/LayeredHaskell-make/src/LHMake/Feature/P/Parser.y @@ -14,16 +14,8 @@ This module provides a parser for Layered Haskell programs with P enabled. -} module LH.Feature.Parser ( -- * Parsing - parseProgram + parseProgram, parsePartialProgram ) where - -import Data.Sequence (Seq, (<|)) - -import LH.Data.SrcLoc -import LH.Feature.AbsSyn -import LH.Text.Lexer -import LH.Text.Parser.Monad -import LH.Text.Token } %name program Block @@ -32,6 +24,7 @@ import LH.Text.Token %monad { LHsParser } %lexer { lexer } { LHsLexeme _ LHsTkEOF } %error { parseError } +%error.expected -- There must be no shift/reduce conflicts. %expect 0 diff --git a/LayeredHaskell.cabal b/LayeredHaskell.cabal index d736a18..8ed0c94 100644 --- a/LayeredHaskell.cabal +++ b/LayeredHaskell.cabal @@ -79,9 +79,18 @@ library LH.Data.SrcLoc LH.Feature.AbsSyn LH.Feature.Parser + LH.Feature.Upp.AbsSyn + LH.Feature.Upp.Parser + LH.Interpreter.Monad LH.Text.Lexer - LH.Text.Token + LH.Text.Parser.Brackets + LH.Text.Parser.Error + LH.Text.Parser.ExpList LH.Text.Parser.Monad + LH.Text.Pretty + LH.Text.Token + LH.Text.Token.Read + LH.Typechecker.Monad -- Modules included in this library but not exported. -- other-modules: @@ -89,6 +98,8 @@ library autogen-modules: LH.Feature.AbsSyn LH.Feature.Parser + LH.Feature.Upp.AbsSyn + LH.Feature.Upp.Parser -- LANGUAGE extensions used by modules in this package. -- other-extensions: @@ -105,7 +116,7 @@ library build-tool-depends: , alex:alex ^>=3.2.7.4 - , happy:happy ^>=1.20.1.1 + , happy:happy ^>=2.2 -- Directories containing source files. hs-source-dirs: src @@ -134,12 +145,13 @@ executable LayeredHaskell build-depends: , LayeredHaskell , base ^>=4.18.3.0 + , containers ^>=0.6.7 , text ^>=2.0.2 build-tool-depends: , LayeredHaskell-make:LayeredHaskell-make , alex:alex ^>=3.2.7.4 - , happy:happy ^>=1.20.1.1 + , happy:happy ^>=2.2 -- Directories containing source files. hs-source-dirs: src-exe diff --git a/README.md b/README.md index 9269e8c..5b7d5f8 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,8 @@ Download the archive corresponding to your operating system from the [latest rel |`LayeredHaskell-win.zip`|Windows| |`LayeredHaskell-osx.tar.gz`|macOS| -If you do not see your operating system, you may have to follow the instructions in the [Building From Source](#building-from-source) section to build the binaries yourself. +> [!NOTE] +> If you do not see your operating system, you may have to follow the instructions in the [Building From Source](#building-from-source) section to build the binaries yourself. ## Building From Source @@ -56,9 +57,11 @@ Execute the following commands. git clone https://github.com/hshkk/LayeredHaskell.git cd LayeredHaskell ``` -Reference the [Usage](#usage) section for information on what commands are available. +> [!TIP] +> Reference the [Usage](#usage) section for information on what commands are available. -Note that it is _not_ recommended to use `cabal install` on either `LayeredHaskell` or `LayeredHaskell-make`, as the generated executable will likely not function as intended, if at all. One should only use `cabal run` as the [Usage](#usage) section describes, or write a (local) command alias. +> [!WARNING] +> Note that it is _not_ recommended to use `cabal install` on either `LayeredHaskell` or `LayeredHaskell-make`, as the generated executable will likely not function as intended, if at all. One should only use `cabal run` as the [Usage](#usage) section describes, or write a (local) command alias. # Usage @@ -71,7 +74,9 @@ To enable (or disable) features, execute the following. cabal run LayeredHaskell-make -- set ``` Substitute `` for a (nonempty) set of features separated by spaces. -To see what features can be enabled, refer to the [What's available?](#whats-available) section. + +> [!TIP] +> To see what features can be enabled, refer to the [What's available?](#whats-available) section. Execute the following command to inspect the set of enabled features without changing the existing configuration. ``` @@ -109,7 +114,8 @@ The main executable can be invoked as follows. (Alternatively, `LayeredHaskell` ``` cabal run LayeredHaskell -- ``` -Currently, the file located at `` will be parsed, and its abstract syntax tree will be printed (provided that there are no parse errors). This will soon be fed into a typechecker and then an interpreter. +> [!NOTE] +> Currently, the file located at `` will be parsed, and its abstract syntax tree will be printed (provided that there are no parse errors). This will soon be fed into a typechecker and then an interpreter. ## Disclaimer diff --git a/docs/DESIGN.md b/docs/DESIGN.md index e49df91..2948bf6 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1,69 +1,63 @@ # Design -## Overview +**Layered Haskell** is a _layered_ functional language in which users can enable and disable various language features at will. +The modularity of Layered Haskell enables language variants that support a gentle introduction to functional programming for novices while also providing a means for exploring language extensions. -An interpreted feature modular language written in Haskell. Lexer is generated -from Alex, and parser is generated from Happy. +The lexer for the language is monolithic (that is, there is only one `Lexer.x` file), and is implemented in Alex (`.x`). The parser(s) for the language are modular (that is, there are several `Parser.y` files), and they are implemented in Happy (`.y`). -[Requirements](./REQUIREMENTS.md) +> **Requirements:** [REQUIREMENTS.md](./REQUIREMENTS.md) ## Architecture -**Switching Between Features**: When a feature selection is made, the -interpreter is recompiled with the specified feature flags, that version is -locally cached, and the new interpreter is run on the given source code. +Whenever the set of enabled features changes, the `LayeredHaskell` executable is rebuilt. Each time the executable is rebuilt, an executable named `LayeredHaskell-make` is invoked. `LayeredHaskell-make` merges Haskell and Happy program fragments to generate source files for a language variant. An input file is then parsed, typechecked, and interpreted using the updated `LayeredHaskell` executable. This flow is illustrated at a high level in the following diagram. -**Input**: -- Source Code: Source code given by the user. -- Feature Selection: Selection of language features to include given by the - user. +![The architecture of Layered Haskell](./LayeredHaskellArchitecture.png) -**Language Components**: -- Lexer: Tokenizes the source code and passes tokens to the parser as they are - generated. The lexer is generated by Alex. -- Parser: Parses tokens to form an abstract syntax tree (AST). The parser is - generated by Happy. -- Type Checker: Verifies correctness of types of functions and values in the AST. -- TC Core: The core set of features for the type checker. -- TC Features: The extended set of features to be superimposed onto the TC core. -- Interpreter Cache: Cache of interpreters of a specific feature set. -- Interpreter: Part of the interpreter as a whole to execute the AST. +`LayeredHaskell-make` defines feature dependencies (what features are needed to enable this feature?) and implications (is this feature automatically enabled when other features are enabled?) via the `resolve` function, which reads from an internal registry containing every feature. These are summarized in the following. -**Output**: -- Program Result: The executed output of the user specified program, or an - error. +|Feature|Name|...depends on...|...is implied by...| +|---|---|---|---| +|Expressions|E*|_none_|_none_| +|Basic types (`Int` and `Bool`)|B|E|_none_| +|(Monomorphic) algebraic datatypes|D|E|_none_| +|Functions and patterns|F|B or D|_none_| +|Case expressions|C*|_none_|F and D| +|List and tuple syntax|L|F and D|_none_| +|(Prenex) polymorphism|P|D|_none_| -![Interpreter Design Diagram](./LayeredHaskellArchitecture.png) -![Feature Dependency Graph](./FeatureDeps.png) +Features marked with an asterisk (*) are _hidden_. These features cannot be enabled manually, since doing so might produce partial or ill-typed source files. -## Interfaces +## Interface -The program will be interfaced through the command line, similar to other -interpreters like Python or GHCi. As of now, features are selected from a -text file at `LayeredHaskell-make/src/LH/Feature/Features`. +Layered Haskell will include a REPL (read-eval-print loop), providing an interactive environment in which students can load files and evaluate arbitrary expressions. -## Data +> [!NOTE] +> The REPL for Layered Haskell will have essentially the same interface as the REPL provided by GHC (the Glasgow Haskell Compiler). -Source code is given as a string of characters either as a file or through the -command line. +## Inputs and outputs -Interpreter feature compilations are kept in a cache as to reduce the number -of interpreter recompilations. +Input programs are effectively given as strings. (More accurately, [Text](https://hackage-content.haskell.org/package/text-2.1.5) values for the sake of efficiency.) + +The aforementioned REPL will be able to load files or read directly from user input. Layered Haskell's parser(s) are well-equipped to handle either kind of input. + +The anticipated interpreter will output values, which are then pretty-printed in the REPL. While the notion of "value" differs across features, we generally define values as expressions that cannot be evaluated any further. For instance, B defines plain integers and Booleans as values. ## Deployment -This project will be deployed as an installable package or source code with -a simple compilation/installation process. +This project will be deployed via a number of executables for each predefined layer, and be distributed via a GitHub Release. There will be three executables for each layer, which should be compatible with reasonably recent versions of Windows, macOS, and Linux, respectively. We have defined a [build script](../scripts/Build.hs) that automates this process. + +The set of enabled features cannot be changed through the executables. +This is a restriction we reasonably impose on students, as they should have no need to manage features at such a granular level. + +## Open questions -## Open Questions +- What should error messages look like? They should support students while also avoiding an unnecessarily complicated implementation. This leads to the question: how should error messages be represented? A plain string does not seem sufficient for this task. +- How should the interpreter and typechecker be implemented across features? -- How will the user select features? -- What is the definition of each feature, and how will these features depend - on each other. +## Deferred questions -## Deferred Questions +- Should (or _can_) type inference be its own feature? +- Should (or _can_) strict and lazy evaluation be their own features? -- What is the structure of interpreter error, how will it propagate, and how - will it be displayed to the user? - - An initial starting point for the implementation of the parser/type checker - is needed before a decision can be made. +> [!NOTE] +> Layered Haskell will use eager evaluation by default. This diverges from Haskell, which uses lazy evaluation. \ No newline at end of file diff --git a/docs/FeatureDeps.png b/docs/FeatureDeps.png deleted file mode 100644 index be6c838..0000000 Binary files a/docs/FeatureDeps.png and /dev/null differ diff --git a/docs/LayeredHaskellArchitecture.png b/docs/LayeredHaskellArchitecture.png index ce75e3e..d7e1fdb 100644 Binary files a/docs/LayeredHaskellArchitecture.png and b/docs/LayeredHaskellArchitecture.png differ diff --git a/docs/RISKS.md b/docs/RISKS.md index ca21c7c..b45986e 100644 --- a/docs/RISKS.md +++ b/docs/RISKS.md @@ -1,6 +1,6 @@ # Risks -### R-1: Modular Parser Design; Technical; Early Development +### R-1: Modular Design; Technical; Early Development **Likelihood:** Moderate @@ -8,15 +8,11 @@ **Owner:** Leo -Our chosen modular parser design could show to be infeasible for the goals of -our project. +Our chosen design (superimposition) could be infeasible for the goals of our project. -**Mitigate:** We spent several weeks researching design solutions and have tried -to strike a balance between proven methods and experimentation in feature -expressibility. +**Mitigate:** We spent several weeks researching design solutions and have tried to strike a balance between proven methods and experimentation. -**Trigger:** Attempting to implement a new feature into the parser, type checker, -or interpreter could be blocked by the modularity architecture. +**Trigger:** Attempting to implement a new feature into the parser, typechecker, or interpreter could be blocked by the architecture. ### R-2: Haskell Knowledge; Team; One Well Experienced Member with Haskell @@ -26,13 +22,11 @@ or interpreter could be blocked by the modularity architecture. **Owner:** Hangil -Half of the team is new to Haskell, so there is a learning curve to writing -Haskell code. +Half of the team is new to Haskell, so there is a learning curve to writing Haskell code. **Mitigate:** Hangil has collected learning resources learning Haskell. -**Trigger:** Blocker to appear when needing to write/review Haskell code beyond -the current skill range of a team member. +**Trigger:** Blocker to appear when needing to write/review Haskell code beyond the current skill range of a team member. ### R-3: Lack of Time; Business; Unconfirmed @@ -42,11 +36,9 @@ the current skill range of a team member. **Owner:** Oscar -The project has a hard deadline to meet all requirements by the end of Spring -term 2027. +The project has a hard deadline to meet all requirements by the end of Spring 2027. -**Mitigate:** We set weekly deadlines each week, and have biweekly meetings with -our project partner to ensure we are on a good pace. +**Mitigate:** We set weekly deadlines and have biweekly meetings with our project partner to ensure we are making reasonable progress on the project. **Trigger:** The remaining work to implement and validate our project's requirements will take longer than the project deadline. diff --git a/src-exe/Main.hs b/src-exe/Main.hs index bc3f3bd..8017029 100644 --- a/src-exe/Main.hs +++ b/src-exe/Main.hs @@ -1,15 +1,22 @@ +{-# LANGUAGE OverloadedStrings #-} module Main where +import Data.Maybe (isJust) import Data.Version (showVersion) import System.Environment (getArgs) import System.Exit (die) -import qualified Data.Text.IO as Text +import qualified Data.Sequence as Seq +import qualified Data.Text.IO as Text (readFile) -import LH.Data.Error (renderError) -import LH.Feature.Parser (parseProgram) +import LH.Data.Error (reportError) +import LH.Data.SrcLoc (LHsSpan(LHsSpan)) +import LH.Feature.Parser (parseProgram) +import LH.Text.Parser.Error (LHsTextError(ParseError, LayerError), layerReason) -import qualified Paths_LayeredHaskell as LH (version) +import qualified LH.Feature.Upp.Parser as Upp (parseProgram, parsePartialProgram) + +import qualified Paths_LayeredHaskell as LH (version) -- | Currently takes a single filepath, parses it, and prints out the AST. main :: IO () @@ -20,11 +27,40 @@ main = do src <- Text.readFile file case parseProgram src of Left err -> do - Text.putStrLn (renderError file src err) - die "" + let lyrErr uppAst = let (label, fix) = layerReason err uppAst in LayerError err label fix + -- We'll only emit the layer error if the one erroneous token is sufficient to identify the issue. + -- Since Upp errored, we don't have an AST to search (hence Seq.empty), + -- so we want to ensure we have something meaningful here. + suff = isJust (fst (layerReason err Seq.empty)) + case Upp.parseProgram src of + Right uppAst -> (reportError file src $ lyrErr uppAst) >> die "" + Left uppErr -> (reportError file src $ case laterError err uppErr of + -- Upp rejects the same token (or fails some other way), so the program is invalid in every layer. + Nothing -> err + -- Upp got past the token the lower layer rejected, + -- so that token must correspond to a disabled feature. + -- But since Upp errored as well, there must be a syntax error later in the file. + -- The layer error will be emitted only if the token is sufficient to identify the error source. + -- Otherwise, the later error is emitted. + Just later -> + let uppPartialAst = Upp.parsePartialProgram src in + -- If even the partial parser fails to produce a result for the first declaration + -- and the erroneous token is not sufficient to identify a layer error, we default + -- to the later generic, but nevertheless unambiguous syntax error. + if Seq.null uppPartialAst && not suff then later else lyrErr uppPartialAst) >> die "" Right ast -> print ast _ -> die "1 filepath expected" +-- | Produces the uppermost parser's error if it occurs /after/ the enabled layer's error. +-- This is called when the uppermost parser got past the token the enabled layer rejected, +-- but it errored for some different reason at a later point. +laterError :: LHsTextError -- ^ The lower layer's error. + -> LHsTextError -- ^ The uppermost layer's error. + -> Maybe LHsTextError +laterError (ParseError (LHsSpan s _) _ _ _) (ParseError usp@(LHsSpan u _) tok prev _) + | u > s = Just (ParseError usp tok prev []) +laterError _ _ = Nothing + -- | Prints the version of @LayeredHaskell@. version :: IO () version = do diff --git a/src/LH/Data/Error.hs b/src/LH/Data/Error.hs index 48887d7..72858b1 100644 --- a/src/LH/Data/Error.hs +++ b/src/LH/Data/Error.hs @@ -15,22 +15,36 @@ and provides a few formatting helpers to aid in the construction of error messag {-# LANGUAGE OverloadedStrings #-} module LH.Data.Error ( -- * Errors - LHsError (..), + LHsError (..), reportError, -- ** Reporting multiple errors LHsMaxError (..), - -- ** Formatting errors - underline, (+>) + -- ** Error codes + ErrorCode, LHsHasErrorCode (..), errorCode, + -- ** Formatting + Label, + PossibleFix, possibleFix, + Reason, reason, + -- ** Underlining + underline, underlines, + -- ** Helper functions for spans + -- | The following functions are intended to be used alongside 'underline' and 'underlines'. + spanFrom, truncateSpan ) where -import Data.Text (Text) +import Data.Text (Text) import Errata import Errata.Styles import qualified Data.Text as Text +import qualified Data.Text.IO as Text (putStrLn) import qualified Data.Text.Lazy as LazyText import LH.Data.SrcLoc (LHsPos (..), LHsSpan (..)) +import LH.Text.Pretty ((<+>)) + +------------------------------------------------------------------------------- +-- Errors -- | A type representing an error is obligated to implement two functions: 'renderError' and 'buildError'. -- @@ -51,6 +65,14 @@ class LHsError a where -- This is where the error message itself should be written, -- in addition to places in the source that it may need to point to. +-- | Prints an error to the terminal using 'renderError'. +reportError :: LHsError a + => FilePath -- ^ The filepath of the source text. + -> Text -- ^ The source text itself. + -> a -- ^ An error. + -> IO () +reportError file src err = Text.putStrLn (renderError file src err) + -- | Multiple simultaneous errors are all printed. -- -- 'renderError' prints the errors separately, while 'buildError' merges them all into one. @@ -64,6 +86,9 @@ instance LHsError a => LHsError [a] where Nothing where built = map (buildError file) errs +------------------------------------------------------------------------------- +-- Errors up to a maximum + -- | A type for representing a number of errors simultaneously, but only up to a maximum. newtype LHsMaxError a = LHsMaxError (Int, [a]) @@ -75,23 +100,66 @@ newtype LHsMaxError a = LHsMaxError (Int, [a]) instance LHsError a => LHsError (LHsMaxError a) where renderError file src (LHsMaxError (n, errs)) = let m = length errs in - renderError file src (take n errs) <> - if m > n - then "\n...and " <> Text.pack (show (m - n)) <> " more errors" - else "" + renderError file src (take n errs) <> if m > n then andNMoreErrors (m - n) else "" buildError file (LHsMaxError (n, errs)) = let m = length errs in (buildError file (take n errs)) { errataBody = - if m > n - then Just $ "\n...and " <> Text.pack (show (m - n)) <> " more errors" - else Nothing + if m > n then Just $ andNMoreErrors (m - n) else Nothing } +-- | Produces the message @"...and @\(n\)@ more errors"@. +andNMoreErrors :: Int -> Text +andNMoreErrors n = "\n...and" <+> Text.pack (show n) <+> "more" <+> errorPluralization n + where + errorPluralization :: Int -> Text + errorPluralization 1 = "error" + errorPluralization _ = "errors" + +------------------------------------------------------------------------------- +-- Error codes + +-- | An error code. +type ErrorCode = Text + +-- | A type that can be displayed as an error code. +class LHsHasErrorCode a where + -- | Creates an error code for an error. + errorCodeWith :: a -> ErrorCode + +-- | Formats an error code with a prefix. +errorCode :: Text -- ^ A prefix, typically one or two characters. + -> Text -- ^ A uniquely assigned error code, typically two integers. + -> ErrorCode +errorCode pfx code = "\ESC[1;31m[" <> pfx <> code <> "]\ESC[0m" + +------------------------------------------------------------------------------- +-- Formatting + +-- | A label; the text associated with a 'Errata.Types.Pointer'. +type Label = Text + +-- | A possible fix. +type PossibleFix = Text + +-- | A reason. +type Reason = Text + +-- | Formats a possible fix. +possibleFix :: Text -> PossibleFix +possibleFix s = "\ESC[34mpossible fix: " <> s <> "\ESC[0m" + +-- | Formats a reason for an error. +reason :: Text -> PossibleFix +reason s = "reason: " <> s + +------------------------------------------------------------------------------- +-- Underlining + -- | Underlines a __single-line__ span alongside a label. underline :: FilePath -- ^ The filepath of the source text. -> LHsSpan -- ^ The source span to underline. - -> Text -- ^ A label. + -> Label -- ^ A label. -> Block underline file (LHsSpan (LHsPos l c) (LHsPos _ c')) label = blockSimple @@ -102,8 +170,43 @@ underline file (LHsSpan (LHsPos l c) (LHsPos _ c')) label = (l, c, c', Just label) Nothing -infix 5 +> +-- | Underlines a __single-line__ span alongside a label and a previous place in the source. +underlines :: FilePath -- ^ The filepath of the source text. + -> LHsSpan -- ^ The primary source span to underline. + -> Label -- ^ A label for the primary source span. + -> Maybe (LHsSpan, Label) -- ^ A previous place in the source with a label. + -> Block +underlines file main mainLabel Nothing = underline file main mainLabel +underlines file main mainLabel (Just (prev, prevLabel)) = + blockConnected + fancyRedStyle + fancyRedPointer + file + Nothing + (toPointer prev prevLabel) + (toPointer main mainLabel) + Nothing + where + toPointer (LHsSpan (LHsPos l c) (LHsPos _ c')) label = (l, c, c', Just label) + +------------------------------------------------------------------------------- +-- Helper functions for spans in error messages -- | Constructs a span of a given length starting at a given position. -(+>) :: LHsPos -> Int -> LHsSpan -pos +> len = LHsSpan pos (pos { posCol = posCol pos + len }) \ No newline at end of file +spanFrom :: LHsPos -- ^ The starting position of the span. + -> Int -- ^ The length of the span. + -> LHsSpan +spanFrom pos len = LHsSpan pos (pos { posCol = posCol pos + len }) + +-- | Truncates a multi-line span, transforming it into a single-line span. +-- The source text is required to identify where the first line of the span ends. +truncateSpan :: LHsSpan + -> Text -- ^ The source text itself. + -> (LHsSpan, Bool) -- ^ The truncated span alongside a Boolean indicating whether the input was changed. +truncateSpan sp@(LHsSpan s@(LHsPos l c) (LHsPos l' _)) src + | l == l' = (sp, False) + | otherwise = (LHsSpan s (LHsPos l c'), True) + where + c' = case drop (l - 1) (Text.lines src) of + (x:_) -> max c (Text.length x + 1) + [] -> c \ No newline at end of file diff --git a/src/LH/Interpreter/Monad.hs b/src/LH/Interpreter/Monad.hs new file mode 100644 index 0000000..5654192 --- /dev/null +++ b/src/LH/Interpreter/Monad.hs @@ -0,0 +1,57 @@ +{- | +Module : LH.Interpreter.Monad +Description : The interpreter monad. +Copyright : (c) Hangil Kim, 2026 + Kairon Johnson, 2026 + Leonidas Sallos, 2026 + Oscar Abelanet, 2026 +License : MIT +Maintainer : kimhang@oregonstate.edu +Stability : experimental + +This module provides the interpreter monad for Layered Haskell. +-} +{-# LANGUAGE GeneralizedNewtypeDeriving #-} +module LH.Interpreter.Monad ( + -- * The interpreter monad + LHsInterp (..), runLHsInterp, + -- ** Bindings + ext, exts, + -- ** Placeholders + LHsInterpError (..) + ) where + +import Control.Monad.Except (MonadError) +import Control.Monad.State.Strict + (MonadState, modify, + StateT, evalStateT) + +import Data.Sequence (Seq) + +import qualified Data.Map as Map (empty, insert) + +import LH.Feature.AbsSyn (Id, LHsVal, LHsEnv) + +-- | A placeholder for interpreter errors. +newtype LHsInterpError = LHsInterpError () + +-- | The interpreter monad. +-- +-- 'LHsEnv', which comes from superimposed source files, maps variables to values. +newtype LHsInterp a = LHsInterp (StateT LHsEnv (Either LHsInterpError) a) + deriving (Functor, Applicative, Monad, MonadState LHsEnv, MonadError LHsInterpError) + +-- | Runs the interpreter monad. +runLHsInterp :: LHsInterp a -> Either LHsInterpError a +runLHsInterp (LHsInterp m) = + evalStateT m initEnv + where + initEnv = Map.empty + +-- | Adds a binding to the environment. +ext :: (Id, LHsVal) -> LHsInterp () +ext (x, v) = modify (Map.insert x v) + +-- | Adds multiple bindings to the environment. +exts :: Seq (Id, LHsVal) -> LHsInterp () +exts = mapM_ ext \ No newline at end of file diff --git a/src/LH/Text/Lexer.x b/src/LH/Text/Lexer.x index a937b8b..392f5d9 100644 --- a/src/LH/Text/Lexer.x +++ b/src/LH/Text/Lexer.x @@ -28,6 +28,7 @@ import qualified Data.Text as Text import qualified Data.Text.Read as Text (decimal) import LH.Data.SrcLoc +import LH.Text.Parser.Error (LHsTextError(LexicalError, UnclosedComment)) import LH.Text.Parser.Monad import LH.Text.Token } @@ -271,7 +272,13 @@ scanToken = do AlexSkip inp' _ -> setInput inp' >> scanToken AlexToken inp' len act -> do setInput inp' - act pos (Text.take len (aiText inp)) >>= maybe scanToken (return . LHsLexeme (spanOf pos len)) + res <- act pos (Text.take len (aiText inp)) + case res of + Nothing -> scanToken + Just tok -> do + let sp = spanOf pos len + updateWithToken sp tok + return (LHsLexeme sp tok) where -- | Handles the end of the input. We either have an 'UnclosedComment' error, -- or every layout block still open is closed before we produce the end-of-file token. diff --git a/src/LH/Text/Parser/Brackets.hs b/src/LH/Text/Parser/Brackets.hs new file mode 100644 index 0000000..3aa092f --- /dev/null +++ b/src/LH/Text/Parser/Brackets.hs @@ -0,0 +1,105 @@ +{- | +Module : LH.Text.Parser.Brackets +Description : Bracket types. +Copyright : (c) Hangil Kim, 2026 + Kairon Johnson, 2026 + Leonidas Sallos, 2026 + Oscar Abelanet, 2026 +License : MIT +Maintainer : kimhang@oregonstate.edu +Stability : experimental + +This module provides a number of definitions for identifying and pretty-printing brackets in the source. +The intention of this module is to improve error messages related to unclosed brackets. + +As an example, consider the following (erroneous) program, assuming the feature providing list syntax is enabled. + +@ +f = + g [ [x,y] + , [y,z] + , [z] + , [] + , [] +@ + +By keeping track of a stack of unclosed brackets in the parser monad (see 'LH.Text.Parser.Monad.stBrack'), +Layered Haskell can point back to the unclosed bracket in the definition of @f@ and provide an informative error message. + +@ +[T11] Syntax error +→ MismatchedBrackets.hs:2:7 + │ +2 │ g [ [x,y] + │ ┌───────^ this `[' is never closed +3 │ │ , [y,z] +4 │ │ , [z] +5 │ │ , [] +6 │ │ , [] + │ └───────────^ something above this is incomplete +expected `]' +@ +-} +module LH.Text.Parser.Brackets ( + -- * Brackets + LHsBracket (..), LHsBracketType (..), + -- ** Identification + -- | The following functions identify the bracket type corresponding to a token. + openBracketType, closeBracketType, + -- ** Pretty-printing + pprOpenBracketType, pprCloseBracketType + ) where + +import Data.Text (Text) + +import qualified Data.Text as Text + +import LH.Data.SrcLoc (LHsSpan) +import LH.Text.Token + (LHsToken + ( LHsTkLBrack, LHsTkRBrack + , LHsTkLParen, LHsTkRParen)) + +------------------------------------------------------------------------------- +-- Brackets + +-- | A bracket type. +data LHsBracketType + = BParen -- ^ A parenthesis. + | BBrack -- ^ A square bracket. + deriving Eq + +-- | Pretty-prints the opening bracket corresponding to a 'LHsBracketType'. +pprOpenBracketType :: LHsBracketType -> Text +pprOpenBracketType BParen = Text.pack "(" +pprOpenBracketType BBrack = Text.pack "[" + +-- | Pretty-prints the closing bracket corresponding to a 'LHsBracketType'. +pprCloseBracketType :: LHsBracketType -> Text +pprCloseBracketType BParen = Text.pack ")" +pprCloseBracketType BBrack = Text.pack "]" + +-- | A bracket paired with the position at which it was pushed onto the stack. +data LHsBracket = LHsBracket !LHsBracketType !LHsSpan + +-- | Identifies which type of bracket a token opens, if any. +-- +-- ==== __Example__ +-- +-- >>> openBracketType LHsTkLParen +-- Just BParen +openBracketType :: LHsToken -> Maybe LHsBracketType +openBracketType LHsTkLParen = Just BParen +openBracketType LHsTkLBrack = Just BBrack +openBracketType _ = Nothing + +-- | Identifies which type of bracket a token closes, if any. +-- +-- ==== __Example__ +-- +-- >>> closeBracketType LHsTkRParen +-- Just BParen +closeBracketType :: LHsToken -> Maybe LHsBracketType +closeBracketType LHsTkRParen = Just BParen +closeBracketType LHsTkRBrack = Just BBrack +closeBracketType _ = Nothing \ No newline at end of file diff --git a/src/LH/Text/Parser/Error.hs b/src/LH/Text/Parser/Error.hs new file mode 100644 index 0000000..51318e2 --- /dev/null +++ b/src/LH/Text/Parser/Error.hs @@ -0,0 +1,326 @@ +{- | +Module : LH.Text.Parser.Error +Description : Lexical and syntax errors. +Copyright : (c) Hangil Kim, 2026 + Kairon Johnson, 2026 + Leonidas Sallos, 2026 + Oscar Abelanet, 2026 +License : MIT +Maintainer : kimhang@oregonstate.edu +Stability : experimental + +This module provides a representation of lexical and syntax errors, including those that are layer-specific. +A number of definitions for identifying sources of layer-specific syntax errors is thus included in this module. +-} +{-# LANGUAGE OverloadedStrings #-} +module LH.Text.Parser.Error ( + -- * Errors + LHsTextError (..), + -- ** Pointing to previous places in the source + prevLabel, + -- ** Lists of expected tokens + Exp, ExpList, + -- ** Sources of layer-specific errors + -- | To identify sources of layer-specific syntax errors, note that the parser and AST corresponding to the /uppermost/ layer is used. + -- This follows from the notion that these errors occur when a layer's parser fails while the uppermost layer's parser succeeds. + layerReason, declReason, exprReason, typeReason, + ) where + +import Control.Applicative ((<|>)) +import Data.Char (isAscii) +import Data.Foldable (asum) +import Data.Maybe (fromMaybe) +import Data.Sequence (Seq(..)) +import Data.Text (Text) + +import Errata + +import qualified Data.Text as Text + +import LH.Data.Error +import LH.Data.SrcLoc + (LHsPos (..), LHsSpan (..), L(..)) +import LH.Text.Parser.Brackets (LHsBracket(LHsBracket), pprOpenBracketType) +import LH.Text.Pretty + ((<+>), quotes) +import LH.Text.Token + (LHsToken (..), pprToken, isVirtual, isKeyword, isOperator) + +import qualified LH.Feature.Upp.AbsSyn as Upp + +-- | A single phrase standing in for a expected token. +type Exp = Text + +-- | A list of phrases standing in for a list of expected tokens. +type ExpList = [Text] + +------------------------------------------------------------------------------- +-- Text-related errors + +-- | A text-related error emitted by the lexer or parser. +data LHsTextError + = LexicalError !LHsPos !Text -- ^ A lexical error emitted by Alex. + | UnclosedComment !LHsPos -- ^ An unclosed multi-line comment error emitted by Alex. + | ParseError !LHsSpan !LHsToken !(Maybe (LHsSpan, Label)) !ExpList + -- ^ A parse error emitted by Happy. + -- + -- The first argument indicates where an unexpected token (the second argument) starts and ends in the source. + -- The (optional) third argument is a previous place in the source alongside a label (see 'prevLabel'). + -- The fourth argument is a list of phrases indicating what was expected to come next (see 'LH.Text.Parser.ExpList.toPhrases'). + | PossibleEq !LHsSpan !ExpList + -- ^ A parse error related to a possible incorrect usage of @'='@ emitted by Happy. + | LayerError LHsTextError !(Maybe Label) !(Maybe PossibleFix) + -- ^ A parse error emitted /outside/ of Happy. + -- + -- 'LayerError's are emitted if a program is rejected by a generated parser but accepted by the uppermost parser. + -- Since the Happy parsers only emit 'ParseError's, 'ParseError's are converted to 'LayerError's when only the uppermost parser succeeds. + -- __Therefore, the first argument to 'LayerError' will always be a 'ParseError'.__ + -- + -- The second argument is an (optional) label and the third argument is an (optional) possible fix. + deriving (Eq, Show) + +-- | The error code prefix for text-related errors is @T@. +errorCodePrefix :: Text +errorCodePrefix = "T" + +-- | +-------------------------------------------------------------+ +-- | Text-related error codes | +-- +=============================================================+ +-- | __Lexical errors (@T00@-@T09@)__ | +-- +-------------------------------+-----------------------------+ +-- | @T00@ | Generic lexical error | +-- +-------------------------------+-----------------------------+ +-- | @T01@ | Unclosed comment | +-- +-------------------------------+-----------------------------+ +-- | __Parse errors (@T10@-@T19@)__ | +-- +-------------------------------+-----------------------------+ +-- | @T10@ | Generic syntax error | +-- +-------------------------------+-----------------------------+ +-- | @T11@ | Indentation error | +-- +-------------------------------+-----------------------------+ +-- | @T12@ | Possible incorrect @'=='@ | +-- +-------------------------------+-----------------------------+ +-- | __Layer-specific errors (@T90@-@T99@)__ | +-- +-------------------------------+-----------------------------+ +-- | @T99@ | Layer-specific syntax error | +-- +-------------------------------+-----------------------------+ +instance LHsHasErrorCode LHsTextError where + errorCodeWith (LexicalError _ _) = errorCode errorCodePrefix "00" + errorCodeWith (UnclosedComment _) = errorCode errorCodePrefix "01" + errorCodeWith (ParseError _ bad _ _) + | isVirtual bad = errorCode errorCodePrefix "11" + | otherwise = errorCode errorCodePrefix "10" + errorCodeWith (PossibleEq _ _) = errorCode errorCodePrefix "12" + errorCodeWith (LayerError _ _ _) = errorCode errorCodePrefix "99" + +-- | Finds a previous place in the source worth pointing at. +-- +-- [Brackets]: If there is an unclosed bracket, 'prevLabel' will point to the bracket that opened it. +-- [Virtual tokens]: If the unexpected token is virtual and 'LH.Text.Parser.Monad.stNVirt' is not 'Nothing', +-- then 'prevLabel' points to 'LH.Text.Parser.Monad.stNVirt' and states @"this definition is incomplete from here"@. +prevLabel :: LHsToken -- ^ An unexpected token. + -> [LHsBracket] -- ^ A stack of unclosed brackets. + -- See 'LH.Text.Parser.Monad.stBrack'. + -> Maybe LHsSpan -- ^ The span of the last seen non-virtual token. + -- See 'LH.Text.Parser.Monad.stNVirt'. + -> Maybe (LHsSpan, Label) +prevLabel tok brs nv + | not (isVirtual tok) = Nothing + -- If a bracket is unclosed... + | LHsBracket bty sp : _ <- brs = + Just (sp, "this" <+> quotes (pprOpenBracketType bty) <+> "is never closed") + -- If a definition is incomplete... + | isVirtual tok, Just sp <- nv = Just (sp, "this definition is incomplete from here") + | otherwise = Nothing + +-- | The wording for lexical and syntax errors are mostly defined within this instance. +instance LHsError LHsTextError where + buildError file err@(LexicalError pos bad) = + errataSimple + (Just $ errorCodeWith err <+> "Unexpected" <+> quotes bad) + (underline file (spanFrom pos (Text.length bad)) "not sure how to interpret this symbol") + lexicalHint + where + lexicalHint + | Text.any (not . isAscii) bad = + Just $ possibleFix "use only ASCII characters in program text\n" + <> reason "outside of comments, Layered Haskell does not support Unicode symbols" + | bad == "!=" = + Just $ possibleFix ("maybe you meant" <+> quotes "/=" <> "?\n") + <> reason ("Layered Haskell uses" <+> quotes "/=" <+> "for inequality, not" <+> quotes "!=") + | bad == "\\=" = + Just $ possibleFix ("maybe you meant" <+> quotes "/=" <> "?\n") + <> reason ("Layered Haskell uses" <+> quotes "/=" <+> "for inequality, not" <+> quotes "\\=") + | bad == "=>" = + Just $ possibleFix ("maybe you meant" <+> quotes "->" <> "?") + | bad == "{" = + Just $ reason "Layered Haskell doesn't use braces" + | bad == "}" = + Just $ reason "Layered Haskell doesn't use braces" + | bad == ";" = + Just $ reason "Layered Haskell doesn't use semicolons" + | bad == "\"" = + Just $ possibleFix "remove all double quotes\n" + <> reason "Layered Haskell does not support string literals" + | bad == "\'" = + Just $ possibleFix "use single quotes only as part of a variable or constructor name\n" + <> reason "Layered Haskell does not support character literals" + | bad == "&" = + Just $ possibleFix ("maybe you meant" <+> quotes "&&" <> "?\n") + <> reason ("Layered Haskell uses" <+> quotes "&&" <+> "for logical AND, not" <+> quotes "&") + | otherwise = Nothing + buildError file err@(UnclosedComment pos) = + errataSimple + (Just $ errorCodeWith err <+> "Unclosed comment") + (underline file (spanFrom pos 2) "this comment is never closed") + commentHint + where + commentHint = Just $ possibleFix $ + "add" <+> quotes "-}" <+> "somewhere after" <+> quotes "{-" <+> "to close the comment" + buildError file err@(ParseError (LHsSpan start end) bad prev exs) = + errataSimple + (Just $ errorCodeWith err <+> "Syntax error") + (underlines file main label prev) + body + where + -- Virtual tokens have an empty span, so we underline at least one character. + main = LHsSpan start (end { posCol = max (posCol end) (posCol start + 1) }) + exl = "expected" <+> Text.intercalate " or " exs + -- A label for the underlined token. + -- A virtual token uses the `parseErrorLabel' since the expected list can't say why the error occurred in general. + -- A non-virtual token uses the expected list, since the `parseErrorLabel' message would just repeat what it intends to say. + -- If the expected list is empty, then we can just use `parseErrorLabel' message, because it's better than nothing! + label | isVirtual bad || null exs = parseErrorLabel bad + | otherwise = exl + -- The body for the error here is just the expected list if the label wasn't able to show it. + body | isVirtual bad && not (null exs) = Just exl + | otherwise = Nothing + buildError file err@(PossibleEq sp exs) = + errataSimple + (Just $ errorCodeWith err <+> "Syntax error") + (underline file sp exl) + possibleEqHint + where + exl = "expected" <+> Text.intercalate " or " exs + possibleEqHint = + Just $ possibleFix ("maybe you meant" <+> quotes "==" <> "?\n") + <> reason ("Layered Haskell uses" <+> quotes "==" <+> "for equality, not" <+> quotes "=") + buildError file err@(LayerError (ParseError sp _ _ _) label fix) = + errataSimple + (Just $ errorCodeWith err <+> "Layer-specific syntax error") + (underline file sp (fromMaybe "this was not expected here" label)) + fix + buildError file (LayerError err _ _) = buildError file err + +-- | Labels for unexpected tokens in 'ParseError's. +parseErrorLabel :: LHsToken -> Label +parseErrorLabel LHsTkVSemi = "a new definition starts here, but the previous one is incomplete" +parseErrorLabel LHsTkVClose = "something before this is incomplete" +parseErrorLabel _ = "this was not expected here" + +-- | Attempts to identify the source of a 'LayerError' (and thus a 'ParseError'), producing a label and a possible fix. +-- +-- Some tokens alone are sufficient to identify the issue, like keywords or operators. +-- Others, like variables, aren't enough to figure out what went wrong, so 'layerReason' will search the AST produced by the +-- uppermost parser to identify the discrepancy. +layerReason :: LHsTextError -> Seq (L Upp.LHsDecl) -> (Maybe Label, Maybe PossibleFix) +layerReason (ParseError (LHsSpan start _) bad _ _) decls + -- If the token alone is sufficient to identify the issue... + | Just why <- explain = + ( Just ("the use of" <+> qbad <+> "is not enabled") + , Just (possibleFix (rmv <> "\n") <> reason (qbad <+> why)) ) + | isKeyword bad = (Just ("keyword" <+> qbad <+> "is not enabled"), Just (possibleFix rmv)) + | isOperator bad + , Nothing <- label = (Just ("operator" <+> qbad <+> "is not enabled"), Just (possibleFix rmv)) + -- Otherwise, we search the rest of the AST to figure out what went wrong. + | otherwise = (label, possibleFix "remove that or switch to a layer enabling it" <$ label) + -- Note that (<$) is just a shortcut for the following. + -- case label of + -- Just _ -> Just (possibleFix ...) + -- Nothing -> Nothing + where + label = asum (fmap (declReason start) decls) + qbad = quotes (pprToken bad) + rmv = "remove all instances of" <+> qbad <+> "or switch to a layer enabling it" + -- Explains tokens whose purpose might not be obvious to students. + explain = case bad of + LHsTkLam -> Just "begins a lambda (i.e., an anonymous function), but it isn't enabled in every layer" + LHsTkArrow -> Just "is used in function definitions, but it isn't enabled in every layer" + LHsTkPipe -> Just "separates definitions in a data declaration, but it isn't enabled in every layer" + _ -> Nothing +layerReason _ _ = (Nothing, Nothing) + +-- | Searches a declaration for the source of a 'LayerError' beginning at the given position. +declReason :: LHsPos -> L Upp.LHsDecl -> Maybe Label +declReason pos (L _ d) = case d of + Upp.LHsEqn _ ps e -> firstAt pos ps "patterns are not enabled" <|> exprReason pos e + Upp.LHsSig _ t -> typeReason pos t + Upp.LHsType _ tvs t -> firstAt pos tvs "type parameters are not enabled" <|> typeReason pos t + -- We don't have a feature for constructor fields, so we only need to search through the types. + Upp.LHsData _ tvs cs -> + firstAt pos tvs "type parameters are not enabled" + <|> asum (fmap (\(_, fs) -> asum (fmap (typeReason pos) fs)) cs) + +-- | Searches an expression for the source of a 'LayerError' beginning at the given position. +exprReason :: LHsPos -> L Upp.LHsExpr -> Maybe Label +exprReason pos (L (LHsSpan s n) e) = case e of + Upp.LHsInt _ | s == pos -> Just "integer literals are not enabled" + Upp.LHsList xs + | s == pos -> Just "lists are not enabled" + | otherwise -> asum (fmap (exprReason pos) xs) + Upp.LHsTuple xs -> between pos xs "tuples are not enabled" <|> asum (fmap (exprReason pos) xs) + Upp.LHsLet ds b -> asum (fmap (declReason pos) ds) <|> exprReason pos b + Upp.LHsApp f x -> exprReason pos f <|> exprReason pos x + Upp.LHsPre _ | s <= pos && pos <= n -> + -- TODO: This isn't optimal, but I don't think it's possible to differentiate + -- between disabled prefix operators and a disabled binary operator in this context. + -- The issue is that the position pointed to is the binary operator itself (via the Bin nonterminal), + -- and not the beginning of '(' Bin ')'. + Just "prefix operators are not enabled, or this operator is not enabled" + Upp.LHsBin _ l r -> exprReason pos l <|> exprReason pos r + Upp.LHsNeg x -> exprReason pos x + Upp.LHsIf c t f -> exprReason pos c <|> exprReason pos t <|> exprReason pos f + Upp.LHsLam _ b -> exprReason pos b + Upp.LHsCase f as -> exprReason pos f <|> asum (fmap (exprReason pos . snd) as) + _ -> Nothing + +-- | Searches a type for the source of a 'LayerError' beginning at the given position. +typeReason :: LHsPos -> L Upp.LHsType -> Maybe Label +typeReason pos (L (LHsSpan s _) t) = case t of + Upp.LHsTyVar _ + | s == pos -> Just "type variables are not enabled" + Upp.LHsTyList x + | s == pos -> Just "list types are not enabled" + | otherwise -> typeReason pos x + Upp.LHsTyTuple xs -> + between pos xs "tuple types are not enabled" <|> asum (fmap (typeReason pos) xs) + Upp.LHsTyFn a b -> typeReason pos a <|> typeReason pos b + Upp.LHsTyCon _ as -> + let firstAtTyCon = + firstAtWith $ \x -> case x of + Upp.LHsTyVar _ -> "type variables are not enabled" + _ -> "type arguments are not enabled" + in firstAtTyCon pos as <|> asum (fmap (typeReason pos) as) + _ -> Nothing + +-- | Produces a label if the first item in a 'Seq'uence begins at the given position. +firstAt :: LHsPos -> Seq (L a) -> Label -> Maybe Label +firstAt pos xs msg = firstAtWith (const msg) pos xs + +-- | Selects a label if the first item in a 'Seq'uence begins at the given position. +firstAtWith + :: (a -> Label) -- ^ A function selecting a label based on the first item's value. + -> LHsPos -- ^ The position at which the first item must begin. + -> Seq (L a) -- ^ A sequence whose first item is inspected. + -> Maybe Label +firstAtWith labelAt pos (L (LHsSpan s _) arg :<| _) + | s == pos = Just (labelAt arg) +firstAtWith _ _ _ = Nothing + +-- | Produces a label if the given position lies between the first and second items in a 'Seq'uence. +-- +-- 'between' is used to search for the comma in a tuple. +between :: LHsPos -> Seq (L a) -> Label -> Maybe Label +between pos (L (LHsSpan _ e) _ :<| L (LHsSpan s _) _ :<| _) msg + | e <= pos && pos < s = Just msg +between _ _ _ = Nothing \ No newline at end of file diff --git a/src/LH/Text/Parser/ExpList.hs b/src/LH/Text/Parser/ExpList.hs new file mode 100644 index 0000000..a4d0bdf --- /dev/null +++ b/src/LH/Text/Parser/ExpList.hs @@ -0,0 +1,94 @@ +{- | +Module : LH.Text.Parser.ExpList +Description : Lists of expected tokens. +Copyright : (c) Hangil Kim, 2026 + Kairon Johnson, 2026 + Leonidas Sallos, 2026 + Oscar Abelanet, 2026 +License : MIT +Maintainer : kimhang@oregonstate.edu +Stability : experimental + +This module provides a definition for rewriting lists of expected tokens (as produced by Happy's @%error.expected@ directive) +into lists of friendlier phrases. +-} +{-# LANGUAGE OverloadedStrings #-} +module LH.Text.Parser.ExpList ( + -- * Lists of expected tokens + toPhrases, toPhrase, + -- ** Layered Haskell + -- | Layered Haskell represents friendly phrases as 'Text' values. + Exp, ExpList, + -- ** Happy + -- | Happy represents expected tokens as strings. + HappyExp, HappyExpList + ) where + +import Data.List (nub) +import Data.Text (Text) + +import qualified Data.Text as Text (dropAround, pack) + +import LH.Text.Pretty (quotes) +import LH.Text.Parser.Error (Exp, ExpList) +import LH.Text.Token (LHsToken, isVirtual) +import LH.Text.Token.Read (isTextOperator) + +-- | A single expected token produced by Happy. +type HappyExp = String + +-- | A list of expected tokens produced by Happy. +type HappyExpList = [String] + +-- | Rewrites a list of expected tokens as a list of friendlier phrases. +-- +-- The following rewrite rules are applied. +-- +-- * If the number of non-virtual tokens in the 'HappyExpList' exceeds 4, the entire list is dropped. +-- This avoids long lists, which might obfuscate the source of the error. +-- * If the 'HappyExpList' contains a virtual semicolon (@SEMI@) or a virtual closing brace (@CLOSE@) and +-- the unexpected token is virtual (the first argument), @"the end of the definition"@ is added to the resulting 'ExpList'. +-- * Otherwise, all non-virtual tokens are rewritten via 'toPhrase' and added to the resulting 'ExpList'. +toPhrases :: LHsToken -- ^ An unexpected token. + -> HappyExpList + -> ExpList +toPhrases tok exs + -- If there are more than 4 expected tokens, remove the list entirely (to avoid an unnecessarily long list). + | length nvirt > 4 = [] + -- If the list of expected tokens contains a SEMI or a CLOSE and the unexpected token is virtual, + -- we add "the end of the definition" to the list of phrases. + | semiOrClose && isVirtual tok = nvirt ++ ["the end of the definition"] + -- Otherwise, we produce just the list of expected non-virtual tokens. + | otherwise = nvirt + where + -- A predicate for whether any one of the expected tokens was SEMI or CLOSE. + semiOrClose = any (`elem` ["SEMI", "CLOSE"]) exs + -- A list of expected non-virtual tokens. + -- Since an operator only indicates whether an expression could continue, + -- we'll opt to hide it from the expected token list when something more specific is expected. + nvirt = dropOperators $ nub [toPhrase ex | ex <- exs, ex `notElem` ["OPEN", "SEMI", "CLOSE"]] + dropOperators ps = case filter (/= "an operator") ps of + [] -> ps + qs -> qs + +-- | Rewrites an expected token as a friendly phrase. +-- +-- * Binary operators are rewritten as @"an operator"@. +-- * Variables are rewritten as @"a variable"@. +-- * Constructors are rewritten as @"a constructor"@. +-- * Integers are rewritten as @"an integer"@. +-- * Everything else is kept as is. +toPhrase :: HappyExp -> Exp +toPhrase ex' = + let ex = rewrite ex' in + case ex of + -- We'll briefly apply the lexer to determine whether `ex' is an operator. + _ | isTextOperator ex -> "an operator" + | ex == "var" -> "a variable" + | ex == "con" -> "a constructor" + | ex == "int" -> "an integer" + | otherwise -> quotes ex + where + -- Removes any surrounding single quotes. (Happy includes these, e.g., the terminal '=='.) + rewrite :: HappyExp -> Text + rewrite = Text.dropAround (== '\'') . Text.pack \ No newline at end of file diff --git a/src/LH/Text/Parser/Monad.hs b/src/LH/Text/Parser/Monad.hs index ab26203..be5ce0f 100644 --- a/src/LH/Text/Parser/Monad.hs +++ b/src/LH/Text/Parser/Monad.hs @@ -10,7 +10,7 @@ Maintainer : kimhang@oregonstate.edu Stability : experimental This module provides the parser monad for Layered Haskell. -Consequently, it includes definitions for a custom Alex wrapper and a representation of errors and state. +Consequently, it includes definitions for a custom Alex wrapper and a representation of state. -} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} @@ -20,16 +20,14 @@ module LH.Text.Parser.Monad ( -- * The parser monad LHsParser (..), runLHsParser, -- ** State - LHsState (..), getInput, setInput, + LHsState (..), getInput, setInput, updateWithToken, -- ** Startcodes LHsStcd (..), getStcd, pushStcd, popStcd, -- ** Layout - getInnermostLayout, pushLayout, popLayout, - -- ** Errors - LHsTextError (..) + getInnermostLayout, pushLayout, popLayout ) where -import Control.Monad.Except (MonadError) +import Control.Monad.Except (MonadError) import Control.Monad.State.Strict (MonadState, gets, modify, StateT, evalStateT) @@ -39,15 +37,15 @@ import Data.Maybe (listToMaybe) import Data.Text (Text) import Data.Word (Word8) -import Errata - import qualified Data.ByteString as Byte import qualified Data.Text as Text import qualified Data.Text.Encoding as Text -import LH.Data.Error (LHsError (buildError), underline, (+>)) -import LH.Data.SrcLoc (LHsPos (..), LHsSpan (..)) -import LH.Text.Token (LHsToken (..)) +import LH.Data.SrcLoc (LHsPos (..), LHsSpan (..)) +import LH.Text.Parser.Brackets (LHsBracket(LHsBracket), openBracketType, closeBracketType) +import LH.Text.Parser.Error (LHsTextError) +import LH.Text.Token + (LHsToken (..), isVirtual) ------------------------------------------------------------------------------- -- Definitions for an Alex wrapper @@ -103,7 +101,7 @@ newtype LHsParser a = LHsParser (StateT LHsState (Either LHsTextError) a) -- | Runs a 'LHsParser' against an input 'Text'. runLHsParser :: LHsParser a -> Text -> Either LHsTextError a runLHsParser (LHsParser m) src = - evalStateT m (LHsState (AlexInput initPos initPrev initBytes src) initStack initStack) + evalStateT m (LHsState (AlexInput initPos initPrev initBytes src) initStack initStack initStack Nothing) where initPos = LHsPos 1 1 initPrev = '\n' @@ -113,11 +111,22 @@ runLHsParser (LHsParser m) src = ------------------------------------------------------------------------------- -- Parser state --- | The parser state, which keeps track of the current input and two stacks. +-- | The parser state, which keeps track of the current input and a number of stacks. data LHsState = LHsState - { stInput :: !AlexInput -- ^ The current input. - , stStcds :: [LHsStcd] -- ^ A stack of startcodes. When empty, the lexer is in the default startcode @0@. - , stLayout :: [Int] -- ^ A stack of the columns of open layout blocks. + { stInput :: !AlexInput + -- ^ The current input. + , stStcds :: [LHsStcd] + -- ^ A stack of startcodes. When empty, the lexer is in the default startcode @0@. + , stLayout :: [Int] + -- ^ A stack of the columns of open layout blocks. + , stBrack :: [LHsBracket] + -- ^ A stack of unclosed brackets. + -- + -- 'stBrack' is used for reporting better error messages related to unclosed brackets. + , stNVirt :: !(Maybe LHsSpan) + -- ^ The span of the last seen non-virtual token. + -- + -- 'stNVirt' is used for reporting better error messages related to incomplete definitions. } -- | Retrieves the current input. @@ -128,6 +137,27 @@ getInput = gets stInput setInput :: AlexInput -> LHsParser () setInput inp = modify (\st -> st { stInput = inp }) +-- | Updates the state after the lexer produces a token. +-- +-- 'updateWithToken' exists to update 'stNVirt' and 'stBrack', +-- since these are the fields of 'LHsState' that might be updated after a new token is produced. +-- For instance, if an incoming 'LH.Text.Token.LHsRParen' closes the innermost entry in 'stBrack' +-- (which should be 'LH.Text.Token.LHsLParen'), +-- then 'updateWithToken' pops 'LH.Text.Token.LHsLParen' from the stack. +updateWithToken :: LHsSpan -> LHsToken -> LHsParser () +updateWithToken sp tok = modify $ \st -> + -- Update stNVirt if tok is non-virtual. + let st' = if isVirtual tok then st else st { stNVirt = Just sp } + -- Update the stack of open brackets. + in case (openBracketType tok, closeBracketType tok, stBrack st') of + -- If tok opens a new bracket, push it onto the stack. + (Just bty, _, brs) -> + st' { stBrack = LHsBracket bty sp : brs } + -- If tok closes a bracket at the front of the stack, pop it. + (_, Just bty, LHsBracket bty' _ : brs') | bty == bty' -> + st' { stBrack = brs' } + _ -> st' + ------------------------------------------------------------------------------- -- Startcodes @@ -161,37 +191,3 @@ pushLayout c = modify (\st -> st { stLayout = c : stLayout st }) popLayout :: LHsParser () popLayout = modify (\st -> st { stLayout = drop 1 (stLayout st) }) -------------------------------------------------------------------------------- --- Errors - --- | A text-related error emitted by the lexer or parser. -data LHsTextError - = LexicalError !LHsPos !Text -- ^ A lexical error emitted by Alex. - | UnclosedComment !LHsPos -- ^ An unclosed multi-line comment error emitted by Alex. - | ParseError !LHsSpan !LHsToken -- ^ A parse error emitted by Happy. - -- The first argument indicates where an unexpected token - -- starts and ends in the source. - deriving (Eq, Show) - -instance LHsError LHsTextError where - buildError file (LexicalError pos bad) = - errataSimple - (Just ("Unexpected '" <> bad <> "'")) - (underline file (pos +> Text.length bad) "not sure how to interpret this symbol") - Nothing - buildError file (UnclosedComment pos) = - errataSimple - (Just "Unclosed comment") - (underline file (pos +> 2) "this comment is never closed") - Nothing - buildError file (ParseError (LHsSpan start end) bad) = - errataSimple - (Just "Parse error") - -- Virtual tokens have an empty span, so we underline at least one character. - (underline file (LHsSpan start (end { posCol = max (posCol end) (posCol start + 1) })) label) - Nothing - where - label = case bad of - LHsTkVSemi -> "this starts a new declaration, but the previous one is unfinished" - LHsTkVClose -> "the block ends here, but something before it is unfinished" - _ -> "this was not expected here" diff --git a/src/LH/Text/Pretty.hs b/src/LH/Text/Pretty.hs new file mode 100644 index 0000000..37ea957 --- /dev/null +++ b/src/LH/Text/Pretty.hs @@ -0,0 +1,30 @@ +{- | +Module : LH.Text.Pretty +Description : Formatting 'Data.Text' values. +Copyright : (c) Hangil Kim, 2026 + Kairon Johnson, 2026 + Leonidas Sallos, 2026 + Oscar Abelanet, 2026 +License : MIT +Maintainer : kimhang@oregonstate.edu +Stability : experimental + +This module provides a set of convenient definitions for formatting 'Data.Text' values. +-} +{-# LANGUAGE OverloadedStrings #-} +module LH.Text.Pretty ( + -- * Formatting + (<+>), quotes + ) where + +import Data.Text (Text) + +-- | Adds quotes around a 'Text' value. +quotes :: Text -> Text +quotes s = "`" <> s <> "'" + +infixr 6 <+> + +-- | Concatenates two 'Text' values together with a space in between. +(<+>) :: Text -> Text -> Text +a <+> b = a <> " " <> b \ No newline at end of file diff --git a/src/LH/Text/Token.hs b/src/LH/Text/Token.hs index c511997..0e1d6a6 100644 --- a/src/LH/Text/Token.hs +++ b/src/LH/Text/Token.hs @@ -11,13 +11,20 @@ Stability : experimental This module provides definitions for tokens. -} +{-# LANGUAGE OverloadedStrings #-} module LH.Text.Token ( -- * Tokens - LHsToken (..) + LHsToken (..), + -- ** Pretty-printing + pprToken, + -- ** Properties + isKeyword, isOperator, isVirtual ) where import Data.Text (Text) +import qualified Data.Text as Text (pack) + -- | A token. data LHsToken --------------------------------------------------------------------------- @@ -90,3 +97,89 @@ data LHsToken -- End-of-file | LHsTkEOF -- ^ The token indicating end-of-file (EOF). deriving (Eq, Show) + +-- | Pretty-prints a token. +-- Note that virtual tokens and 'LHsTkEOF' are pretty-printed as the empty string. +pprToken :: LHsToken -> Text +pprToken (LHsTkVar x) = x +pprToken (LHsTkCon c) = c +pprToken (LHsTkInt n) = Text.pack (show n) +pprToken LHsTkArrow = "->" +pprToken LHsTkPlus = "+" +pprToken LHsTkMinus = "-" +pprToken LHsTkTimes = "*" +pprToken LHsTkOr = "||" +pprToken LHsTkAnd = "&&" +pprToken LHsTkLt = "<" +pprToken LHsTkGt = ">" +pprToken LHsTkLte = "<=" +pprToken LHsTkGte = ">=" +pprToken LHsTkEqEq = "==" +pprToken LHsTkNotEq = "/=" +pprToken LHsTkDot = "." +pprToken LHsTkDollar = "$" +pprToken LHsTkColon = ":" +pprToken LHsTkPlusPlus = "++" +pprToken LHsTkExclExcl = "!!" +pprToken LHsTkLam = "\\" +pprToken LHsTkEq = "=" +pprToken LHsTkPipe = "|" +pprToken LHsTkColonColon = "::" +pprToken LHsTkLParen = "(" +pprToken LHsTkRParen = ")" +pprToken LHsTkLBrack = "[" +pprToken LHsTkRBrack = "]" +pprToken LHsTkComma = "," +pprToken LHsTkUnderscore = "_" +pprToken LHsTkLet = "let" +pprToken LHsTkIn = "in" +pprToken LHsTkCase = "case" +pprToken LHsTkOf = "of" +pprToken LHsTkData = "data" +pprToken LHsTkType = "type" +pprToken LHsTkIf = "if" +pprToken LHsTkThen = "then" +pprToken LHsTkElse = "else" +pprToken LHsTkVOpen = "" +pprToken LHsTkVClose = "" +pprToken LHsTkVSemi = "" +pprToken LHsTkEOF = "" + +-- | Is a given token a keyword? +isKeyword :: LHsToken -> Bool +isKeyword LHsTkLet = True +isKeyword LHsTkIn = True +isKeyword LHsTkCase = True +isKeyword LHsTkOf = True +isKeyword LHsTkData = True +isKeyword LHsTkType = True +isKeyword LHsTkIf = True +isKeyword LHsTkThen = True +isKeyword LHsTkElse = True +isKeyword _ = False + +-- | Is a given token an operator? +isOperator :: LHsToken -> Bool +isOperator LHsTkPlus = True +isOperator LHsTkMinus = True +isOperator LHsTkTimes = True +isOperator LHsTkOr = True +isOperator LHsTkAnd = True +isOperator LHsTkLt = True +isOperator LHsTkGt = True +isOperator LHsTkLte = True +isOperator LHsTkGte = True +isOperator LHsTkEqEq = True +isOperator LHsTkNotEq = True +isOperator LHsTkDot = True +isOperator LHsTkDollar = True +isOperator LHsTkColon = True +isOperator LHsTkPlusPlus = True +isOperator LHsTkExclExcl = True +isOperator _ = False + +-- | Is a given token virtual? See 'LHsTkVSemi' and 'LHsTkVClose'. +isVirtual :: LHsToken -> Bool +isVirtual LHsTkVSemi = True +isVirtual LHsTkVClose = True +isVirtual _ = False \ No newline at end of file diff --git a/src/LH/Text/Token/Read.hs b/src/LH/Text/Token/Read.hs new file mode 100644 index 0000000..5963c89 --- /dev/null +++ b/src/LH/Text/Token/Read.hs @@ -0,0 +1,45 @@ +{- | +Module : LH.Text.Token.Read +Description : Reading 'Data.Text' values into tokens. +Copyright : (c) Hangil Kim, 2026 + Kairon Johnson, 2026 + Leonidas Sallos, 2026 + Oscar Abelanet, 2026 +License : MIT +Maintainer : kimhang@oregonstate.edu +Stability : experimental + +This module provides a number of convenient definitions for reading 'Data.Text' values into tokens. +-} +module LH.Text.Token.Read ( + -- * Reading tokens + readTokenWithPred, + -- ** Properties + isTextKeyword, isTextOperator + ) where + +import Data.Text (Text) + +import LH.Data.SrcLoc (LHsLexeme (..)) +import LH.Text.Lexer (scanTokens) +import LH.Text.Token (LHsToken, isKeyword, isOperator) + +-- | Attempts to read a /single/ token from a string and checks it against a predicate. +-- +-- The intended use of this function is to apply the predicates defined within the "LH.Text.Token" module, +-- such as 'LH.Text.Token.isKeyword' or 'LH.Text.Token.isOperator'. This module provides definitions for these +-- in the form of 'isTextKeyword' and 'isTextOperator'. +readTokenWithPred :: Text + -> (LHsToken -> Bool) -- ^ A predicate. + -> Bool +readTokenWithPred s p + | Right [LHsLexeme _ tok] <- scanTokens s = p tok + | otherwise = False + +-- | Is a given 'Text' value a keyword? +isTextKeyword :: Text -> Bool +isTextKeyword = flip readTokenWithPred isKeyword + +-- | Is a given 'Text' value an operator? +isTextOperator :: Text -> Bool +isTextOperator = flip readTokenWithPred isOperator \ No newline at end of file diff --git a/src/LH/Typechecker/Monad.hs b/src/LH/Typechecker/Monad.hs new file mode 100644 index 0000000..32f1d3f --- /dev/null +++ b/src/LH/Typechecker/Monad.hs @@ -0,0 +1,57 @@ +{- | +Module : LH.Typechecker.Monad +Description : The typechecker monad. +Copyright : (c) Hangil Kim, 2026 + Kairon Johnson, 2026 + Leonidas Sallos, 2026 + Oscar Abelanet, 2026 +License : MIT +Maintainer : kimhang@oregonstate.edu +Stability : experimental + +This module provides the typechecker monad for Layered Haskell. +-} +{-# LANGUAGE GeneralizedNewtypeDeriving #-} +module LH.Typechecker.Monad ( + -- * The typechecker monad + LHsTC (..), runLHsTC, + -- ** Bindings + ext, exts, + -- ** Placeholders + LHsTCError (..) + ) where + +import Control.Monad.Except (MonadError) +import Control.Monad.State.Strict + (MonadState, modify, + StateT, evalStateT) + +import Data.Sequence (Seq) + +import qualified Data.Map as Map (empty, insert) + +import LH.Feature.AbsSyn (Id, LHsType, LHsTEnv) + +-- | A placeholder for typechecker errors. +newtype LHsTCError = LHsTCError () + +-- | The typechecker monad. +-- +-- 'LHsTEnv', which comes from superimposed source files, maps variables to types. +newtype LHsTC a = LHsTC (StateT LHsTEnv (Either LHsTCError) a) + deriving (Functor, Applicative, Monad, MonadState LHsTEnv, MonadError LHsTCError) + +-- | Runs the typechecker monad. +runLHsTC :: LHsTC a -> Either LHsTCError a +runLHsTC (LHsTC m) = + evalStateT m initEnv + where + initEnv = Map.empty + +-- | Adds a binding to the type environment. +ext :: (Id, LHsType) -> LHsTC () +ext (x, v) = modify (Map.insert x v) + +-- | Adds multiple bindings to the type environment. +exts :: Seq (Id, LHsType) -> LHsTC () +exts = mapM_ ext \ No newline at end of file diff --git a/test/LH/Test/Text/Lexer.hs b/test/LH/Test/Text/Lexer.hs index 34fe1c8..b2c20c5 100644 --- a/test/LH/Test/Text/Lexer.hs +++ b/test/LH/Test/Text/Lexer.hs @@ -13,6 +13,7 @@ import qualified Data.Text as Text import LH.Data.SrcLoc import LH.Text.Lexer +import LH.Text.Parser.Error (LHsTextError(LexicalError, UnclosedComment)) import LH.Text.Parser.Monad import LH.Text.Token @@ -65,32 +66,32 @@ eofAt src n (l, c) = tokensAsProgram :: Text -> Either LHsTextError [LHsToken] tokensAsProgram = fmap (map (\(LHsLexeme _ tok) -> tok)) . scanTokensAsProgram --- Pretty-prints tokens including layout. +-- Reads tokens from text, including layout. -- For instance, "{ x = a ; y = b }". -pprTokens :: Text -> [LHsToken] -pprTokens = map pprToken . Text.words +readTokens :: Text -> [LHsToken] +readTokens = map readToken . Text.words where - pprToken "{" = LHsTkVOpen - pprToken ";" = LHsTkVSemi - pprToken "}" = LHsTkVClose - pprToken "=" = LHsTkEq - pprToken "->" = LHsTkArrow - pprToken "|" = LHsTkPipe - pprToken "::" = LHsTkColonColon - pprToken "let" = LHsTkLet - pprToken "in" = LHsTkIn - pprToken "case" = LHsTkCase - pprToken "of" = LHsTkOf - pprToken "data" = LHsTkData - pprToken "type" = LHsTkType - pprToken name + readToken "{" = LHsTkVOpen + readToken ";" = LHsTkVSemi + readToken "}" = LHsTkVClose + readToken "=" = LHsTkEq + readToken "->" = LHsTkArrow + readToken "|" = LHsTkPipe + readToken "::" = LHsTkColonColon + readToken "let" = LHsTkLet + readToken "in" = LHsTkIn + readToken "case" = LHsTkCase + readToken "of" = LHsTkOf + readToken "data" = LHsTkData + readToken "type" = LHsTkType + readToken name | isUpper (Text.head name) = LHsTkCon name | otherwise = LHsTkVar name -- Does the source produce an expected list of tokens (including virtual ones)? layoutsTo :: HasCallStack => Text -> Text -> Spec layoutsTo src expected = it (show src) $ - tokensAsProgram src `shouldBe` Right (pprTokens expected) + tokensAsProgram src `shouldBe` Right (readTokens expected) ------------------------------------------------------------------------------- -- Tests diff --git a/test/LH/Test/Text/Parser.hs b/test/LH/Test/Text/Parser.hs index dfed04b..7838258 100644 --- a/test/LH/Test/Text/Parser.hs +++ b/test/LH/Test/Text/Parser.hs @@ -2,7 +2,7 @@ -- This module provides a test suite for Layered Haskell's parsers. module LH.Test.Text.Parser (spec) where -import Control.Monad (forM_, unless, void) +import Control.Monad (forM, forM_, unless, void) import System.Directory import System.Exit (ExitCode (..)) import System.FilePath @@ -11,12 +11,12 @@ import System.Process (readProcessWithExitCode) import Test.Hspec -import LHMake.Data.Feature (FeatureName, superimpose, combos) +import LHMake.Data.Feature (Layer, superimpose, superimposeUpp, layers) import LHMake.Data.Error (LHsMakeError) spec :: Spec spec = case cases of - Left err -> it "generates feature combinations" (expectationFailure err) + Left err -> it "generates layers" (expectationFailure err) Right tests -> -- Build the LayeredHaskell library. beforeAll_ build $ @@ -45,27 +45,46 @@ spec = case cases of build :: IO () build = void (run "cabal" ["build", "lib:LayeredHaskell"]) --- Generates the source files for a feature combination. +-- Generates the source files for a layer. -- The tests then operate on a temporary directory named @LayeredHaskell-@. -withBuild :: [FeatureName] -> (FilePath -> IO ()) -> IO () +withBuild :: Layer -> (FilePath -> IO ()) -> IO () withBuild args tests = withSystemTempDirectory "LayeredHaskell-test" $ \dir -> do - let featureDir = dir "LH" "Feature" - -- Create ../LH/Feature/, which will then receive the superimposed files. - createDirectoryIfMissing True featureDir - superimpose args (addTrailingPathSeparator featureDir) - files <- listDirectory featureDir - -- For each Happy file, we execute Happy to produce a set of Haskell modules. - forM_ [file | file <- files, takeExtension file == ".y"] $ \y -> - run "happy" [featureDir y, "-g", "-a", "-c", "-o", featureDir replaceExtension y "hs"] - -- Then, we can run cabal on the driver file. + superimpose args dir + superimposeUpp dir + compile "src" dir ".x" $ \inp out -> + run "alex" [inp, "-g", "-o", out] + compile dir dir ".y" $ \inp out -> + run "happy" [inp, "-g", "-a", "-c", "-o", out] _ <- run "cabal" - [ "exec", "--", "ghc", "-O0", "-package", "LayeredHaskell", "-i" ++ dir, "-outputdir", dir "build" - , "-o", dir "driver" <.> exeExtension, "test/LH/Test/Text/Parser/Driver.hs" ] + [ "exec", "--", "ghc", "-O0", "-hide-package", "LayeredHaskell" + , "-i" ++ dir, "-isrc", "-outputdir", dir "build" + , "-o", dir "driver" <.> exeExtension + , "test/LH/Test/Text/Parser/Driver.hs" ] tests dir + where + -- Finds every file with the given extension under `from', then applies a + -- function `k' to each file. (This is used for compiling Alex and Happy files.) + -- The output is a Haskell file at the same relative path under `to'. + compile :: FilePath -> FilePath -> String -> (FilePath -> FilePath -> IO a) -> IO () + compile from to ext generator = do + inps <- fmap (filter ((== ext) . takeExtension)) (listFilesRecursive from) + forM_ inps $ \inp -> do + let out = to replaceExtension (makeRelative from inp) "hs" + createDirectoryIfMissing True (takeDirectory out) + void (generator inp out) + + -- Lists every file under a folder, including files inside subfolders. + listFilesRecursive :: FilePath -> IO [FilePath] + listFilesRecursive root = do + entries <- listDirectory root + fmap concat $ forM entries $ \entry -> do + let path = root entry + isDir <- doesDirectoryExist path + if isDir then listFilesRecursive path else return [path] -- Runs a program and returns what the program prints. -- The test fails if the program exited with an error. -run :: FilePath -> [FeatureName] -> IO String +run :: FilePath -> Layer -> IO String run exe args = do (code, out, err) <- readProcessWithExitCode exe args "" unless (code == ExitSuccess) $ @@ -82,14 +101,14 @@ type Source = (String, String, String) -- A testcase. data Case = Case { cName :: String -- ^ The name of the testcase. - , cFeats :: [FeatureName] -- ^ The feature combination corresponding to the testcase. + , cFeats :: Layer -- ^ The layer corresponding to the testcase. , cInputs :: [Source] -- ^ A set of testcase inputs. } -- Testcase inputs. -- A testcase input is added when all of its features are enabled, -- whether it be manually or automatically. -inputs :: [([FeatureName], [Source])] +inputs :: [(Layer, [Source])] inputs = [ (["E"], e) , (["B"], b) @@ -104,14 +123,14 @@ inputs = , (["P", "L"], pl) ] --- Produces the testcase inputs for a set of enabled features. -inputsFor :: [FeatureName] -> [Source] +-- Produces the testcase inputs for a given layer. +inputsFor :: Layer -> [Source] inputsFor enabled = concat [tests | (req, tests) <- inputs, all (`elem` enabled) req] -- A set of testcases. cases :: LHsMakeError [Case] -cases = fmap (map toCase) combos +cases = fmap (map toCase) layers where toCase entry = let names = map fst (filter snd entry) @@ -620,6 +639,18 @@ l = "prefix list indexing operator" "h = (!!) a b" "LHsEqn \"h\" (fromList []) (LHsApp (LHsApp (LHsPre LHsListIndex) (LHsVar \"a\")) (LHsVar \"b\"))" + , source + "applying function to empty list" + "f = g []" + "LHsEqn \"f\" (fromList []) (LHsApp (LHsVar \"g\") (LHsList (fromList [])))" + , source + "applying function to nonempty list" + "f = g [x,y,z]" + "LHsEqn \"f\" (fromList []) (LHsApp (LHsVar \"g\") (LHsList (fromList [LHsVar \"x\",LHsVar \"y\",LHsVar \"z\"])))" + , source + "applying function to tuple" + "f = g (x,y,z)" + "LHsEqn \"f\" (fromList []) (LHsApp (LHsVar \"g\") (LHsTuple (fromList [LHsVar \"x\",LHsVar \"y\",LHsVar \"z\"])))" ] lb :: [Source]