diff --git a/code/drasil-code/lib/Language/Drasil/Code/Imperative/Import.hs b/code/drasil-code/lib/Language/Drasil/Code/Imperative/Import.hs index 8fc55f54a1..da14781757 100644 --- a/code/drasil-code/lib/Language/Drasil/Code/Imperative/Import.hs +++ b/code/drasil-code/lib/Language/Drasil/Code/Imperative/Import.hs @@ -9,11 +9,12 @@ module Language.Drasil.Code.Imperative.Import (codeType, spaceCodeType, import Language.Drasil (HasSymbol, HasUID(..), HasSpace(..), Space (Rational, Real), RealInterval(..), UID, Constraint(..), Inclusive (..)) import Database.Drasil (symbResolve) -import Language.Drasil.CodeExpr (sy, ($<), ($>), ($<=), ($>=), ($&&)) +import Language.Drasil.CodeExpr (sy, ($<), ($>), ($<=), ($>=), ($&&),in') +import qualified Language.Drasil.CodeExpr as CE (int) import Language.Drasil.CodeExpr.Development (CodeExpr(..), ArithBinOp(..), - AssocArithOper(..), AssocBoolOper(..), BoolBinOp(..), EqBinOp(..), + AssocArithOper(..), AssocBoolOper(..), AssocConcatOper(..), BoolBinOp(..), EqBinOp(..), LABinOp(..), OrdBinOp(..), UFunc(..), UFuncB(..), UFuncVV(..), UFuncVN(..), - VVNBinOp(..), VVVBinOp(..), NVVBinOp(..)) + VVNBinOp(..), VVVBinOp(..), NVVBinOp(..), ESSBinOp(..), ESBBinOp(..)) import Language.Drasil.Code.Imperative.Comments (getComment) import Language.Drasil.Code.Imperative.ConceptMatch (conceptToGOOL) import Language.Drasil.Code.Imperative.GenerateGOOL (auxClass, fApp, ctorCall, @@ -37,17 +38,7 @@ import Language.Drasil.Mod (Func(..), FuncData(..), FuncDef(..), FuncStmt(..), Mod(..), Name, Description, StateVariable(..), fstdecl) import qualified Language.Drasil.Mod as M (Class(..)) -import GOOL.Drasil (Label, SFile, MSBody, MSBlock, VSType, SVariable, SValue, - MSStatement, MSParameter, SMethod, CSStateVar, SClass, NamedArgs, - Initializers, OOProg, PermanenceSym(..), bodyStatements, BlockSym(..), - TypeSym(..), VariableSym(..), OOVariableSym(..), VariableElim(..), ($->), ValueSym(..), - Literal(..), VariableValue(..), NumericExpression(..), BooleanExpression(..), - Comparison(..), ValueExpression(..), OOValueExpression(..), - objMethodCallMixedArgs, List(..), StatementSym(..), AssignStatement(..), - DeclStatement(..), IOStatement(..), StringStatement(..), ControlStatement(..), - ifNoElse, ScopeSym(..), ParameterSym(..), MethodSym(..), OOMethodSym(..), - pubDVar, privDVar, nonInitConstructor, convTypeOO, ScopeTag(..), CodeType(..), - onStateValue) +import GOOL.Drasil hiding (Set, get) import qualified GOOL.Drasil as C (CodeType(List, Array)) import Prelude hiding (sin, cos, tan, log, exp) @@ -297,6 +288,7 @@ convExpr (AssocA Add l) = foldl1 (#+) <$> mapM convExpr l convExpr (AssocA Mul l) = foldl1 (#*) <$> mapM convExpr l convExpr (AssocB And l) = foldl1 (?&&) <$> mapM convExpr l convExpr (AssocB Or l) = foldl1 (?||) <$> mapM convExpr l +convExpr (AssocC SUnion l) = foldl1 (#+) <$> mapM convExpr l convExpr (C c) = do g <- get let v = quantvar (lookupC g c) @@ -336,6 +328,8 @@ convExpr (OrdBinaryOp o a b) = liftM2 (ordBfunc o) (convExpr a) (convExpr b) convExpr (VVVBinaryOp o a b) = liftM2 (vecVecVecBfunc o) (convExpr a) (convExpr b) convExpr (VVNBinaryOp o a b) = liftM2 (vecVecNumBfunc o) (convExpr a) (convExpr b) convExpr (NVVBinaryOp o a b) = liftM2 (numVecVecBfunc o) (convExpr a) (convExpr b) +convExpr (ESSBinaryOp o a b) = liftM2 (elementSetSetBfunc o) (convExpr a) (convExpr b) +convExpr (ESBBinaryOp o a b) = liftM2 (elementSetBoolBfunc o) (convExpr a) (convExpr b) convExpr (Case c l) = doit l -- FIXME this is sub-optimal where doit [] = error "should never happen" -- TODO: change error message? @@ -347,6 +341,11 @@ convExpr (Matrix [l]) = do -- hd will never fail here return $ litArray (fmap valueType (head ar)) ar convExpr Matrix{} = error "convExpr: Matrix" +convExpr (Set l) = do + ar <- mapM convExpr l + -- hd will never fail here + return $ litSet (fmap valueType (head ar)) ar +--convExpr Set{} = error "convExpr: Set" convExpr Operator{} = error "convExpr: Operator" convExpr (RealI c ri) = do g <- get @@ -380,6 +379,7 @@ convCall c x ns f libf = do -- | Converts a 'Constraint' to a 'CodeExpr'. renderC :: (HasUID c, HasSymbol c) => c -> Constraint CodeExpr -> CodeExpr renderC s (Range _ rr) = renderRealInt s rr +renderC s (Elem _ rr) = renderSet s rr -- | Converts an interval ('RealInterval') to a 'CodeExpr'. renderRealInt :: (HasUID c, HasSymbol c) => c -> RealInterval CodeExpr CodeExpr -> CodeExpr @@ -392,6 +392,9 @@ renderRealInt s (UpTo (Exc, a)) = sy s $< a renderRealInt s (UpFrom (Inc, a)) = sy s $>= a renderRealInt s (UpFrom (Exc, a)) = sy s $> a +renderSet :: (HasUID c, HasSymbol c) => c -> CodeExpr -> CodeExpr +renderSet e s = in' s (sy e) + -- | Maps a 'UFunc' to the corresponding GOOL unary function. unop :: (OOProg r) => UFunc -> (SValue r -> SValue r) unop Sqrt = (#/^) @@ -442,6 +445,7 @@ eqBfunc NEq = (?!=) -- Maps an 'LABinOp' to it's corresponding GOOL binary function. laBfunc :: (OOProg r) => LABinOp -> (SValue r -> SValue r -> SValue r) laBfunc Index = listAccess +laBfunc IndexOf = indexOf -- Maps an 'OrdBinOp' to it's corresponding GOOL binary function. ordBfunc :: (OOProg r) => OrdBinOp -> (SValue r -> SValue r -> SValue r) @@ -464,6 +468,15 @@ vecVecNumBfunc Dot = error "convExpr DotProduct" numVecVecBfunc :: NVVBinOp -> (SValue r -> SValue r -> SValue r) numVecVecBfunc Scale = error "convExpr Scaling of Vectors" +-- Maps a 'ESSBinOp' to it's corresponding GOOL binary function. +elementSetSetBfunc :: ESSBinOp -> (SValue r -> SValue r -> SValue r) +elementSetSetBfunc SAdd = error "convExpr Adding an Element to a Set" +elementSetSetBfunc SRemove = error "convExpr Removing an Element to a Set" + +-- Maps a 'ESSBinOp' to it's corresponding GOOL binary function. +elementSetBoolBfunc :: (OOProg r) => ESBBinOp -> (SValue r -> SValue r -> SValue r) +elementSetBoolBfunc SContains = contains + -- medium hacks -- -- | Converts a 'Mod' to GOOL. diff --git a/code/drasil-code/lib/Language/Drasil/Code/Imperative/Modules.hs b/code/drasil-code/lib/Language/Drasil/Code/Imperative/Modules.hs index 7f29db0519..9a994e4d54 100644 --- a/code/drasil-code/lib/Language/Drasil/Code/Imperative/Modules.hs +++ b/code/drasil-code/lib/Language/Drasil/Code/Imperative/Modules.hs @@ -38,7 +38,7 @@ import Language.Drasil.Code.CodeQuantityDicts (inFileName, inParams, consts) import Language.Drasil.Code.DataDesc (DataDesc, junkLine, singleton) import Language.Drasil.Code.ExtLibImport (defs, imports, steps) import Language.Drasil.Choices (Comments(..), ConstantStructure(..), - ConstantRepr(..), ConstraintBehaviour(..), ImplementationType(..), + ConstantRepr(..), ConstraintBehaviour(..), ImplementationType(..), Logging(..), Structure(..), hasSampleInput, InternalConcept(..)) import Language.Drasil.CodeSpec (CodeSpec(..)) import Language.Drasil.Expr.Development (Completeness(..)) @@ -389,6 +389,9 @@ printConstraint c = do printConstraint' (Range _ (UpFrom (_, e))) = do lb <- convExpr e return $ [printStr "above ", print lb] ++ printExpr e db ++ [printStrLn "."] + printConstraint' (Elem _ e) = do + lb <- convExpr e + return $ [printStr "an element of the set ", print lb] ++ [printStrLn "."] printConstraint' c -- | Don't print expressions that are just literals, because that would be diff --git a/code/drasil-code/lib/Language/Drasil/CodeSpec.hs b/code/drasil-code/lib/Language/Drasil/CodeSpec.hs index 16a422bf49..444f635dd7 100644 --- a/code/drasil-code/lib/Language/Drasil/CodeSpec.hs +++ b/code/drasil-code/lib/Language/Drasil/CodeSpec.hs @@ -13,7 +13,7 @@ import Language.Drasil.Chunk.ConstraintMap (ConstraintCEMap, ConstraintCE, const import Language.Drasil.Chunk.CodeDefinition (CodeDefinition, qtov, qtoc, odeDef, auxExprs) import Language.Drasil.Choices (Choices(..), Maps(..), ODE(..), ExtLib(..)) -import Language.Drasil.CodeExpr.Development (expr, eNamesRI) +import Language.Drasil.CodeExpr.Development (expr, eNamesRI, eDep) import Language.Drasil.Chunk.CodeBase import Language.Drasil.Mod (Func(..), FuncData(..), FuncDef(..), Mod(..), Name) @@ -193,3 +193,5 @@ getConstraints cm cs = concat $ mapMaybe (\c -> Map.lookup (c ^. uid) cm) cs constraintvars :: ConstraintCE -> ChunkDB -> [CodeChunk] constraintvars (Range _ ri) m = map (codeChunk . varResolve m) $ nub $ eNamesRI ri +constraintvars (Elem _ ri) m = + map (codeChunk . varResolve m) $ eDep ri diff --git a/code/drasil-data/lib/Data/Drasil/Constraints.hs b/code/drasil-data/lib/Data/Drasil/Constraints.hs index f42984ad91..b5fd2d7365 100644 --- a/code/drasil-data/lib/Data/Drasil/Constraints.hs +++ b/code/drasil-data/lib/Data/Drasil/Constraints.hs @@ -4,5 +4,5 @@ module Data.Drasil.Constraints where import Language.Drasil gtZeroConstr, probConstr :: ConstraintE -gtZeroConstr = physc $ UpFrom (Exc, exactDbl 0) -probConstr = physc $ Bounded (Inc, exactDbl 0) (Inc, exactDbl 1) +gtZeroConstr = physRange $ UpFrom (Exc, exactDbl 0) +probConstr = physRange $ Bounded (Inc, exactDbl 0) (Inc, exactDbl 1) diff --git a/code/drasil-example/dblpend/lib/Drasil/DblPend/Unitals.hs b/code/drasil-example/dblpend/lib/Drasil/DblPend/Unitals.hs index 04fe5b7e1d..d87f6836ba 100644 --- a/code/drasil-example/dblpend/lib/Drasil/DblPend/Unitals.hs +++ b/code/drasil-example/dblpend/lib/Drasil/DblPend/Unitals.hs @@ -187,4 +187,4 @@ pendDisAngle = cuc' "pendDisAngle" (nounPhraseSP "dependent variables") "column vector of displacement of rods with its derivatives" lTheta' radian (Vect Real) - [physc $ UpFrom (Inc, exactDbl 0)] (exactDbl 0) + [physRange $ UpFrom (Inc, exactDbl 0)] (exactDbl 0) diff --git a/code/drasil-example/gamephysics/lib/Drasil/GamePhysics/Unitals.hs b/code/drasil-example/gamephysics/lib/Drasil/GamePhysics/Unitals.hs index cb4f87b1e0..5b47966b80 100644 --- a/code/drasil-example/gamephysics/lib/Drasil/GamePhysics/Unitals.hs +++ b/code/drasil-example/gamephysics/lib/Drasil/GamePhysics/Unitals.hs @@ -327,11 +327,11 @@ mmntOfInCons = constrained' QP.momentOfInertia [gtZeroConstr] (dbl 74.5) gravAccelCons = constrained' QP.gravitationalConst [] (lit $ QP.gravitationalConstValue ^. defnExpr) posCons = constrained' QP.position [] (dbl 0.412) --FIXME: should be (0.412, 0.502) vector veloCons = constrained' QP.velocity [] (dbl 2.51) -orientCons = constrained' QM.orientation [sfwrc $ Bounded (Inc, exactDbl 0) (Inc, exactDbl 2 $* sy QM.pi_)] (half $ sy QM.pi_) -- physical constraint not needed space is radians +orientCons = constrained' QM.orientation [sfwrRange $ Bounded (Inc, exactDbl 0) (Inc, exactDbl 2 $* sy QM.pi_)] (half $ sy QM.pi_) -- physical constraint not needed space is radians angVeloCons = constrained' QP.angularVelocity [] (dbl 2.1) forceCons = constrained' QP.force [] (dbl 98.1) torqueCons = constrained' QP.torque [] (exactDbl 200) -restCoefCons = constrained' QP.restitutionCoef [physc $ Bounded (Inc, exactDbl 0) (Inc, exactDbl 1)] (dbl 0.8) +restCoefCons = constrained' QP.restitutionCoef [physRange $ Bounded (Inc, exactDbl 0) (Inc, exactDbl 1)] (dbl 0.8) posOutCons = constrained' QP.position [] (exactDbl 0) veloOutCons = constrained' QP.velocity [] (exactDbl 0) diff --git a/code/drasil-example/glassbr/lib/Drasil/GlassBR/Unitals.hs b/code/drasil-example/glassbr/lib/Drasil/GlassBR/Unitals.hs index ffe5861969..f65425a600 100644 --- a/code/drasil-example/glassbr/lib/Drasil/GlassBR/Unitals.hs +++ b/code/drasil-example/glassbr/lib/Drasil/GlassBR/Unitals.hs @@ -4,7 +4,6 @@ import Language.Drasil import Language.Drasil.Display (Symbol(..)) import Language.Drasil.ShortHands import Language.Drasil.Chunk.Concept.NamedCombinators - import Prelude hiding (log) import Data.Drasil.Concepts.Math (xComp, yComp, zComp) @@ -17,7 +16,6 @@ import Drasil.GlassBR.Concepts (aR, annealed, fullyT, glaPlane, glassTypeFac, stdOffDist) import Drasil.GlassBR.References (astm2009, astm2012, astm2016) import Drasil.GlassBR.Units (sFlawPU) - --FIXME: Many of the current terms can be separated into terms and defns? {--} @@ -33,7 +31,7 @@ modElas = uc' "modElas" (nounPhraseSP "modulus of elasticity of glass") constrained :: [ConstrainedChunk] constrained = map cnstrw inputDataConstraints ++ - [cnstrw probBr, cnstrw probFail, cnstrw stressDistFac] + [cnstrw probBr, cnstrw probFail, cnstrw stressDistFac, cnstrw nomThick] plateLen, plateWidth, aspectRatio, charWeight, standOffDist :: UncertQ pbTol, tNT :: UncertainChunk @@ -74,17 +72,17 @@ inputDataConstraints = map uncrtnw inputsWUnitsUncrtn ++ plateLen = uqcND "plateLen" (nounPhraseSP "plate length (long dimension)") lA metre Real [ gtZeroConstr, - physc $ UpFrom (Inc, sy plateWidth), - sfwrc $ Bounded (Inc , sy dimMin) (Inc , sy dimMax)] (dbl 1.5) defaultUncrt + physRange $ UpFrom (Inc, sy plateWidth), + sfwrRange $ Bounded (Inc , sy dimMin) (Inc , sy dimMax)] (dbl 1.5) defaultUncrt plateWidth = uqcND "plateWidth" (nounPhraseSP "plate width (short dimension)") lB metre Real - [ physc $ Bounded (Exc, exactDbl 0) (Inc, sy plateLen), - sfwrc $ Bounded (Inc, sy dimMin) (Inc, sy dimMax)] (dbl 1.2) defaultUncrt + [ physRange $ Bounded (Exc, exactDbl 0) (Inc, sy plateLen), + sfwrRange $ Bounded (Inc, sy dimMin) (Inc, sy dimMax)] (dbl 1.2) defaultUncrt aspectRatio = uq (constrained' (dqdNoUnit aspectRatioCon (variable "AR") Real) - [ physc $ UpFrom (Inc, exactDbl 1), - sfwrc $ UpTo (Inc, sy arMax)] (dbl 1.5)) defaultUncrt + [ physRange $ UpFrom (Inc, exactDbl 1), + sfwrRange $ UpTo (Inc, sy arMax)] (dbl 1.5)) defaultUncrt pbTol = uvc "pbTol" (nounPhraseSP "tolerable probability of breakage") (sub cP (Concat [lBreak, lTol])) Real @@ -93,7 +91,7 @@ pbTol = uvc "pbTol" (nounPhraseSP "tolerable probability of breakage") charWeight = uqcND "charWeight" (nounPhraseSP "charge weight") lW kilogram Real [ gtZeroConstr, - sfwrc $ Bounded (Inc, sy cWeightMin) (Inc, sy cWeightMax)] + sfwrRange $ Bounded (Inc, sy cWeightMin) (Inc, sy cWeightMax)] (exactDbl 42) defaultUncrt tNT = uvc "tNT" (nounPhraseSP "TNT equivalent factor") @@ -102,13 +100,12 @@ tNT = uvc "tNT" (nounPhraseSP "TNT equivalent factor") standOffDist = uq (constrained' (uc sD (variable "SD") Real metre) [ gtZeroConstr, - sfwrc $ Bounded (Inc, sy sdMin) (Inc, sy sdMax)] (exactDbl 45)) defaultUncrt + sfwrRange $ Bounded (Inc, sy sdMin) (Inc, sy sdMax)] (exactDbl 45)) defaultUncrt nomThick = cuc "nomThick" - (nounPhraseSent $ S "nominal thickness" +:+ displayDblConstrntsAsSet - nomThick nominalThicknesses) + (nounPhraseSent $ S "nominal thickness") lT millimetre {-Discrete nominalThicknesses, but not implemented-} Rational - [{- TODO: add back constraint: enumc nominalThicknesses -}] $ exactDbl 8 + [sfwrElem $ mkSet (map dbl nominalThicknesses)] $ exactDbl 8 -- for testing glassTypeCon = constrainedNRV' (dqdNoUnit glassTy lG String) [{- TODO: add back constraint: EnumeratedStr Software $ map (abrv . snd) glassType -}] @@ -127,7 +124,7 @@ probBr = cvc "probBr" (nounPhraseSP "probability of breakage") [probConstr] (Just $ dbl 0.4) stressDistFac = cvc "stressDistFac" (nounPhraseSP "stress distribution factor (Function)") - cJ Real [physc $ Bounded (Inc, sy stressDistFacMin) (Inc, sy stressDistFacMax)] (Just $ exactDbl 15) + cJ Real [physRange $ Bounded (Inc, sy stressDistFacMin) (Inc, sy stressDistFacMax)] (Just $ exactDbl 15) probFail = cvc "probFail" (nounPhraseSP "probability of failure") (sub cP lFail) Real @@ -420,7 +417,7 @@ actualThicknesses :: [Double] actualThicknesses = map snd glassThickness nominalThicknesses :: [Double] -nominalThicknesses = map fst glassThickness +nominalThicknesses = map fst glassThickness glassTypeFactors :: [Integer] glassTypeFactors = map fst glassType diff --git a/code/drasil-example/pdcontroller/lib/Drasil/PDController/Unitals.hs b/code/drasil-example/pdcontroller/lib/Drasil/PDController/Unitals.hs index d2c5d8ea08..15e85477aa 100644 --- a/code/drasil-example/pdcontroller/lib/Drasil/PDController/Unitals.hs +++ b/code/drasil-example/pdcontroller/lib/Drasil/PDController/Unitals.hs @@ -78,7 +78,7 @@ ipPropGainUnc = uq ipPropGain defaultUncrt qdPropGain = qw ipPropGain ipDerivGain - = constrained' (dqdNoUnit derGain symKd Real) [physc $ UpFrom (Inc, exactDbl 0)] + = constrained' (dqdNoUnit derGain symKd Real) [physRange $ UpFrom (Inc, exactDbl 0)] (exactDbl 1) ipDerGainUnc = uq ipDerivGain defaultUncrt qdDerivGain = qw ipDerivGain @@ -90,14 +90,14 @@ qdSetPointTD = qw ipSetPt --FIXME: the original timeStep is 0.01, this will trigger an error in Java ODE solver --change it from 0.01 to 0.001 is a temporary fix to make ODE solver working ipStepTime = constrained' (uc stepTime symTStep Real second) - [physc $ Bounded (Inc, frac 1 1000) (Exc, sy ipSimTime)] + [physRange $ Bounded (Inc, frac 1 1000) (Exc, sy ipSimTime)] (dbl 0.001) ipStepTimeUnc = uq ipStepTime defaultUncrt qdStepTime = qw ipStepTime ipSimTime = constrained' (uc simulationTime symTSim Real second) - [physc $ Bounded (Inc, exactDbl 1) (Inc, exactDbl 60)] + [physRange $ Bounded (Inc, exactDbl 1) (Inc, exactDbl 60)] (exactDbl 10) ipSimTimeUnc = uq ipSimTime defaultUncrt qdSimTime = qw ipSimTime diff --git a/code/drasil-example/projectile/lib/Drasil/Projectile/Unitals.hs b/code/drasil-example/projectile/lib/Drasil/Projectile/Unitals.hs index 3e7d2ecd7b..a1c17b0550 100644 --- a/code/drasil-example/projectile/lib/Drasil/Projectile/Unitals.hs +++ b/code/drasil-example/projectile/lib/Drasil/Projectile/Unitals.hs @@ -32,9 +32,9 @@ flightDurUnc = uq flightDur defaultUncrt flightDur, landPos, launAngle, launSpeed, offset, targPos :: ConstrConcept flightDur = constrainedNRV' (uc C.flightDur (subStr lT "flight") Real second) [gtZeroConstr] landPos = constrainedNRV' (uc C.landPos (subStr lP "land" ) Real metre ) [gtZeroConstr] -launAngle = constrained' (ucStaged C.launAngle (autoStage lTheta ) Real radian) [physc $ Bounded (Exc, exactDbl 0) (Exc, half $ sy pi_)] (sy pi_ $/ exactDbl 4) +launAngle = constrained' (ucStaged C.launAngle (autoStage lTheta ) Real radian) [physRange $ Bounded (Exc, exactDbl 0) (Exc, half $ sy pi_)] (sy pi_ $/ exactDbl 4) launSpeed = constrained' (uc C.launSpeed (subStr lV "launch") Real velU ) [gtZeroConstr] (exactDbl 100) -offset = constrainedNRV' (uc C.offset (subStr lD "offset") Real metre ) [physc $ UpFrom (Exc, neg $ sy targPos)] +offset = constrainedNRV' (uc C.offset (subStr lD "offset") Real metre ) [physRange $ UpFrom (Exc, neg $ sy targPos)] targPos = constrained' (uc C.targPos (subStr lP "target") Real metre ) [gtZeroConstr] (exactDbl 1000) --- diff --git a/code/drasil-example/ssp/lib/Drasil/SSP/Unitals.hs b/code/drasil-example/ssp/lib/Drasil/SSP/Unitals.hs index c06ab52c82..7cbb776008 100644 --- a/code/drasil-example/ssp/lib/Drasil/SSP/Unitals.hs +++ b/code/drasil-example/ssp/lib/Drasil/SSP/Unitals.hs @@ -84,7 +84,7 @@ outputs = [fs] {- monotonicIn :: [Constraint] --FIXME: Move this? -monotonicIn = [physc $ \_ -> -- FIXME: Hack with "index" ! +monotonicIn = [physRange $ \_ -> -- FIXME: Hack with "index" ! (idx xi (sy index) $< idx xi (sy index + 1) $=> idx yi (sy index) $< idx yi (sy index + 1))] -} @@ -152,7 +152,7 @@ effCohesion = uqc "c'" (cn "effective cohesion") fricAngle = uqc "varphi'" (cn "effective angle of friction") ("the angle of inclination with respect to the horizontal axis of " ++ "the Mohr-Coulomb shear resistance line") --http://www.geotechdata.info - (prime vPhi) degree Real [physc $ Bounded (Exc, exactDbl 0) (Exc, exactDbl 90)] + (prime vPhi) degree Real [physRange $ Bounded (Exc, exactDbl 0) (Exc, exactDbl 90)] (exactDbl 25) defaultUncrt dryWeight = uqc "gamma" (cn "soil dry unit weight") diff --git a/code/drasil-example/swhs/lib/Drasil/SWHS/Unitals.hs b/code/drasil-example/swhs/lib/Drasil/SWHS/Unitals.hs index f520ebcc6b..8201bfe749 100644 --- a/code/drasil-example/swhs/lib/Drasil/SWHS/Unitals.hs +++ b/code/drasil-example/swhs/lib/Drasil/SWHS/Unitals.hs @@ -264,21 +264,21 @@ tempPCM, tempW, watE, pcmE :: ConstrConcept tankLength = uqc "tankLength" (nounPhraseSP "length of tank") "the length of the tank" cL metre Real [gtZeroConstr, - sfwrc $ Bounded (Inc, sy tankLengthMin) (Inc, sy tankLengthMax)] (dbl 1.5) + sfwrRange $ Bounded (Inc, sy tankLengthMin) (Inc, sy tankLengthMax)] (dbl 1.5) defaultUncrt -- Constraint 2 diam = uqc "diam" (nounPhraseSP "diameter of tank") "the diameter of the tank" cD metre Real - [gtZeroConstr, sfwrc $ Bounded (Inc, sy arMin) (Inc, sy arMax)] + [gtZeroConstr, sfwrRange $ Bounded (Inc, sy arMin) (Inc, sy arMax)] (dbl 0.412) defaultUncrt -- Constraint 3 pcmVol = uqc "pcmVol" (nounPhraseSP "volume of PCM") "the amount of space occupied by a given quantity of phase change material" (sub (eqSymb vol) lPCM) m_3 Real - [physc $ Bounded (Exc, exactDbl 0) (Exc, sy tankVol), - sfwrc $ UpFrom (Inc, sy fracMin $* sy tankVol)] + [physRange $ Bounded (Exc, exactDbl 0) (Exc, sy tankVol), + sfwrRange $ UpFrom (Inc, sy fracMin $* sy tankVol)] (dbl 0.05) defaultUncrt -- needs to add (D,L)*minfract to end of last constraint @@ -292,14 +292,14 @@ pcmSA = uqc "pcmSA" "area covered by the outermost layer of the phase change material" (sub cA lPCM) m_2 Real [gtZeroConstr, - sfwrc $ Bounded (Inc, sy pcmVol) (Inc, (exactDbl 2 $/ sy thickness) $* sy tankVol)] + sfwrRange $ Bounded (Inc, sy pcmVol) (Inc, (exactDbl 2 $/ sy thickness) $* sy tankVol)] (dbl 1.2) defaultUncrt -- Constraint 5 pcmDensity = uq (cuc'' "pcmDensity" (nounPhraseSP "density of PCM") "Mass per unit volume of the phase change material" (autoStage $ sub (eqSymb density) lPCM) densityU Real - [gtZeroConstr, sfwrc $ Bounded (Exc, sy pcmDensityMin) (Exc, sy pcmDensityMax)] + [gtZeroConstr, sfwrRange $ Bounded (Exc, sy pcmDensityMin) (Exc, sy pcmDensityMax)] (exactDbl 1007)) defaultUncrt -- Constraint 6 @@ -307,7 +307,7 @@ tempMeltP = uqc "tempMeltP" (nounPhraseSP "melting point temperature for PCM") "temperature at which the phase change material transitions from a solid to a liquid" (sup (sub (eqSymb temp) lMelt) lPCM) centigrade Real - [physc $ Bounded (Exc, exactDbl 0) (Exc, sy tempC)] (dbl 44.2) defaultUncrt + [physRange $ Bounded (Exc, exactDbl 0) (Exc, sy tempC)] (dbl 44.2) defaultUncrt -- Constraint 7 htCapSP = uqc "htCapSP" @@ -316,7 +316,7 @@ htCapSP = uqc "htCapSP" "given unit mass of solid phase change material by a given amount") (sup (sub (eqSymb heatCapSpec) lPCM) lSolid) UT.heatCapSpec Real [gtZeroConstr, - sfwrc $ Bounded (Exc, sy htCapSPMin) (Exc, sy htCapSPMax)] + sfwrRange $ Bounded (Exc, sy htCapSPMin) (Exc, sy htCapSPMax)] (exactDbl 1760) defaultUncrt -- Constraint 8 @@ -326,7 +326,7 @@ htCapLP = uqc "htCapLP" "given unit mass of liquid phase change material by a given amount") (sup (sub (eqSymb heatCapSpec) lPCM) lLiquid) UT.heatCapSpec Real [gtZeroConstr, - sfwrc $ Bounded (Exc, sy htCapLPMin) (Exc, sy htCapLPMax )] + sfwrRange $ Bounded (Exc, sy htCapLPMin) (Exc, sy htCapLPMax )] (exactDbl 2270) defaultUncrt --Constraint 9 @@ -334,7 +334,7 @@ htFusion = uqc "htFusion" (nounPhraseSP "specific latent heat of fusion") "amount of thermal energy required to completely melt a unit mass of a substance" (sub cH lFusion) specificE Real [gtZeroConstr, - sfwrc $ Bounded (Exc, sy htFusionMin) (Exc, sy htFusionMax)] (exactDbl 211600) defaultUncrt + sfwrRange $ Bounded (Exc, sy htFusionMin) (Exc, sy htFusionMax)] (exactDbl 211600) defaultUncrt -- Constraint 10 -- The "S "heating coil" " should be replaced by "phrase coil", @@ -344,18 +344,18 @@ coilSA = uqc "coilSA" (nounPhrase'' (phrase surArea) (phrase surArea) CapFirst CapWords)) "area covered by the outermost layer of the coil" (sub cA lCoil) m_2 Real [gtZeroConstr, - sfwrc $ UpTo (Inc, sy coilSAMax)] (dbl 0.12) defaultUncrt + sfwrRange $ UpTo (Inc, sy coilSAMax)] (dbl 0.12) defaultUncrt -- Constraint 11 tempC = uqc "tempC" (nounPhraseSP "temperature of the heating coil") "the average kinetic energy of the particles within the coil" (sub (eqSymb temp) lCoil) centigrade Real - [physc $ Bounded (Exc, exactDbl 0) (Exc, exactDbl 100)] (exactDbl 50) defaultUncrt + [physRange $ Bounded (Exc, exactDbl 0) (Exc, exactDbl 100)] (exactDbl 50) defaultUncrt -- Constraint 12 wDensity = uq (cuc'' "wDensity" (density `of_` water) "mass per unit volume of water" (autoStage $ sub (eqSymb density) lWater) densityU Real - [gtZeroConstr, sfwrc $ Bounded (Exc, sy wDensityMin) (Inc, sy wDensityMax)] + [gtZeroConstr, sfwrRange $ Bounded (Exc, sy wDensityMin) (Inc, sy wDensityMax)] (exactDbl 1000)) defaultUncrt -- Constraint 13 @@ -364,7 +364,7 @@ htCapW = uqc "htCapW" (heatCapSpec `of_` water) "temperature of a given unit mass of water by a given amount") (sub (eqSymb heatCapSpec) lWater) UT.heatCapSpec Real [gtZeroConstr, - sfwrc $ Bounded (Exc, sy htCapWMin) (Exc, sy htCapWMax)] (exactDbl 4186) defaultUncrt + sfwrRange $ Bounded (Exc, sy htCapWMin) (Exc, sy htCapWMax)] (exactDbl 4186) defaultUncrt -- Constraint 14 coilHTC = uqc "coilHTC" (nounPhraseSP @@ -374,7 +374,7 @@ coilHTC = uqc "coilHTC" (nounPhraseSP (sub (eqSymb htTransCoeff) lCoil) UT.heatTransferCoef Real [gtZeroConstr, - sfwrc $ Bounded (Inc, sy coilHTCMin) (Inc, sy coilHTCMax)] (exactDbl 1000) defaultUncrt + sfwrRange $ Bounded (Inc, sy coilHTCMin) (Inc, sy coilHTCMax)] (exactDbl 1000) defaultUncrt -- Constraint 15 pcmHTC = uqc "pcmHTC" @@ -383,13 +383,13 @@ pcmHTC = uqc "pcmHTC" "the thermal flux from the phase change material to the surrounding water") (sub lH lPCM) UT.heatTransferCoef Real [gtZeroConstr, - sfwrc $ Bounded (Inc, sy pcmHTCMin) (Inc, sy pcmHTCMax)] (exactDbl 1000) defaultUncrt + sfwrRange $ Bounded (Inc, sy pcmHTCMin) (Inc, sy pcmHTCMax)] (exactDbl 1000) defaultUncrt -- Constraint 16 tempInit = uqc "tempInit" (nounPhraseSP "initial temperature") "the temperature at the beginning of the simulation" (sub (eqSymb temp) lInit) centigrade Real - [physc $ Bounded (Exc, exactDbl 0) (Exc, sy meltPt)] (exactDbl 40) defaultUncrt + [physRange $ Bounded (Exc, exactDbl 0) (Exc, sy meltPt)] (exactDbl 40) defaultUncrt -- Constraint 17 timeFinal = uqc "timeFinal" (nounPhraseSP "final time") @@ -397,13 +397,13 @@ timeFinal = uqc "timeFinal" (nounPhraseSP "final time") "simulation to its conclusion") (sub (eqSymb time) lFinal) second Real [gtZeroConstr, - sfwrc $ UpTo (Exc, sy timeFinalMax)] (exactDbl 50000) defaultUncrt + sfwrRange $ UpTo (Exc, sy timeFinalMax)] (exactDbl 50000) defaultUncrt timeStep = uqc "timeStep" (nounPhraseSP "time step for simulation") ("the finite discretization of time used in the numerical method " ++ "for solving the computational model") (sub (eqSymb time) lStep) second Real - [physc $ Bounded (Exc, exactDbl 0) (Exc, sy timeFinal)] + [physRange $ Bounded (Exc, exactDbl 0) (Exc, sy timeFinal)] (dbl 0.01) defaultUncrt -- Output Constraints @@ -416,26 +416,26 @@ tempW = cuc' "tempW" (nounPhraseSP "temperature of the water") "the average kinetic energy of the particles within the water" (sub (eqSymb temp) lWater) centigrade (Vect Real) - [physc $ Bounded (Inc, sy tempInit) (Inc, sy tempC)] (exactDbl 0) + [physRange $ Bounded (Inc, sy tempInit) (Inc, sy tempC)] (exactDbl 0) -- Constraint 19 tempPCM = cuc' "tempPCM" (nounPhraseSP "temperature of the phase change material") "the average kinetic energy of the particles within the phase change material" (sub (eqSymb temp) lPCM) centigrade Real - [physc $ Bounded (Inc, sy tempInit) (Inc, sy tempC)] (exactDbl 0) + [physRange $ Bounded (Inc, sy tempInit) (Inc, sy tempC)] (exactDbl 0) -- Constraint 20 watE = cuc' "watE" (nounPhraseSP "change in heat energy in the water") "change in thermal energy within the water" (sub (eqSymb sensHeat) lWater) joule Real - [physc $ UpFrom (Inc, exactDbl 0)] (exactDbl 0) + [physRange $ UpFrom (Inc, exactDbl 0)] (exactDbl 0) -- Constraint 21 pcmE = cuc' "pcmE" (nounPhraseSP "change in heat energy in the PCM") "change in thermal energy within the phase change material" (sub (eqSymb sensHeat) lPCM) joule Real - [physc $ UpFrom (Inc, exactDbl 0)] (exactDbl 0) + [physRange $ UpFrom (Inc, exactDbl 0)] (exactDbl 0) --------------------------------- -- Uncertainties with no Units -- @@ -445,12 +445,12 @@ absTol, relTol :: UncertainChunk absTol = uvc "absTol" (nounPhraseSP "absolute tolerance") (sub cA lTol) Real - [physc $ Bounded (Exc, exactDbl 0) (Exc, exactDbl 1)] + [physRange $ Bounded (Exc, exactDbl 0) (Exc, exactDbl 1)] (dbl (10.0**(-10))) (uncty 0.01 Nothing) relTol = uvc "relTol" (nounPhraseSP "relative tolerance") (sub cR lTol) Real - [physc $ Bounded (Exc, exactDbl 0) (Exc, exactDbl 1)] + [physRange $ Bounded (Exc, exactDbl 0) (Exc, exactDbl 1)] (dbl (10.0**(-10))) (uncty 0.01 Nothing) ------------------------- diff --git a/code/drasil-example/swhsnopcm/lib/Drasil/SWHSNoPCM/Unitals.hs b/code/drasil-example/swhsnopcm/lib/Drasil/SWHSNoPCM/Unitals.hs index 9730a54e93..eb0ec54b62 100644 --- a/code/drasil-example/swhsnopcm/lib/Drasil/SWHSNoPCM/Unitals.hs +++ b/code/drasil-example/swhsnopcm/lib/Drasil/SWHSNoPCM/Unitals.hs @@ -25,7 +25,7 @@ tempInit :: UncertQ tempInit = uqc "tempInit" (nounPhraseSP "initial temperature") "the temperature at the beginning of the simulation" (sub (eqSymb temp) lInit) centigrade Real - [physc $ Bounded (Exc, exactDbl 0) (Exc, exactDbl 100)] (exactDbl 40) defaultUncrt + [physRange $ Bounded (Exc, exactDbl 0) (Exc, exactDbl 100)] (exactDbl 40) defaultUncrt specParamValList :: [ConstQDef] specParamValList = [tankLengthMin, tankLengthMax, diff --git a/code/drasil-gool/lib/GOOL/Drasil.hs b/code/drasil-gool/lib/GOOL/Drasil.hs index 023375fdf0..8e2ed4183b 100644 --- a/code/drasil-gool/lib/GOOL/Drasil.hs +++ b/code/drasil-gool/lib/GOOL/Drasil.hs @@ -17,7 +17,7 @@ module GOOL.Drasil (Label, GSProgram, SFile, MSBody, MSBlock, VSType, OOValueExpression(..), funcApp, funcAppNamedArgs, selfFuncApp, extFuncApp, libFuncApp, newObj, extNewObj, libNewObj, exists, objMethodCall, objMethodCallNamedArgs, objMethodCallMixedArgs, objMethodCallNoParams, - FunctionSym(..), ($.), selfAccess, GetSet(..), List(..), listSlice, + FunctionSym(..), ($.), selfAccess, GetSet(..), List(..), Set(..), listSlice, listIndexExists, at, ObserverPattern(..), StrategyPattern(..), ScopeSym(..), ParameterSym(..), MethodSym(..), OOMethodSym(..), privMethod, pubMethod, initializer, nonInitConstructor, StateVarSym(..), privDVar, pubDVar, pubSVar, @@ -39,7 +39,7 @@ import GOOL.Drasil.InterfaceCommon (Label, MSBody, MSBlock, VSType, SVariable, listOf, listVar, ValueSym(..), Argument(..), Literal(..), MathConstant(..), VariableValue(..), CommandLineArgs(..), NumericExpression(..), BooleanExpression(..), Comparison(..), ValueExpression(..), funcApp, - funcAppNamedArgs, extFuncApp, libFuncApp, exists, List(..), listSlice, + funcAppNamedArgs, extFuncApp, libFuncApp, exists, List(..), Set(..), listSlice, listIndexExists, at, ScopeSym(..), ParameterSym(..), MethodSym(..), convType) import GOOL.Drasil.InterfaceGOOL (GSProgram, SFile, FSModule, SClass, CSStateVar, VSFunction, OOProg, ProgramSym(..), FileSym(..), ModuleSym(..), diff --git a/code/drasil-gool/lib/GOOL/Drasil/CodeInfo.hs b/code/drasil-gool/lib/GOOL/Drasil/CodeInfo.hs index 65f7864c70..876a477073 100644 --- a/code/drasil-gool/lib/GOOL/Drasil/CodeInfo.hs +++ b/code/drasil-gool/lib/GOOL/Drasil/CodeInfo.hs @@ -8,7 +8,7 @@ import GOOL.Drasil.InterfaceCommon (MSBody, VSType, SValue, MSStatement, VariableSym(..), VariableElim(..), ValueSym(..), Argument(..), Literal(..), MathConstant(..), VariableValue(..), CommandLineArgs(..), NumericExpression(..), BooleanExpression(..), Comparison(..), - ValueExpression(..), List(..), InternalList(..), ThunkSym(..), VectorType(..), + ValueExpression(..), List(..), Set(..), InternalList(..), ThunkSym(..), VectorType(..), VectorDecl(..), VectorThunk(..), VectorExpression(..), ThunkAssign(..), StatementSym(..), AssignStatement(..), DeclStatement(..), IOStatement(..), StringStatement(..), FuncAppStatement(..), CommentStatement(..), @@ -142,6 +142,7 @@ instance Literal CodeInfo where litString _ = noInfo litArray _ = executeList litList _ = executeList + litSet _ = executeList instance MathConstant CodeInfo where pi = noInfo @@ -186,6 +187,7 @@ instance BooleanExpression CodeInfo where (?!) = execute1 (?&&) = execute2 (?||) = execute2 + isin = execute2 instance Comparison CodeInfo where (?<) = execute2 @@ -241,7 +243,10 @@ instance List CodeInfo where listAccess = execute2 listSet = execute3 indexOf = execute2 - + +instance Set CodeInfo where + contains = execute2 + instance InternalList CodeInfo where listSlice' b e s _ vl = zoom lensMStoVS $ do mapM_ (fromMaybe noInfo) [b,e,s] diff --git a/code/drasil-gool/lib/GOOL/Drasil/CodeType.hs b/code/drasil-gool/lib/GOOL/Drasil/CodeType.hs index 72f27d1c9a..14f0ec430b 100644 --- a/code/drasil-gool/lib/GOOL/Drasil/CodeType.hs +++ b/code/drasil-gool/lib/GOOL/Drasil/CodeType.hs @@ -15,6 +15,7 @@ data CodeType = Boolean | InFile | OutFile | List CodeType + | Set CodeType | Array CodeType | Object ClassName | Func [CodeType] CodeType diff --git a/code/drasil-gool/lib/GOOL/Drasil/Helpers.hs b/code/drasil-gool/lib/GOOL/Drasil/Helpers.hs index 4522f44d51..42be20d00f 100644 --- a/code/drasil-gool/lib/GOOL/Drasil/Helpers.hs +++ b/code/drasil-gool/lib/GOOL/Drasil/Helpers.hs @@ -89,6 +89,7 @@ on2StateWrapped f a' b' = do getInnerType :: C.CodeType -> C.CodeType getInnerType (C.List innerT) = innerT getInnerType (C.Array innerT) = innerT +getInnerType (C.Set innerT) = innerT getInnerType _ = error "Attempt to extract inner type of list from a non-list type" getNestDegree :: Integer -> C.CodeType -> Integer diff --git a/code/drasil-gool/lib/GOOL/Drasil/InterfaceCommon.hs b/code/drasil-gool/lib/GOOL/Drasil/InterfaceCommon.hs index e432983d3d..33feff7f25 100644 --- a/code/drasil-gool/lib/GOOL/Drasil/InterfaceCommon.hs +++ b/code/drasil-gool/lib/GOOL/Drasil/InterfaceCommon.hs @@ -11,7 +11,7 @@ module GOOL.Drasil.InterfaceCommon ( ValueSym(..), Argument(..), Literal(..), litZero, MathConstant(..), VariableValue(..), CommandLineArgs(..), NumericExpression(..), BooleanExpression(..), Comparison(..), ValueExpression(..), funcApp, - funcAppNamedArgs, extFuncApp, libFuncApp, exists, List(..), InternalList(..), + funcAppNamedArgs, extFuncApp, libFuncApp, exists, List(..), Set(..), InternalList(..), listSlice, listIndexExists, at, ThunkSym(..), VectorType(..), VectorDecl(..), VectorThunk(..), VectorExpression(..), ThunkAssign(..), StatementSym(..), AssignStatement(..), (&=), assignToListIndex, DeclStatement(..), @@ -40,7 +40,7 @@ class (VectorType r, VectorDecl r, VectorThunk r, IOStatement r, StringStatement r, FuncAppStatement r, CommentStatement r, ControlStatement r, InternalList r, Argument r, Literal r, MathConstant r, VariableValue r, CommandLineArgs r, NumericExpression r, BooleanExpression r, - Comparison r, ValueExpression r, List r, TypeElim r, VariableElim r + Comparison r, ValueExpression r, List r, Set r, TypeElim r, VariableElim r ) => SharedProg r -- Shared between OO and Procedural -- @@ -79,6 +79,7 @@ class TypeSym r where infile :: VSType r outfile :: VSType r listType :: VSType r -> VSType r + setType :: VSType r -> VSType r arrayType :: VSType r -> VSType r listInnerType :: VSType r -> VSType r funcType :: [VSType r] -> VSType r -> VSType r @@ -126,6 +127,7 @@ class (ValueSym r) => Literal r where litString :: String -> SValue r litArray :: VSType r -> [SValue r] -> SValue r litList :: VSType r -> [SValue r] -> SValue r + litSet :: VSType r -> [SValue r] -> SValue r litZero :: (TypeElim r, Literal r) => VSType r -> SValue r litZero t = do @@ -189,6 +191,7 @@ class (ValueSym r) => BooleanExpression r where infixl 2 ?&& (?||) :: SValue r -> SValue r -> SValue r infixl 1 ?|| + isin :: SValue r -> SValue r -> SValue r class (ValueSym r) => Comparison r where (?<) :: SValue r -> SValue r -> SValue r @@ -270,6 +273,9 @@ class (ValueSym r) => List r where -- Arguments are: List, Value indexOf :: SValue r -> SValue r -> SValue r +class (ValueSym r) => Set r where + contains :: SValue r -> SValue r -> SValue r + class (ValueSym r) => InternalList r where listSlice' :: Maybe (SValue r) -> Maybe (SValue r) -> Maybe (SValue r) -> SVariable r -> SValue r -> MSBlock r @@ -481,6 +487,7 @@ convType Double = double convType Char = char convType String = string convType (List t) = listType (convType t) +convType (Set t) = setType (convType t) convType (Array t) = arrayType (convType t) convType (Func ps r) = funcType (map convType ps) (convType r) convType Void = void diff --git a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CLike.hs b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CLike.hs index c61857c804..6d5bb92cf0 100644 --- a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CLike.hs +++ b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CLike.hs @@ -2,7 +2,7 @@ -- | Implementations for C-like renderers are defined here. module GOOL.Drasil.LanguageRenderer.CLike (charRender, float, double, char, - listType, void, notOp, andOp, orOp, self, litTrue, litFalse, litFloat, + listType, setType, void, notOp, andOp, orOp, inOp, self, litTrue, litFalse, litFloat, inlineIf, libFuncAppMixedArgs, libNewObjMixedArgs, listSize, increment1, decrement1, varDec, varDecDef, listDec, extObjDecNew, switch, for, while, intFunc, multiAssignError, multiReturnError, multiTypeError @@ -34,7 +34,7 @@ import GOOL.Drasil.LanguageRenderer (forLabel, whileLabel, containing) import qualified GOOL.Drasil.LanguageRenderer as R (switch, increment, decrement, this', this) import GOOL.Drasil.LanguageRenderer.Constructors (mkStmt, mkStmtNoEnd, - mkStateVal, mkStateVar, VSOp, unOpPrec, andPrec, orPrec) + mkStateVal, mkStateVar, VSOp, unOpPrec, andPrec, orPrec, inPrec) import GOOL.Drasil.State (lensMStoVS, lensVStoMS, addLibImportVS, getClassName, useVarName) @@ -69,6 +69,12 @@ listType lst t' = do typeFromData (List (getType t)) (lst `containing` getTypeString t) $ text lst <> angles (RC.type' t) +setType :: (RenderSym r) => String -> VSType r -> VSType r +setType lst t' = do + t <- t' + typeFromData (Set (getType t)) (lst + `containing` getTypeString t) $ text lst <> angles (RC.type' t) + void :: (RenderSym r) => VSType r void = typeFromData Void voidRender (text voidRender) @@ -84,7 +90,8 @@ andOp = andPrec "&&" orOp :: (Monad r) => VSOp r orOp = orPrec "||" - +inOp :: (Monad r) => VSOp r +inOp = inPrec "" -- Variables -- self :: (RenderSym r) => SVariable r @@ -165,7 +172,12 @@ listDec f vl v = do sz <- zoom lensMStoVS vl vd <- IC.varDec v mkStmt (RC.statement vd <> f sz) - +setDec :: (RenderSym r) => (r (Value r) -> Doc) -> SValue r -> SVariable r -> MSStatement r +setDec f vl v = do + sz <- zoom lensMStoVS vl + vd <- IC.varDec v + mkStmt (RC.statement vd <> f sz) + extObjDecNew :: (RenderSym r) => Library -> SVariable r -> [SValue r] -> MSStatement r extObjDecNew l v vs = IC.varDecDef v (extNewObj l (onStateValue variableType v) diff --git a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CSharpRenderer.hs b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CSharpRenderer.hs index 9350d0fa23..0fb31952a8 100644 --- a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CSharpRenderer.hs +++ b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CSharpRenderer.hs @@ -16,7 +16,7 @@ import GOOL.Drasil.InterfaceCommon (SharedProg, Label, MSBody, VSType, ValueSym(..), Argument(..), Literal(..), litZero, MathConstant(..), VariableValue(..), CommandLineArgs(..), NumericExpression(..), BooleanExpression(..), Comparison(..), ValueExpression(..), funcApp, - extFuncApp, List(..), InternalList(..), ThunkSym(..), VectorType(..), + extFuncApp, List(..), Set(..), InternalList(..), ThunkSym(..), VectorType(..), VectorDecl(..), VectorThunk(..), VectorExpression(..), ThunkAssign(..), StatementSym(..), AssignStatement(..), (&=), DeclStatement(..), IOStatement(..), StringStatement(..), FuncAppStatement(..), @@ -68,14 +68,14 @@ import qualified GOOL.Drasil.LanguageRenderer.LanguagePolymorphic as G ( modFromData, fileDoc, fileFromData, defaultOptSpace) import qualified GOOL.Drasil.LanguageRenderer.CommonPseudoOO as CP (int, constructor, doxFunc, doxClass, doxMod, extVar, classVar, objVarSelf, - extFuncAppMixedArgs, indexOf, listAddFunc, discardFileLine, intClass, - arrayType, pi, printSt, arrayDec, arrayDecDef, openFileA, forEach, docMain, + extFuncAppMixedArgs, indexOf, contains, listAddFunc, discardFileLine, intClass, + arrayType, pi, printSt, arrayDec, arrayDecDef, setDec, setDecDef, openFileA, forEach, docMain, mainFunction, buildModule', string, constDecDef, docInOutFunc, bindingError, notNull, listDecDef, destructorError, stateVarDef, constVar, listSetFunc, extraClass, listAccessFunc, doubleRender, openFileR, openFileW, stateVar, inherit, implements, intToIndex, indexToInt) import qualified GOOL.Drasil.LanguageRenderer.CLike as C (float, double, char, - listType, void, notOp, andOp, orOp, self, litTrue, litFalse, litFloat, + listType, setType, void, notOp, andOp, orOp, inOp, self, litTrue, litFalse, litFloat, inlineIf, libFuncAppMixedArgs, libNewObjMixedArgs, listSize, increment1, decrement1, varDec, varDecDef, listDec, extObjDecNew, switch, for, while, intFunc, multiAssignError, multiReturnError, multiTypeError) @@ -201,6 +201,9 @@ instance TypeSym CSharpCode where modify (addLangImportVS csGeneric) C.listType csList t arrayType = CP.arrayType + setType t = do + modify (addLangImportVS csGeneric) + C.setType csSet t listInnerType = G.listInnerType funcType = csFuncType void = C.void @@ -253,6 +256,7 @@ instance BinaryOpSym CSharpCode where moduloOp = G.moduloOp andOp = C.andOp orOp = C.orOp + inOp = C.inOp instance OpElim CSharpCode where uOp = opDoc . unCSC @@ -306,6 +310,7 @@ instance Literal CSharpCode where litInt = G.litInt litString = G.litString litArray = csLitList arrayType + litSet = csLitList setType litList = csLitList listType instance MathConstant CSharpCode where @@ -351,6 +356,7 @@ instance BooleanExpression CSharpCode where (?!) = typeUnExpr notOp bool (?&&) = typeBinExpr andOp bool (?||) = typeBinExpr orOp bool + isin = typeBinExpr inOp bool instance Comparison CSharpCode where (?<) = typeBinExpr lessOp bool @@ -422,7 +428,10 @@ instance List CSharpCode where listAccess = G.listAccess listSet = G.listSet indexOf = CP.indexOf csIndex - + +instance Set CSharpCode where + contains = CP.contains csContains + instance InternalList CSharpCode where listSlice' = M.listSlice @@ -740,15 +749,16 @@ csForEach = text "foreach" csNamedArgSep = colon <> space csLambdaSep = text "=>" -csSystem, csConsole, csGeneric, csIO, csList, csInt, csFloat, csBool, +csSystem, csConsole, csGeneric, csIO, csList, csSet, csInt, csFloat, csBool, csChar, csParse, csReader, csWriter, csReadLine, csWrite, csWriteLine, - csIndex, csListAdd, csListAppend, csClose, csEOS, csSplit, csMain, + csIndex, csContains, csListAdd, csListAppend, csClose, csEOS, csSplit, csMain, csFunc :: String csSystem = "System" csConsole = "Console" csGeneric = csSysAccess $ "Collections" `access` "Generic" csIO = csSysAccess "IO" csList = "List" +csSet = "HashSet" csInt = "Int32" csFloat = "Single" csBool = "Boolean" @@ -760,6 +770,7 @@ csReadLine = "ReadLine" csWrite = "Write" csWriteLine = "WriteLine" csIndex = "IndexOf" +csContains = "Contains" csListAdd = "Insert" csListAppend = "Add" csClose = "Close" diff --git a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CommonPseudoOO.hs b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CommonPseudoOO.hs index f368812c64..03f2dab1ed 100644 --- a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CommonPseudoOO.hs +++ b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CommonPseudoOO.hs @@ -1,15 +1,15 @@ -- | Implementations defined here are valid in some, but not all, language renderers module GOOL.Drasil.LanguageRenderer.CommonPseudoOO (int, constructor, doxFunc, - doxClass, doxMod, docMod', extVar, classVar, objVarSelf, indexOf, listAddFunc, + doxClass, doxMod, docMod', extVar, classVar, objVarSelf, indexOf, contains, containsInt, listAddFunc, discardFileLine, intClass, funcType, buildModule, arrayType, pi, printSt, arrayDec, arrayDecDef, openFileA, forEach, docMain, mainFunction, - buildModule', call', listSizeFunc, listAccessFunc', string, constDecDef, - docInOutFunc, bindingError, extFuncAppMixedArgs, notNull, listDecDef, - destructorError, stateVarDef, constVar, litArray, listSetFunc, extraClass, + buildModule', call', listSizeFunc, setAddFunc, listAccessFunc', string, constDecDef, + docInOutFunc, bindingError, extFuncAppMixedArgs, notNull, listDecDef, setDecDef, + destructorError, stateVarDef, constVar, litArray, litSet, listSetFunc, litSetFunc, extraClass, listAccessFunc, doubleRender, double, openFileR, openFileW, stateVar, self, - multiAssign, multiReturn, listDec, funcDecDef, inOutCall, forLoopError, + multiAssign, multiReturn, listDec, setDec, funcDecDef, inOutCall, forLoopError, mainBody, inOutFunc, docInOutFunc', boolRender, bool, floatRender, float, stringRender', - string', inherit, implements, listSize, listAdd, listAppend, intToIndex, + string', inherit, implements, listSize, setSize, listAdd, listAppend, intToIndex, indexToInt, intToIndex', indexToInt' ) where @@ -24,8 +24,8 @@ import GOOL.Drasil.InterfaceCommon (Label, Library, MSBody, VSType, SVariable, (&=), ControlStatement(returnStmt), ScopeSym(..), MethodSym(function), NumericExpression((#+), (#-))) import qualified GOOL.Drasil.InterfaceCommon as IC ( - TypeSym(int, double, string, listType, arrayType, void), VariableSym(var), - Literal(litTrue, litFalse, litList, litInt), VariableValue(valueOf), + TypeSym(int, bool, double, string, listType, arrayType, void), VariableSym(var), + Literal(litTrue, litFalse, litList, litSet, litInt), VariableValue(valueOf), StatementSym(valStmt), DeclStatement(varDec, varDecDef, constDecDef), List(intToIndex, indexToInt), ParameterSym(param, pointerParam), MethodSym(mainFunction)) @@ -131,10 +131,20 @@ objVarSelf = IG.objVar IG.self indexOf :: (RenderSym r) => Label -> SValue r -> SValue r -> SValue r indexOf f l v = IC.indexToInt $ IG.objAccess l (IG.func f IC.int [v]) +contains :: (RenderSym r) => Label -> SValue r -> SValue r -> SValue r +contains f s v = IG.objAccess s (IG.func f IC.bool [v]) + +containsInt :: (RenderSym r) => Label -> Label -> SValue r -> SValue r -> SValue r +containsInt f fn s v = contains f s v ?!= IG.objAccess s (IG.func fn IC.bool []) + listAddFunc :: (RenderSym r) => Label -> SValue r -> SValue r -> VSFunction r listAddFunc f i v = IG.func f (IC.listType $ onStateValue valueType v) [i, v] - + +setAddFunc :: (RenderSym r) => Label -> SValue r -> SValue r -> VSFunction r +setAddFunc f i v = IG.func f (IC.listType $ onStateValue valueType v) + [i, v] + discardFileLine :: (RenderSym r) => Label -> SValue r -> MSStatement r discardFileLine n f = IC.valStmt $ objMethodCallNoParams IC.string f n @@ -313,6 +323,12 @@ listDecDef v vals = do let lst = IC.litList (listInnerType $ return $ variableType vr) vals IC.varDecDef (return vr) lst +setDecDef :: (RenderSym r) => SVariable r -> [SValue r] -> MSStatement r +setDecDef v vals = do + vr <- zoom lensMStoVS v + let st = IC.litSet (listInnerType $ return $ variableType vr) vals + IC.varDecDef (return vr) st + destructorError :: String -> String destructorError l = "Destructors not allowed in " ++ l @@ -332,6 +348,14 @@ litArray :: (RenderSym r) => (Doc -> Doc) -> VSType r -> [SValue r] -> SValue r litArray f t es = sequence es >>= (\elems -> mkStateVal (IC.arrayType t) (f $ valueList elems)) +litSet :: (RenderSym r) => (Doc -> Doc) -> VSType r -> [SValue r] -> SValue r +litSet f t es = sequence es >>= (\elems -> mkStateVal (IC.arrayType t) + (f $ valueList elems)) + +litSetFunc :: (RenderSym r) => String -> VSType r -> [SValue r] -> SValue r +litSetFunc s t es = sequence es >>= (\elems -> mkStateVal (IC.arrayType t) + (text s <> parens (valueList elems))) + -- Python, C#, C++, and Swift-- extraClass :: (RenderSym r) => Label -> Maybe Label -> [CSStateVar r] -> @@ -349,6 +373,7 @@ listSetFunc f v idx setVal = join $ on2StateValues (\i toVal -> funcFromData (f (RC.value i) (RC.value toVal)) (onStateValue valueType v)) (intValue idx) setVal + -- Java, C#, and Swift -- doubleRender :: String @@ -401,6 +426,9 @@ multiReturn f vs = do listDec :: (RenderSym r) => SVariable r -> MSStatement r listDec v = IC.varDecDef v $ IC.litList (onStateValue variableType v) [] +setDec :: (RenderSym r) => SVariable r -> MSStatement r +setDec v = IC.varDecDef v $ IC.litSet (onStateValue variableType v) [] + funcDecDef :: (RenderSym r) => SVariable r -> [SVariable r] -> MSBody r -> MSStatement r funcDecDef v ps b = do @@ -509,6 +537,12 @@ listSize l = do f <- S.listSizeFunc l mkVal (RC.functionType f) (RC.function f) +setSize :: (RenderSym r) => SValue r -> SValue r +setSize l = do + f <- S.listSizeFunc l + mkVal (RC.functionType f) (RC.function f) + + -- Julia and MATLAB -- -- | Call to insert a value into a list in a language where this is not a method. listAdd :: (RenderSym r) => SValue r -> SValue r -> SValue r -> SValue r diff --git a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/Constructors.hs b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/Constructors.hs index 8b64b07e74..85649331c5 100644 --- a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/Constructors.hs +++ b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/Constructors.hs @@ -2,7 +2,7 @@ module GOOL.Drasil.LanguageRenderer.Constructors ( mkStmt, mkStmtNoEnd, mkStateVal, mkVal, mkStateVar, mkVar, mkStaticVar, VSOp, mkOp, unOpPrec, compEqualPrec, compPrec, addPrec, multPrec, powerPrec, - andPrec, orPrec, unExpr, unExpr', unExprNumDbl, typeUnExpr, binExpr, + andPrec, orPrec, inPrec, unExpr, unExpr', unExprNumDbl, typeUnExpr, binExpr, binExpr', binExprNumDbl', typeBinExpr ) where @@ -96,6 +96,9 @@ andPrec = mkOp 3 . text orPrec :: (Monad r) => String -> VSOp r orPrec = mkOp 2 . text +inPrec :: (Monad r) => String -> VSOp r +inPrec = mkOp 2 . text + -- Expressions -- -- | Constructs a unary expression like ln(v), for some operator ln and value v diff --git a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CppRenderer.hs b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CppRenderer.hs index 50fb66b696..368e5ddb2e 100644 --- a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CppRenderer.hs +++ b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/CppRenderer.hs @@ -17,7 +17,7 @@ import GOOL.Drasil.InterfaceCommon (SharedProg, Label, MSBody, VSType, VariableSym(..), VariableElim(..), ValueSym(..), Argument(..), Literal(..), litZero, MathConstant(..), VariableValue(..), CommandLineArgs(..), NumericExpression(..), BooleanExpression(..), Comparison(..), - ValueExpression(..), funcApp, extFuncApp, List(..), InternalList(..), + ValueExpression(..), funcApp, extFuncApp, List(..), Set(..), InternalList(..), ThunkSym(..), VectorType(..), VectorDecl(..), VectorThunk(..), VectorExpression(..), ThunkAssign(..), StatementSym(..), AssignStatement(..), DeclStatement(..), IOStatement(..), StringStatement(..), FuncAppStatement(..), @@ -45,7 +45,7 @@ import GOOL.Drasil.RendererClasses (RenderSym, RenderFile(..), ImportSym(..), import qualified GOOL.Drasil.RendererClasses as RC (import', perm, body, block, type', uOp, bOp, variable, value, function, statement, scope, parameter, method, stateVar, class', module', blockComment') -import GOOL.Drasil.LanguageRenderer (addExt, classDec, dot, blockCmtStart, +import GOOL.Drasil.LanguageRenderer (inLabel, addExt, classDec, dot, blockCmtStart, blockCmtEnd, docCmtStart, bodyStart, bodyEnd, endStatement, commentStart, returnLabel, elseIfLabel, tryLabel, catchLabel, throwLabel, array', constDec', listSep', argc, argv, constDec, mainFunc, containing, functionDox, valueList, @@ -72,13 +72,13 @@ import qualified GOOL.Drasil.LanguageRenderer.LanguagePolymorphic as G ( fileFromData, defaultOptSpace) import GOOL.Drasil.LanguageRenderer.LanguagePolymorphic (classVarCheckStatic) import qualified GOOL.Drasil.LanguageRenderer.CommonPseudoOO as CP (int, - constructor, doxFunc, doxClass, doxMod, funcType, buildModule, litArray, - call', listSizeFunc, listAccessFunc', string, constDecDef, docInOutFunc, + constructor, doxFunc, doxClass, doxMod, funcType, buildModule, litArray, litSet, + call', listSizeFunc, listAccessFunc', contains, forEach, containsInt, string, constDecDef, docInOutFunc, listSetFunc, extraClass, intToIndex, indexToInt) import qualified GOOL.Drasil.LanguageRenderer.CLike as C (charRender, float, - double, char, listType, void, notOp, andOp, orOp, self, litTrue, litFalse, + double, char, listType, void, notOp, andOp, orOp, inOp, self, litTrue, litFalse, litFloat, inlineIf, libFuncAppMixedArgs, libNewObjMixedArgs, listSize, - increment1, decrement1, varDec, varDecDef, listDec, extObjDecNew, switch, + increment1, decrement1, varDec, setType, varDecDef, listDec, extObjDecNew, switch, for, while, intFunc, multiAssignError, multiReturnError, multiTypeError) import qualified GOOL.Drasil.LanguageRenderer.Macros as M (runStrategy, listSlice, stringListVals, stringListLists, forRange, notifyObservers) @@ -211,6 +211,7 @@ instance (Pair p) => TypeSym (p CppSrcCode CppHdrCode) where infile = on2StateValues pair infile infile outfile = on2StateValues pair outfile outfile listType = pair1 listType listType + setType = pair1 setType setType arrayType = pair1 arrayType arrayType listInnerType = pair1 listInnerType listInnerType funcType = pair1List1Val funcType funcType @@ -264,6 +265,7 @@ instance (Pair p) => BinaryOpSym (p CppSrcCode CppHdrCode) where moduloOp = on2StateValues pair moduloOp moduloOp andOp = on2StateValues pair andOp andOp orOp = on2StateValues pair orOp orOp + inOp = on2StateValues pair inOp inOp instance (Pair p) => OpElim (p CppSrcCode CppHdrCode) where uOp o = RC.uOp $ pfst o @@ -316,6 +318,7 @@ instance (Pair p) => Literal (p CppSrcCode CppHdrCode) where litInt v =on2StateValues pair (litInt v) (litInt v) litString s = on2StateValues pair (litString s) (litString s) litArray = pair1Val1List litArray litArray + litSet = pair1Val1List litSet litSet litList = pair1Val1List litList litList instance (Pair p) => MathConstant (p CppSrcCode CppHdrCode) where @@ -361,6 +364,7 @@ instance (Pair p) => BooleanExpression (p CppSrcCode CppHdrCode) where (?!) = pair1 (?!) (?!) (?&&) = pair2 (?&&) (?&&) (?||) = pair2 (?||) (?||) + isin = pair2 isin isin instance (Pair p) => Comparison (p CppSrcCode CppHdrCode) where (?<) = pair2 (?<) (?<) @@ -440,6 +444,9 @@ instance (Pair p) => List (p CppSrcCode CppHdrCode) where listSet = pair3 listSet listSet indexOf = pair2 indexOf indexOf +instance (Pair p) => Set (p CppSrcCode CppHdrCode) where + contains = pair2 contains contains + instance (Pair p) => InternalList (p CppSrcCode CppHdrCode) where listSlice' b e s vr vl = pair2 (listSlice' (fmap (onStateValue pfst) b) (fmap (onStateValue pfst) e) @@ -1091,6 +1098,9 @@ instance TypeSym CppSrcCode where listType t = do modify (addUsing vector . addLangImportVS vector) C.listType vector t + setType t = do + modify (addUsing cppSet . addLangImportVS cppSet) + C.setType cppSet t arrayType = cppArrayType listInnerType = G.listInnerType funcType = CP.funcType @@ -1148,6 +1158,7 @@ instance BinaryOpSym CppSrcCode where moduloOp = G.moduloOp andOp = C.andOp orOp = C.orOp + inOp = C.inOp instance OpElim CppSrcCode where uOp = opDoc . unCPPSC @@ -1214,6 +1225,7 @@ instance Literal CppSrcCode where litInt = G.litInt litString = G.litString litArray = CP.litArray braces + litSet = cppLitSet setType litList _ _ = error $ "List literals not supported in " ++ cppName instance MathConstant CppSrcCode where @@ -1268,6 +1280,7 @@ instance BooleanExpression CppSrcCode where (?!) = typeUnExpr notOp bool (?&&) = typeBinExpr andOp bool (?||) = typeBinExpr orOp bool + isin = typeBinExpr inOp bool instance Comparison CppSrcCode where (?<) = typeBinExpr lessOp bool @@ -1340,6 +1353,10 @@ instance List CppSrcCode where listSet = G.listSet indexOf l v = addAlgorithmImportVS $ cppIndexFunc l v #- iterBegin l +instance Set CppSrcCode where + contains = CP.containsInt cppIndex cppIterEnd + + instance InternalList CppSrcCode where listSlice' = M.listSlice @@ -1531,13 +1548,7 @@ instance ControlStatement CppSrcCode where for = C.for bodyStart bodyEnd forRange = M.forRange - forEach i v b = do - e <- zoom lensMStoVS i - let l = variableName e - t = toState $ variableType e - iterI = var l (iterator t) - for (varDecDef iterI (iterBegin v)) (setIterVar iterI ?!= iterEnd v) - (iterI &++) b + forEach = CP.forEach bodyStart bodyEnd (text "for") (text ":") while = C.while parens bodyStart bodyEnd tryCatch = G.tryCatch cppTryCatch @@ -1793,6 +1804,9 @@ instance TypeSym CppHdrCode where listType t = do modify (addHeaderUsing vector . addHeaderLangImport vector) C.listType vector t + setType t = do + modify (addHeaderUsing cppSet . addHeaderLangImport cppSet) + C.setType cppSet t arrayType = cppArrayType listInnerType = G.listInnerType funcType = CP.funcType @@ -1847,6 +1861,7 @@ instance BinaryOpSym CppHdrCode where moduloOp = mkOp 0 empty andOp = mkOp 0 empty orOp = mkOp 0 empty + inOp = mkOp 0 empty instance OpElim CppHdrCode where uOp = opDoc . unCPPHC @@ -1900,6 +1915,7 @@ instance Literal CppHdrCode where litInt = G.litInt litString = G.litString litArray = CP.litArray braces + litSet = cppLitSet setType litList _ _ = error $ "List literals not supported in " ++ cppName instance MathConstant CppHdrCode where @@ -1947,6 +1963,7 @@ instance BooleanExpression CppHdrCode where (?!) _ = mkStateVal void empty (?&&) _ _ = mkStateVal void empty (?||) _ _ = mkStateVal void empty + isin _ _ = mkStateVal void empty instance Comparison CppHdrCode where (?<) _ _ = mkStateVal void empty @@ -2015,6 +2032,9 @@ instance List CppHdrCode where listSet _ _ _ = mkStateVal void empty indexOf _ _ = mkStateVal void empty +instance Set CppHdrCode where + contains _ _ = mkStateVal void empty + instance InternalList CppHdrCode where listSlice' _ _ _ _ _ = toState $ toCode empty @@ -2415,7 +2435,7 @@ nmSpc, ptrAccess, std, algorithm, cppString, vector, sstream, stringstream, cppIterator, cppOpen, stod, stof, cppIgnore, numLimits, streamsize, max, endl, cin, cout, cppIndex, cppListAccess, cppListAdd, cppListAppend, cppIterBegin, cppIterEnd, cppR, cppW, cppA, cppGetLine, cppClose, cppClear, - cppStr, mathDefines :: String + cppStr, mathDefines, cppSet :: String nmSpc = "::" ptrAccess = "->" std = "std" @@ -2456,6 +2476,7 @@ cppClose = "close" cppClear = "clear" cppStr = "str" mathDefines = "_USE_MATH_DEFINES" +cppSet = "set" nmSpcAccess :: String -> String -> String nmSpcAccess ns e = ns ++ nmSpc ++ e @@ -2748,6 +2769,13 @@ cppsStateVarDef cns s p vr' vl' = do text n `nmSpcAccess'` RC.variable vr <+> equals <+> RC.value vl <> endStatement) empty) emptS +cppLitSet :: (RenderSym r) => (VSType r -> VSType r) -> VSType r -> [SValue r] + -> SValue r +cppLitSet f t' es' = do + es <- sequence es' + lt <- f t' + mkVal lt (RC.type' lt + <> braces (valueList es)) cpphStateVarDef :: (RenderSym r) => Doc -> r (Permanence r) -> SVariable r -> SValue r -> CS Doc diff --git a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/JavaRenderer.hs b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/JavaRenderer.hs index 10869878fb..81503dc89a 100644 --- a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/JavaRenderer.hs +++ b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/JavaRenderer.hs @@ -16,7 +16,7 @@ import GOOL.Drasil.InterfaceCommon (SharedProg, Label, MSBody, VSType, ValueSym(..), Argument(..), Literal(..), litZero, MathConstant(..), VariableValue(..), CommandLineArgs(..), NumericExpression(..), BooleanExpression(..), Comparison(..), ValueExpression(..), funcApp, - extFuncApp, List(..), InternalList(..), ThunkSym(..), VectorType(..), + extFuncApp, List(..), Set(..), InternalList(..), ThunkSym(..), VectorType(..), VectorDecl(..), VectorThunk(..), VectorExpression(..), ThunkAssign(..), StatementSym(..), AssignStatement(..), (&=), DeclStatement(..), IOStatement(..), StringStatement(..), FuncAppStatement(..), @@ -57,7 +57,7 @@ import qualified GOOL.Drasil.LanguageRenderer as R (sqrt, abs, log10, commentedMod, commentedItem) import GOOL.Drasil.LanguageRenderer.Constructors (mkStmt, mkStateVal, mkVal, VSOp, unOpPrec, powerPrec, unExpr, unExpr', unExprNumDbl, typeUnExpr, binExpr, - binExprNumDbl', typeBinExpr) + binExprNumDbl', typeBinExpr, inPrec) import qualified GOOL.Drasil.LanguageRenderer.LanguagePolymorphic as G ( multiBody, block, multiBlock, listInnerType, obj, csc, sec, cot, negateOp, equalOp, notEqualOp, greaterOp, greaterEqualOp, lessOp, lessEqualOp, plusOp, @@ -73,10 +73,10 @@ import qualified GOOL.Drasil.LanguageRenderer.LanguagePolymorphic as G ( import GOOL.Drasil.LanguageRenderer.LanguagePolymorphic (docFuncRepr) import qualified GOOL.Drasil.LanguageRenderer.CommonPseudoOO as CP (int, constructor, doxFunc, doxClass, doxMod, extVar, classVar, objVarSelf, - extFuncAppMixedArgs, indexOf, listAddFunc, discardFileLine, intClass, + extFuncAppMixedArgs, indexOf, contains, listAddFunc, discardFileLine, intClass, funcType, arrayType, pi, printSt, arrayDec, arrayDecDef, openFileA, forEach, docMain, mainFunction, buildModule', bindingError, listDecDef, - destructorError, stateVarDef, constVar, litArray, call', listSizeFunc, + destructorError, stateVarDef, constVar, litArray, litSetFunc, listSetFunc, call', listSizeFunc, listAccessFunc', notNull, doubleRender, double, openFileR, openFileW, stateVar, floatRender, float, string', intToIndex, indexToInt) import qualified GOOL.Drasil.LanguageRenderer.CLike as C (float, double, char, @@ -208,6 +208,7 @@ instance TypeSym JavaCode where infile = jInfileType outfile = jOutfileType listType = jListType + setType = jSetType arrayType = CP.arrayType listInnerType = G.listInnerType funcType = CP.funcType @@ -261,6 +262,7 @@ instance BinaryOpSym JavaCode where moduloOp = G.moduloOp andOp = C.andOp orOp = C.orOp + inOp = inPrec jContains instance OpElim JavaCode where uOp = opDoc . unJC @@ -314,6 +316,8 @@ instance Literal JavaCode where litInt = G.litInt litString = G.litString litArray = CP.litArray braces + litSet = CP.litSetFunc jSetOf + litList t es = do zoom lensVStoMS $ modify (if null es then id else addLangImport $ utilImport jArrays) @@ -362,6 +366,7 @@ instance BooleanExpression JavaCode where (?!) = typeUnExpr notOp bool (?&&) = typeBinExpr andOp bool (?||) = typeBinExpr orOp bool + isin = typeBinExpr inOp bool instance Comparison JavaCode where (?<) = typeBinExpr lessOp bool @@ -406,7 +411,7 @@ instance OOValueExpression JavaCode where libNewObjMixedArgs = C.libNewObjMixedArgs instance RenderValue JavaCode where - inputFunc = modify (addLangImportVS $ utilImport jScanner) >> mkStateVal + inputFunc = modify (addLangImportVS $ utilImport jUtil) >> mkStateVal (obj jScanner) (parens $ new' <+> jScanner' <> parens (jSystem jStdIn)) printFunc = mkStateVal void (jSystem (jStdOut `access` printLabel)) printLnFunc = mkStateVal void (jSystem (jStdOut `access` jPrintLn)) @@ -455,6 +460,9 @@ instance List JavaCode where listSet = G.listSet indexOf = CP.indexOf jIndex +instance Set JavaCode where + contains = CP.contains jContains + instance InternalList JavaCode where listSlice' = M.listSlice @@ -795,13 +803,17 @@ jBool' = "Boolean" jInteger = "Integer" jObject = "Object" jScanner = "Scanner" +jUtil = "*" +jContains = "contains" jPrintWriter = "PrintWriter" jFile = "File" jFileWriter = "FileWriter" jIOExc = "IOException" jFNFExc = "FileNotFoundException" jArrays = "Arrays" +jSet = "Set" jAsList = jArrays `access` "asList" +jSetOf = jSet `access` "of" jStdIn = "in" jStdOut = "out" jPrintLn = "println" @@ -847,6 +859,19 @@ jListType t = do lstInt = arrayList `containing` jInteger lstBool = arrayList `containing` jBool' +jSetType :: (RenderSym r) => VSType r -> VSType r +jSetType t = do + modify (addLangImportVS $ utilImport "Set") + t >>= (jSetType' . getType) + where jSetType' Integer = typeFromData (Set Integer) + stInt (text stInt) + jSetType' Float = C.listType "HashSet" CP.float + jSetType' Double = C.listType "HashSet" CP.double + jSetType' Boolean = typeFromData (Set Boolean) stBool (text stBool) + jSetType' _ = C.listType "HashSet" t + stInt = "HashSet" `containing` jInteger + stBool = "HashSet" `containing` jBool' + jArrayType :: VSType JavaCode jArrayType = arrayType (obj jObject) @@ -863,6 +888,9 @@ jFileWriterType = do jAsListFunc :: VSType JavaCode -> [SValue JavaCode] -> SValue JavaCode jAsListFunc t = funcApp jAsList (listType t) +jAsSetFunc :: VSType JavaCode -> [SValue JavaCode] -> SValue JavaCode +jAsSetFunc t = funcApp jSetOf (setType t) + jEqualsFunc :: SValue JavaCode -> VSFunction JavaCode jEqualsFunc v = func jEquals bool [v] diff --git a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/LanguagePolymorphic.hs b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/LanguagePolymorphic.hs index 2bf46866fe..fa4209dc5d 100644 --- a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/LanguagePolymorphic.hs +++ b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/LanguagePolymorphic.hs @@ -4,12 +4,12 @@ module GOOL.Drasil.LanguageRenderer.LanguagePolymorphic (fileFromData, multiBody, block, multiBlock, listInnerType, obj, negateOp, csc, sec, cot, equalOp, notEqualOp, greaterOp, greaterEqualOp, lessOp, lessEqualOp, - plusOp, minusOp, multOp, divideOp, moduloOp, var, staticVar, objVar, + plusOp, minusOp, multOp, divideOp, moduloOp, inOp, var, staticVar, objVar, classVarCheckStatic, arrayElem, litChar, litDouble, litInt, litString, valueOf, arg, argsList, call, funcAppMixedArgs, selfFuncAppMixedArgs, newObjMixedArgs, lambda, objAccess, objMethodCall, func, get, set, listAdd, listAppend, listAccess, listSet, getFunc, setFunc, - listAppendFunc, stmt, loopStmt, emptyStmt, assign, subAssign, increment, + listAppendFunc, setAddFunc, stmt, loopStmt, emptyStmt, assign, subAssign, increment, objDecNew, print, closeFile, returnStmt, valStmt, comment, throw, ifCond, tryCatch, construct, param, method, getMethod, setMethod, initStmts, function, docFuncRepr, docFunc, buildClass, implementingClass, docClass, @@ -29,10 +29,10 @@ import GOOL.Drasil.InterfaceCommon (Label, Library, MSBody, MSBlock, VSType, IOStatement(printStr, printStrLn, printFile, printFileStr, printFileStrLn), ifNoElse, ScopeSym(..)) import qualified GOOL.Drasil.InterfaceCommon as IC (TypeSym(int, double, char, - string, listType, arrayType, listInnerType, funcType, void), VariableSym(var), - Literal(litInt, litFloat, litDouble, litString), VariableValue(valueOf), + string, listType, setType, arrayType, listInnerType, funcType, void), VariableSym(var), + Literal(litInt, litFloat, litDouble, litString, litSet), VariableValue(valueOf), List(listSize, listAccess), StatementSym(valStmt), DeclStatement(varDecDef), - IOStatement(print), ControlStatement(returnStmt, for), ParameterSym(param), + IOStatement(print), ControlStatement(returnStmt, for, forEach), ParameterSym(param), List(intToIndex)) import GOOL.Drasil.InterfaceGOOL (SFile, FSModule, SClass, VSFunction, CSStateVar, FileSym(File), ModuleSym(Module), newObj, objMethodCallNoParams, @@ -155,6 +155,9 @@ divideOp = multPrec "/" moduloOp :: (Monad r) => VSOp r moduloOp = multPrec "%" +inOp :: (Monad r) => VSOp r +inOp = multPrec "isin" + -- Variables -- var :: (RenderSym r) => Label -> VSType r -> SVariable r @@ -285,6 +288,7 @@ listAccess v i = do let i' = IC.intToIndex i t = IC.listInnerType $ return $ valueType v' checkType (List _) = S.listAccessFunc t i' + checkType (Set _) = S.listAccessFunc t i' checkType (Array _) = i' >>= (\ix -> funcFromData (brackets (RC.value ix)) t) checkType _ = error "listAccess called on non-list-type value" @@ -307,7 +311,8 @@ setFunc t v toVal = v >>= (\vr -> IG.func (setterName $ variableName vr) t listAppendFunc :: (RenderSym r) => Label -> SValue r -> VSFunction r listAppendFunc f v = IG.func f (IC.listType $ onStateValue valueType v) [v] - +setAddFunc :: (RenderSym r) => Label -> SValue r -> VSFunction r +setAddFunc f v = IG.func f (IC.listType $ onStateValue valueType v) [v] -- Statements -- stmt :: (RenderSym r) => MSStatement r -> MSStatement r @@ -355,6 +360,16 @@ printList n v prFn prStrFn prLnFn = multi [prStrFn "[", prLnFn "]"] where l_i = "list_i" ++ show n i = IC.var l_i IC.int + +printSet :: (RenderSym r) => Integer -> SValue r -> (SValue r -> MSStatement r) + -> (String -> MSStatement r) -> (String -> MSStatement r) -> MSStatement r +printSet n v prFn prStrFn prLnFn = multi [prStrFn "{ ", + IC.forEach i v + (bodyStatements [prFn (IC.valueOf i),prStrFn " "]), +--(IC.forEach i v (bodyStatements [prFn (IC.valueOf i)])), + prLnFn "}"] + where set_i = "set_i" ++ show n + i = IC.var set_i IC.double printObj :: ClassName -> (String -> MSStatement r) -> MSStatement r printObj n prLnFn = prLnFn $ "Instance of " ++ n ++ " object" @@ -365,6 +380,8 @@ print newLn f printFn v = zoom lensMStoVS v >>= print' . getType . valueType where print' (List t) = printList (getNestDegree 1 t) v prFn prStrFn prLnFn print' (Object n) = printObj n prLnFn + print' (Set t) = printSet (getNestDegree 1 t) v prFn prStrFn + prLnFn print' _ = S.printSt newLn f printFn v prFn = maybe IC.print printFile f prStrFn = maybe printStr printFileStr f diff --git a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/PythonRenderer.hs b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/PythonRenderer.hs index 7e7d62a0be..ef2f198bd0 100644 --- a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/PythonRenderer.hs +++ b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/PythonRenderer.hs @@ -14,7 +14,7 @@ import GOOL.Drasil.InterfaceCommon (SharedProg, Label, Library, VSType, TypeSym(..), TypeElim(..), VariableSym(..), VariableElim(..), ValueSym(..), Argument(..), Literal(..), litZero, MathConstant(..), VariableValue(..), CommandLineArgs(..), NumericExpression(..), BooleanExpression(..), - Comparison(..), ValueExpression(..), funcApp, extFuncApp, List(..), + Comparison(..), ValueExpression(..), funcApp, extFuncApp, List(..), Set(..), InternalList(..), ThunkSym(..), VectorType(..), VectorDecl(..), VectorThunk(..), VectorExpression(..), ThunkAssign(..), StatementSym(..), AssignStatement(..), (&=), DeclStatement(..), IOStatement(..), @@ -51,7 +51,7 @@ import qualified GOOL.Drasil.LanguageRenderer as R (sqrt, fabs, log10, classVar, listSetFunc, castObj, dynamic, break, continue, addComments, commentedMod, commentedItem) import GOOL.Drasil.LanguageRenderer.Constructors (mkStmtNoEnd, mkStateVal, - mkVal, mkStateVar, VSOp, unOpPrec, powerPrec, multPrec, andPrec, orPrec, + mkVal, mkStateVar, VSOp, unOpPrec, powerPrec, multPrec, andPrec, orPrec, inPrec, unExpr, unExpr', typeUnExpr, binExpr, typeBinExpr) import qualified GOOL.Drasil.LanguageRenderer.LanguagePolymorphic as G ( multiBody, block, multiBlock, listInnerType, obj, negateOp, csc, sec, cot, @@ -68,9 +68,9 @@ import qualified GOOL.Drasil.LanguageRenderer.LanguagePolymorphic as G ( import qualified GOOL.Drasil.LanguageRenderer.CommonPseudoOO as CP (int, constructor, doxFunc, doxClass, doxMod, extVar, classVar, objVarSelf, extFuncAppMixedArgs, indexOf, listAddFunc, discardFileLine, intClass, - funcType, buildModule, bindingError, notNull, listDecDef, destructorError, - stateVarDef, constVar, litArray, listSetFunc, extraClass, listAccessFunc, - multiAssign, multiReturn, listDec, funcDecDef, inOutCall, forLoopError, + funcType, buildModule, bindingError, notNull, listDecDef, setDecDef, destructorError, + stateVarDef, constVar, litArray, litSet, listSetFunc, extraClass, listAccessFunc, + multiAssign, multiReturn, listDec, setDec, funcDecDef, inOutCall, forLoopError, mainBody, inOutFunc, docInOutFunc', listSize, intToIndex, indexToInt) import qualified GOOL.Drasil.LanguageRenderer.Macros as M (ifExists, decrement1, increment1, runStrategy, stringListVals, stringListLists, @@ -97,7 +97,7 @@ import Control.Monad.State (modify) import Data.List (intercalate, sort) import qualified Data.Map as Map (lookup) import Text.PrettyPrint.HughesPJ (Doc, text, (<>), (<+>), parens, empty, equals, - vcat, colon, brackets, isEmpty, quotes) + vcat, colon, brackets, isEmpty, quotes, braces) import GOOL.Drasil.LanguageRenderer.LanguagePolymorphic (OptionalSpace(..)) pyExt :: String @@ -193,6 +193,7 @@ instance TypeSym PythonCode where infile = typeFromData InFile "" empty outfile = typeFromData OutFile "" empty listType t' = t' >>=(\t -> typeFromData (List (getType t)) "" empty) + setType t' = t' >>=(\t -> typeFromData (Set (getType t)) "" empty) arrayType = listType listInnerType = G.listInnerType funcType = CP.funcType @@ -246,6 +247,7 @@ instance BinaryOpSym PythonCode where moduloOp = G.moduloOp andOp = andPrec pyAnd orOp = orPrec pyOr + inOp = inPrec pyIn instance OpElim PythonCode where uOp = opDoc . unPC @@ -301,6 +303,7 @@ instance Literal PythonCode where litInt = G.litInt litString = G.litString litArray = CP.litArray brackets + litSet = CP.litSet braces litList = litArray instance MathConstant PythonCode where @@ -354,6 +357,7 @@ instance BooleanExpression PythonCode where (?!) = typeUnExpr notOp bool (?&&) = typeBinExpr andOp bool (?||) = typeBinExpr orOp bool + isin = typeBinExpr inOp bool instance Comparison PythonCode where (?<) = typeBinExpr lessOp bool @@ -431,6 +435,9 @@ instance List PythonCode where listSet = G.listSet indexOf = CP.indexOf pyIndex +instance Set PythonCode where + contains a b = isin b a + instance InternalList PythonCode where listSlice' b e s vn vo = pyListSlice vn vo (getVal b) (getVal e) (getVal s) where getVal = fromMaybe (mkStateVal void empty) @@ -804,7 +811,7 @@ pyInputFunc = text "input()" -- raw_input() for < Python 3.0 pyPrintFunc = text printLabel pyListSize, pyIndex, pyInsert, pyAppendFunc, pyReadline, pyReadlines, pyOpen, pyClose, - pyRead, pyWrite, pyAppend, pySplit, pyRange, pyRstrip, pyMath :: String + pyRead, pyWrite, pyAppend, pySplit, pyRange, pyRstrip, pyMath, pyIn :: String pyListSize = "len" pyIndex = "index" pyInsert = "insert" @@ -820,6 +827,7 @@ pySplit = "split" pyRange = "range" pyRstrip = "rstrip" pyMath = "math" +pyIn = "in" pyDef, pyLambdaDec, pyElseIf, pyRaise, pyExcept :: Doc pyDef = text "def" diff --git a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/SwiftRenderer.hs b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/SwiftRenderer.hs index de781dd094..39c131501d 100644 --- a/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/SwiftRenderer.hs +++ b/code/drasil-gool/lib/GOOL/Drasil/LanguageRenderer/SwiftRenderer.hs @@ -17,7 +17,7 @@ import GOOL.Drasil.InterfaceCommon (SharedProg, Label, MSBody, MSBlock, VSType, Literal(..), litZero, MathConstant(..), VariableValue(..), CommandLineArgs(..), NumericExpression(..), BooleanExpression(..), Comparison(..), ValueExpression(..), funcApp, funcAppNamedArgs, extFuncApp, - List(..), listSlice, InternalList(..), ThunkSym(..), VectorType(..), + List(..), Set(..), listSlice, InternalList(..), ThunkSym(..), VectorType(..), VectorDecl(..), VectorThunk(..), VectorExpression(..), ThunkAssign(..), StatementSym(..), AssignStatement(..), (&=), DeclStatement(..), IOStatement(..), StringStatement(..), FuncAppStatement(..), @@ -45,7 +45,7 @@ import GOOL.Drasil.RendererClasses (MSMthdType, RenderSym, import qualified GOOL.Drasil.RendererClasses as RC (import', perm, body, block, type', uOp, bOp, variable, value, function, statement, scope, parameter, method, stateVar, class', module', blockComment') -import GOOL.Drasil.LanguageRenderer (dot, blockCmtStart, blockCmtEnd, +import GOOL.Drasil.LanguageRenderer (valueList, dot, blockCmtStart, blockCmtEnd, docCmtStart, bodyStart, bodyEnd, commentStart, elseIfLabel, forLabel, inLabel, tryLabel, catchLabel, throwLabel, throwsLabel, importLabel, listSep', printLabel, listSep, piLabel, access, tuple, FuncDocRenderer, @@ -70,13 +70,13 @@ import qualified GOOL.Drasil.LanguageRenderer.LanguagePolymorphic as G ( function, docFunc, buildClass, implementingClass, docClass, commentedClass, modFromData, fileDoc, fileFromData, defaultOptSpace) import qualified GOOL.Drasil.LanguageRenderer.CommonPseudoOO as CP (classVar, - objVarSelf, intClass, buildModule, docMod', bindingError, extFuncAppMixedArgs, - notNull, listDecDef, destructorError, stateVarDef, constVar, litArray, - listSetFunc, extraClass, listAccessFunc, doubleRender, double, openFileR, + objVarSelf, intClass, buildModule, docMod', contains, bindingError, extFuncAppMixedArgs, + notNull, listDecDef, destructorError, stateVarDef, constVar, litArray, litSet, + listSetFunc, litSetFunc, extraClass, listAccessFunc, doubleRender, double, openFileR, openFileW, self, multiAssign, multiReturn, listDec, funcDecDef, inOutCall, forLoopError, mainBody, inOutFunc, docInOutFunc', bool, float, stringRender', string', inherit, implements, intToIndex, indexToInt) -import qualified GOOL.Drasil.LanguageRenderer.CLike as C (notOp, andOp, orOp, +import qualified GOOL.Drasil.LanguageRenderer.CLike as C (notOp, andOp, orOp, inOp, litTrue, litFalse, inlineIf, libFuncAppMixedArgs, libNewObjMixedArgs, listSize, varDecDef, extObjDecNew, switch, while) import qualified GOOL.Drasil.LanguageRenderer.Macros as M (ifExists, decrement1, @@ -258,6 +258,7 @@ instance BinaryOpSym SwiftCode where moduloOp = G.moduloOp andOp = C.andOp orOp = C.orOp + inOp = C.inOp instance OpElim SwiftCode where uOp = opDoc . unSC @@ -311,6 +312,7 @@ instance Literal SwiftCode where litInt = G.litInt litString = G.litString litArray = CP.litArray brackets + litSet = swiftLitSetFunc swiftSet litList = litArray instance MathConstant SwiftCode where @@ -363,7 +365,8 @@ instance BooleanExpression SwiftCode where (?!) = typeUnExpr notOp bool (?&&) = typeBinExpr andOp bool (?||) = typeBinExpr orOp bool - + isin = typeBinExpr inOp bool + instance Comparison SwiftCode where (?<) = swiftNumBinExpr (typeBinExpr lessOp bool) (?<=) = swiftNumBinExpr (typeBinExpr lessEqualOp bool) @@ -439,6 +442,9 @@ instance List SwiftCode where listSet = G.listSet indexOf = swiftIndexOf +instance Set SwiftCode where + contains = CP.contains swiftContains + instance InternalList SwiftCode where listSlice' b e s vn vo = swiftListSlice vn vo b e (fromMaybe (litInt 1) s) @@ -864,7 +870,7 @@ swiftMain, swiftFoundation, swiftMath, swiftNil, swiftInt, swiftChar, swiftSeekEnd, swiftClose, swiftJoined, swiftAppendPath, swiftUrls, swiftSplit, swiftData, swiftEncoding, swiftOf, swiftFrom, swiftTo, swiftBy, swiftAt, swiftTerm, swiftFor, swiftIn, swiftContentsOf, swiftWriteTo, swiftSep, - swiftSepBy, swiftUnwrap :: String + swiftSepBy, swiftUnwrap, swiftContains, swiftSet :: String swiftMain = "main" swiftFoundation = "Foundation" swiftMath = swiftFoundation @@ -907,6 +913,8 @@ swiftWriteTo = "forWritingTo" swiftSep = "separator" swiftSepBy = "separatedBy" swiftUnwrap = "!" +swiftContains = "contains" +swiftSet = "Set" swiftUnaryMath :: (Monad r) => String -> VSOp r swiftUnaryMath = addMathImport . unOpPrec @@ -937,6 +945,10 @@ swiftLambda ps ex = braces $ parens (hicat listSep' swiftReadableTypes :: [CodeType] swiftReadableTypes = [Integer, Double, Float, Boolean, Char] +swiftLitSetFunc :: (RenderSym r) => String -> VSType r -> [SValue r] -> SValue r +swiftLitSetFunc s t es = sequence es >>= (\elems -> mkStateVal (arrayType t) + (text s <> parens (brackets (valueList elems)))) + swiftCast :: (RenderSym r) => VSType r -> SValue r -> SValue r swiftCast t' v' = do t <- t' diff --git a/code/drasil-gool/lib/GOOL/Drasil/RendererClasses.hs b/code/drasil-gool/lib/GOOL/Drasil/RendererClasses.hs index 86f44a8420..8fa769ada0 100644 --- a/code/drasil-gool/lib/GOOL/Drasil/RendererClasses.hs +++ b/code/drasil-gool/lib/GOOL/Drasil/RendererClasses.hs @@ -131,6 +131,7 @@ class BinaryOpSym r where moduloOp :: VSBinOp r andOp :: VSBinOp r orOp :: VSBinOp r + inOp :: VSBinOp r class OpElim r where uOp :: r (UnaryOp r) -> Doc diff --git a/code/drasil-lang/lib/Language/Drasil.hs b/code/drasil-lang/lib/Language/Drasil.hs index 93073b3d99..a3b62ada9b 100644 --- a/code/drasil-lang/lib/Language/Drasil.hs +++ b/code/drasil-lang/lib/Language/Drasil.hs @@ -15,7 +15,7 @@ module Language.Drasil ( , square, half , oneHalf, oneThird , apply1, apply2 - , m2x2, vec2D, dgnl2x2, rowVec, columnVec + , m2x2, vec2D, dgnl2x2, rowVec, columnVec, mkSet , Completeness, Relation -- ** Literals Language @@ -129,7 +129,7 @@ module Language.Drasil ( -- *** Constrained and Uncertain Values -- Language.Drasil.Constraint , ConstraintReason(..), Constraint(..), ConstraintE - , physc, sfwrc, isPhysC, isSfwrC + , physRange, sfwrRange, physElem, sfwrElem, isPhysC, isSfwrC -- Language.Drasil.Chunk.Constrained , ConstrainedChunk(..), ConstrConcept(..) , cuc, cvc, constrained', cuc', cuc'', constrainedNRV' @@ -306,7 +306,7 @@ import Language.Drasil.WellTyped (RequiresChecking(..), Typed(..), TypingContext import Language.Drasil.Expr.Class (ExprC(..), frac, recip_, square, half, oneHalf, oneThird, apply1, apply2, - m2x2, vec2D, dgnl2x2, rowVec, columnVec) + m2x2, vec2D, dgnl2x2, rowVec, columnVec, mkSet) import Language.Drasil.Expr.Lang (Expr, Completeness, Relation) import Language.Drasil.Literal.Class (LiteralC(..)) import Language.Drasil.Literal.Lang (Literal) @@ -351,7 +351,7 @@ import Language.Drasil.Chunk.CommonIdea import Language.Drasil.Chunk.Concept import Language.Drasil.Chunk.Concept.Core (sDom) -- exported for drasil-database FIXME: move to development package? import Language.Drasil.Chunk.Constrained -import Language.Drasil.Constraint (physc, sfwrc, isPhysC, isSfwrC, +import Language.Drasil.Constraint (physRange, sfwrRange, physElem, sfwrElem, isSfwrC, isPhysC, Constraint(..), ConstraintE, ConstraintReason(..)) import Language.Drasil.Chunk.DefinedQuantity import Language.Drasil.Chunk.Eq (QDefinition, fromEqn, fromEqn', fromEqnSt, diff --git a/code/drasil-lang/lib/Language/Drasil/CodeExpr/Convert.hs b/code/drasil-lang/lib/Language/Drasil/CodeExpr/Convert.hs index 90ee3c4a0a..0ff9af2329 100644 --- a/code/drasil-lang/lib/Language/Drasil/CodeExpr/Convert.hs +++ b/code/drasil-lang/lib/Language/Drasil/CodeExpr/Convert.hs @@ -28,10 +28,12 @@ expr :: LD.Expr -> CodeExpr expr (LD.Lit l) = Lit l expr (LD.AssocA ao es) = AssocA (assocArithOp ao) $ map expr es expr (LD.AssocB bo es) = AssocB (assocBoolOp bo) $ map expr es +expr (LD.AssocC bo es) = AssocC (assocConcatOp bo) $ map expr es expr (LD.C u) = C u expr (LD.FCall u es) = FCall u (map expr es) [] expr (LD.Case c es) = Case c $ map (bimap expr expr) es expr (LD.Matrix es) = Matrix $ map (map expr) es +expr (LD.Set es) = Set $ map expr es expr (LD.UnaryOp uo e) = UnaryOp (uFunc uo) (expr e) expr (LD.UnaryOpB uo e) = UnaryOpB (uFuncB uo) (expr e) expr (LD.UnaryOpVV uo e) = UnaryOpVV (uFuncVV uo) (expr e) @@ -44,6 +46,8 @@ expr (LD.OrdBinaryOp bo l r) = OrdBinaryOp (ordBinOp bo) (expr l) (expr r) expr (LD.VVVBinaryOp bo l r) = VVVBinaryOp (vvvBinOp bo) (expr l) (expr r) expr (LD.VVNBinaryOp bo l r) = VVNBinaryOp (vvnBinOp bo) (expr l) (expr r) expr (LD.NVVBinaryOp bo l r) = NVVBinaryOp (nvvBinOp bo) (expr l) (expr r) +expr (LD.ESSBinaryOp bo l r) = ESSBinaryOp (essBinOp bo) (expr l) (expr r) +expr (LD.ESBBinaryOp bo l r) = ESBBinaryOp (esbBinOp bo) (expr l) (expr r) expr (LD.Operator aao dd e) = Operator (assocArithOp aao) (renderDomainDesc dd) (expr e) expr (LD.RealI u ri) = RealI u (realInterval ri) @@ -53,9 +57,13 @@ realInterval (Bounded (il, el) (ir, er)) = Bounded (il, expr el) (ir, expr er) realInterval (UpTo (i, e)) = UpTo (i, expr e) realInterval (UpFrom (i, e)) = UpFrom (i, expr e) +con :: E.Expr -> CodeExpr +con er = expr er + -- | Convert constrained expressions ('ConstraintE') into 'Constraint''CodeExpr's. constraint :: ConstraintE -> Constraint CodeExpr constraint (Range r ri) = Range r (realInterval ri) +constraint (Elem r ri) = Elem r (con ri) -- | Convert 'DomainDesc Expr Expr' into 'DomainDesc CodeExpr CodeExpr's. renderDomainDesc :: DiscreteDomainDesc E.Expr E.Expr -> DiscreteDomainDesc CodeExpr CodeExpr @@ -94,6 +102,13 @@ vvnBinOp LD.Dot = Dot nvvBinOp :: LD.NVVBinOp -> NVVBinOp nvvBinOp LD.Scale = Scale +essBinOp :: LD.ESSBinOp -> ESSBinOp +essBinOp LD.SAdd = SAdd +essBinOp LD.SRemove = SRemove + +esbBinOp :: LD.ESBBinOp -> ESBBinOp +esbBinOp LD.SContains = SContains + assocArithOp :: LD.AssocArithOper -> AssocArithOper assocArithOp LD.Add = Add -- TODO: These L.'s should be exported through L.D.Development assocArithOp LD.Mul = Mul @@ -102,6 +117,9 @@ assocBoolOp :: LD.AssocBoolOper -> AssocBoolOper assocBoolOp LD.And = And -- TODO: These L.'s should be exported through L.D.Development assocBoolOp LD.Or = Or +assocConcatOp :: LD.AssocConcatOper -> AssocConcatOper +assocConcatOp LD.SUnion = SUnion + uFunc :: LD.UFunc -> UFunc uFunc LD.Abs = Abs -- TODO: These L.'s should be exported through L.D.Development uFunc LD.Log = Log diff --git a/code/drasil-lang/lib/Language/Drasil/CodeExpr/Development.hs b/code/drasil-lang/lib/Language/Drasil/CodeExpr/Development.hs index f7806f0926..00248e5fb0 100644 --- a/code/drasil-lang/lib/Language/Drasil/CodeExpr/Development.hs +++ b/code/drasil-lang/lib/Language/Drasil/CodeExpr/Development.hs @@ -3,7 +3,7 @@ module Language.Drasil.CodeExpr.Development ( -- CodeExpr CodeExpr(..), ArithBinOp(..), EqBinOp(..), BoolBinOp(..), LABinOp(..), OrdBinOp(..), - VVVBinOp(..), VVNBinOp(..), NVVBinOp(..), AssocArithOper(..), AssocBoolOper(..), + VVVBinOp(..), VVNBinOp(..), NVVBinOp(..), ESSBinOp(..), ESBBinOp(..), AssocArithOper(..), AssocBoolOper(..), AssocConcatOper(..), UFunc(..), UFuncB(..), UFuncVV(..), UFuncVN(..), -- Class CodeExprC(..), @@ -18,7 +18,7 @@ module Language.Drasil.CodeExpr.Development ( import Language.Drasil.CodeExpr.Lang (CodeExpr(..), UFuncVV(..), UFuncVN(..), UFuncB(..), UFunc(..), - AssocBoolOper(..), AssocArithOper(..), VVNBinOp(..), NVVBinOp(..), + AssocBoolOper(..), AssocArithOper(..), AssocConcatOper(..),VVNBinOp(..), NVVBinOp(..), ESSBinOp(..), ESBBinOp(..), VVVBinOp(..), OrdBinOp(..), LABinOp(..), BoolBinOp(..), EqBinOp(..), ArithBinOp(..)) import Language.Drasil.CodeExpr.Class (CodeExprC(..)) diff --git a/code/drasil-lang/lib/Language/Drasil/CodeExpr/Extract.hs b/code/drasil-lang/lib/Language/Drasil/CodeExpr/Extract.hs index fd24eb816e..beac827382 100644 --- a/code/drasil-lang/lib/Language/Drasil/CodeExpr/Extract.hs +++ b/code/drasil-lang/lib/Language/Drasil/CodeExpr/Extract.hs @@ -14,6 +14,7 @@ import Data.List (nub) eNames :: CodeExpr -> [UID] eNames (AssocA _ l) = concatMap eNames l eNames (AssocB _ l) = concatMap eNames l +eNames (AssocC _ l) = concatMap eNames l eNames (C c) = [c] eNames Lit{} = [] eNames (FCall f x ns) = f : concatMap eNames x ++ map fst ns ++ @@ -36,8 +37,11 @@ eNames (OrdBinaryOp _ a b) = eNames a ++ eNames b eNames (VVVBinaryOp _ a b) = eNames a ++ eNames b eNames (VVNBinaryOp _ a b) = eNames a ++ eNames b eNames (NVVBinaryOp _ a b) = eNames a ++ eNames b +eNames (ESSBinaryOp _ _ s) = eNames s +eNames (ESBBinaryOp _ _ s) = eNames s eNames (Operator _ _ e) = eNames e eNames (Matrix a) = concatMap (concatMap eNames) a +eNames (Set a) = concatMap eNames a eNames (RealI c b) = c : eNamesRI b -- | Generic traversal of everything that could come from an interval to names (similar to 'eNames'). @@ -52,6 +56,7 @@ eNamesRI (UpFrom (_, il)) = eNames il eNames' :: CodeExpr -> [UID] eNames' (AssocA _ l) = concatMap eNames' l eNames' (AssocB _ l) = concatMap eNames' l +eNames' (AssocC _ l) = concatMap eNames' l eNames' (C c) = [c] eNames' Lit{} = [] eNames' (FCall _ x ns) = concatMap eNames' x ++ map fst ns ++ @@ -75,8 +80,11 @@ eNames' (OrdBinaryOp _ a b) = eNames' a ++ eNames' b eNames' (VVVBinaryOp _ a b) = eNames' a ++ eNames' b eNames' (VVNBinaryOp _ a b) = eNames' a ++ eNames' b eNames' (NVVBinaryOp _ a b) = eNames' a ++ eNames' b +eNames' (ESSBinaryOp _ _ s) = eNames' s +eNames' (ESBBinaryOp _ _ s) = eNames' s eNames' (Operator _ _ e) = eNames' e eNames' (Matrix a) = concatMap (concatMap eNames') a +eNames' (Set a) = concatMap eNames' a eNames' (RealI c b) = c : eNamesRI' b -- | Generic traversal of everything that could come from an interval to names without functions (similar to 'eNames''). diff --git a/code/drasil-lang/lib/Language/Drasil/CodeExpr/Lang.hs b/code/drasil-lang/lib/Language/Drasil/CodeExpr/Lang.hs index 283dc1719d..a84bf49f34 100644 --- a/code/drasil-lang/lib/Language/Drasil/CodeExpr/Lang.hs +++ b/code/drasil-lang/lib/Language/Drasil/CodeExpr/Lang.hs @@ -26,7 +26,7 @@ data BoolBinOp = Impl | Iff deriving Eq -- | Index operator. -data LABinOp = Index +data LABinOp = Index | IndexOf deriving Eq -- | Ordered binary operators (less than, greater than, less than or equal to, greater than or equal to). @@ -45,6 +45,16 @@ data VVNBinOp = Dot data NVVBinOp = Scale deriving Eq +-- | Element + Set -> Set +data ESSBinOp = SAdd | SRemove + deriving Eq + +-- | Element + Set -> Bool +data ESBBinOp = SContains + deriving Eq + +data AssocConcatOper = SUnion + deriving Eq -- | Associative operators (adding and multiplication). Also specifies whether it is for integers or for real numbers. data AssocArithOper = Add | Mul deriving Eq @@ -82,6 +92,8 @@ data CodeExpr where AssocA :: AssocArithOper -> [CodeExpr] -> CodeExpr -- | Takes an associative boolean operator with a list of expressions. AssocB :: AssocBoolOper -> [CodeExpr] -> CodeExpr + + AssocC :: AssocConcatOper -> [CodeExpr] -> CodeExpr -- | C stands for "Chunk", for referring to a chunk in an expression. -- Implicitly assumes that the chunk has a symbol. C :: UID -> CodeExpr @@ -108,7 +120,8 @@ data CodeExpr where Case :: Completeness -> [(CodeExpr, CodeExpr)] -> CodeExpr -- | Represents a matrix of expressions. Matrix :: [[CodeExpr]] -> CodeExpr - + -- | Represents a set of expressions + Set :: [CodeExpr] -> CodeExpr -- | Unary operation for most functions (eg. sin, cos, log, etc.). UnaryOp :: UFunc -> CodeExpr -> CodeExpr -- | Unary operation for @Bool -> Bool@ operations. @@ -134,6 +147,10 @@ data CodeExpr where VVNBinaryOp :: VVNBinOp -> CodeExpr -> CodeExpr -> CodeExpr -- | Binary operator for @Number x Vector -> Vector@ operations (scaling). NVVBinaryOp :: NVVBinOp -> CodeExpr -> CodeExpr -> CodeExpr + -- | Set operator for Set + Set -> Set + ESSBinaryOp :: ESSBinOp -> CodeExpr -> CodeExpr -> CodeExpr + -- | Set operator for Element + Set -> Bool + ESBBinaryOp :: ESBBinOp -> CodeExpr -> CodeExpr -> CodeExpr -- | Operators are generalized arithmetic operators over a 'DomainDesc' -- of an 'Expr'. Could be called BigOp. diff --git a/code/drasil-lang/lib/Language/Drasil/Constraint.hs b/code/drasil-lang/lib/Language/Drasil/Constraint.hs index 6c7c9f49d1..32d614634a 100644 --- a/code/drasil-lang/lib/Language/Drasil/Constraint.hs +++ b/code/drasil-lang/lib/Language/Drasil/Constraint.hs @@ -4,11 +4,11 @@ module Language.Drasil.Constraint ( -- * Types Constraint(..), ConstraintE, ConstraintReason(..), -- * Functions - physc, sfwrc, isPhysC, isSfwrC + physRange, sfwrRange, physElem, sfwrElem, isPhysC, isSfwrC ) where import Language.Drasil.Expr.Lang -import Language.Drasil.Space (RealInterval(..)) +import Language.Drasil.Space (RealInterval(..), Space(..)) -- | The reason behind the constraint's existence. data ConstraintReason = Physical | Software @@ -21,20 +21,30 @@ data Constraint a where -- | By default, physical and software constraints are ranges. Range :: ConstraintReason -> RealInterval a a -> Constraint a + Elem :: ConstraintReason -> a -> Constraint a + -- | Smart constructor for range of 'Physical' constraints between two given expressions. -physc :: RealInterval Expr Expr -> ConstraintE -physc = Range Physical +physRange :: RealInterval Expr Expr -> ConstraintE +physRange = Range Physical + +physElem :: Expr -> ConstraintE +physElem = Elem Physical -- | Smart constructor for range of 'Software' constraints between two given expressions. -sfwrc :: RealInterval Expr Expr -> ConstraintE -sfwrc = Range Software +sfwrRange :: RealInterval Expr Expr -> ConstraintE +sfwrRange = Range Software + +sfwrElem :: Expr -> ConstraintE +sfwrElem = Elem Software -isPhysC, isSfwrC :: Constraint e -> Bool +isPhysC, isSfwrC:: Constraint e -> Bool -- | Helpful for filtering for Physical constraints. True if constraint is 'Physical'. isPhysC (Range Physical _) = True +isPhysC (Elem Physical _) = True isPhysC _ = False -- | Helpful for filtering for Software constraints. True if constraint is 'Software'. isSfwrC (Range Software _) = True +isSfwrC (Elem Software _) = True isSfwrC _ = False diff --git a/code/drasil-lang/lib/Language/Drasil/Expr/Class.hs b/code/drasil-lang/lib/Language/Drasil/Expr/Class.hs index 0772ede25e..3da2a5dbbf 100644 --- a/code/drasil-lang/lib/Language/Drasil/Expr/Class.hs +++ b/code/drasil-lang/lib/Language/Drasil/Expr/Class.hs @@ -5,7 +5,7 @@ module Language.Drasil.Expr.Class ( square, half, oneHalf, oneThird, apply1, apply2, - m2x2, vec2D, dgnl2x2, rowVec, columnVec + m2x2, vec2D, dgnl2x2, rowVec, columnVec, mkSet ) where import Prelude hiding (sqrt, log, sin, cos, tan, exp) @@ -64,6 +64,9 @@ apply2 f a b = apply f [sy a, sy b] m2x2 :: ExprC r => r -> r -> r -> r -> r m2x2 a b c d = matrix [[a,b],[c,d]] +mkSet :: ExprC r => [r] -> r +mkSet [r] = sSet [r] +mkSet r = sSet r -- | Create a 2D vector (a matrix with two rows, one column). First argument is placed above the second. vec2D :: ExprC r => r -> r -> r vec2D a b = matrix [[a],[b]] @@ -90,7 +93,6 @@ class ExprC r where infixr 4 $= infixr 9 $&& infixr 9 $|| - lit :: Literal -> r -- * Binary Operators @@ -114,7 +116,8 @@ class ExprC r where ($=>), ($<=>) :: r -> r -> r ($&&), ($||) :: r -> r -> r - + + in' :: r -> r -> r -- | Smart constructor for taking the absolute value of an expression. abs_ :: r -> r @@ -174,13 +177,15 @@ class ExprC r where -- | Smart constructor for indexing. idx :: r -> r -> r - + + idxOf :: r -> r -> r + -- | Smart constructor for the summation, product, and integral functions over an interval. defint, defsum, defprod :: Symbol -> r -> r -> r -> r -- | Smart constructor for 'real interval' membership. realInterval :: HasUID c => c -> RealInterval r r -> r - + -- | Euclidean function : takes a vector and returns the sqrt of the sum-of-squares. euclidean :: [r] -> r @@ -205,6 +210,7 @@ class ExprC r where -- | Create a matrix. matrix :: [[r]] -> r + sSet :: [r] -> r -- | Applies a given function with a list of parameters. apply :: (HasUID f, HasSymbol f) => f -> [r] -> r @@ -273,7 +279,9 @@ instance ExprC Expr where a $&& b = AssocB And [a, b] -- | Smart constructor for the boolean /or/ operator. a $|| b = AssocB Or [a, b] - + + in' e s = ESBBinaryOp SContains e s + -- | Smart constructor for taking the absolute value of an expression. abs_ = UnaryOp Abs @@ -336,6 +344,7 @@ instance ExprC Expr where -- | Smart constructor for indexing. idx = LABinaryOp Index + idxOf = LABinaryOp IndexOf -- | Integrate over some expression with bounds (∫). defint v low high = Operator Add (BoundedDD v Continuous low high) @@ -367,6 +376,7 @@ instance ExprC Expr where matrix = Matrix + sSet = Set -- | Applies a given function with a list of parameters. apply f [] = sy f apply f ps = FCall (f ^. uid) ps @@ -435,6 +445,8 @@ instance ExprC M.ModelExpr where -- | Smart constructor for the boolean /or/ operator. a $|| b = M.AssocB M.Or [a, b] + in' e s = M.ESBBinaryOp M.SContains e s + -- | Smart constructor for taking the absolute value of an expression. abs_ = M.UnaryOp M.Abs @@ -497,6 +509,9 @@ instance ExprC M.ModelExpr where -- | Smart constructor for indexing. idx = M.LABinaryOp M.Index + -- | Smart constructor for indexing. + idxOf = M.LABinaryOp M.IndexOf + -- | Integrate over some expression with bounds (∫). defint v low high = M.Operator M.Add (BoundedDD v Continuous low high) @@ -528,6 +543,7 @@ instance ExprC M.ModelExpr where matrix = M.Matrix + sSet = M.Set -- | Applies a given function with a list of parameters. apply f [] = sy f apply f ps = M.FCall (f ^. uid) ps @@ -598,6 +614,8 @@ instance ExprC C.CodeExpr where -- | Smart constructor for the boolean /or/ operator. a $|| b = C.AssocB C.Or [a, b] + in' e s = C.ESBBinaryOp C.SContains e s + -- | Smart constructor for taking the absolute value of an expression. abs_ = C.UnaryOp C.Abs @@ -660,6 +678,7 @@ instance ExprC C.CodeExpr where -- | Smart constructor for indexing. idx = C.LABinaryOp C.Index + idxOf = C.LABinaryOp C.IndexOf -- | Integrate over some expression with bounds (∫). defint v low high = C.Operator C.Add (BoundedDD v Continuous low high) @@ -691,6 +710,7 @@ instance ExprC C.CodeExpr where matrix = C.Matrix + sSet = C.Set -- | Applies a given function with a list of parameters. apply f [] = sy f apply f ps = C.FCall (f ^. uid) ps [] diff --git a/code/drasil-lang/lib/Language/Drasil/Expr/Development.hs b/code/drasil-lang/lib/Language/Drasil/Expr/Development.hs index 2e40a77d29..36036b2232 100644 --- a/code/drasil-lang/lib/Language/Drasil/Expr/Development.hs +++ b/code/drasil-lang/lib/Language/Drasil/Expr/Development.hs @@ -2,8 +2,8 @@ module Language.Drasil.Expr.Development ( -- Expr Expr(..), UFunc(..), UFuncB(..), UFuncVV(..), UFuncVN(..) , ArithBinOp(..), BoolBinOp(..), EqBinOp(..), LABinOp(..), OrdBinOp(..) - , VVVBinOp(..), VVNBinOp(..), NVVBinOp(..) - , AssocArithOper(..), AssocBoolOper(..) + , VVVBinOp(..), VVNBinOp(..), NVVBinOp(..), ESSBinOp(..), ESBBinOp(..) + , AssocArithOper(..), AssocBoolOper(..), AssocConcatOper(..) , Completeness(..), Relation -- Expr.Extract , eDep, eNames, eNames', eNamesRI diff --git a/code/drasil-lang/lib/Language/Drasil/Expr/Extract.hs b/code/drasil-lang/lib/Language/Drasil/Expr/Extract.hs index a23908944a..b06fbbabdb 100644 --- a/code/drasil-lang/lib/Language/Drasil/Expr/Extract.hs +++ b/code/drasil-lang/lib/Language/Drasil/Expr/Extract.hs @@ -11,6 +11,7 @@ import Language.Drasil.UID (UID) eNames :: Expr -> [UID] eNames (AssocA _ l) = concatMap eNames l eNames (AssocB _ l) = concatMap eNames l +eNames (AssocC _ l) = concatMap eNames l eNames (C c) = [c] eNames Lit{} = [] eNames (FCall f x) = f : concatMap eNames x @@ -28,8 +29,11 @@ eNames (OrdBinaryOp _ a b) = eNames a ++ eNames b eNames (VVVBinaryOp _ a b) = eNames a ++ eNames b eNames (VVNBinaryOp _ a b) = eNames a ++ eNames b eNames (NVVBinaryOp _ a b) = eNames a ++ eNames b +eNames (ESSBinaryOp _ _ s) = eNames s +eNames (ESBBinaryOp _ _ s) = eNames s eNames (Operator _ _ e) = eNames e eNames (Matrix a) = concatMap (concatMap eNames) a +eNames (Set a) = concatMap eNames a eNames (RealI c b) = c : eNamesRI b -- | Generic traversal of everything that could come from an interval to names (similar to 'eNames'). @@ -44,6 +48,7 @@ eNamesRI (UpFrom (_, il)) = eNames il eNames' :: Expr -> [UID] eNames' (AssocA _ l) = concatMap eNames' l eNames' (AssocB _ l) = concatMap eNames' l +eNames' (AssocC _ l) = concatMap eNames' l eNames' (C c) = [c] eNames' Lit{} = [] eNames' (FCall _ x) = concatMap eNames' x @@ -61,8 +66,11 @@ eNames' (OrdBinaryOp _ a b) = eNames' a ++ eNames' b eNames' (VVVBinaryOp _ a b) = eNames' a ++ eNames' b eNames' (VVNBinaryOp _ a b) = eNames' a ++ eNames' b eNames' (NVVBinaryOp _ a b) = eNames' a ++ eNames' b +eNames' (ESSBinaryOp _ _ s) = eNames' s +eNames' (ESBBinaryOp _ _ s) = eNames' s eNames' (Operator _ _ e) = eNames' e eNames' (Matrix a) = concatMap (concatMap eNames') a +eNames' (Set a) = concatMap eNames' a eNames' (RealI c b) = c : eNamesRI' b -- | Generic traversal of everything that could come from an interval to names without functions (similar to 'eNames''). diff --git a/code/drasil-lang/lib/Language/Drasil/Expr/Lang.hs b/code/drasil-lang/lib/Language/Drasil/Expr/Lang.hs index ef86f11008..6a5b09b4dc 100644 --- a/code/drasil-lang/lib/Language/Drasil/Expr/Lang.hs +++ b/code/drasil-lang/lib/Language/Drasil/Expr/Lang.hs @@ -39,7 +39,7 @@ data BoolBinOp = Impl | Iff deriving Eq -- | Index operator. -data LABinOp = Index +data LABinOp = Index | IndexOf deriving Eq -- | Ordered binary operators (less than, greater than, less than or equal to, greater than or equal to). @@ -58,7 +58,17 @@ data VVNBinOp = Dot data NVVBinOp = Scale deriving Eq --- TODO: I suppose these can be merged to just Add and Mul? +-- | Element + Set -> Set +data ESSBinOp = SAdd | SRemove + deriving Eq + +-- | Element + Set -> Bool +data ESBBinOp = SContains + deriving Eq + +data AssocConcatOper = SUnion + deriving Eq + -- | Associative operators (adding and multiplication). Also specifies whether it is for integers or for real numbers. data AssocArithOper = Add | Mul deriving Eq @@ -100,6 +110,8 @@ data Expr where AssocA :: AssocArithOper -> [Expr] -> Expr -- | Takes an associative boolean operator with a list of expressions. AssocB :: AssocBoolOper -> [Expr] -> Expr + + AssocC :: AssocConcatOper -> [Expr] -> Expr -- | C stands for "Chunk", for referring to a chunk in an expression. -- Implicitly assumes that the chunk has a symbol. C :: UID -> Expr @@ -109,7 +121,8 @@ data Expr where Case :: Completeness -> [(Expr, Relation)] -> Expr -- | Represents a matrix of expressions. Matrix :: [[Expr]] -> Expr - + -- | Represents a set of expressions + Set :: [Expr] -> Expr -- | Unary operation for most functions (eg. sin, cos, log, etc.). UnaryOp :: UFunc -> Expr -> Expr -- | Unary operation for @Bool -> Bool@ operations. @@ -135,7 +148,10 @@ data Expr where VVNBinaryOp :: VVNBinOp -> Expr -> Expr -> Expr -- | Binary operator for @Expr x Vector -> Vector@ operations (scaling). NVVBinaryOp :: NVVBinOp -> Expr -> Expr -> Expr - + -- | Set operator for Element + Set -> Set + ESSBinaryOp :: ESSBinOp -> Expr -> Expr -> Expr + -- | Set operator for Element + Set -> Bool + ESBBinaryOp :: ESBBinOp -> Expr -> Expr -> Expr -- | Operators are generalized arithmetic operators over a 'DomainDesc' -- of an 'Expr'. Could be called BigOp. -- ex: Summation is represented via 'Add' over a discrete domain. @@ -163,6 +179,8 @@ instance Eq Expr where VVVBinaryOp o a b == VVVBinaryOp p c d = o == p && a == c && b == d VVNBinaryOp o a b == VVNBinaryOp p c d = o == p && a == c && b == d NVVBinaryOp o a b == NVVBinaryOp p c d = o == p && a == c && b == d + ESSBinaryOp o a b == ESSBinaryOp p c d = o == p && a == c && b == d + ESBBinaryOp o a b == ESBBinaryOp p c d = o == p && a == c && b == d _ == _ = False -- ^ TODO: This needs to add more equality checks @@ -250,6 +268,20 @@ instance Typed Expr Space where infer cxt (AssocB _ exs) = allOfType cxt exs S.Boolean S.Boolean $ "Associative boolean operation expects all operands to be of the same type (" ++ show S.Boolean ++ ")." + infer cxt (AssocC _ (e:exs)) = + case infer cxt e of + Left spaceValue | spaceValue /= S.Void -> + -- If the inferred type of e is a valid Space, call allOfType with spaceValue + allOfType cxt exs spaceValue spaceValue + "Associative arithmetic operation expects all operands to be of the same expected type." + Left l -> + -- Handle the case when sp is a Left value but spaceValue is invalid + Right ("Expected all operands in addition/multiplication to be numeric, but found " ++ show l) + Right r -> + -- If sp is a Right value containing a TypeError + Right r + infer _ (AssocC SUnion _) = Right "Associative addition requires at least one operand." + infer cxt (C uid) = inferFromContext cxt uid infer cxt (FCall uid exs) = case (inferFromContext cxt uid, map (infer cxt) exs) of @@ -283,6 +315,12 @@ instance Typed Expr Space where (const False) expT t = fromLeft (error "Infer on Matrix had a strong expectation of Left-valued data.") expT -- This error should never occur. + infer cxt (Set (exs)) = + case infer cxt (head exs) of + Left sp -> if S.isBasicNumSpace sp then Left sp else Right (show sp) + Right err -> Right ("Expressions in case" ++ show err) + --infer _ (Set _) = Right "Expressions in case" + infer cxt (UnaryOp uf ex) = case infer cxt ex of Left sp -> case uf of Abs -> if S.isBasicNumSpace sp && sp /= S.Natural @@ -361,7 +399,13 @@ instance Typed Expr Space where (Left lt , Left _) -> Right $ "List accessor expects a list/vector, but received `" ++ show lt ++ "`." (_ , Right e) -> Right e (Right e , _ ) -> Right e - + infer cxt (LABinaryOp IndexOf l n) = case (infer cxt l, infer cxt n) of + (Left (S.Set lt), Left nt) -> if S.isBasicNumSpace lt && nt == lt-- I guess we should only want it to be natural numbers, but integers or naturals is fine for now + then Left lt + else Right $ "List accessor not of type Integer nor Natural, but of type `" ++ show nt ++ "`" + (Left lt , Left _) -> Right $ "List accessor expects a list/vector, but received `" ++ show lt ++ "`." + (_ , Right e) -> Right e + (Right e , _ ) -> Right e infer cxt (OrdBinaryOp _ l r) = case (infer cxt l, infer cxt r) of (Left lt, Left rt) -> if S.isBasicNumSpace lt && lt == rt then Left S.Boolean @@ -369,6 +413,17 @@ instance Typed Expr Space where (_, Right re) -> Right re (Right le, _) -> Right le + infer cxt (NVVBinaryOp Scale l r) = case (infer cxt l, infer cxt r) of + (Left lt, Left (S.Vect rsp)) -> if S.isBasicNumSpace lt && lt == rsp + then Left rsp + else if lt /= rsp then + Right $ "Vector scaling expects a scaling by the same kind as the vector's but found scaling by`" ++ show lt ++ "` over vectors of type `" ++ show rsp ++ "`." + else + Right $ "Vector scaling expects a numeric scaling, but found `" ++ show lt ++ "`." + (Left _, Left rsp) -> Right $ "Vector scaling expects vector as second operand. Received `" ++ show rsp ++ "`." + (_, Right rx) -> Right rx + (Right lx, _) -> Right lx + infer cxt (VVVBinaryOp o l r) = vvvInfer cxt o l r {- case (infer cxt l, infer cxt r) of (Left lTy, Left rTy) -> if lTy == rTy && S.isBasicNumSpace lTy && lTy /= S.Natural @@ -386,16 +441,21 @@ instance Typed Expr Space where (_, Right rx) -> Right rx (Right lx, _) -> Right lx - infer cxt (NVVBinaryOp Scale l r) = case (infer cxt l, infer cxt r) of - (Left lt, Left (S.Vect rsp)) -> if S.isBasicNumSpace lt && lt == rsp - then Left rsp - else if lt /= rsp then - Right $ "Vector scaling expects a scaling by the same kind as the vector's but found scaling by`" ++ show lt ++ "` over vectors of type `" ++ show rsp ++ "`." - else - Right $ "Vector scaling expects a numeric scaling, but found `" ++ show lt ++ "`." - (Left _, Left rsp) -> Right $ "Vector scaling expects vector as second operand. Received `" ++ show rsp ++ "`." - (_, Right rx) -> Right rx - (Right lx, _) -> Right lx + infer cxt (ESSBinaryOp _ l r) = case (infer cxt l, infer cxt r) of + (Left lt, Left rt@(S.Set rsp)) -> if S.isBasicNumSpace lt && lt == rsp + then Left lt + else Right $ "Set Add/Sub should only be applied to Set of same space. Received `" ++ show lt ++ "` / `" ++ show rt ++ "`." + (_ , Right e) -> Right e + (Right e, _ ) -> Right e + (Left lt, Left rsp) -> Right $ "Set union expects set operands. Received `" ++ show lt ++ "` · `" ++ show rsp ++ "`." + + infer cxt (ESBBinaryOp _ l r) = case (infer cxt l, infer cxt r) of + (Left lt, Left rt@(S.Set rsp)) -> if S.isBasicNumSpace lt && lt == rsp + then Left lt + else Right $ "Set contains should only be applied to Set of same space. Received `" ++ show lt ++ "` / `" ++ show rt ++ "`." + (_ , Right e) -> Right e + (Right e, _ ) -> Right e + (Left lt, Left rsp) -> Right $ "Set union expects set operands. Received `" ++ show lt ++ "` · `" ++ show rsp ++ "`." infer cxt (Operator _ (S.BoundedDD _ _ bot top) body) = let expTy = S.Integer in @@ -431,4 +491,4 @@ instance Typed Expr Space where (_ , Right x) -> Right x (Right x, _ ) -> Right x riTy (S.UpTo (_, x)) = infer cxt x - riTy (S.UpFrom (_, x)) = infer cxt x + riTy (S.UpFrom (_, x)) = infer cxt x \ No newline at end of file diff --git a/code/drasil-lang/lib/Language/Drasil/ModelExpr/Convert.hs b/code/drasil-lang/lib/Language/Drasil/ModelExpr/Convert.hs index 15de833c07..868b2615fd 100644 --- a/code/drasil-lang/lib/Language/Drasil/ModelExpr/Convert.hs +++ b/code/drasil-lang/lib/Language/Drasil/ModelExpr/Convert.hs @@ -17,6 +17,9 @@ assocBoolOper :: E.AssocBoolOper -> AssocBoolOper assocBoolOper E.And = And assocBoolOper E.Or = Or +assocConcatOper :: E.AssocConcatOper -> AssocConcatOper +assocConcatOper E.SUnion = SUnion + uFunc :: E.UFunc -> UFunc uFunc E.Abs = Abs uFunc E.Log = Log @@ -77,14 +80,23 @@ vvnBinOp E.Dot = Dot nvvBinOp :: E.NVVBinOp -> NVVBinOp nvvBinOp E.Scale = Scale +essBinOp :: E.ESSBinOp -> ESSBinOp +essBinOp E.SAdd = SAdd +essBinOp E.SRemove = SRemove + +esbBinOp :: E.ESBBinOp -> ESBBinOp +esbBinOp E.SContains = SContains + expr :: E.Expr -> ModelExpr expr (E.Lit a) = Lit a expr (E.AssocA ao es) = AssocA (assocArithOper ao) $ map expr es expr (E.AssocB bo es) = AssocB (assocBoolOper bo) $ map expr es +expr (E.AssocC ao es) = AssocC (assocConcatOper ao) $ map expr es expr (E.C u) = C u expr (E.FCall u es) = FCall u (map expr es) expr (E.Case c ces) = Case c (map (bimap expr expr) ces) expr (E.Matrix es) = Matrix $ map (map expr) es +expr (E.Set e) = Set $ map expr e expr (E.UnaryOp u e) = UnaryOp (uFunc u) (expr e) expr (E.UnaryOpB u e) = UnaryOpB (uFuncB u) (expr e) expr (E.UnaryOpVV u e) = UnaryOpVV (uFuncVV u) (expr e) @@ -97,6 +109,8 @@ expr (E.OrdBinaryOp o l r) = OrdBinaryOp (ordBinOp o) (expr l) (expr r) expr (E.VVVBinaryOp v l r) = VVVBinaryOp (vvvBinOp v) (expr l) (expr r) expr (E.VVNBinaryOp v l r) = VVNBinaryOp (vvnBinOp v) (expr l) (expr r) expr (E.NVVBinaryOp v l r) = NVVBinaryOp (nvvBinOp v) (expr l) (expr r) +expr (E.ESSBinaryOp o l r) = ESSBinaryOp (essBinOp o) (expr l) (expr r) +expr (E.ESBBinaryOp o l r) = ESBBinaryOp (esbBinOp o) (expr l) (expr r) expr (E.Operator ao dd e) = Operator (assocArithOper ao) (domainDesc dd) (expr e) expr (E.RealI u ri) = RealI u (realInterval ri) diff --git a/code/drasil-lang/lib/Language/Drasil/ModelExpr/Development.hs b/code/drasil-lang/lib/Language/Drasil/ModelExpr/Development.hs index 964602a4ed..920ce3c11d 100644 --- a/code/drasil-lang/lib/Language/Drasil/ModelExpr/Development.hs +++ b/code/drasil-lang/lib/Language/Drasil/ModelExpr/Development.hs @@ -5,8 +5,8 @@ module Language.Drasil.ModelExpr.Development ( -- ModelExpr ModelExpr(..), UFunc(..), UFuncB(..), UFuncVV(..), UFuncVN(..) , ArithBinOp(..), BoolBinOp(..), EqBinOp(..), LABinOp(..), OrdBinOp(..) - , SpaceBinOp(..), StatBinOp(..), VVVBinOp(..), VVNBinOp(..), NVVBinOp(..) - , AssocArithOper(..), AssocBoolOper(..) + , SpaceBinOp(..), StatBinOp(..), VVVBinOp(..), VVNBinOp(..), NVVBinOp(..), ESSBinOp(..), ESBBinOp(..) + , AssocArithOper(..), AssocBoolOper(..), AssocConcatOper(..) , DerivType(..), Completeness(..) -- * Functions @@ -15,7 +15,7 @@ module Language.Drasil.ModelExpr.Development ( -- ModelExpr.Extract , meDep -- ModelExpr.Precedence - , mePrec, precB, precA + , mePrec,precC, precB, precA ) where import Language.Drasil.Expr.Lang (Completeness(..)) diff --git a/code/drasil-lang/lib/Language/Drasil/ModelExpr/Extract.hs b/code/drasil-lang/lib/Language/Drasil/ModelExpr/Extract.hs index d7ec4625d5..c813de45c6 100644 --- a/code/drasil-lang/lib/Language/Drasil/ModelExpr/Extract.hs +++ b/code/drasil-lang/lib/Language/Drasil/ModelExpr/Extract.hs @@ -11,6 +11,7 @@ import Language.Drasil.UID (UID) meNames :: ModelExpr -> [UID] meNames (AssocA _ l) = concatMap meNames l meNames (AssocB _ l) = concatMap meNames l +meNames (AssocC _ l) = concatMap meNames l meNames (Deriv _ _ a b) = b : meNames a meNames (C c) = [c] meNames Lit{} = [] @@ -32,8 +33,11 @@ meNames (OrdBinaryOp _ a b) = meNames a ++ meNames b meNames (VVVBinaryOp _ a b) = meNames a ++ meNames b meNames (VVNBinaryOp _ a b) = meNames a ++ meNames b meNames (NVVBinaryOp _ a b) = meNames a ++ meNames b +meNames (ESSBinaryOp _ _ s) = meNames s +meNames (ESBBinaryOp _ _ s) = meNames s meNames (Operator _ _ e) = meNames e meNames (Matrix a) = concatMap (concatMap meNames) a +meNames (Set a) = concatMap meNames a meNames (RealI c b) = c : meNamesRI b meNames (ForAll _ _ de) = meNames de @@ -49,6 +53,7 @@ meNamesRI (UpFrom (_, il)) = meNames il meNames' :: ModelExpr -> [UID] meNames' (AssocA _ l) = concatMap meNames' l meNames' (AssocB _ l) = concatMap meNames' l +meNames' (AssocC _ l) = concatMap meNames' l meNames' (Deriv _ _ a b) = b : meNames' a meNames' (C c) = [c] meNames' Lit{} = [] @@ -70,8 +75,11 @@ meNames' (StatBinaryOp _ a b) = meNames' a ++ meNames' b meNames' (VVVBinaryOp _ a b) = meNames' a ++ meNames' b meNames' (VVNBinaryOp _ a b) = meNames' a ++ meNames' b meNames' (NVVBinaryOp _ a b) = meNames' a ++ meNames' b +meNames' (ESSBinaryOp _ _ s) = meNames' s +meNames' (ESBBinaryOp _ _ s) = meNames' s meNames' (Operator _ _ e) = meNames' e meNames' (Matrix a) = concatMap (concatMap meNames') a +meNames' (Set a) = concatMap meNames' a meNames' (RealI c b) = c : meNamesRI' b meNames' (ForAll _ _ de) = meNames' de diff --git a/code/drasil-lang/lib/Language/Drasil/ModelExpr/Lang.hs b/code/drasil-lang/lib/Language/Drasil/ModelExpr/Lang.hs index 62695a7f29..b7444142f6 100644 --- a/code/drasil-lang/lib/Language/Drasil/ModelExpr/Lang.hs +++ b/code/drasil-lang/lib/Language/Drasil/ModelExpr/Lang.hs @@ -27,7 +27,7 @@ data BoolBinOp = Impl | Iff deriving Eq -- | Index operator. -data LABinOp = Index +data LABinOp = Index | IndexOf deriving Eq -- | Ordered binary operators (less than, greater than, less than or equal to, greater than or equal to). @@ -46,6 +46,17 @@ data VVNBinOp = Dot data NVVBinOp = Scale deriving Eq +-- | Element + Set -> Set +data ESSBinOp = SAdd | SRemove + deriving Eq + +-- | Element + Set -> Bool +data ESBBinOp = SContains + deriving Eq + +data AssocConcatOper = SUnion + deriving Eq + -- | Associative operators (adding and multiplication). Also specifies whether it is for integers or for real numbers. data AssocArithOper = Add | Mul deriving Eq @@ -97,6 +108,8 @@ data ModelExpr where AssocA :: AssocArithOper -> [ModelExpr] -> ModelExpr -- | Takes an associative boolean operator with a list of expressions. AssocB :: AssocBoolOper -> [ModelExpr] -> ModelExpr + + AssocC :: AssocConcatOper -> [ModelExpr] -> ModelExpr -- | Derivative syntax is: -- Type ('Part'ial or 'Total') -> principal part of change -> with respect to -- For example: Deriv Part y x1 would be (dy/dx1). @@ -110,7 +123,8 @@ data ModelExpr where Case :: Completeness -> [(ModelExpr, ModelExpr)] -> ModelExpr -- | Represents a matrix of expressions. Matrix :: [[ModelExpr]] -> ModelExpr - + -- | Represents a set of expressions + Set :: [ModelExpr] -> ModelExpr -- | Unary operation for most functions (eg. sin, cos, log, etc.). UnaryOp :: UFunc -> ModelExpr -> ModelExpr -- | Unary operation for @Bool -> Bool@ operations. @@ -140,6 +154,10 @@ data ModelExpr where VVNBinaryOp :: VVNBinOp -> ModelExpr -> ModelExpr -> ModelExpr -- | Binary operator for @Number x Vector -> Vector@ operations (scaling). NVVBinaryOp :: NVVBinOp -> ModelExpr -> ModelExpr -> ModelExpr + -- | Set operator for Element + Set -> Set + ESSBinaryOp :: ESSBinOp -> ModelExpr -> ModelExpr -> ModelExpr + -- | Set operator for Element + Set -> Bool + ESBBinaryOp :: ESBBinOp -> ModelExpr -> ModelExpr -> ModelExpr -- | Operators are generalized arithmetic operators over a 'DomainDesc' -- of an 'Expr'. Could be called BigOp. @@ -198,6 +216,8 @@ instance Eq ModelExpr where LABinaryOp o a b == LABinaryOp p c d = o == p && a == c && b == d VVVBinaryOp o a b == VVVBinaryOp p c d = o == p && a == c && b == d VVNBinaryOp o a b == VVNBinaryOp p c d = o == p && a == c && b == d + ESSBinaryOp o a b == ESSBinaryOp p c d = o == p && a == c && b == d + ESBBinaryOp o a b == ESBBinaryOp p c d = o == p && a == c && b == d _ == _ = False -- ^ TODO: This needs to add more equality checks diff --git a/code/drasil-lang/lib/Language/Drasil/ModelExpr/Precedence.hs b/code/drasil-lang/lib/Language/Drasil/ModelExpr/Precedence.hs index 92bc48528f..06dcee5294 100644 --- a/code/drasil-lang/lib/Language/Drasil/ModelExpr/Precedence.hs +++ b/code/drasil-lang/lib/Language/Drasil/ModelExpr/Precedence.hs @@ -47,6 +47,12 @@ prec2VVN _ = 190 prec2NVV :: NVVBinOp -> Int prec2NVV _ = 190 +prec2ESS :: ESSBinOp -> Int +prec2ESS _ = 190 + +prec2ESB :: ESBBinOp -> Int +prec2ESB _ = 190 + -- | precA - precedence for arithmetic-related Binary-Associative (Commutative) operators. precA :: AssocArithOper -> Int precA Mul = 190 @@ -58,6 +64,9 @@ precB And = 120 precB Or = 110 precB Equivalence = 100 +precC :: AssocConcatOper -> Int +precC SUnion = 180 + -- | prec1 - precedence of unary operators. prec1 :: UFunc -> Int prec1 Neg = 230 @@ -82,11 +91,13 @@ mePrec Lit{} = 500 mePrec Spc{} = 500 mePrec (AssocA op _) = precA op mePrec (AssocB op _) = precB op +mePrec (AssocC op _) = precC op mePrec C{} = 500 mePrec Deriv{} = prec2Arith Frac mePrec FCall{} = 210 mePrec Case{} = 200 mePrec Matrix{} = 220 +mePrec Set{} = 220 mePrec (UnaryOp fn _) = prec1 fn mePrec (UnaryOpB fn _) = prec1B fn mePrec (UnaryOpVV fn _) = prec1VV fn @@ -102,5 +113,7 @@ mePrec (OrdBinaryOp bo _ _) = prec2Ord bo mePrec (VVVBinaryOp bo _ _) = prec2VVV bo mePrec (VVNBinaryOp bo _ _) = prec2VVN bo mePrec (NVVBinaryOp bo _ _) = prec2NVV bo +mePrec (ESSBinaryOp bo _ _) = prec2ESS bo +mePrec (ESBBinaryOp bo _ _) = prec2ESB bo mePrec RealI{} = 170 mePrec ForAll{} = 130 diff --git a/code/drasil-lang/lib/Language/Drasil/Sentence/Fold.hs b/code/drasil-lang/lib/Language/Drasil/Sentence/Fold.hs index 6f8583e589..f4f233ee0b 100644 --- a/code/drasil-lang/lib/Language/Drasil/Sentence/Fold.hs +++ b/code/drasil-lang/lib/Language/Drasil/Sentence/Fold.hs @@ -31,6 +31,7 @@ foldConstraints c e = E $ foldr1 ($&&) $ map constraintToExpr e where constraintToExpr (Range _ ri) = express $ realInterval c ri + -- | Partial function application of 'foldle' for sentences specifically. -- Folds with spaces and adds a period (".") at the end. foldlSent :: [Sentence] -> Sentence diff --git a/code/drasil-lang/lib/Language/Drasil/Space.hs b/code/drasil-lang/lib/Language/Drasil/Space.hs index b0c16092a7..82d2a22481 100644 --- a/code/drasil-lang/lib/Language/Drasil/Space.hs +++ b/code/drasil-lang/lib/Language/Drasil/Space.hs @@ -37,6 +37,7 @@ data Space = | Char | String | Vect Space -- TODO: Length for vectors? + | Set Space | Matrix Int Int Space | Array Space | Actor String @@ -86,9 +87,10 @@ getActorName :: Space -> String getActorName (Actor n) = n getActorName _ = error "getActorName called on non-actor space" --- | Gets the inner 'Space' of a vector. +-- | Gets the inner 'Space' of a vector or set. getInnerSpace :: Space -> Space getInnerSpace (Vect s) = s +--getInnerSpace (Set s) = s getInnerSpace _ = error "getInnerSpace called on non-vector space" -- | Is this Space a basic numeric space? @@ -100,6 +102,7 @@ isBasicNumSpace Natural = True isBasicNumSpace Boolean = False isBasicNumSpace Char = False isBasicNumSpace String = False +isBasicNumSpace Set {} = False isBasicNumSpace Vect {} = False isBasicNumSpace Matrix {} = False isBasicNumSpace Array {} = False diff --git a/code/drasil-printers/lib/Language/Drasil/Printing/AST.hs b/code/drasil-printers/lib/Language/Drasil/Printing/AST.hs index 7df5be8785..43dfb0a428 100644 --- a/code/drasil-printers/lib/Language/Drasil/Printing/AST.hs +++ b/code/drasil-printers/lib/Language/Drasil/Printing/AST.hs @@ -12,7 +12,7 @@ data Ops = IsIn | Integer | Real | Rational | Natural | Boolean | Comma | Prime | Ln | Sin | Cos | Tan | Sec | Csc | Cot | Arcsin | Arccos | Arctan | Not | Dim | Exp | Neg | Cross | Dot | Scale | Eq | NEq | Lt | Gt | LEq | GEq | Impl | Iff | Subt | And | Or | Add | Mul | Summ | Inte | Prod | Point | Perc | LArrow | RArrow | ForAll - | VAdd | VSub | Partial + | VAdd | VSub | Partial | SAdd | SRemove | SUnion | SContains -- | Holds the type of "text fencing" ("(), {}, |, ||"). data Fence = Paren | Curly | Norm | Abs @@ -31,6 +31,7 @@ data Expr = Dbl Double | Str String | Case [(Expr, Expr)] -- ^ Case expressions | Mtx [[Expr]] -- ^ Matrix. + | Set [Expr] | Row [Expr] | Ident String | Label String diff --git a/code/drasil-printers/lib/Language/Drasil/Printing/Import/CodeExpr.hs b/code/drasil-printers/lib/Language/Drasil/Printing/Import/CodeExpr.hs index acaf4dba7b..35f22af98e 100644 --- a/code/drasil-printers/lib/Language/Drasil/Printing/Import/CodeExpr.hs +++ b/code/drasil-printers/lib/Language/Drasil/Printing/Import/CodeExpr.hs @@ -108,8 +108,9 @@ codeExpr :: CodeExpr -> PrintingInformation -> P.Expr codeExpr (Lit l) sm = literal l sm codeExpr (AssocB And l) sm = assocExpr P.And (precB And) l sm codeExpr (AssocB Or l) sm = assocExpr P.Or (precB Or) l sm -codeExpr (AssocA Add l) sm = P.Row $ addExpr l Add sm -codeExpr (AssocA Mul l) sm = P.Row $ mulExpr l Mul sm +codeExpr (AssocA Add l) sm = P.Row $ addExpr l Add sm +codeExpr (AssocA Mul l) sm = P.Row $ mulExpr l Mul sm +codeExpr (AssocC SUnion l) sm = P.Row $ mulExpr l Mul sm codeExpr (C c) sm = symbol $ lookupC (sm ^. stg) (sm ^. ckdb) c codeExpr (FCall f [x] []) sm = P.Row [symbol $ lookupC (sm ^. stg) (sm ^. ckdb) f, parens $ codeExpr x sm] @@ -123,45 +124,49 @@ codeExpr (Case _ ps) sm = if length ps < 2 then error "Attempting to use multi-case codeExpr incorrectly" else P.Case (zip (map (flip codeExpr sm . fst) ps) (map (flip codeExpr sm . snd) ps)) -codeExpr (Matrix a) sm = P.Mtx $ map (map (`codeExpr` sm)) a -codeExpr (UnaryOp Log u) sm = mkCall sm P.Log u -codeExpr (UnaryOp Ln u) sm = mkCall sm P.Ln u -codeExpr (UnaryOp Sin u) sm = mkCall sm P.Sin u -codeExpr (UnaryOp Cos u) sm = mkCall sm P.Cos u -codeExpr (UnaryOp Tan u) sm = mkCall sm P.Tan u -codeExpr (UnaryOp Sec u) sm = mkCall sm P.Sec u -codeExpr (UnaryOp Csc u) sm = mkCall sm P.Csc u -codeExpr (UnaryOp Cot u) sm = mkCall sm P.Cot u -codeExpr (UnaryOp Arcsin u) sm = mkCall sm P.Arcsin u -codeExpr (UnaryOp Arccos u) sm = mkCall sm P.Arccos u -codeExpr (UnaryOp Arctan u) sm = mkCall sm P.Arctan u -codeExpr (UnaryOp Exp u) sm = P.Row [P.MO P.Exp, P.Sup $ codeExpr u sm] -codeExpr (UnaryOp Abs u) sm = P.Fenced P.Abs P.Abs $ codeExpr u sm -codeExpr (UnaryOpB Not u) sm = P.Row [P.MO P.Not, codeExpr u sm] -codeExpr (UnaryOpVN Norm u) sm = P.Fenced P.Norm P.Norm $ codeExpr u sm -codeExpr (UnaryOpVN Dim u) sm = mkCall sm P.Dim u -codeExpr (UnaryOp Sqrt u) sm = P.Sqrt $ codeExpr u sm -codeExpr (UnaryOp Neg u) sm = neg sm u -codeExpr (UnaryOpVV NegV u) sm = neg sm u -codeExpr (ArithBinaryOp Frac a b) sm = P.Div (codeExpr a sm) (codeExpr b sm) -codeExpr (ArithBinaryOp Pow a b) sm = pow sm a b -codeExpr (ArithBinaryOp Subt a b) sm = P.Row [codeExpr a sm, P.MO P.Subt, codeExpr b sm] -codeExpr (BoolBinaryOp Impl a b) sm = mkBOp sm P.Impl a b -codeExpr (BoolBinaryOp Iff a b) sm = mkBOp sm P.Iff a b -codeExpr (EqBinaryOp Eq a b) sm = mkBOp sm P.Eq a b -codeExpr (EqBinaryOp NEq a b) sm = mkBOp sm P.NEq a b -codeExpr (LABinaryOp Index a b) sm = indx sm a b -codeExpr (OrdBinaryOp Lt a b) sm = mkBOp sm P.Lt a b -codeExpr (OrdBinaryOp Gt a b) sm = mkBOp sm P.Gt a b -codeExpr (OrdBinaryOp LEq a b) sm = mkBOp sm P.LEq a b -codeExpr (OrdBinaryOp GEq a b) sm = mkBOp sm P.GEq a b -codeExpr (VVNBinaryOp Dot a b) sm = mkBOp sm P.Dot a b -codeExpr (VVVBinaryOp Cross a b) sm = mkBOp sm P.Cross a b -codeExpr (VVVBinaryOp VAdd a b) sm = mkBOp sm P.VAdd a b -codeExpr (VVVBinaryOp VSub a b) sm = mkBOp sm P.VSub a b -codeExpr (NVVBinaryOp Scale a b) sm = mkBOp sm P.Scale a b -codeExpr (Operator o d e) sm = eop sm o d e -codeExpr (RealI c ri) sm = renderRealInt sm (lookupC (sm ^. stg) +codeExpr (Matrix a) sm = P.Mtx $ map (map (`codeExpr` sm)) a +codeExpr (Set a) sm = P.Row $ map (`codeExpr` sm) a +codeExpr (UnaryOp Log u) sm = mkCall sm P.Log u +codeExpr (UnaryOp Ln u) sm = mkCall sm P.Ln u +codeExpr (UnaryOp Sin u) sm = mkCall sm P.Sin u +codeExpr (UnaryOp Cos u) sm = mkCall sm P.Cos u +codeExpr (UnaryOp Tan u) sm = mkCall sm P.Tan u +codeExpr (UnaryOp Sec u) sm = mkCall sm P.Sec u +codeExpr (UnaryOp Csc u) sm = mkCall sm P.Csc u +codeExpr (UnaryOp Cot u) sm = mkCall sm P.Cot u +codeExpr (UnaryOp Arcsin u) sm = mkCall sm P.Arcsin u +codeExpr (UnaryOp Arccos u) sm = mkCall sm P.Arccos u +codeExpr (UnaryOp Arctan u) sm = mkCall sm P.Arctan u +codeExpr (UnaryOp Exp u) sm = P.Row [P.MO P.Exp, P.Sup $ codeExpr u sm] +codeExpr (UnaryOp Abs u) sm = P.Fenced P.Abs P.Abs $ codeExpr u sm +codeExpr (UnaryOpB Not u) sm = P.Row [P.MO P.Not, codeExpr u sm] +codeExpr (UnaryOpVN Norm u) sm = P.Fenced P.Norm P.Norm $ codeExpr u sm +codeExpr (UnaryOpVN Dim u) sm = mkCall sm P.Dim u +codeExpr (UnaryOp Sqrt u) sm = P.Sqrt $ codeExpr u sm +codeExpr (UnaryOp Neg u) sm = neg sm u +codeExpr (UnaryOpVV NegV u) sm = neg sm u +codeExpr (ArithBinaryOp Frac a b) sm = P.Div (codeExpr a sm) (codeExpr b sm) +codeExpr (ArithBinaryOp Pow a b) sm = pow sm a b +codeExpr (ArithBinaryOp Subt a b) sm = P.Row [codeExpr a sm, P.MO P.Subt, codeExpr b sm] +codeExpr (BoolBinaryOp Impl a b) sm = mkBOp sm P.Impl a b +codeExpr (BoolBinaryOp Iff a b) sm = mkBOp sm P.Iff a b +codeExpr (EqBinaryOp Eq a b) sm = mkBOp sm P.Eq a b +codeExpr (EqBinaryOp NEq a b) sm = mkBOp sm P.NEq a b +codeExpr (LABinaryOp Index a b) sm = indx sm a b +codeExpr (OrdBinaryOp Lt a b) sm = mkBOp sm P.Lt a b +codeExpr (OrdBinaryOp Gt a b) sm = mkBOp sm P.Gt a b +codeExpr (OrdBinaryOp LEq a b) sm = mkBOp sm P.LEq a b +codeExpr (OrdBinaryOp GEq a b) sm = mkBOp sm P.GEq a b +codeExpr (VVNBinaryOp Dot a b) sm = mkBOp sm P.Dot a b +codeExpr (VVVBinaryOp Cross a b) sm = mkBOp sm P.Cross a b +codeExpr (VVVBinaryOp VAdd a b) sm = mkBOp sm P.VAdd a b +codeExpr (VVVBinaryOp VSub a b) sm = mkBOp sm P.VSub a b +codeExpr (NVVBinaryOp Scale a b) sm = mkBOp sm P.Scale a b +codeExpr (ESSBinaryOp SAdd a b) sm = mkBOp sm P.SAdd a b +codeExpr (ESSBinaryOp SRemove a b) sm = mkBOp sm P.SRemove a b +codeExpr (ESBBinaryOp SContains a b) sm = mkBOp sm P.SContains a b +codeExpr (Operator o d e) sm = eop sm o d e +codeExpr (RealI c ri) sm = renderRealInt sm (lookupC (sm ^. stg) (sm ^. ckdb) c) ri -- | Common method of converting associative operations into printable layout AST. diff --git a/code/drasil-printers/lib/Language/Drasil/Printing/Import/ModelExpr.hs b/code/drasil-printers/lib/Language/Drasil/Printing/Import/ModelExpr.hs index 369c712757..ebace61636 100644 --- a/code/drasil-printers/lib/Language/Drasil/Printing/Import/ModelExpr.hs +++ b/code/drasil-printers/lib/Language/Drasil/Printing/Import/ModelExpr.hs @@ -115,8 +115,9 @@ modelExpr (Lit l) sm = literal l sm modelExpr (AssocB And l) sm = assocExpr P.And (precB And) l sm modelExpr (AssocB Or l) sm = assocExpr P.Or (precB Or) l sm modelExpr (AssocB Equivalence l) sm = assocExpr P.Eq (precB Equivalence) l sm -modelExpr (AssocA Add l) sm = P.Row $ addExpr l Add sm -modelExpr (AssocA Mul l) sm = P.Row $ mulExpr l Mul sm +modelExpr (AssocA Add l) sm = P.Row $ addExpr l Add sm +modelExpr (AssocA Mul l) sm = P.Row $ mulExpr l Mul sm +modelExpr (AssocC SUnion l) sm = assocExpr P.SUnion (precC SUnion) l sm modelExpr (Deriv 0 Part a _) sm = P.Row [modelExpr a sm] modelExpr (Deriv 0 Total a _) sm = P.Row [modelExpr a sm] modelExpr (Deriv n Part a b) sm = @@ -136,6 +137,7 @@ modelExpr (Case _ ps) sm = then error "Attempting to use multi-case modelExpr incorrectly" else P.Case (zip (map (flip modelExpr sm . fst) ps) (map (flip modelExpr sm . snd) ps)) modelExpr (Matrix a) sm = P.Mtx $ map (map (`modelExpr` sm)) a +modelExpr (Set a) sm = P.Set $ map (`modelExpr` sm) a modelExpr (UnaryOp Log u) sm = mkCall sm P.Log u modelExpr (UnaryOp Ln u) sm = mkCall sm P.Ln u modelExpr (UnaryOp Sin u) sm = mkCall sm P.Sin u @@ -172,6 +174,9 @@ modelExpr (VVVBinaryOp Cross a b) sm = mkBOp sm P.Cross a b modelExpr (VVVBinaryOp VAdd a b) sm = mkBOp sm P.VAdd a b modelExpr (VVVBinaryOp VSub a b) sm = mkBOp sm P.VSub a b modelExpr (NVVBinaryOp Scale a b) sm = mkBOp sm P.Scale a b +modelExpr (ESSBinaryOp SAdd a b) sm = mkBOp sm P.SAdd a b +modelExpr (ESSBinaryOp SRemove a b) sm = mkBOp sm P.SRemove a b +modelExpr (ESBBinaryOp SContains a b) sm = mkBOp sm P.SContains a b modelExpr (Operator o d e) sm = eop sm o d e modelExpr (RealI c ri) sm = renderRealInt sm (lookupC (sm ^. stg) (sm ^. ckdb) c) ri