packages feed

claferIG-0.5.8: src/Language/Clafer/IG/Constraints.hs

{-# LANGUAGE NamedFieldPuns #-}

{-
 Copyright (C) 2012-2017 Jimmy Liang <http://gsd.uwaterloo.ca>

 Permission is hereby granted, free of charge, to any person obtaining a copy of
 this software and associated documentation files (the "Software"), to deal in
 the Software without restriction, including without limitation the rights to
 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 of the Software, and to permit persons to whom the Software is furnished to do
 so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
-}

module Language.Clafer.IG.Constraints (Constraint(..), Cardinality(..), ClaferInfo(..), ConstraintInfo(..), isLowerCardinalityConstraint, isUpperCardinalityConstraint, lookupConstraint, parseConstraints, parseAssertions, isOnLine)  where

import Data.List
import Data.Maybe
import Data.Ord
import Language.Clafer
import Language.Clafer.Front.AbsClafer (Span(..))
import Language.Clafer.Import (ModelFile, modelText, modelPosition)
import Language.Clafer.Intermediate.Intclafer
import qualified Language.Clafer.Intermediate.Intclafer as I



data Constraint =
    ExactCardinalityConstraint {range::Span, claferInfo::ClaferInfo} |
    LowerCardinalityConstraint {range::Span, claferInfo::ClaferInfo} |
    UpperCardinalityConstraint {range::Span, claferInfo::ClaferInfo} |
    UserConstraint {range::Span, constraintInfo::ConstraintInfo}
    deriving (Show, Eq)


data Cardinality = Cardinality {lower::Integer, upper::Maybe Integer} deriving Eq

instance Show Cardinality where
    show (Cardinality 0 Nothing) = "*"
    show (Cardinality 1 Nothing) = "+"
    show (Cardinality lower Nothing) = show lower ++ "..*"
    show (Cardinality 0 (Just 1)) = "?"
    show (Cardinality lower (Just upper))
        | lower == upper = show lower
        | otherwise      = show lower ++ ".." ++ show upper


data ClaferInfo = ClaferInfo {uniqueId::String, cardinality::Cardinality} deriving Eq

instance Show ClaferInfo where
    show (ClaferInfo uniqueId cardinality) = uniqueId ++ " " ++ show cardinality


-- | A constraint of the model: its position in the complete model, its text, and its position
--   as shown, the file and the position in it (@file.cfr:3:5@).
data ConstraintInfo = ConstraintInfo {pId::String, pos::Span, syntax::String, position::String, fileLine::Integer} deriving Eq

instance Show ConstraintInfo where
    show ConstraintInfo{syntax, position} = syntax ++ " (" ++ position ++ ")"

-- | Whether a constraint spans the given line of its file.
isOnLine :: Integer -> ConstraintInfo -> Bool
isOnLine n ConstraintInfo{pos = Span (Pos l1 _) (Pos l2 _), fileLine} = fileLine <= n && n <= fileLine + l2 - l1

isLowerCardinalityConstraint :: Constraint -> Bool
isLowerCardinalityConstraint LowerCardinalityConstraint{} = True
isLowerCardinalityConstraint _ = False


isUpperCardinalityConstraint :: Constraint -> Bool
isUpperCardinalityConstraint UpperCardinalityConstraint{} = True
isUpperCardinalityConstraint _ = False


to :: Span -> Pos
to (Span _ t) = t
{-from :: Span -> Pos
from (Span f _) = f -}


lookupConstraint :: Span -> [Constraint] -> Constraint
lookupConstraint constraint' constraints =
    case [x | x <- constraints, constraint' == range x] of
        [] -> error $ show constraint' ++ " not equal to known constraints " ++ show constraints
        cs -> minimumBy (comparing $ to . range) cs


parseConstraints :: [ModelFile] -> IModule -> [(Span, IrTrace)] -> [Constraint]
parseConstraints modelFiles imodule mapping =
    mapMaybe (uncurry convert) mapping
    where
    clafers = _mDecls imodule >>= subclafers
    pexps = (mapMaybe constraint $ _mDecls imodule ++ concatMap _elements clafers) >>= subexpressions
    convert s IrPExp{pUid} =
        Just $ UserConstraint s $ constraintInfoOf modelFiles $ findPExp pUid
    convert s LowerCard{pUid, isGroup = False} =
        Just $ LowerCardinalityConstraint s $ claferInfo pUid
    convert s UpperCard{pUid, isGroup = False} =
        Just $ UpperCardinalityConstraint s $ claferInfo pUid
    convert s ExactCard{pUid, isGroup = False} =
        Just $ ExactCardinalityConstraint s $ claferInfo pUid
    convert _ _ = Nothing

    findPExp pUid   = fromMaybe (error $ "Unknown constraint " ++ pUid) $ find ((== pUid) . _pid) pexps
    findClafer pUid = fromMaybe (error $ "Unknown clafer " ++ pUid) $ find ((== pUid) . _uid) clafers
    convertCard (l, -1) = Cardinality l Nothing
    convertCard (l, h)  = Cardinality l $ Just h
    claferInfo pUid =
        ClaferInfo (_ident claf) $ convertCard $ fromJust $ _card claf
        where
        claf = findClafer pUid


-- | The assertions of the model, in the order of the model, with their names in the Alloy output.
parseAssertions :: [ModelFile] -> IModule -> [(String, ConstraintInfo)]
parseAssertions modelFiles imodule =
    [ (assertionName pexp, constraintInfoOf modelFiles pexp) | pexp <- sortOn _inPos $ mapMaybe assertion elements ]
    where
    elements = _mDecls imodule ++ concatMap _elements (_mDecls imodule >>= subclafers)
    assertion (IEConstraint False pexp) = Just pexp
    assertion _ = Nothing


-- | The information of a constraint: its text and position in the files of the model.
constraintInfoOf :: [ModelFile] -> PExp -> ConstraintInfo
constraintInfoOf modelFiles pexp = ConstraintInfo (_pid pexp) (_inPos pexp) (extract $ _inPos pexp) (showPosition $ _inPos pexp) (positionLine $ _inPos pexp)
    where
    -- the columns count a tab up to the next multiple of 8, as the compiler does
    text = map expandTabs $ lines $ modelText modelFiles
    showPosition (Span (Pos l c) _) = let (path, l') = modelPosition modelFiles l in path ++ ":" ++ show l' ++ ":" ++ show c
    positionLine (Span (Pos l _) _) = snd $ modelPosition modelFiles l
    -- an expression's span ends before the parentheses that close its last operand, e.g.,
    -- `initially (a --> b` of `initially (a --> b)`, which are added
    extract (Span (Pos l1 c1) (Pos l2 c2)) = closeParentheses (extract' l1 c1 l2 c2) (drop (fromInteger $ c2 - 1) $ text !! (fromInteger $ l2 - 1))
    extract' l1 c1 l2 c2
        | l1 == l2  = drop (fromInteger $ c1 - 1) $ take (fromInteger $ c2 - 1) $ text !! (fromInteger $ l1 - 1)
        | otherwise = unlines $ f1 : fs ++ [fn]
        where
        f1 = drop (fromInteger $ c1 - 1) $ text !! (fromInteger $ l1 - 1)
        fs = map (text !!) [(fromInteger $ l1) .. (fromInteger $ l2 - 2)]
        fn = take (fromInteger $ c2 - 1) $ text !! (fromInteger $ l2 - 1)
    closeParentheses extracted rest
        | open > 0, ')' : rest' <- dropWhile (== ' ') rest = closeParentheses (extracted ++ takeWhile (== ' ') rest ++ ")") rest'
        | otherwise = extracted
        where
        open = length (filter (== '(') extracted) - length (filter (== ')') extracted)


-- | The line with its tabs as spaces, up to the next multiple of 8
expandTabs :: String -> String
expandTabs = expand 0
    where
    expand column ('\t' : rest) = let n = 8 - column `mod` 8 in replicate n ' ' ++ expand (column + n) rest
    expand column (x : rest) = x : expand (column + 1) rest
    expand _ [] = []

subclafers :: IElement -> [IClafer]
subclafers (IEClafer claf) = claf : (_elements claf >>= subclafers)
subclafers _ = []

constraint :: IElement -> Maybe PExp
constraint (IEConstraint _ pexp') = Just pexp'
constraint _ = Nothing

subexpressions :: PExp -> [PExp]
subexpressions p@PExp{I._exp = exp'} =
    p : subexpressions' exp'
    where
    subexpressions' IDeclPExp{_oDecls, _bpexp} =
        concatMap (subexpressions . _body) _oDecls ++ subexpressions _bpexp
    subexpressions' IFunExp{_exps} = concatMap subexpressions _exps
    subexpressions' _ = []