jsonlogic-hs 0.1.0.0 → 0.2.0.0
raw patch · 41 files changed
+3264/−576 lines, 41 filesdep +deepseqdep +ghc-bignumnew-component:exe:jsonlogicPVP ok
version bump matches the API change (PVP)
Dependencies added: deepseq, ghc-bignum
API changes (from Hackage documentation)
- JsonLogic: Config :: Int -> Int -> Int -> Int -> ArityMode -> Config
- JsonLogic: [arityMode] :: Config -> ArityMode
- JsonLogic: [maxArrayLength] :: Config -> Int
- JsonLogic: [maxDepth] :: Config -> Int
- JsonLogic: [maxSteps] :: Config -> Int
- JsonLogic: [maxStringLength] :: Config -> Int
- JsonLogic: type CustomOperator = Value -> [Value] -> Either Text Value
- JsonLogic.Core.Analysis: DataUse :: [Text] -> Bool -> DataUse
- JsonLogic.Core.Analysis: [usedPaths] :: DataUse -> [Text]
- JsonLogic.Core.Analysis: [usesAllData] :: DataUse -> Bool
- JsonLogic.Core.Analysis: data DataUse
- JsonLogic.Core.Analysis: dataUse :: Rule -> DataUse
- JsonLogic.Core.Analysis: instance GHC.Internal.Base.Monoid JsonLogic.Core.Analysis.Reads
- JsonLogic.Core.Analysis: instance GHC.Internal.Base.Semigroup JsonLogic.Core.Analysis.Reads
- JsonLogic.Core.Analysis: instance GHC.Internal.Classes.Eq JsonLogic.Core.Analysis.DataUse
- JsonLogic.Core.Analysis: instance GHC.Internal.Show.Show JsonLogic.Core.Analysis.DataUse
- JsonLogic.Core.Config: Config :: Int -> Int -> Int -> Int -> ArityMode -> Config
- JsonLogic.Core.Config: Lenient :: ArityMode
- JsonLogic.Core.Config: Strict :: ArityMode
- JsonLogic.Core.Config: [arityMode] :: Config -> ArityMode
- JsonLogic.Core.Config: [maxArrayLength] :: Config -> Int
- JsonLogic.Core.Config: [maxDepth] :: Config -> Int
- JsonLogic.Core.Config: [maxSteps] :: Config -> Int
- JsonLogic.Core.Config: [maxStringLength] :: Config -> Int
- JsonLogic.Core.Config: data ArityMode
- JsonLogic.Core.Config: data Config
- JsonLogic.Core.Config: defaultConfig :: Config
- JsonLogic.Core.Config: instance GHC.Internal.Classes.Eq JsonLogic.Core.Config.ArityMode
- JsonLogic.Core.Config: instance GHC.Internal.Classes.Eq JsonLogic.Core.Config.Config
- JsonLogic.Core.Config: instance GHC.Internal.Show.Show JsonLogic.Core.Config.ArityMode
- JsonLogic.Core.Config: instance GHC.Internal.Show.Show JsonLogic.Core.Config.Config
- JsonLogic.Core.Custom: data Operators
- JsonLogic.Core.Custom: instance GHC.Internal.Base.Monoid JsonLogic.Core.Custom.Operators
- JsonLogic.Core.Custom: instance GHC.Internal.Base.Semigroup JsonLogic.Core.Custom.Operators
- JsonLogic.Core.Custom: lookupOperator :: Operators -> OperatorName -> Maybe CustomOperator
- JsonLogic.Core.Custom: noOperators :: Operators
- JsonLogic.Core.Custom: operatorsFromList :: [(OperatorName, CustomOperator)] -> Either OperatorsError Operators
- JsonLogic.Core.Custom: type CustomOperator = Value -> [Value] -> Either Text Value
- JsonLogic.Core.Errors: ArityMismatch :: OperatorName -> Arity -> Int -> ParseError
- JsonLogic.Core.Errors: ArrayLimit :: Int -> LimitKind
- JsonLogic.Core.Errors: AtLeast :: Int -> Arity
- JsonLogic.Core.Errors: Between :: Int -> Int -> Arity
- JsonLogic.Core.Errors: CustomOperatorFailed :: OperatorName -> Text -> EvalError
- JsonLogic.Core.Errors: DepthExceeded :: Int -> ParseError
- JsonLogic.Core.Errors: DuplicateOperatorName :: OperatorName -> OperatorsError
- JsonLogic.Core.Errors: EvalFailure :: Location -> EvalError -> Error
- JsonLogic.Core.Errors: Exactly :: Int -> Arity
- JsonLogic.Core.Errors: InvalidOperand :: OperatorName -> EvalError
- JsonLogic.Core.Errors: LimitExceeded :: LimitKind -> EvalError
- JsonLogic.Core.Errors: ParseFailure :: Location -> ParseError -> Error
- JsonLogic.Core.Errors: ReservedOperatorName :: OperatorName -> OperatorsError
- JsonLogic.Core.Errors: StepLimit :: Int -> LimitKind
- JsonLogic.Core.Errors: StringLimit :: Int -> LimitKind
- JsonLogic.Core.Errors: UnknownOperator :: OperatorName -> EvalError
- JsonLogic.Core.Errors: ValueDepthLimit :: Int -> LimitKind
- JsonLogic.Core.Errors: data Arity
- JsonLogic.Core.Errors: data Error
- JsonLogic.Core.Errors: data EvalError
- JsonLogic.Core.Errors: data LimitKind
- JsonLogic.Core.Errors: data OperatorsError
- JsonLogic.Core.Errors: data ParseError
- JsonLogic.Core.Errors: errorLocation :: Error -> Location
- JsonLogic.Core.Errors: instance GHC.Internal.Classes.Eq JsonLogic.Core.Errors.Arity
- JsonLogic.Core.Errors: instance GHC.Internal.Classes.Eq JsonLogic.Core.Errors.Error
- JsonLogic.Core.Errors: instance GHC.Internal.Classes.Eq JsonLogic.Core.Errors.EvalError
- JsonLogic.Core.Errors: instance GHC.Internal.Classes.Eq JsonLogic.Core.Errors.LimitKind
- JsonLogic.Core.Errors: instance GHC.Internal.Classes.Eq JsonLogic.Core.Errors.OperatorsError
- JsonLogic.Core.Errors: instance GHC.Internal.Classes.Eq JsonLogic.Core.Errors.ParseError
- JsonLogic.Core.Errors: instance GHC.Internal.Show.Show JsonLogic.Core.Errors.Arity
- JsonLogic.Core.Errors: instance GHC.Internal.Show.Show JsonLogic.Core.Errors.Error
- JsonLogic.Core.Errors: instance GHC.Internal.Show.Show JsonLogic.Core.Errors.EvalError
- JsonLogic.Core.Errors: instance GHC.Internal.Show.Show JsonLogic.Core.Errors.LimitKind
- JsonLogic.Core.Errors: instance GHC.Internal.Show.Show JsonLogic.Core.Errors.OperatorsError
- JsonLogic.Core.Errors: instance GHC.Internal.Show.Show JsonLogic.Core.Errors.ParseError
- JsonLogic.Core.Errors: renderError :: Error -> Text
- JsonLogic.Core.Errors: renderEvalError :: EvalError -> Text
- JsonLogic.Core.Errors: renderParseError :: ParseError -> Text
- JsonLogic.Core.Eval: compileRule :: Config -> Operators -> Rule -> Program
- JsonLogic.Core.Eval: data Program
- JsonLogic.Core.Eval: evaluate :: Rule -> Value -> Either (Location, EvalError) Value
- JsonLogic.Core.Eval: instance GHC.Internal.Base.Applicative JsonLogic.Core.Eval.Run
- JsonLogic.Core.Eval: instance GHC.Internal.Base.Functor JsonLogic.Core.Eval.Run
- JsonLogic.Core.Eval: instance GHC.Internal.Base.Monad JsonLogic.Core.Eval.Run
- JsonLogic.Core.Eval: runProgram :: Program -> Value -> Either (Location, EvalError) Value
- JsonLogic.Core.Location: Index :: Int -> Segment
- JsonLogic.Core.Location: Key :: Text -> Segment
- JsonLogic.Core.Location: child :: Location -> Segment -> Location
- JsonLogic.Core.Location: data Location
- JsonLogic.Core.Location: data Segment
- JsonLogic.Core.Location: fromSegments :: [Segment] -> Location
- JsonLogic.Core.Location: instance GHC.Internal.Classes.Eq JsonLogic.Core.Location.Location
- JsonLogic.Core.Location: instance GHC.Internal.Classes.Eq JsonLogic.Core.Location.Segment
- JsonLogic.Core.Location: instance GHC.Internal.Classes.Ord JsonLogic.Core.Location.Location
- JsonLogic.Core.Location: instance GHC.Internal.Classes.Ord JsonLogic.Core.Location.Segment
- JsonLogic.Core.Location: instance GHC.Internal.Show.Show JsonLogic.Core.Location.Location
- JsonLogic.Core.Location: instance GHC.Internal.Show.Show JsonLogic.Core.Location.Segment
- JsonLogic.Core.Location: locationSegments :: Location -> [Segment]
- JsonLogic.Core.Location: renderLocation :: Location -> Text
- JsonLogic.Core.Location: root :: Location
- JsonLogic.Core.Number: decimalToDouble :: Integer -> Integer -> Double
- JsonLogic.Core.Number: doubleToScientific :: Double -> Scientific
- JsonLogic.Core.Number: isJsSpace :: Char -> Bool
- JsonLogic.Core.Number: maximumJs :: [Double] -> Double
- JsonLogic.Core.Number: minimumJs :: [Double] -> Double
- JsonLogic.Core.Number: numberToString :: Double -> Text
- JsonLogic.Core.Number: parseFloatString :: Text -> Double
- JsonLogic.Core.Number: remainderJs :: Double -> Double -> Double
- JsonLogic.Core.Number: scientificToDouble :: Scientific -> Double
- JsonLogic.Core.Number: shortestDigits :: Double -> ([Int], Int)
- JsonLogic.Core.Number: shortestDigitsExact :: Double -> ([Int], Int)
- JsonLogic.Core.Number: stringToNumber :: Text -> Double
- JsonLogic.Core.Operator: BAdd :: Builtin
- JsonLogic.Core.Operator: BAll :: Builtin
- JsonLogic.Core.Operator: BAnd :: Builtin
- JsonLogic.Core.Operator: BCat :: Builtin
- JsonLogic.Core.Operator: BDiv :: Builtin
- JsonLogic.Core.Operator: BDoubleNot :: Builtin
- JsonLogic.Core.Operator: BFilter :: Builtin
- JsonLogic.Core.Operator: BGt :: Builtin
- JsonLogic.Core.Operator: BGte :: Builtin
- JsonLogic.Core.Operator: BIf :: Builtin
- JsonLogic.Core.Operator: BIn :: Builtin
- JsonLogic.Core.Operator: BLog :: Builtin
- JsonLogic.Core.Operator: BLooseEq :: Builtin
- JsonLogic.Core.Operator: BLooseNeq :: Builtin
- JsonLogic.Core.Operator: BLt :: Builtin
- JsonLogic.Core.Operator: BLte :: Builtin
- JsonLogic.Core.Operator: BMap :: Builtin
- JsonLogic.Core.Operator: BMax :: Builtin
- JsonLogic.Core.Operator: BMerge :: Builtin
- JsonLogic.Core.Operator: BMin :: Builtin
- JsonLogic.Core.Operator: BMissing :: Builtin
- JsonLogic.Core.Operator: BMissingSome :: Builtin
- JsonLogic.Core.Operator: BMod :: Builtin
- JsonLogic.Core.Operator: BMul :: Builtin
- JsonLogic.Core.Operator: BNone :: Builtin
- JsonLogic.Core.Operator: BNot :: Builtin
- JsonLogic.Core.Operator: BOr :: Builtin
- JsonLogic.Core.Operator: BReduce :: Builtin
- JsonLogic.Core.Operator: BSome :: Builtin
- JsonLogic.Core.Operator: BStrictEq :: Builtin
- JsonLogic.Core.Operator: BStrictNeq :: Builtin
- JsonLogic.Core.Operator: BSub :: Builtin
- JsonLogic.Core.Operator: BSubstr :: Builtin
- JsonLogic.Core.Operator: BTernary :: Builtin
- JsonLogic.Core.Operator: BVar :: Builtin
- JsonLogic.Core.Operator: OperatorName :: Text -> OperatorName
- JsonLogic.Core.Operator: allBuiltins :: [Builtin]
- JsonLogic.Core.Operator: builtinName :: Builtin -> Text
- JsonLogic.Core.Operator: builtinOperatorName :: Builtin -> OperatorName
- JsonLogic.Core.Operator: data Builtin
- JsonLogic.Core.Operator: instance GHC.Internal.Classes.Eq JsonLogic.Core.Operator.Builtin
- JsonLogic.Core.Operator: instance GHC.Internal.Classes.Eq JsonLogic.Core.Operator.OperatorName
- JsonLogic.Core.Operator: instance GHC.Internal.Classes.Ord JsonLogic.Core.Operator.Builtin
- JsonLogic.Core.Operator: instance GHC.Internal.Classes.Ord JsonLogic.Core.Operator.OperatorName
- JsonLogic.Core.Operator: instance GHC.Internal.Enum.Bounded JsonLogic.Core.Operator.Builtin
- JsonLogic.Core.Operator: instance GHC.Internal.Enum.Enum JsonLogic.Core.Operator.Builtin
- JsonLogic.Core.Operator: instance GHC.Internal.Show.Show JsonLogic.Core.Operator.Builtin
- JsonLogic.Core.Operator: instance GHC.Internal.Show.Show JsonLogic.Core.Operator.OperatorName
- JsonLogic.Core.Operator: lookupBuiltin :: Text -> Maybe Builtin
- JsonLogic.Core.Operator: newtype OperatorName
- JsonLogic.Core.Parse: parseRule :: Value -> Either (Location, ParseError) Rule
- JsonLogic.Core.Parse: parseRuleWith :: Config -> Value -> Either (Location, ParseError) Rule
- JsonLogic.Core.Rule: Add :: [a] -> RuleF a
- JsonLogic.Core.Rule: All :: a -> a -> RuleF a
- JsonLogic.Core.Rule: And :: [a] -> RuleF a
- JsonLogic.Core.Rule: Arr :: [a] -> RuleF a
- JsonLogic.Core.Rule: Cat :: [a] -> RuleF a
- JsonLogic.Core.Rule: CustomOp :: OperatorName -> [a] -> RuleF a
- JsonLogic.Core.Rule: Discard :: a -> [a] -> RuleF a
- JsonLogic.Core.Rule: Div :: a -> a -> RuleF a
- JsonLogic.Core.Rule: DoubleNot :: a -> RuleF a
- JsonLogic.Core.Rule: Filter :: a -> a -> RuleF a
- JsonLogic.Core.Rule: Gt :: a -> a -> RuleF a
- JsonLogic.Core.Rule: Gte :: a -> a -> RuleF a
- JsonLogic.Core.Rule: If :: [a] -> RuleF a
- JsonLogic.Core.Rule: In :: a -> a -> RuleF a
- JsonLogic.Core.Rule: Lit :: Value -> RuleF a
- JsonLogic.Core.Rule: Log :: a -> RuleF a
- JsonLogic.Core.Rule: LooseEq :: a -> a -> RuleF a
- JsonLogic.Core.Rule: LooseNeq :: a -> a -> RuleF a
- JsonLogic.Core.Rule: Lt :: a -> a -> Maybe a -> RuleF a
- JsonLogic.Core.Rule: Lte :: a -> a -> Maybe a -> RuleF a
- JsonLogic.Core.Rule: Map :: a -> a -> RuleF a
- JsonLogic.Core.Rule: Max :: [a] -> RuleF a
- JsonLogic.Core.Rule: Merge :: [a] -> RuleF a
- JsonLogic.Core.Rule: Min :: [a] -> RuleF a
- JsonLogic.Core.Rule: Missing :: [a] -> RuleF a
- JsonLogic.Core.Rule: MissingSome :: a -> a -> RuleF a
- JsonLogic.Core.Rule: Mod :: a -> a -> RuleF a
- JsonLogic.Core.Rule: Mul :: [a] -> RuleF a
- JsonLogic.Core.Rule: Node :: Location -> RuleF a -> Node a
- JsonLogic.Core.Rule: None :: a -> a -> RuleF a
- JsonLogic.Core.Rule: Not :: a -> RuleF a
- JsonLogic.Core.Rule: Or :: [a] -> RuleF a
- JsonLogic.Core.Rule: Reduce :: a -> a -> a -> RuleF a
- JsonLogic.Core.Rule: Some :: a -> a -> RuleF a
- JsonLogic.Core.Rule: StrictEq :: a -> a -> RuleF a
- JsonLogic.Core.Rule: StrictNeq :: a -> a -> RuleF a
- JsonLogic.Core.Rule: Sub :: a -> Maybe a -> RuleF a
- JsonLogic.Core.Rule: Substr :: a -> a -> Maybe a -> RuleF a
- JsonLogic.Core.Rule: Var :: a -> Maybe a -> RuleF a
- JsonLogic.Core.Rule: [nodeLocation] :: Node a -> Location
- JsonLogic.Core.Rule: [nodeRule] :: Node a -> RuleF a
- JsonLogic.Core.Rule: data Node a
- JsonLogic.Core.Rule: data RuleF a
- JsonLogic.Core.Rule: instance Data.Functor.Classes.Eq1 JsonLogic.Core.Rule.Node
- JsonLogic.Core.Rule: instance Data.Functor.Classes.Eq1 JsonLogic.Core.Rule.RuleF
- JsonLogic.Core.Rule: instance Data.Functor.Classes.Show1 JsonLogic.Core.Rule.Node
- JsonLogic.Core.Rule: instance Data.Functor.Classes.Show1 JsonLogic.Core.Rule.RuleF
- JsonLogic.Core.Rule: instance GHC.Internal.Base.Functor JsonLogic.Core.Rule.Node
- JsonLogic.Core.Rule: instance GHC.Internal.Base.Functor JsonLogic.Core.Rule.RuleF
- JsonLogic.Core.Rule: instance GHC.Internal.Classes.Eq a => GHC.Internal.Classes.Eq (JsonLogic.Core.Rule.Node a)
- JsonLogic.Core.Rule: instance GHC.Internal.Classes.Eq a => GHC.Internal.Classes.Eq (JsonLogic.Core.Rule.RuleF a)
- JsonLogic.Core.Rule: instance GHC.Internal.Data.Foldable.Foldable JsonLogic.Core.Rule.Node
- JsonLogic.Core.Rule: instance GHC.Internal.Data.Foldable.Foldable JsonLogic.Core.Rule.RuleF
- JsonLogic.Core.Rule: instance GHC.Internal.Data.Traversable.Traversable JsonLogic.Core.Rule.Node
- JsonLogic.Core.Rule: instance GHC.Internal.Data.Traversable.Traversable JsonLogic.Core.Rule.RuleF
- JsonLogic.Core.Rule: instance GHC.Internal.Show.Show JsonLogic.Core.Rule.Shown
- JsonLogic.Core.Rule: instance GHC.Internal.Show.Show a => GHC.Internal.Show.Show (JsonLogic.Core.Rule.Node a)
- JsonLogic.Core.Rule: instance GHC.Internal.Show.Show a => GHC.Internal.Show.Show (JsonLogic.Core.Rule.RuleF a)
- JsonLogic.Core.Rule: stripLocations :: Rule -> Term
- JsonLogic.Core.Rule: type Rule = Fix Node
- JsonLogic.Core.Rule: type Term = Fix RuleF
- JsonLogic.Core.Ryu: shortestDecimalRyu :: Double -> (Word64, Int)
- JsonLogic.Core.Utf16: compareUtf16 :: Text -> Text -> Ordering
- JsonLogic.Core.Utf16: fromUtf16Units :: [Word16] -> Text
- JsonLogic.Core.Utf16: utf16CharAt :: Int -> Text -> Maybe Text
- JsonLogic.Core.Utf16: utf16Length :: Text -> Int
- JsonLogic.Core.Utf16: utf16Slice :: Int -> Int -> Text -> Text
- JsonLogic.Core.Utf16: utf16Units :: Text -> [Word16]
- JsonLogic.Core.Value: VArr :: Vector Val -> Val
- JsonLogic.Core.Value: VBool :: Bool -> Val
- JsonLogic.Core.Value: VNull :: Val
- JsonLogic.Core.Value: VNum :: Double -> Val
- JsonLogic.Core.Value: VObj :: KeyMap Val -> Val
- JsonLogic.Core.Value: VStr :: Text -> Val
- JsonLogic.Core.Value: VUndefined :: Val
- JsonLogic.Core.Value: data Val
- JsonLogic.Core.Value: fromValue :: Value -> Val
- JsonLogic.Core.Value: instance GHC.Internal.Classes.Eq JsonLogic.Core.Value.Val
- JsonLogic.Core.Value: instance GHC.Internal.Show.Show JsonLogic.Core.Value.Val
- JsonLogic.Core.Value: jsonWeightUpTo :: Int -> Value -> Int
- JsonLogic.Core.Value: lessOrEqual :: Val -> Val -> Bool
- JsonLogic.Core.Value: lessThan :: Val -> Val -> Bool
- JsonLogic.Core.Value: looseEquals :: Val -> Val -> Bool
- JsonLogic.Core.Value: nestsDeeperThan :: Int -> Value -> Bool
- JsonLogic.Core.Value: parseFloat :: Val -> Double
- JsonLogic.Core.Value: strictEquals :: Val -> Val -> Bool
- JsonLogic.Core.Value: toJoinText :: Val -> Text
- JsonLogic.Core.Value: toJsString :: Val -> Text
- JsonLogic.Core.Value: toNumber :: Val -> Double
- JsonLogic.Core.Value: toValue :: Val -> Value
- JsonLogic.Core.Value: truthy :: Val -> Bool
- JsonLogic.Core.Value: valWeightUpTo :: Int -> Val -> Int
+ JsonLogic: CustomError :: Text -> Text -> Maybe Value -> CustomError
+ JsonLogic: DataDepthLimit :: Int -> LimitKind
+ JsonLogic: FailWhenReached :: UnknownOperators
+ JsonLogic: FollowArityMode :: UnknownOperators
+ JsonLogic: InvalidConfig :: ConfigError -> ParseError
+ JsonLogic: InvalidOperatorName :: OperatorName -> OperatorsError
+ JsonLogic: IterationLimit :: Int -> LimitKind
+ JsonLogic: JsNumbers :: NumericSafety
+ JsonLogic: LossyNumber :: Scientific -> EvalError
+ JsonLogic: LossyNumberLiteral :: Scientific -> ParseError
+ JsonLogic: MalformedData :: String -> BytesError
+ JsonLogic: MalformedRule :: String -> BytesError
+ JsonLogic: NegativeLimit :: Text -> ConfigError
+ JsonLogic: NodeLimitExceeded :: Int -> ParseError
+ JsonLogic: OperandIssue :: Int -> Text -> Text -> OperandIssue
+ JsonLogic: OperatorThrew :: SomeException -> RunFailure
+ JsonLogic: PreserveSource :: NumericSafety
+ JsonLogic: Refused :: Error -> BytesError
+ JsonLogic: RejectAtCompile :: UnknownOperators
+ JsonLogic: RejectLossy :: NumericSafety
+ JsonLogic: Rejected :: Error -> RunFailure
+ JsonLogic: TimedOut :: RunFailure
+ JsonLogic: UnknownOperatorName :: OperatorName -> [OperatorName] -> ParseError
+ JsonLogic: [errorCode] :: CustomError -> Text
+ JsonLogic: [errorDetails] :: CustomError -> Maybe Value
+ JsonLogic: [errorMessage] :: CustomError -> Text
+ JsonLogic: [operandActual] :: OperandIssue -> Text
+ JsonLogic: [operandExpected] :: OperandIssue -> Text
+ JsonLogic: [operandIndex] :: OperandIssue -> Int
+ JsonLogic: applyBytes :: ByteString -> ByteString -> Either BytesError ByteString
+ JsonLogic: applyBytesWith :: Config -> Operators -> ByteString -> ByteString -> Either BytesError ByteString
+ JsonLogic: checkData :: Config -> Value -> Either Error ()
+ JsonLogic: combineOperators :: Operators -> Operators -> Either OperatorsError Operators
+ JsonLogic: customFailure :: Text -> CustomError
+ JsonLogic: data BytesError
+ JsonLogic: data CustomError
+ JsonLogic: data CustomOperator
+ JsonLogic: data NumericSafety
+ JsonLogic: data Operand
+ JsonLogic: data OperandIssue
+ JsonLogic: data RunFailure
+ JsonLogic: data Step a
+ JsonLogic: data UnknownOperators
+ JsonLogic: errorKind :: Error -> Text
+ JsonLogic: force :: Operand -> Step Value
+ JsonLogic: instance Control.DeepSeq.NFData JsonLogic.Rule
+ JsonLogic: instance GHC.Internal.Show.Show JsonLogic.BytesError
+ JsonLogic: instance GHC.Internal.Show.Show JsonLogic.RunFailure
+ JsonLogic: lazyOperator :: Arity -> (Value -> [Operand] -> Step Value) -> CustomOperator
+ JsonLogic: newtype ConfigError
+ JsonLogic: pureOperator :: Arity -> (Value -> [Value] -> Either CustomError Value) -> CustomOperator
+ JsonLogic: runWithTimeout :: Int -> Rule -> Value -> IO (Either RunFailure Value)
+ JsonLogic: stepFail :: CustomError -> Step a
+ JsonLogic: tryRun :: Rule -> Value -> IO (Either RunFailure Value)
+ JsonLogic: unlimited :: Int
+ JsonLogic: unresolvedOperators :: Rule -> [(Location, OperatorName)]
+ JsonLogic: validate :: Config -> Operators -> Value -> [Error]
+ JsonLogic: validateConfig :: Config -> Either ConfigError Config
- JsonLogic: CustomOperatorFailed :: OperatorName -> Text -> EvalError
+ JsonLogic: CustomOperatorFailed :: OperatorName -> CustomError -> EvalError
- JsonLogic: InvalidOperand :: OperatorName -> EvalError
+ JsonLogic: InvalidOperand :: OperatorName -> OperandIssue -> EvalError
Files
- CHANGELOG.md +88/−3
- README.md +6/−8
- app/Main.hs +147/−0
- bench/Bench.hs +66/−21
- community/Community.hs +7/−2
- differential/Differential.hs +63/−4
- differential/oracle.js +5/−3
- docs/COMPATIBILITY.md +15/−9
- docs/LIMITS.md +26/−11
- docs/STABILITY.md +3/−3
- docs/TUTORIAL.md +47/−14
- jsonlogic-hs.cabal +52/−51
- outliers/Outliers.hs +7/−2
- src/JsonLogic.hs +199/−22
- src/JsonLogic/Core/Analysis.hs +16/−4
- src/JsonLogic/Core/Check.hs +87/−0
- src/JsonLogic/Core/Config.hs +156/−7
- src/JsonLogic/Core/Custom.hs +96/−25
- src/JsonLogic/Core/Errors.hs +221/−9
- src/JsonLogic/Core/Eval.hs +315/−165
- src/JsonLogic/Core/Location.hs +18/−1
- src/JsonLogic/Core/Number.hs +30/−59
- src/JsonLogic/Core/Operator.hs +6/−1
- src/JsonLogic/Core/Parse.hs +68/−21
- src/JsonLogic/Core/Rule.hs +17/−21
- src/JsonLogic/Core/Run.hs +75/−0
- src/JsonLogic/Core/Ryu.hs +6/−5
- src/JsonLogic/Core/Utf16.hs +230/−43
- src/JsonLogic/Core/Value.hs +189/−18
- test/AuditSpec.hs +529/−0
- test/CompatSpec.hs +28/−13
- test/EvalSpec.hs +20/−11
- test/LimitsSpec.hs +30/−2
- test/LocationSpec.hs +3/−3
- test/NumberSpec.hs +1/−0
- test/Oracle.hs +167/−0
- test/ParseSpec.hs +7/−6
- test/RegressionSpec.hs +196/−0
- test/Spec.hs +4/−0
- test/community/expected.json +3/−3
- tutorial/Tutorial.hs +15/−6
CHANGELOG.md view
@@ -1,7 +1,92 @@ # Changelog for jsonlogic-hs -## 0.1.0.0 -- unreleased+## 0.2.0.0 -- 2026-11-24 +Everything below is relative to 0.1.0.0 (2026-10-23). This is a major version+under the PVP: a few things were removed or changed, listed first.++### Upgrading from 0.1.0.0++* **`Config`'s constructor is no longer exported.** Build a configuration with+ record update on `defaultConfig` (`defaultConfig {maxSteps = 5000}`); the+ fields are still exported, so new fields will not break your code.+* **`Operators` is no longer a `Semigroup` or `Monoid`**: the instances+ combined silently and shadowed a name defined twice. Use `combineOperators`,+ which refuses a name both registries define.+* **Unknown operators are refused when a rule is compiled** (strict mode, the+ default), naming the nearest known operators, even if the rule would never+ reach them. `unknownOperators = FailWhenReached` (or `Lenient`) keeps the+ reference's laziness; `unresolvedOperators` lists them. The strict community+ score moves from 839 to 829: the ten cases are rules whose unknown operator+ is never reached.+* **Limits changed.** `maxIterations` (new) bounds the elements any of the six+ iterating operators visits and is separate from `maxArrayLength`, which now+ bounds only what is built, so a filter over a large dataset that keeps few+ elements no longer needs `maxArrayLength` raised. `maxNodes` and+ `maxDataDepth` are new. A result whose size is more than the step budget+ could have built, plus the data it may hold, now fails with+ `LimitExceeded (StepLimit n)`.+* **`JsonLogic` is the one documented module.** The `JsonLogic.Core` modules+ are hidden from Haddock and carry no stability promise;+ `JsonLogic.Core.Rule.Rule` is now `RuleTree`. Import `JsonLogic` only.++### New++* `applyBytes` and `applyBytesWith` (JSON text in and out; the data is screened+ by `checkData` first), and a `jsonlogic` command (`eval`, `check`, `uses`) to+ try, check and inspect rules without writing Haskell.+* `validate` reports every problem in a rule, in document order. `checkData`+ screens untrusted data (depth, and lossy numbers).+* `tryRun` and `runWithTimeout` run a rule and return `Either RunFailure+ Value`. They do not swallow asynchronous exceptions (a `timeout`,+ `killThread`, a stack or heap overflow), so `timeout n (tryRun r d)` behaves+ as expected.+* Specific, machine-readable errors: `InvalidOperand` names the operand, what+ it needed and what it got; `Error` has a `ToJSON` instance with stable+ `kind` tags and a `displayException` that reads as a sentence; `CustomError`+ carries a code, a message and details.+* `numericSafety`: numbers a double cannot hold (`9007199254740993`) keep their+ digits when passed through unchanged with `PreserveSource`, or are refused+ with `RejectLossy`. The default is unchanged (the reference rounds).+* `validateConfig` and `unlimited` for limits; custom operators can be lazy+ (`lazyOperator`, `force`, `stepFail`) so a `coalesce` can short-circuit, and+ remain pure by design.++### Fixed++* **A tiny rule could build an exponentially large result.** Arrays are shared,+ so a `reduce` whose body wraps its accumulator in a two-element array twice+ built a result that doubled per element while costing a few steps; anything+ that then walked it hung. The result is now checked against the budget.+* **`in` on long strings is linear time.** The text library's search is+ quadratic in the worst case, and a hostile needle was charged by length only.+ Long needles now use a linear-time search.+* **`applyBytes` and the command screen the data's depth** before evaluating.+* **A severed surrogate pair keeps its identity**: the halves of `"😀"`+ compare unequal, order by code unit, and `cat` joins them back, as in+ JavaScript. Before, both became U+FFFD, so they compared equal.+* **Lenient mode evaluates surplus operands before applying the operator**, as+ the reference does, so the reference's error is the one reported.+* `Ord Location` follows position in the rule, not the internal+ representation; `apply` no longer runs the data-use analysis it does not+ need; `compile` and `apply` agree on every rule, including refused ones.++### Testing and documentation++* The differential tester runs the reference unpatched and generates+ surrogate-half and surplus-operand cases; the 0.1.0.0 code fails 91 of+ 12,000 of them, this version none. Its generator no longer compares two+ reads of the same `var` path, where the reference compares references.+* Each audit change is pinned by a test (`test/AuditSpec.hs`); the one+ deviation that can change a result on realistic input, that arrays and+ objects are never equal (`DEV-IDENTITY`), is now pinned too.+* Corrections to the documentation: the strict score, the CI description, the+ README's API summary and links, the list of deviations. The README states+ that AI was used in writing the code and documentation. CI blocks on weeder,+ and `.gitattributes` keeps the fixtures byte-exact.++## 0.1.0.0 -- 2026-10-23+ First release. ### Reading and evaluating rules@@ -50,8 +135,8 @@ * Every example in `docs/TUTORIAL.md` is checked by a test suite. * `scripts/check-harness.sh` feeds every runner missing, empty, truncated and tampered fixtures and demands a failure.-* CI: GHC 9.6 to 9.14 on Linux, plus macOS and Windows; `-Werror` on the- primary compiler; hlint, fourmolu, weeder, shellcheck and actionlint;+* CI: GHC 9.6 to 9.14 on Linux; `-Werror` on the+ primary compiler; hlint, fourmolu, weeder and shellcheck; `cabal check`; the source distribution built, tested and documented on its own; a downstream project using only `JsonLogic`.
README.md view
@@ -4,8 +4,7 @@ small rule language that is itself JSON, so rules can be stored, shared between systems and evaluated against data without running arbitrary code. -A substantial amount of the code and documentation was written with AI-assistance.+A SUBSTANTIAL AMOUNT OF CODE AND DOCUMENTATION HAS BEEN DONE USING AI. It is held to the JavaScript reference implementation, [json-logic-js](https://github.com/jwadhams/json-logic-js) 2.0.5. On our own@@ -20,7 +19,7 @@ | Classic shared suite (jsonlogic.com/tests.json) | 278 / 278 | | Outlier catalogue, answers recorded from json-logic-js | 26,980 / 26,980 (lenient mode) | | Random differential test against json-logic-js | every CI run, fresh seed |-| Community suite (json-logic/compat-tables) | 782 / 1138 lenient, 839 / 1138 strict |+| Community suite (json-logic/compat-tables) | 782 / 1138 lenient, 829 / 1138 strict | | Haddock coverage | 100% of every module | The community suite (json-logic/compat-tables) is mostly written for the newer@@ -60,7 +59,7 @@ dataUse :: Rule -> DataUse -- what it can read operatorsFromList :: [(OperatorName, CustomOperator)] -> Either OperatorsError Operators-type CustomOperator = Value -> [Value] -> Either Text Value+pureOperator :: Arity -> (Value -> [Value] -> Either CustomError Value) -> CustomOperator data Error = ParseFailure Location ParseError | EvalFailure Location EvalError renderLocation :: Location -> Text -- an RFC 6901 JSON Pointer@@ -122,9 +121,9 @@ against exact ones on hundreds of thousands of doubles, and `dataUse`'s guarantee. - **Hygiene, blocking in CI**: `-Werror` on the primary GHC, a matrix of- GHC 9.6 to 9.14 plus macOS and Windows, hlint, fourmolu, shellcheck, actionlint, `cabal check`, a build of the source+ GHC 9.6 to 9.14 on Linux, hlint, fourmolu, shellcheck, `cabal check`, a build of the source distribution on its own, and a downstream project that uses only the public- module. Dead code is checked with weeder, which is advisory for now.+ module. Dead code is checked with weeder. Implementing JsonLogic in another language? The fixtures are plain JSON and JSONL with a documented format; [`docs/CONFORMANCE.md`](https://github.com/Bombay-Boyz/jsonlogic-hs/blob/main/docs/CONFORMANCE.md)@@ -146,7 +145,7 @@ | Implementation | Classic suite (278) | Outlier catalogue (26,980) | Community suite (1,138) | | --- | --- | --- | --- |-| **jsonlogic-hs** (measured by this repo's own test runner, see note below) | 278 (100%) | 26,980 (100%, lenient mode) | 782 lenient / 839 strict |+| **jsonlogic-hs** (measured by this repo's own test runner, see note below) | 278 (100%) | 26,980 (100%, lenient mode) | 782 lenient / 829 strict | | json-logic-js 2.0.5 (the reference) | 278 (100%) | 26,980 (100%) | 782 (68.7%) | | jsonlogic 0.5.1 (Rust) | 270 (97.1%) | 22,881 (84.8%) | 761 (66.9%) | | panzi-json-logic 1.0.1 (Python) | 277 (99.6%) | 21,361 (79.2%) | 790 (69.4%) |@@ -234,7 +233,6 @@ - [`docs/STABILITY.md`](https://github.com/Bombay-Boyz/jsonlogic-hs/blob/main/docs/STABILITY.md): what is covered by the versioning policy. - [`docs/AUDIT-2026-10.md`](https://github.com/Bombay-Boyz/jsonlogic-hs/blob/main/docs/AUDIT-2026-10.md): the external audit's findings and how each was resolved. - [`docs/adr/`](https://github.com/Bombay-Boyz/jsonlogic-hs/tree/main/docs/adr/): recorded decisions and deviations from the engineering standard.-- [`VISION.md`](https://github.com/Bombay-Boyz/jsonlogic-hs/blob/main/VISION.md) and [`ENGINEERING_STANDARD.md`](https://github.com/Bombay-Boyz/jsonlogic-hs/blob/main/ENGINEERING_STANDARD.md): the design and the rules this codebase follows. ## Licence
+ app/Main.hs view
@@ -0,0 +1,147 @@+{-# LANGUAGE OverloadedStrings #-}++-- |+-- The @jsonlogic@ command: try, check and inspect rules without writing+-- Haskell.+--+-- > jsonlogic eval RULE [DATA] [options] apply a rule to data (default null)+-- > jsonlogic check RULE [options] report every problem in a rule+-- > jsonlogic uses RULE [options] print the data paths a rule reads+--+-- RULE and DATA are files of JSON, or @-@ for standard input. The result+-- of @eval@ is written to standard output as JSON. Exit status: 0 success,+-- 1 the rule was refused or failed, 2 bad usage or input that is not JSON.+module Main (main) where++import Control.Monad (forM_)+import qualified Data.Aeson as Aeson+import qualified Data.ByteString.Lazy as LBS+import qualified Data.ByteString.Lazy.Char8 as Char8+import Data.List (isPrefixOf)+import qualified Data.Text as Text+import qualified Data.Text.IO as Text.IO+import System.Environment (getArgs)+import System.Exit (ExitCode (..), exitWith)+import System.IO (hPutStrLn, stderr, stdin)+import Text.Read (readMaybe)++import JsonLogic++data Format = Text | JsonFormat+ deriving (Eq)++data Options = Options+ { optConfig :: Config+ , optFormat :: Format+ , optTimeout :: Maybe Int+ , optFiles :: [FilePath]+ }++usage :: String+usage =+ unlines+ [ "usage: jsonlogic eval RULE [DATA] [options]"+ , " jsonlogic check RULE [options]"+ , " jsonlogic uses RULE [options]"+ , ""+ , "RULE and DATA are JSON files, or - for standard input."+ , ""+ , "options:"+ , " --lenient the reference's arity rules; unknown operators fail only when reached"+ , " --allow-unknown unknown operators fail only when reached"+ , " --max-steps N evaluation step budget"+ , " --max-depth N rule nesting limit"+ , " --preserve-numbers keep the digits of numbers a double cannot hold, when passed through"+ , " --reject-lossy refuse numbers a double cannot hold"+ , " --timeout MS wall-clock limit for eval, in milliseconds"+ , " --format text|json how problems are reported (default text)"+ ]++main :: IO ()+main = do+ args <- getArgs+ case args of+ command : rest | command `elem` ["eval", "check", "uses"] -> case parseOptions rest of+ Left problem -> bad problem+ Right options -> dispatch command options+ _ -> bad "expected a command: eval, check or uses"++bad :: String -> IO a+bad message = hPutStrLn stderr ("jsonlogic: " ++ message) >> hPutStrLn stderr usage >> exitWith (ExitFailure 2)++parseOptions :: [String] -> Either String Options+parseOptions = go (Options defaultConfig Text Nothing [])+ where+ go options [] = Right options {optFiles = reverse (optFiles options)}+ go options (flag : rest) = case flag of+ "--lenient" -> go (setConfig options (\c -> c {arityMode = Lenient})) rest+ "--allow-unknown" -> go (setConfig options (\c -> c {unknownOperators = FailWhenReached})) rest+ "--preserve-numbers" -> go (setConfig options (\c -> c {numericSafety = PreserveSource})) rest+ "--reject-lossy" -> go (setConfig options (\c -> c {numericSafety = RejectLossy})) rest+ "--max-steps" -> number flag rest (\n -> setConfig options (\c -> c {maxSteps = n}))+ "--max-depth" -> number flag rest (\n -> setConfig options (\c -> c {maxDepth = n}))+ "--timeout" -> number flag rest (\n -> options {optTimeout = Just n})+ "--format" -> case rest of+ "text" : more -> go options {optFormat = Text} more+ "json" : more -> go options {optFormat = JsonFormat} more+ _ -> Left "--format takes text or json"+ _+ | "--" `isPrefixOf` flag -> Left ("unknown option " ++ flag)+ | otherwise -> go options {optFiles = flag : optFiles options} rest+ setConfig options f = options {optConfig = f (optConfig options)}+ number flag rest build = case rest of+ value : more | Just n <- readMaybe value, n >= 0 -> go (build n) more+ _ -> Left (flag ++ " takes a non-negative number")++dispatch :: String -> Options -> IO ()+dispatch command options = case (command, optFiles options) of+ ("eval", [ruleFile]) -> eval options ruleFile Nothing+ ("eval", [ruleFile, dataFile]) -> eval options ruleFile (Just dataFile)+ ("check", [ruleFile]) -> check options ruleFile+ ("uses", [ruleFile]) -> uses options ruleFile+ _ -> bad ("wrong number of files for " ++ command)++readJson :: String -> FilePath -> IO Aeson.Value+readJson what path = do+ bytes <- if path == "-" then LBS.hGetContents stdin else LBS.readFile path+ case Aeson.eitherDecode bytes of+ Left problem -> hPutStrLn stderr ("jsonlogic: " ++ what ++ " is not JSON: " ++ problem) >> exitWith (ExitFailure 2)+ Right value -> pure value++report :: Options -> [Error] -> IO a+report options problems = do+ case optFormat options of+ Text -> forM_ problems (Text.IO.hPutStrLn stderr . renderError)+ JsonFormat -> Char8.hPutStrLn stderr (Aeson.encode problems)+ exitWith (ExitFailure 1)++eval :: Options -> FilePath -> Maybe FilePath -> IO ()+eval options ruleFile dataFile = do+ rule <- readJson "the rule" ruleFile+ input <- maybe (pure Aeson.Null) (readJson "the data") dataFile+ ready <- either (report options . pure) pure (compile (optConfig options) noOperators rule)+ either (report options . pure) pure (checkData (optConfig options) input)+ outcome <- case optTimeout options of+ Just milliseconds -> runWithTimeout (milliseconds * 1000) ready input+ Nothing -> tryRun ready input+ case outcome of+ Right result -> Char8.putStrLn (Aeson.encode result)+ Left (Rejected problem) -> report options [problem]+ Left TimedOut -> hPutStrLn stderr "jsonlogic: timed out" >> exitWith (ExitFailure 1)+ Left (OperatorThrew e) -> hPutStrLn stderr ("jsonlogic: " ++ show e) >> exitWith (ExitFailure 1)++check :: Options -> FilePath -> IO ()+check options ruleFile = do+ rule <- readJson "the rule" ruleFile+ case validate (optConfig options) noOperators rule of+ [] -> pure ()+ problems -> report options problems++uses :: Options -> FilePath -> IO ()+uses options ruleFile = do+ rule <- readJson "the rule" ruleFile+ ready <- either (report options . pure) pure (compile (optConfig options) noOperators rule)+ let use = dataUse ready+ if usesAllData use+ then putStrLn "(all of the data)"+ else forM_ (usedPaths use) (putStrLn . Text.unpack)
bench/Bench.hs view
@@ -4,15 +4,24 @@ -- Benchmarks (Standard 5.6): statistically sound timing and allocation of -- the engine, by tasty-bench. ----- Four groups, so each cost is read on its own:+-- Five groups, so each cost is read on its own: -- -- * @one-shot@: 'apply', which reads the rule and evaluates it, the cost of -- a rule used once.--- * @compile only@: reading a rule, with no evaluation.+-- * @compile only@: reading a rule and building all of its code, with no+-- evaluation. -- * @precompiled run@: 'run' of a rule read beforehand, the cost of a rule -- used many times. One-shot minus this is the reading cost.--- * @limits@: a rule that stops at a resource limit.+-- * @limits@: a rule that stops at a resource limit, and is refused before+-- it is read.+-- * @large inputs@: the shapes that were once able to do far more work than+-- the step budget showed: long strings, huge numbers, wide rules, a custom+-- operator over a large datum. Each is held to its budget here, so a+-- regression shows as time. --+-- Every result is forced with 'nf', not by encoding it: what is timed is+-- the engine, not the JSON encoder.+-- -- Large inputs live in the /data/, built once, and every rule or datum -- depends on the argument tasty-bench passes in, so GHC cannot lift a -- benchmark's work out of the timing loop and run it only once.@@ -25,20 +34,15 @@ -- runs on one machine; see bench/README.md. module Main (main) where -import Data.Aeson (Value (..), encode, object, toJSON, (.=))+import Data.Aeson (Value (..), object, toJSON, (.=)) import qualified Data.Aeson.Key as Key-import qualified Data.ByteString.Lazy as LBS import Data.Either (fromRight)+import Data.Scientific (scientific) import qualified Data.Text as Text-import Test.Tasty.Bench (Benchmark, bench, bgroup, defaultMain, whnf)+import Test.Tasty.Bench (Benchmark, bench, bgroup, defaultMain, nf) import JsonLogic --- | The size of the encoded answer: forces the whole result, and gives the--- benchmark an 'Int' to hold on to.-size :: Either Error Value -> Int-size = fromIntegral . LBS.length . encode . fromRight Null- num :: Int -> Value num = toJSON @@ -67,7 +71,7 @@ -- | One custom operator, to price the extension point. customOps :: Operators-customOps = fromRight noOperators (operatorsFromList [(OperatorName "double", doubling)])+customOps = fromRight noOperators (operatorsFromList [(OperatorName "double", pureOperator (Exactly 1) doubling)]) where doubling _ [Number k] = Right (Number (k * 2)) doubling _ _ = Left "expected one number"@@ -98,34 +102,75 @@ oneShot :: (String, Int -> Value) -> Benchmark oneShot (name, rule) =- bench name (whnf (\n -> size (applyWith customOps (rule n) (dataFor n))) 1)--verdict :: Either Error Rule -> Int-verdict = either (const 0) (const 1)+ bench name (nf (\n -> applyWith customOps (rule n) (dataFor n)) 1) +-- | 'compile' builds all of a rule's code, so forcing it times all of that. compileOnly :: (String, Int -> Value) -> Benchmark compileOnly (name, rule) =- bench name (whnf (verdict . compile defaultConfig customOps . rule) 1)+ bench name (nf (compile defaultConfig customOps . rule) 1) -- | The rule is read once, outside the timing loop; only 'run' is timed. precompiledRun :: (String, Int -> Value) -> Benchmark precompiledRun (name, rule) =- bench name (whnf (\n -> maybe 0 (\r -> size (run r (dataFor n))) compiled) 1)+ bench name (nf (\n -> fmap (\r -> run r (dataFor n)) compiled) 1) where- compiled = either (const Nothing) Just (compile defaultConfig customOps (rule 0))+ compiled = compile defaultConfig customOps (rule 0) -- | 110,000 operands against a limit of 100,000 steps: the cost of being -- refused. limitHit :: Benchmark limitHit = bench "step limit reached, 110,000 operands" $- whnf (\n -> size (applyWithConfig defaultConfig{maxSteps = 100000} customOps (call "+" (num n : replicate 110000 (num 1))) Null)) 1+ nf (\n -> applyWithConfig defaultConfig{maxSteps = 100000} customOps (call "+" (num n : replicate 110000 (num 1))) Null) 1 +-- | Twice the node limit: refused before any of it is read.+nodeLimitHit :: Benchmark+nodeLimitHit =+ bench "node limit reached, 2,000,000 operands" $+ nf (\n -> applyWith customOps (call "+" (num n : replicate 2000000 (num 1))) Null) 1++-- ---------------------------------------------------------------------+-- Large inputs+-- ---------------------------------------------------------------------++-- | A 1,000,000-character string, built once.+bigString :: Value+bigString = String (Text.replicate 1000000 "a")++-- | A 100,000-key object, built once.+bigObject :: Value+bigObject = object [Key.fromText (Text.pack ("k" ++ show i)) .= i | i <- [1 .. 100000 :: Int]]++-- | A decimal number of 200,000 digits, built once.+bigNumber :: Value+bigNumber = Number (scientific (10 ^ (200000 :: Int) + 12345) (-200000))++-- | Operators that read, compare and search a 1,000,000-character string, a+-- number of times each: far more than the step budget allows for the long+-- ones, so these are timed refusals, and the one-use rows are timed work.+largeInputs :: [(String, Int -> (Value, Value))]+largeInputs =+ [ ("one comparison of two 1M-character strings", \n -> (call "<" [var "big", var "big"], withBig n))+ , ("one substr of a 1M-character string", \n -> (call "substr" [var "big", num 0, num 1], withBig n))+ , ("one search of a 1M-character string", \n -> (call "in" ["b", var "big"], withBig n))+ , ("1,000 comparisons of 1M-character strings, refused", \n -> (call "+" (replicate 1000 (call "<" [var "big", var "big"])), withBig n))+ , ("a 200,000-digit JSON number read", \n -> (call "+" [var "number", num n], withBig n))+ , ("custom operator, 200 calls over a 100,000-key datum", \n -> (call "+" (replicate 200 (call "double" [num n])), bigObject))+ , ("100,000-operand rule", \n -> (call "+" (num n : replicate 100000 (num 1)), Null))+ ]+ where+ withBig n = object ["big" .= bigString, "number" .= bigNumber, "n" .= n]++largeInput :: (String, Int -> (Value, Value)) -> Benchmark+largeInput (name, workload) =+ bench name (nf (\n -> let (rule, dat) = workload n in applyWith customOps rule dat) 1)+ main :: IO () main = defaultMain [ bgroup "one-shot" (map oneShot workloads) , bgroup "compile only" (map compileOnly workloads) , bgroup "precompiled run" (map precompiledRun workloads)- , bgroup "limits" [limitHit]+ , bgroup "limits" [limitHit, nodeLimitHit]+ , bgroup "large inputs" (map largeInput largeInputs) ]
community/Community.hs view
@@ -134,9 +134,14 @@ errorType failure = case failure of ParseFailure _ (ArityMismatch{}) -> "Invalid Arguments" ParseFailure _ (DepthExceeded _) -> "Limit Exceeded"+ ParseFailure _ (NodeLimitExceeded _) -> "Limit Exceeded"+ ParseFailure _ (UnknownOperatorName _ _) -> "Unknown Operator"+ ParseFailure _ (InvalidConfig _) -> "Invalid Configuration"+ ParseFailure _ (LossyNumberLiteral _) -> "Invalid Arguments" EvalFailure _ (UnknownOperator _) -> "Unknown Operator"- EvalFailure _ (InvalidOperand _) -> "Invalid Arguments"- EvalFailure _ (CustomOperatorFailed _ reason) -> reason+ EvalFailure _ (InvalidOperand _ _) -> "Invalid Arguments"+ EvalFailure _ (CustomOperatorFailed _ reason) -> errorMessage reason+ EvalFailure _ (LossyNumber _) -> "Invalid Arguments" EvalFailure _ (LimitExceeded _) -> "Limit Exceeded" -- | compat-tables' @compareValues@.
differential/Differential.hs view
@@ -48,7 +48,7 @@ import System.Exit (exitFailure) import System.IO (hSetEncoding, stderr, stdout, utf8) import System.Process (callProcess)-import Test.QuickCheck (Gen, choose, elements, frequency, vectorOf)+import Test.QuickCheck (Gen, choose, elements, frequency, suchThat, vectorOf) import Test.QuickCheck.Gen (unGen) import Test.QuickCheck.Random (mkQCGen) @@ -230,6 +230,8 @@ , (2, genIf ctx depth) , (1, genArrayRule ctx depth) , (2, genStringFocus)+ , (1, genSurrogateFocus)+ , (1, genSurplusFocus) ] -- | Between @low@ and @high@ sub-rules.@@ -251,6 +253,45 @@ , (2, (\op -> call op [a, toJSON (1 :: Int)]) <$> elements ["+", "*", "/", "%", "-", "<", "=="]) ] +-- | Slices that cut a surrogate pair in two, compared, ordered, searched for+-- and joined again: the halves must stay unequal, order by code unit, and+-- re-join into the character, as in JavaScript.+genSurrogateFocus :: Gen Value+genSurrogateFocus = do+ source <- String <$> elements ["\x1F600", "a\x1F600\&b", "\x1F680\x1F600", "\x1F600\x1F680\&x"]+ let half = do+ start <- choose (0, 5) :: Gen Int+ len <- choose (1, 2) :: Gen Int+ pure (call "substr" [source, toJSON start, toJSON len])+ a <- half+ b <- half+ frequency+ [ (4, (\op -> call op [a, b]) <$> elements ["==", "===", "!=", "!==", "<", "<=", ">", ">=", "in"])+ , (3, pure (call "cat" [a, b]))+ , (2, (\op -> call op [call "cat" [a, b], source]) <$> elements ["===", "==", "in"])+ , (1, (\op -> call op [a, source]) <$> elements ["in", "==", "<"])+ ]++-- | A builtin given one operand more than it takes (which only lenient mode+-- accepts), where the extra operand is evaluated before the operator is+-- applied. When both the extra operand and the operator can fail, the+-- reference reports the extra operand's failure.+genSurplusFocus :: Gen Value+genSurplusFocus = do+ extra <- elements [call "nope" [], toJSON (1 :: Int), Null, String "x"]+ (op, operands) <-+ elements+ [ ("missing_some", [toJSON (1 :: Int), Null])+ , ("missing_some", [toJSON (1 :: Int), toJSON ["a" :: Text]])+ , ("!", [toJSON (0 :: Int)])+ , ("!!", [String "x"])+ , ("==", [toJSON (1 :: Int), toJSON (1 :: Int)])+ , ("var", [String "a", toJSON (2 :: Int)])+ , ("-", [toJSON (5 :: Int), toJSON (2 :: Int)])+ , ("in", [String "a", String "abc"])+ ]+ pure (call op (operands ++ [extra]))+ genLogic :: Ctx -> Int -> Gen Value genLogic ctx depth = frequency@@ -271,10 +312,28 @@ | shorthand -> object [op .= x] | otherwise -> call op [x] +-- | The path of every @var@ inside a rule.+varPaths :: Value -> [Value]+varPaths (Array items) = concatMap varPaths (foldr (:) [] items)+varPaths (Object fields) = concatMap entry (KeyMap.toList fields)+ where+ entry ("var", Array args) = take 1 (foldr (:) [] args) ++ concatMap varPaths (foldr (:) [] args)+ entry ("var", other) = other : varPaths other+ entry (_, inner) = varPaths inner+varPaths _ = []++-- | True when no @var@ path is read on both sides of a comparison. The+-- reference compares arrays and objects by identity, so the same container+-- reached twice is equal to itself there and never equal here+-- (docs/COMPATIBILITY.md, DEV-IDENTITY).+readsNoPathTwice :: [Value] -> Bool+readsNoPathTwice [a, b] = null [p | p <- varPaths a, p `elem` varPaths b]+readsNoPathTwice _ = True+ genCompare :: Ctx -> Int -> Gen Value genCompare ctx depth = frequency- [ (4, call <$> elements ["==", "===", "!=", "!=="] <*> genArgs ctx depth 2 2)+ [ (4, call <$> elements ["==", "===", "!=", "!=="] <*> (genArgs ctx depth 2 2 `suchThat` readsNoPathTwice)) , (3, call <$> elements ["<", "<="] <*> genArgs ctx depth 2 3) , (3, call <$> elements [">", ">="] <*> genArgs ctx depth 2 2) ]@@ -456,8 +515,8 @@ -- | The messages the reference gives for each class of library error. errorClass :: Error -> Maybe [String] errorClass (EvalFailure _ (UnknownOperator _)) = Just ["Unrecognized operation", "apply is not a function"]-errorClass (EvalFailure _ (InvalidOperand (OperatorName "*"))) = Just ["Reduce of empty array"]-errorClass (EvalFailure _ (InvalidOperand _)) = Just ["Cannot read properties"]+errorClass (EvalFailure _ (InvalidOperand (OperatorName "*") _)) = Just ["Reduce of empty array"]+errorClass (EvalFailure _ (InvalidOperand _ _)) = Just ["Cannot read properties"] errorClass _ = Nothing json :: Value -> String
differential/oracle.js view
@@ -29,9 +29,11 @@ } console.error("oracle: json-logic-js " + version + ", node " + process.version); -// Lone surrogates cannot be held in a Haskell Text (nor decoded by aeson), so-// the reference's answer is normalised the way String.prototype.toWellFormed-// would: each becomes U+FFFD. This is the one documented string deviation.+// The reference runs untouched. A slice that cuts a surrogate pair gives a+// lone surrogate, as in JavaScript, and jsonlogic-hs reproduces it (halves+// compare unequal, order by code unit, and re-join into the character). Only+// the final answer is made well-formed, because JSON text cannot carry a lone+// surrogate: it is written as U+FFFD, as String.prototype.toWellFormed does. function wellFormed(x) { if (typeof x === "string") return typeof x.toWellFormed === "function" ? x.toWellFormed() : x; if (Array.isArray(x)) return x.map(wellFormed);
docs/COMPATIBILITY.md view
@@ -61,16 +61,22 @@ which parsed JSON values do not have. It differs from the reference only where the *same* array or object is reached twice, for example `{"===": [{"var": ""}, {"var": ""}]}` on `{}`, which is `true` in-JavaScript. Generated tests avoid such comparisons.+JavaScript, or a `reduce` whose body compares `accumulator` with itself once it+holds an array. Generated rules do not compare two reads of the same `var` path. -### DEV-LONE-SURROGATE: a severed surrogate pair becomes U+FFFD+### DEV-LONE-SURROGATE: a lone surrogate leaves the rule as U+FFFD Strings are measured, indexed, sliced and ordered by UTF-16 code unit, as in-JavaScript: `"😀"` has length 2, and sorts below `"\uE000"`. A Haskell `Text`-cannot hold half of a surrogate pair, so a slice that cuts through one-(`{"substr": ["😀", 0, 1]}`, or indexing `s.0`) returns U+FFFD for the-severed half. This is exactly what `String.prototype.toWellFormed()` makes-of the reference's answer, and is how the fixture normalises it.+JavaScript: `"😀"` has length 2, and sorts below `"\uE000"`. A slice that+cuts through a surrogate pair (`{"substr": ["😀", 0, 1]}`, or indexing+`s.0`) is a string that holds a lone surrogate, which a Haskell `Text` cannot,+so inside the evaluation it is kept as its UTF-16 code units. It behaves as in+JavaScript there: the two halves are unequal, they order by code unit, they+are found by `in`, and `cat` joins them back into the character. It becomes+U+FFFD only in the *result*, because JSON text cannot carry a lone surrogate+(what `String.prototype.toWellFormed()` makes of the reference's answer). The+differential tester runs the reference unpatched and normalises only the final+answer. ### DEV-INHERITED: only own properties are visible @@ -119,10 +125,10 @@ value, variadic `/` and `-`, chained `==` and lazily evaluated comparison chains. jsonlogic-hs implements the classic language of json-logic-js 2.0.5. In lenient mode it scores 782 of 1,138 on the suite, file for file the same-as json-logic-js; in strict mode 839, because a wrong argument count is then+as json-logic-js; in strict mode 829, because a wrong argument count is then an error, as that dialect also asks. The per-file score is pinned in `test/community/expected.json`. Implementing the 2.0 dialect as a selectable-`Config` setting is on the roadmap (`VISION.md`).+`Config` setting is on the roadmap. ## Errors are richer than the reference's
docs/LIMITS.md view
@@ -20,8 +20,15 @@ | `maxDepth` | 64 | levels of nesting of the rule, of any literal in it, and of a custom operator's result | `ParseFailure _ (DepthExceeded n)` or `EvalFailure _ (LimitExceeded (ValueDepthLimit n))` | | `maxSteps` | 1,000,000 | see below | `EvalFailure _ (LimitExceeded (StepLimit n))` | | `maxStringLength` | 1,048,576 | UTF-16 code units, the longest string `cat` builds | `EvalFailure _ (LimitExceeded (StringLimit n))` |-| `maxArrayLength` | 100,000 | elements, the longest array `merge` builds and the longest `map` or `filter` iterates | `EvalFailure _ (LimitExceeded (ArrayLimit n))` |+| `maxArrayLength` | 100,000 | elements, the longest array `merge`, `map` or `filter` builds | `EvalFailure _ (LimitExceeded (ArrayLimit n))` |+| `maxIterations` | 100,000 | elements, the longest array `map`, `filter`, `reduce`, `all`, `none` or `some` iterates: the same for all six, and separate from what is built | `EvalFailure _ (LimitExceeded (IterationLimit n))` |+| `maxNodes` | 1,000,000 | nodes in the rule's JSON, checked before it is read | `ParseFailure _ (NodeLimitExceeded n)` |+| `maxDataDepth` | 1,000 | levels of nesting of the data, checked by `checkData` | `EvalFailure _ (LimitExceeded (DataDepthLimit n))` | +A limit of `unlimited` means no limit. A negative limit is refused by+`validateConfig` (every entry point calls it) as `InvalidConfig`, instead of+silently meaning "refuse everything".+ Each limit is exact: a rule that needs exactly the limit succeeds and one more fails, and the tests check both sides of every boundary. The `_` in each error is the location of the node that hit the limit.@@ -45,27 +52,35 @@ ## What is not bounded -- **Wall-clock time.** The limits bound work, not seconds. Run untrusted- evaluations with a timeout (`System.Timeout.timeout`) as well if that- matters; evaluation is pure and can be interrupted safely.+- **Wall-clock time.** The limits bound work, not seconds. Use+ `runWithTimeout` as well if that matters; evaluation is pure and can be+ interrupted safely. `tryRun` and `runWithTimeout` re-throw asynchronous+ exceptions (a timeout, `killThread`), so cancellation always reaches the+ caller. - **A custom operator's own work.** The library cannot see inside it. Its *result* is held to the depth and step limits. - **The size of the input.** The rule and the data are values you already hold. Parsing JSON text is aeson's job, and it has no depth limit of its- own: bound the size of untrusted text before decoding it.-- **Searching or slicing a very large string.** `in`, `substr` and string- comparison take time linear in the string, which comes from the data you- hold; the string limit bounds what `cat` builds, not what the data holds.-- **Reading a long numeric string.** It is linear in its length (a- million-digit string takes about 0.15 s), not bounded by a step.+ own: bound the size of untrusted text before decoding it, and screen the+ decoded data once with `checkData` (depth, and under `RejectLossy`,+ numbers a double cannot carry). Evaluation does not walk the data.+- **Reading a very long JSON number.** Converting a number literal to a+ double is close to linear in its digits (a million-digit literal takes+ about 11 ms, measured) and is not charged to a step; the size of the rule+ and the data is bounded by whoever supplies them. +Searching, slicing and reading a long numeric string, by contrast, *are*+charged: one step per 64 bytes scanned (`in`, `substr`, string comparison)+and per 8 bytes read as a number.+ ## Cost The limits are cheap. Every node costs one counter decrement, and the work that is charged in proportion to size is work that is done anyway. On one machine (`bench/Bench.hs`, `run` of a compiled rule): `map` or `filter` over 10,000 elements takes about 2 ms, `reduce` about 3 ms, and a small rule well-under a microsecond. To apply one rule many times, `compile` it once and+under a microsecond. (Each `run` also converts the data it reads, so a rule+with a tiny body over a large array is dominated by that.) To apply one rule many times, `compile` it once and `run` it: reading and compiling happen once. `bash scripts/bench.sh` times a fixed set of workloads and records the
docs/STABILITY.md view
@@ -9,9 +9,9 @@ never on `renderError` text, whose wording may change in any release. The rendered form of a `Location` (`renderLocation`) is RFC 6901 and will not change.-- **`JsonLogic.Core.*`** is exposed for the test suites and for advanced use- (working with the rule tree directly). It carries **no stability promise- before 1.0**, and may change in any release.+- **`JsonLogic.Core.*`** is exposed so that the test suites can reach it, and+ hidden from the documentation. It carries **no stability promise**, and may+ change in any release without a version bump: import `JsonLogic` only. - Behaviour pinned by the classic suite, the outlier fixture, the community score (`test/community/expected.json`) or `docs/COMPATIBILITY.md` is not changed without a changelog entry and, for a deliberate deviation, a version
docs/TUTORIAL.md view
@@ -98,10 +98,17 @@ ```haskell apply (json "{\"if\": [true, {\"nope\": [1]}]}") Null--- Left (EvalFailure (fromSegments [Key "if",Index 1]) (UnknownOperator (OperatorName "nope")))+-- Left (ParseFailure (fromSegments [Key "if",Index 1]) (UnknownOperatorName (OperatorName "nope") [OperatorName "none"])) +apply (json "{\"missing_sone\": [1, [\"a\"]]}") Null -- a typo names its nearest operators+-- Left (ParseFailure (fromSegments []) (UnknownOperatorName (OperatorName "missing_sone") [OperatorName "missing_some"]))++-- every problem in a rule, not only the first:+map errorLocation (validate defaultConfig noOperators (json "{\"and\": [{\"nope\": []}, {\"mox\": []}]}"))+-- [fromSegments [Key "and",Index 0],fromSegments [Key "and",Index 1]]+ either renderError (const "") (apply (json "{\"if\": [true, {\"nope\": [1]}]}") Null)--- "at /if/1: unknown operator \"nope\""+-- "at /if/1: unknown operator \"nope\"; did you mean \"none\"?" ``` Match on constructors, not on `renderError`'s text, which may change:@@ -116,12 +123,16 @@ Left other -> "failed: " ++ show (renderError other) ``` -Two things are not errors in JsonLogic, because they are not in JavaScript:-odd operands produce `null`, `false` or `NaN`-turned-`null`, and an unknown-operator in a branch that is never taken is never looked at:+Odd operands are not errors in JsonLogic, because they are not in JavaScript:+they produce `null`, `false` or `NaN`-turned-`null`. An unknown operator is+refused when the rule is compiled, because a typo is the commonest mistake in+a rule written by a person. The reference only notices one if it reaches it;+ask for that with `unknownOperators = FailWhenReached` (lenient arity mode+does so too): ```haskell-apply (json "{\"or\": [true, {\"nope\": []}]}") Null -- Right (Bool True)+applyWithConfig defaultConfig{unknownOperators = FailWhenReached} noOperators+ (json "{\"or\": [true, {\"nope\": []}]}") Null -- Right (Bool True) ``` ## 5. Strict and lenient arity@@ -170,8 +181,9 @@ import qualified Data.Text as Text startsWith :: CustomOperator-startsWith _ [String prefix, String s] = Right (Bool (prefix `Text.isPrefixOf` s))-startsWith _ _ = Left "starts_with takes two strings"+startsWith = pureOperator (Exactly 2) $ \_ arguments -> case arguments of+ [String prefix, String s] -> Right (Bool (prefix `Text.isPrefixOf` s))+ _ -> Left "starts_with takes two strings" operators :: Either OperatorsError Operators operators = operatorsFromList [(OperatorName "starts_with", startsWith)]@@ -179,14 +191,35 @@ -- with Right ops = operators: applyWith ops (json "{\"starts_with\": [\"ad\", {\"var\": \"role\"}]}") (json "{\"role\": \"admin\"}") -- Right (Bool True)-applyWith ops (json "{\"starts_with\": [1]}") Null--- Left (EvalFailure (fromSegments []) (CustomOperatorFailed (OperatorName "starts_with") "starts_with takes two strings"))+applyWith ops (json "{\"starts_with\": [1, 2]}") Null+-- Left (EvalFailure (fromSegments []) (CustomOperatorFailed (OperatorName "starts_with") (CustomError {errorCode = "failed", errorMessage = "starts_with takes two strings", errorDetails = Nothing})))+applyWith ops (json "{\"starts_with\": [1]}") Null -- the declared arity is checked at compile time+-- Left (ParseFailure (fromSegments []) (ArityMismatch (OperatorName "starts_with") (Exactly 2) 1)) ``` -A registry refuses a builtin name (`ReservedOperatorName`) and a name given-twice (`DuplicateOperatorName`) instead of silently picking one. Registries-combine with `<>`, the left one winning. Operators are resolved when the rule-is compiled; the full contract is on `CustomOperator`.+A registry refuses a builtin name (`ReservedOperatorName`), a name given+twice (`DuplicateOperatorName`) and an empty or padded name+(`InvalidOperatorName`) instead of silently picking one. Registries combine+with `combineOperators`, which refuses a name both define. Operators are+resolved when the rule is compiled; the full contract is on `CustomOperator`.++A *lazy* operator receives its operands unevaluated and decides which to+evaluate, so it can short-circuit. It runs in `Step`, inside the same step+budget, and uses `force` and `stepFail`:++```haskell+coalesce :: CustomOperator+coalesce = lazyOperator (AtLeast 1) $ \_ operands -> go operands+ where+ go [] = pure Null+ go (operand : rest) = do+ value <- force operand+ if value == Null then go rest else pure value+```++Operators are pure on purpose: one that needs the clock or a database is given+that information in the data before the rule runs, which keeps evaluation+deterministic and its limits meaningful. ## 8. What does this rule read?
jsonlogic-hs.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.0 name: jsonlogic-hs-version: 0.1.0.0+version: 0.2.0.0 synopsis: JsonLogic rule engine, checked against the JavaScript reference description: jsonlogic-hs is a native Haskell implementation of JsonLogic@@ -26,9 +26,10 @@ supplied by the caller, and dataUse reports which parts of the data a rule can read. - The supported API is the "JsonLogic" module; docs/TUTORIAL.md walks through- it. The "JsonLogic.Core" modules are exposed for advanced use and may- change before 1.0.+ The supported API is the "JsonLogic" module; the "JsonLogic.Core" modules are+ hidden from the documentation and carry no stability promise;+ docs/TUTORIAL.md walks through it. The package also installs a small+ command, jsonlogic, to evaluate, check and inspect rules. category: Data, JSON license: MIT license-file: LICENSE@@ -104,13 +105,27 @@ if flag(werror) ghc-options: -Werror --- The supported API is the JsonLogic module. JsonLogic.Core.* is exposed for--- advanced use and for the test suites, and may change before 1.0.+-- Shared dependency bounds: one place to change them, so no component can+-- drift from the others.+common deps+ build-depends: base >=4.18 && <4.23+ , aeson >=2.1 && <2.4+ , bytestring >=0.11 && <0.13+ , text >=2.0 && <2.3++-- One library. The JsonLogic module is the API; the JsonLogic.Core modules+-- are compiled into the same library so the tests can reach them, and are+-- hidden from the documentation (OPTIONS_HADDOCK hide): JsonLogic re-exports+-- what is public, with its documentation, and nothing else is documented or+-- supported (docs/STABILITY.md). A private internal library would keep them+-- unimportable, but Haddock cannot link a package's documentation to its own+-- private sublibrary, so the public module's re-exports would lose theirs. library- import: warnings+ import: warnings, deps hs-source-dirs: src exposed-modules: JsonLogic JsonLogic.Core.Analysis+ JsonLogic.Core.Check JsonLogic.Core.Config JsonLogic.Core.Custom JsonLogic.Core.Errors@@ -120,41 +135,49 @@ JsonLogic.Core.Operator JsonLogic.Core.Parse JsonLogic.Core.Rule+ JsonLogic.Core.Run JsonLogic.Core.Ryu JsonLogic.Core.Utf16 JsonLogic.Core.Value- build-depends: base >=4.18 && <4.23- , aeson >=2.1 && <2.4- , containers >=0.6 && <0.9+ build-depends: containers >=0.6 && <0.9 , data-fix >=0.3 && <0.4+ , deepseq >=1.4 && <1.7+ , ghc-bignum >=1.3 && <2 , scientific >=0.3 && <0.4- , text >=2.0 && <2.3 , vector >=0.12.3 && <0.14 +-- The command-line tool: try, check and inspect rules without writing Haskell.+executable jsonlogic+ import: warnings, deps+ hs-source-dirs: app+ main-is: Main.hs+ build-depends: jsonlogic-hs+ test-suite jsonlogic-hs-test- import: warnings+ import: warnings, deps type: exitcode-stdio-1.0 hs-source-dirs: test main-is: Spec.hs other-modules: AnalysisSpec+ AuditSpec CompatSpec EvalSpec Gen LimitsSpec LocationSpec NumberSpec+ Oracle ParseSpec+ RegressionSpec Support ValueSpec -- a runaway allocation fails the test instead of swapping the machine ghc-options: -rtsopts "-with-rtsopts=-M2g"- build-depends: base >=4.18 && <4.23- , aeson >=2.1 && <2.4- , bytestring >=0.11 && <0.13- , data-fix >=0.3 && <0.4+ build-depends: data-fix >=0.3 && <0.4+ , deepseq >=1.4 && <1.7 , hspec >=2.10 && <2.12 , QuickCheck >=2.14 && <2.20- , text >=2.0 && <2.3+ , scientific >=0.3 && <0.4 , vector >=0.12.3 && <0.14 , jsonlogic-hs @@ -162,14 +185,11 @@ -- does not pass. Run it with: -- cabal test jsonlogic-hs-conformance --test-show-details=direct test-suite jsonlogic-hs-conformance- import: warnings+ import: warnings, deps type: exitcode-stdio-1.0 hs-source-dirs: conformance main-is: Conformance.hs- build-depends: base >=4.18 && <4.23- , aeson >=2.1 && <2.4- , bytestring >=0.11 && <0.13- , directory >=1.3 && <1.4+ build-depends: directory >=1.3 && <1.4 , jsonlogic-hs -- Replays the committed outlier fixture (test/outliers.jsonl), the@@ -177,44 +197,32 @@ -- Needs neither Node nor a network. Pass a path to replay another tier: -- cabal run jsonlogic-hs-outliers -- /path/to/full.jsonl test-suite jsonlogic-hs-outliers- import: warnings+ import: warnings, deps type: exitcode-stdio-1.0 hs-source-dirs: outliers main-is: Outliers.hs- build-depends: base >=4.18 && <4.23- , aeson >=2.1 && <2.4- , bytestring >=0.11 && <0.13- , containers >=0.6 && <0.9+ build-depends: containers >=0.6 && <0.9 , directory >=1.3 && <1.4 , scientific >=0.3 && <0.4- , text >=2.0 && <2.3 , jsonlogic-hs -- Every example in docs/TUTORIAL.md, checked against the library. test-suite jsonlogic-hs-tutorial- import: warnings+ import: warnings, deps type: exitcode-stdio-1.0 hs-source-dirs: tutorial main-is: Tutorial.hs- build-depends: base >=4.18 && <4.23- , aeson >=2.1 && <2.4- , bytestring >=0.11 && <0.13- , text >=2.0 && <2.3- , jsonlogic-hs+ build-depends: jsonlogic-hs -- Scores the library on the community suite (test/community, from -- json-logic/compat-tables) and fails if the score differs from -- test/community/expected.json. See test/community/README.md. test-suite jsonlogic-hs-community- import: warnings+ import: warnings, deps type: exitcode-stdio-1.0 hs-source-dirs: community main-is: Community.hs- build-depends: base >=4.18 && <4.23- , aeson >=2.1 && <2.4- , bytestring >=0.11 && <0.13- , directory >=1.3 && <1.4- , text >=2.0 && <2.3+ build-depends: directory >=1.3 && <1.4 , vector >=0.12.3 && <0.14 , jsonlogic-hs @@ -222,35 +230,28 @@ -- Node.js, so it is a flag-gated executable and not part of `cabal test`. -- See differential/README.md. executable jsonlogic-hs-differential- import: warnings+ import: warnings, deps if !flag(differential) buildable: False hs-source-dirs: differential main-is: Differential.hs- build-depends: base >=4.18 && <4.23- , aeson >=2.1 && <2.4- , bytestring >=0.11 && <0.13- , directory >=1.3 && <1.4+ build-depends: directory >=1.3 && <1.4 , process >=1.6 && <1.7 , QuickCheck >=2.14 && <2.20 , scientific >=0.3 && <0.4- , text >=2.0 && <2.3 , jsonlogic-hs -- Benchmarks. See docs/LIMITS.md and bench/Bench.hs. executable jsonlogic-hs-bench- import: warnings+ import: warnings, deps if !flag(bench) buildable: False hs-source-dirs: bench main-is: Bench.hs -- -T makes the RTS keep allocation statistics, which tasty-bench reports ghc-options: -rtsopts "-with-rtsopts=-T"- build-depends: base >=4.18 && <4.23- , aeson >=2.1 && <2.4- , bytestring >=0.11 && <0.13+ build-depends: scientific >=0.3 && <0.4 , tasty-bench >=0.3 && <0.5- , text >=2.0 && <2.3 , jsonlogic-hs source-repository head
outliers/Outliers.hs view
@@ -120,6 +120,8 @@ ++ show (count "strict-ok") ++ "\n strict rejected by arity: " ++ show (count "strict-arity")+ ++ "\n strict rejected unknown operator: "+ ++ show (count "strict-unknown") ++ "\n inherited-property deviation: " ++ show (count "inherited") ++ "\n re-evaluation deviation (skipped): "@@ -211,6 +213,9 @@ | strictRejects c name accepted given -> bump "strict-arity" | otherwise -> failWith (describe c "strict" target strict "arity rejection that the operator's arity does not justify")+ -- an operator nobody registered is refused when the rule is compiled+ -- (the reference finds out only if it reaches it): always justified+ Left (ParseFailure _ (UnknownOperatorName _ _)) -> bump "strict-unknown" _ -> case judge target strict of Nothing -> bump "strict-ok" Just why -> failWith (describe c "strict" target strict why)@@ -240,8 +245,8 @@ classOf message e = case e of EvalFailure _ (UnknownOperator _) -> "Unrecognized operation" `isInfixOf` m || "apply is not a function" `isInfixOf` m- EvalFailure _ (InvalidOperand (OperatorName "*")) -> "Reduce of empty array" `isInfixOf` m- EvalFailure _ (InvalidOperand _) -> "Cannot read properties" `isInfixOf` m+ EvalFailure _ (InvalidOperand (OperatorName "*") _) -> "Reduce of empty array" `isInfixOf` m+ EvalFailure _ (InvalidOperand _ _) -> "Cannot read properties" `isInfixOf` m ParseFailure _ (ArityMismatch (OperatorName "*") _ 0) -> "Reduce of empty array" `isInfixOf` m _ -> False where
src/JsonLogic.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE BangPatterns #-}+ -- | -- Module : JsonLogic --@@ -8,7 +10,8 @@ -- -- Both are aeson 'Value's. The default 'Config' bounds nesting depth, -- evaluation steps, string length and array length, so a rule from an--- untrusted source cannot exhaust time or memory.+-- untrusted source cannot exhaust time or memory, and refuses a rule that+-- names an operator nobody supplied. -- -- To run one rule against many inputs, 'compile' it once and 'run' it: --@@ -17,7 +20,8 @@ -- > Right compiled -> map (run compiled) inputs -- -- Every 'Error' carries the 'Location' in the rule where it happened, as a--- JSON Pointer.+-- JSON Pointer, and has a @ToJSON@ instance for responses to programs.+-- 'validate' reports every problem in a rule, not only the first. -- -- This module is the whole supported API. The @JsonLogic.Core.*@ modules -- are exposed for the test suites and for advanced use; they carry no@@ -27,26 +31,62 @@ apply , applyWith , applyWithConfig+ , applyBytes+ , applyBytesWith+ , BytesError (..) -- * Compiling a rule once , Rule , compile , run+ , tryRun+ , runWithTimeout+ , RunFailure (..) + -- * Checking before running+ , validate+ , checkData+ , unresolvedOperators+ -- * What a rule reads , DataUse (..) , dataUse -- * Configuration- , Config (..)+ , Config+ ( maxDepth+ , maxSteps+ , maxStringLength+ , maxArrayLength+ , maxIterations+ , maxNodes+ , maxDataDepth+ , arityMode+ , unknownOperators+ , numericSafety+ ) , ArityMode (..)+ , UnknownOperators (..)+ , NumericSafety (..)+ , ConfigError (..) , defaultConfig+ , unlimited+ , validateConfig -- * Custom operators , CustomOperator+ , pureOperator+ , lazyOperator+ , Operand+ , Step+ , force+ , stepFail+ , CustomError (..)+ , customFailure , Operators , noOperators , operatorsFromList+ , combineOperators , OperatorsError (..) , OperatorName (..) @@ -54,9 +94,11 @@ , Error (..) , ParseError (..) , EvalError (..)+ , OperandIssue (..) , LimitKind (..) , Arity (..) , errorLocation+ , errorKind , renderError -- * Locations@@ -67,48 +109,158 @@ , renderLocation ) where +import Control.DeepSeq (NFData (..))+import qualified Control.DeepSeq as DeepSeq+import Control.Exception (SomeAsyncException (..), SomeException, evaluate, fromException, throwIO, try) import Data.Aeson (Value)+import qualified Data.Aeson as Aeson import Data.Bifunctor (first)+import qualified Data.ByteString.Lazy as LazyByteString+import Data.Maybe (fromMaybe)+import System.Timeout (timeout) import JsonLogic.Core.Analysis (DataUse (..)) import qualified JsonLogic.Core.Analysis as Analysis-import JsonLogic.Core.Config (ArityMode (..), Config (..), defaultConfig)-import JsonLogic.Core.Custom (CustomOperator, Operators, noOperators, operatorsFromList)+import JsonLogic.Core.Check (unknownOperatorsIn)+import JsonLogic.Core.Config+ ( ArityMode (..)+ , Config (..)+ , ConfigError (..)+ , NumericSafety (..)+ , UnknownOperators (..)+ , defaultConfig+ , unlimited+ , validateConfig+ )+import JsonLogic.Core.Custom+ ( CustomOperator+ , Operand+ , Operators+ , Step+ , combineOperators+ , force+ , lazyOperator+ , noOperators+ , operatorsFromList+ , pureOperator+ , stepFail+ ) import JsonLogic.Core.Errors ( Arity (..)+ , CustomError (..) , Error (..) , EvalError (..) , LimitKind (..)+ , OperandIssue (..) , OperatorsError (..) , ParseError (..)+ , customFailure+ , errorKind , errorLocation , renderError ) import JsonLogic.Core.Eval (Program, compileRule, runProgram)-import JsonLogic.Core.Location (Location, Segment (..), fromSegments, locationSegments, renderLocation)+import JsonLogic.Core.Location (Location, Segment (..), fromSegments, locationSegments, renderLocation, root) import JsonLogic.Core.Operator (OperatorName (..))-import JsonLogic.Core.Parse (parseRuleWith)-import qualified JsonLogic.Core.Rule as Core+import JsonLogic.Core.Parse (parseProblems, parseRuleChecked)+import JsonLogic.Core.Value (firstLossyNumber, nestsDeeperThan) -- | A rule that has been read, checked and compiled, ready to run against -- any number of inputs. It keeps the 'Config' and the custom operators it was--- compiled with.-data Rule = Rule Core.Rule Program+-- compiled with, and nothing of the JSON it was read from.+data Rule = Rule !DataUse ![(Location, OperatorName)] !Program --- | Read a rule and compile it. Fails with a 'ParseFailure' if the rule--- nests too deeply or, in 'Strict' mode, gives an operator the wrong number of--- arguments. Custom operators are resolved here, once; an operator the--- registry does not have is reported as 'UnknownOperator' only if a run--- reaches it, because the reference evaluates rules lazily.+-- | A @Rule@ is compiled completely when it is built, so there is nothing+-- left to evaluate.+instance NFData Rule where+ rnf (Rule use unknown program) = rnf use `seq` rnf unknown `seq` program `seq` ()++-- | Read a rule and compile it. Fails with a 'ParseFailure' if the+-- configuration is invalid, the rule has too many nodes or nests too deeply,+-- and, with the default 'Config', if it gives an operator the wrong number of+-- arguments or names an operator that is neither builtin nor registered (the+-- error names the nearest known operators). 'Lenient' arity mode, or+-- 'FailWhenReached', accepts such a rule as the reference does and fails+-- only if a run reaches the operator; 'unresolvedOperators' lists them.+--+-- All of the work is done when the 'Right' is demanded, not on the first+-- 'run'. compile :: Config -> Operators -> Value -> Either Error Rule compile config operators value = do- tree <- first (uncurry ParseFailure) (parseRuleWith config value)- pure (Rule tree (compileRule config operators tree))+ tree <- first (uncurry ParseFailure) (parseRuleChecked config (Just operators) value)+ let !use = DeepSeq.force (Analysis.dataUse tree)+ !unknown = DeepSeq.force (unknownOperatorsIn operators tree)+ !program = compileRule config operators tree+ pure (Rule use unknown program) -- | Run a compiled rule against some data. run :: Rule -> Value -> Either Error Value-run (Rule _ program) input = first (uncurry EvalFailure) (runProgram program input)+run (Rule _ _ program) input = first (uncurry EvalFailure) (runProgram program input) +-- | Why 'tryRun' did not produce an answer.+data RunFailure+ = -- | The rule or a limit said no: a value, not a bug.+ Rejected Error+ | -- | A custom operator threw an exception (or one was raised while its+ -- result was forced). Asynchronous exceptions are never reported here.+ OperatorThrew SomeException+ | -- | Only from 'runWithTimeout': the time ran out.+ TimedOut+ deriving (Show)++-- | 'run', for callers who cannot let an exception escape: a custom+-- operator is ordinary Haskell and may throw, and 'run' being pure does not+-- stop it. The result is forced inside the 'try', so an exception raised+-- while a lazy part of it is evaluated is caught too.+--+-- Only /synchronous/ exceptions are caught. An asynchronous one (a+-- 'System.Timeout.timeout', a @killThread@, a stack or heap overflow, an+-- interrupt) is the caller's to receive, so it is re-thrown: swallowing it+-- would leave a cancelled thread running and make every enclosing timeout+-- report success.+tryRun :: Rule -> Value -> IO (Either RunFailure Value)+tryRun rule input = do+ outcome <- try (evaluate (DeepSeq.force (run rule input)))+ case outcome of+ Right (Right result) -> pure (Right result)+ Right (Left problem) -> pure (Left (Rejected problem))+ Left exception+ | Just (SomeAsyncException _) <- fromException exception -> throwIO exception+ | otherwise -> pure (Left (OperatorThrew exception))++-- | 'tryRun' under a wall-clock limit, in microseconds. The limits in+-- 'Config' bound work and memory, not time: a custom operator that is slow is+-- still slow, and this is how to bound it.+runWithTimeout :: Int -> Rule -> Value -> IO (Either RunFailure Value)+runWithTimeout microseconds rule input =+ fromMaybe (Left TimedOut) <$> timeout microseconds (tryRun rule input)++-- | Every problem 'compile' would find in a rule, not only the first, in+-- document order, so that a rule can be fixed in one pass. Empty exactly when+-- 'compile' succeeds (and the first element is the error 'compile' returns).+validate :: Config -> Operators -> Value -> [Error]+validate config operators value =+ map (uncurry ParseFailure) (parseProblems config (Just operators) value)++-- | Screen untrusted data once, before running rules against it: it must not+-- nest deeper than 'maxDataDepth' and, under 'RejectLossy', must hold no+-- number a double cannot carry. Evaluation itself does not walk the data.+checkData :: Config -> Value -> Either Error ()+checkData config input+ | nestsDeeperThan (maxDataDepth config) input =+ Left (EvalFailure root (LimitExceeded (DataDepthLimit (maxDataDepth config))))+ | numericSafety config == RejectLossy+ , Just n <- firstLossyNumber input =+ Left (EvalFailure root (LossyNumber n))+ | otherwise = Right ()++-- | The operators in a compiled rule that are neither builtin nor+-- registered, and where each is. With the default configuration there are+-- none (the rule would not have compiled); under 'FailWhenReached' or+-- 'Lenient' they are the places a run can fail with 'UnknownOperator'.+unresolvedOperators :: Rule -> [(Location, OperatorName)]+unresolvedOperators (Rule _ unknown _) = unknown+ -- | What a compiled rule can read from its data, found without running it: -- if 'usesAllData' is false, its result depends on the data only through -- the values at 'usedPaths'. Unlike the reference's @uses_data@, a @var@@@ -117,7 +269,7 @@ -- -- > dataUse <$> compile defaultConfig noOperators rule dataUse :: Rule -> DataUse-dataUse (Rule tree _) = Analysis.dataUse tree+dataUse (Rule use _ _) = use -- | Apply a rule to some data, with the builtin operators only and the -- default 'Config'.@@ -130,8 +282,33 @@ applyWith = applyWithConfig defaultConfig -- | Apply a rule to some data with an explicit 'Config' and extra--- operators. Equal to 'compile' then 'run'.+-- operators. Equal to 'compile' then 'run', without the data-use analysis+-- that only a kept @Rule@ needs. applyWithConfig :: Config -> Operators -> Value -> Value -> Either Error Value applyWithConfig config operators rule input = do- compiled <- compile config operators rule- run compiled input+ tree <- first (uncurry ParseFailure) (parseRuleChecked config (Just operators) rule)+ first (uncurry EvalFailure) (runProgram (compileRule config operators tree) input)++-- | Why 'applyBytes' failed.+data BytesError+ = -- | The rule is not JSON.+ MalformedRule String+ | -- | The data is not JSON.+ MalformedData String+ | -- | The rule or the evaluation was refused.+ Refused Error+ deriving (Show)++-- | 'apply' on JSON text: the rule, the data, and the result.+applyBytes :: LazyByteString.ByteString -> LazyByteString.ByteString -> Either BytesError LazyByteString.ByteString+applyBytes = applyBytesWith defaultConfig noOperators++-- | 'applyBytes' with an explicit 'Config' and extra operators.+applyBytesWith ::+ Config -> Operators -> LazyByteString.ByteString -> LazyByteString.ByteString -> Either BytesError LazyByteString.ByteString+applyBytesWith config operators rule input = do+ ruleValue <- first MalformedRule (Aeson.eitherDecode rule)+ inputValue <- first MalformedData (Aeson.eitherDecode input)+ first Refused (checkData config inputValue)+ result <- first Refused (applyWithConfig config operators ruleValue inputValue)+ pure (Aeson.encode result)
src/JsonLogic/Core/Analysis.hs view
@@ -1,3 +1,5 @@+{-# OPTIONS_HADDOCK hide #-}+ -- | -- Module : JsonLogic.Core.Analysis --@@ -23,25 +25,30 @@ , dataUse ) where +import Control.DeepSeq (NFData (..)) import Data.Aeson (Value (..)) import Data.Fix (foldFix) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as Text -import JsonLogic.Core.Rule (Node (..), Rule, RuleF (..))+import JsonLogic.Core.Parse (buildBuiltin)+import JsonLogic.Core.Rule (Node (..), RuleF (..), RuleTree) import JsonLogic.Core.Value (fromValue, toJsString) -- | What a rule can read from its data. data DataUse = DataUse- { usedPaths :: [Text]+ { usedPaths :: ![Text] -- ^ The paths it can read, sorted and without duplicates.- , usesAllData :: Bool+ , usesAllData :: !Bool -- ^ Whether it can read anything else, so that 'usedPaths' is not the -- whole story. } deriving (Eq, Show) +instance NFData DataUse where+ rnf (DataUse paths whole) = rnf paths `seq` rnf whole+ -- | What the rule can read, as a set while it is built. data Reads = Reads !(Set.Set Text) !Bool @@ -68,7 +75,7 @@ Computed -- | What a rule can read from its data.-dataUse :: Rule -> DataUse+dataUse :: RuleTree -> DataUse dataUse rule = case layerReads (foldFix layer rule) of Reads paths whole -> DataUse (Set.toAscList paths) whole @@ -94,6 +101,11 @@ None collection _ -> layerReads collection Some collection _ -> layerReads collection Reduce collection _ initial -> layerReads collection <> layerReads initial+ -- a builtin given surplus operands (lenient mode) reads what the same call+ -- without them reads, and the surplus operands are evaluated as well+ Applied builtin used extras -> case buildBuiltin builtin used of+ Just inner -> readsOf inner <> foldMap layerReads extras+ Nothing -> operands <> everything -- a custom operator is handed the whole datum CustomOp _ _ -> operands <> everything _ -> operands
+ src/JsonLogic/Core/Check.hs view
@@ -0,0 +1,87 @@+{-# OPTIONS_HADDOCK hide #-}++-- |+-- Module : JsonLogic.Core.Check+--+-- Problems with a rule that depend on the registry of custom operators, and+-- so cannot be found by reading the rule alone: an operator nobody+-- registered (with a suggestion for what was probably meant), and a+-- registered operator given the wrong number of operands.+module JsonLogic.Core.Check+ ( customProblem+ , unknownOperatorsIn+ , suggest+ ) where++import Data.Fix (foldFix)+import Data.Foldable (fold)+import Data.List (sortOn)+import Data.List.NonEmpty (NonEmpty (..))+import Data.Maybe (isNothing)+import Data.Text (Text)+import qualified Data.Text as Text++import JsonLogic.Core.Config (ArityMode (..), Config (..), rejectsUnknownOperators)+import JsonLogic.Core.Custom (Operators, lookupOperator, operatorArity, operatorNames)+import JsonLogic.Core.Errors (Arity (..), ParseError (..))+import JsonLogic.Core.Location (Location)+import JsonLogic.Core.Operator (Builtin, OperatorName (..), allBuiltins, builtinName)+import JsonLogic.Core.Rule (Node (..), RuleF (..), RuleTree)++-- | What is wrong with a call to a non-builtin operator given this many+-- operands, if anything. An unknown operator is a problem only when the+-- configuration refuses them at compile time; the arity of a registered+-- operator is checked only in strict arity mode.+customProblem :: Config -> Operators -> OperatorName -> Int -> Maybe ParseError+customProblem config operators name@(OperatorName text) count =+ case lookupOperator operators name of+ Nothing+ | rejectsUnknownOperators config -> Just (UnknownOperatorName name (suggest operators text))+ | otherwise -> Nothing+ Just implementation+ | arityMode config == Strict+ , not (admits (operatorArity implementation) count) ->+ Just (ArityMismatch name (operatorArity implementation) count)+ | otherwise -> Nothing+ where+ admits (Exactly n) c = c == n+ admits (AtLeast n) c = c >= n+ admits (Between low high) c = c >= low && c <= high++-- | Every operator in a rule that is neither builtin nor registered, with+-- where it is, in the order they appear.+unknownOperatorsIn :: Operators -> RuleTree -> [(Location, OperatorName)]+unknownOperatorsIn operators = foldFix layer+ where+ layer (Node location node) = own <> fold node+ where+ own = case node of+ CustomOp name _ | isNothing (lookupOperator operators name) -> [(location, name)]+ _ -> []++-- | The known operator names nearest to a name: within two edits, and no+-- farther than the nearest one found, at most three. Builtins and registered+-- operators are both known. Empty when nothing is close.+suggest :: Operators -> Text -> [OperatorName]+suggest operators name = case sortOn id close of+ [] -> []+ ranked@((best, _) : _) -> take 3 [OperatorName candidate | (d, candidate) <- ranked, d == best]+ where+ close = [(d, candidate) | candidate <- known, let d = editDistance name candidate, d <= 2, d < Text.length name]+ known = map builtinName (allBuiltins :: [Builtin]) ++ [n | OperatorName n <- operatorNames operators]++-- | Levenshtein distance, by the usual table kept one row at a time. Total:+-- no partial function, and the rows are never empty by construction. Uses+-- only what every supported GHC's Prelude has, and the strings are operator+-- names, so a lazy fold costs nothing.+editDistance :: Text -> Text -> Int+editDistance a b = lastOf (foldl row [0 .. length as] (Text.unpack b))+ where+ as = Text.unpack a+ -- the row for the prefix of @b@ read so far plus @c@, from the row before+ row previous c = case previous of+ [] -> []+ corner : rest -> scanl (compute c) (corner + 1) (zip3 as previous rest)+ compute c left (ac, diagonal, up) =+ minimum (left + 1 :| [up + 1, diagonal + (if ac == c then 0 else 1)])+ lastOf = foldl (\_ x -> x) 0
src/JsonLogic/Core/Config.hs view
@@ -1,18 +1,47 @@+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}+ -- | -- Module : JsonLogic.Core.Config -- -- Configuration for reading and evaluating rules: the resource limits that--- make it safe to evaluate rules from an untrusted source, and the arity--- mode.+-- make it safe to evaluate rules from an untrusted source, the arity mode,+-- how unknown operators and lossy numbers are treated. -- -- There is no global state. A @Config@ is an ordinary value passed to -- 'JsonLogic.compile' or 'JsonLogic.applyWithConfig'.+--+-- The @Config@ constructor is not exported: build one from 'defaultConfig'+-- with record update (@defaultConfig {maxSteps = 10000}@), so that adding a+-- field is never a breaking change. 'validateConfig' (called by every entry+-- point) refuses a configuration that cannot mean anything, such as a+-- negative limit. module JsonLogic.Core.Config ( ArityMode (..)- , Config (..)+ , UnknownOperators (..)+ , NumericSafety (..)+ , Config+ ( maxDepth+ , maxSteps+ , maxStringLength+ , maxArrayLength+ , maxIterations+ , maxNodes+ , maxDataDepth+ , arityMode+ , unknownOperators+ , numericSafety+ )+ , ConfigError (..) , defaultConfig+ , unlimited+ , validateConfig+ , rejectsUnknownOperators ) where +import Control.DeepSeq (NFData (..))+import Data.Text (Text)+ -- | What to do with an operator given the wrong number of arguments. data ArityMode = -- | Reject it with a precise 'JsonLogic.ArityMismatch'. The default:@@ -25,8 +54,42 @@ Lenient deriving (Eq, Show) --- | Limits and mode. All limits bound /work and memory/, not wall-clock--- time: a custom operator that is slow is still slow.+-- | What to do with a rule that names an operator that is neither builtin+-- nor registered.+data UnknownOperators+ = -- | 'RejectAtCompile' in 'Strict' arity mode and 'FailWhenReached' in+ -- 'Lenient' mode, so that each mode is internally consistent. The+ -- default.+ FollowArityMode+ | -- | Refuse the rule when it is compiled, naming the operator, where it+ -- is, and the nearest known operators.+ RejectAtCompile+ | -- | Accept the rule and fail only if a run reaches the operator, as the+ -- reference does (it evaluates rules lazily).+ FailWhenReached+ deriving (Eq, Show)++-- | How numbers that a JavaScript double cannot hold exactly are treated.+-- Such a number is an integer above 2^53, or a decimal whose nearest+-- double does not print back as the same digits.+data NumericSafety+ = -- | The reference's behaviour: every number is read as a double, and+ -- printed as the shortest digits that read back as it. A value that+ -- merely passes through a rule can change (@9007199254740993@ comes out+ -- as @9007199254740992@). The default.+ JsNumbers+ | -- | Arithmetic and comparison use doubles as in 'JsNumbers', but a+ -- number that reaches the result unchanged keeps its original digits.+ PreserveSource+ | -- | Refuse such a number, in the rule or the data, with a+ -- 'JsonLogic.LossyNumber' error instead of rounding it.+ RejectLossy+ deriving (Eq, Show)++-- | Limits and modes. All limits bound /work and memory/, not wall-clock+-- time: a custom operator that is slow is still slow. A limit of+-- 'unlimited' means no limit; a negative limit is refused by+-- 'validateConfig'. data Config = Config { maxDepth :: !Int -- ^ How deeply a rule (and any literal inside it, and any value a custom@@ -42,15 +105,66 @@ -- ^ The longest string @cat@ may build, in UTF-16 code units. Default -- 1,048,576. , maxArrayLength :: !Int- -- ^ The longest array @merge@, @map@ or @filter@ may build. Default+ -- ^ The longest array @merge@, @map@ or @filter@ may /build/. Default -- 100,000.+ , maxIterations :: !Int+ -- ^ The longest array @map@, @filter@, @reduce@, @all@, @none@ or @some@+ -- may /iterate/: the same for all six. Separate from 'maxArrayLength',+ -- which bounds what is built, so that admitting a large dataset does not+ -- loosen the guard against amplification. Default 100,000.+ , maxNodes :: !Int+ -- ^ How many nodes the rule's JSON may have: every scalar, array and+ -- object counts one. Checked before the rule is read, so an enormous+ -- rule is refused without being built. Default 1,000,000.+ , maxDataDepth :: !Int+ -- ^ How deeply the data may nest. Enforced by 'JsonLogic.checkData',+ -- which callers use to screen untrusted input once; evaluation itself+ -- does not walk the data. Default 1,000. , arityMode :: !ArityMode -- ^ 'Strict' (the default) or 'Lenient'.+ , unknownOperators :: !UnknownOperators+ -- ^ 'FollowArityMode' (the default), 'RejectAtCompile' or+ -- 'FailWhenReached'.+ , numericSafety :: !NumericSafety+ -- ^ 'JsNumbers' (the default), 'PreserveSource' or 'RejectLossy'. } deriving (Eq, Show) +-- | Why a @Config@ was refused.+newtype ConfigError+ = -- | The named field holds a negative limit.+ NegativeLimit Text+ deriving (Eq, Show)++instance NFData ArityMode where+ rnf mode = mode `seq` ()++instance NFData UnknownOperators where+ rnf mode = mode `seq` ()++instance NFData NumericSafety where+ rnf mode = mode `seq` ()++instance NFData ConfigError where+ rnf (NegativeLimit field) = rnf field++instance NFData Config where+ rnf (Config depth steps string array iterations nodes dataDepth mode unknown numeric) =+ depth+ `seq` steps+ `seq` string+ `seq` array+ `seq` iterations+ `seq` nodes+ `seq` dataDepth+ `seq` rnf mode+ `seq` rnf unknown+ `seq` rnf numeric+ -- | The default configuration: depth 64, one million steps, 1 MiB strings--- (in code units), 100,000-element arrays, strict arity.+-- (in code units), 100,000-element arrays built and iterated, a million rule+-- nodes, data depth 1,000, strict arity, unknown operators refused when the+-- rule is compiled, reference number semantics. defaultConfig :: Config defaultConfig = Config@@ -58,5 +172,40 @@ , maxSteps = 1000000 , maxStringLength = 1048576 , maxArrayLength = 100000+ , maxIterations = 100000+ , maxNodes = 1000000+ , maxDataDepth = 1000 , arityMode = Strict+ , unknownOperators = FollowArityMode+ , numericSafety = JsNumbers }++-- | The value of a limit that is not limited.+unlimited :: Int+unlimited = maxBound++-- | Refuse a configuration that cannot mean anything. Every entry point+-- calls this, so a bad limit is an error and never a silent \"refuse+-- everything\".+validateConfig :: Config -> Either ConfigError Config+validateConfig config = case [name | (name, value) <- limits, value < 0] of+ name : _ -> Left (NegativeLimit name)+ [] -> Right config+ where+ limits =+ [ ("maxDepth", maxDepth config)+ , ("maxSteps", maxSteps config)+ , ("maxStringLength", maxStringLength config)+ , ("maxArrayLength", maxArrayLength config)+ , ("maxIterations", maxIterations config)+ , ("maxNodes", maxNodes config)+ , ("maxDataDepth", maxDataDepth config)+ ]++-- | Whether a configuration refuses unknown operators when a rule is+-- compiled.+rejectsUnknownOperators :: Config -> Bool+rejectsUnknownOperators config = case unknownOperators config of+ RejectAtCompile -> True+ FailWhenReached -> False+ FollowArityMode -> arityMode config == Strict
src/JsonLogic/Core/Custom.hs view
@@ -1,3 +1,5 @@+{-# OPTIONS_HADDOCK hide #-}+ -- | -- Module : JsonLogic.Core.Custom --@@ -5,71 +7,140 @@ -- rule language. A registry is built once, checked when it is built, and -- handed to 'JsonLogic.compile', which resolves every custom operator in the -- rule against it.+--+-- Two kinds of operator exist. An /eager/ operator ('pureOperator') is a+-- function of its already-evaluated arguments. A /lazy/ operator+-- ('lazyOperator') is handed its operands unevaluated and decides which to+-- evaluate, so it can short-circuit: a @coalesce@, a @try@, an @and_then@.+-- Both are pure. An operator that needs the clock or a database is given+-- that information in the data, by the caller, before the rule runs; this+-- keeps evaluation deterministic and its limits meaningful. module JsonLogic.Core.Custom- ( CustomOperator+ ( CustomOperator (..)+ , pureOperator+ , lazyOperator+ , Operand (..)+ , Step (..)+ , force+ , stepFail+ , operatorArity , Operators , noOperators , operatorsFromList+ , combineOperators , lookupOperator+ , operatorNames ) where import Control.Monad (foldM) import qualified Data.Aeson as Aeson import qualified Data.Map.Strict as Map import Data.Maybe (isJust)-import Data.Text (Text)+import qualified Data.Text as Text -import JsonLogic.Core.Errors (OperatorsError (..))+import JsonLogic.Core.Errors (Arity (..), CustomError, EvalError (..), OperatorsError (..)) import JsonLogic.Core.Operator (OperatorName (..), lookupBuiltin)+import JsonLogic.Core.Run (At, Run, failAt)+import JsonLogic.Core.Value (Val, toValue) --- | A caller-supplied operator: given the data being evaluated against and--- its already-evaluated arguments, produce a result or a reason it failed.+-- | An operand of a lazy operator, not yet evaluated. Evaluating it+-- ('force') spends steps and can fail like any rule node; evaluating it+-- twice is evaluating it twice.+newtype Operand = Operand (Run Val)++-- | What a lazy operator computes in: evaluating operands, and failing.+-- It runs inside the evaluator's step budget, so a lazy operator cannot+-- escape the limits by choosing what to evaluate.+newtype Step a = Step {runStep :: At -> OperatorName -> Run a}++instance Functor Step where+ fmap f (Step m) = Step $ \at name -> fmap f (m at name)++instance Applicative Step where+ pure a = Step $ \_ _ -> pure a+ Step mf <*> Step ma = Step $ \at name -> mf at name <*> ma at name++instance Monad Step where+ Step m >>= k = Step $ \at name -> m at name >>= \a -> runStep (k a) at name++-- | Evaluate an operand, in the data scope the operator was called in.+force :: Operand -> Step Aeson.Value+force (Operand run) = Step $ \_ _ -> fmap toValue run++-- | Stop the evaluation with 'JsonLogic.Core.Errors.CustomOperatorFailed'.+stepFail :: CustomError -> Step a+stepFail reason = Step $ \at name -> failAt at (CustomOperatorFailed name reason)++-- | A caller-supplied operator, with the number of arguments it takes. -- -- The contract, in full: ----- * All of the operator's operands are evaluated, left to right, before it--- runs, as for the reference's own ordinary operators. An operator that--- nobody supplied is therefore reported only after its operands have run,--- and only if the rule reaches it.+-- * In strict arity mode the library checks the number of operands when+-- the rule is compiled, and refuses a rule that gives the wrong number.+-- In lenient mode the count is not checked, and the operator checks its+-- own. -- * The data argument is the datum in scope: inside @map@, @filter@ and the -- other iterating operators, the current element. It is converted to JSON -- lazily, so an operator that ignores it pays nothing for it. -- * Arguments and result are JSON. JavaScript values with no JSON form -- cross the boundary as @null@: @NaN@, the infinities and @undefined@.--- * The number of arguments is not checked by the library; the operator--- checks its own.--- * @Left reason@ stops the evaluation with--- 'JsonLogic.Core.Errors.CustomOperatorFailed'.+-- * An eager operator's operands are all evaluated, left to right, before+-- it runs; a lazy operator is handed them unevaluated.+-- * A failure ('Left', or 'stepFail') stops the evaluation with+-- 'JsonLogic.Core.Errors.CustomOperatorFailed', carrying the 'CustomError'+-- unchanged. -- * The result is held to the configured depth and step limits; the -- operator's own work is not (the library cannot see inside it).-type CustomOperator = Aeson.Value -> [Aeson.Value] -> Either Text Aeson.Value+data CustomOperator+ = Eager !Arity (Aeson.Value -> [Aeson.Value] -> Either CustomError Aeson.Value)+ | Lazy !Arity (Aeson.Value -> [Operand] -> Step Aeson.Value) --- | A registry of custom operators.-newtype Operators = Operators (Map.Map OperatorName CustomOperator)+-- | An eager operator: a pure function of the datum and the evaluated+-- operands.+pureOperator :: Arity -> (Aeson.Value -> [Aeson.Value] -> Either CustomError Aeson.Value) -> CustomOperator+pureOperator = Eager --- | Registries combine left-biased: where both define a name, the left one--- wins. Neither can hold a builtin name, so neither can the combination.-instance Semigroup Operators where- Operators left <> Operators right = Operators (Map.union left right)+-- | A lazy operator: it receives its operands unevaluated and 'force's the+-- ones it needs.+lazyOperator :: Arity -> (Aeson.Value -> [Operand] -> Step Aeson.Value) -> CustomOperator+lazyOperator = Lazy -instance Monoid Operators where- mempty = noOperators+-- | How many operands an operator takes.+operatorArity :: CustomOperator -> Arity+operatorArity (Eager arity _) = arity+operatorArity (Lazy arity _) = arity --- | No custom operators: any operator outside the builtin set is an--- 'JsonLogic.Core.Errors.UnknownOperator' when it is reached.+-- | A registry of custom operators.+newtype Operators = Operators (Map.Map OperatorName CustomOperator)++-- | No custom operators: any operator outside the builtin set is unknown. noOperators :: Operators noOperators = Operators Map.empty -- | Custom operators from an association list. A name that is a builtin--- operator, or that appears twice, is refused rather than silently ignored.+-- operator, that is empty or has leading or trailing whitespace, or that+-- appears twice, is refused rather than silently ignored. operatorsFromList :: [(OperatorName, CustomOperator)] -> Either OperatorsError Operators operatorsFromList entries = Operators <$> foldM add Map.empty entries where add table (name@(OperatorName text), implementation)+ | Text.null text || Text.strip text /= text = Left (InvalidOperatorName name) | isJust (lookupBuiltin text) = Left (ReservedOperatorName name) | Map.member name table = Left (DuplicateOperatorName name) | otherwise = Right (Map.insert name implementation table) +-- | Combine two registries. A name defined by both is an error: neither+-- definition silently wins.+combineOperators :: Operators -> Operators -> Either OperatorsError Operators+combineOperators (Operators left) (Operators right) =+ case Map.keys (Map.intersection left right) of+ [] -> Right (Operators (Map.union left right))+ name : _ -> Left (DuplicateOperatorName name)+ -- | The operator registered under a name. lookupOperator :: Operators -> OperatorName -> Maybe CustomOperator lookupOperator (Operators table) name = Map.lookup name table++-- | The names in a registry, in order.+operatorNames :: Operators -> [OperatorName]+operatorNames (Operators table) = Map.keys table
src/JsonLogic/Core/Errors.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-} -- | -- Module : JsonLogic.Core.Errors@@ -9,23 +10,34 @@ -- -- Callers match on the constructors, never on rendered text. 'renderError' -- produces a message for people and logs; its wording may change in any--- release.+-- release. For programs, 'Error' has a 'ToJSON' instance with stable+-- @kind@ tags. module JsonLogic.Core.Errors ( Arity (..)+ , CustomError (..)+ , customFailure , Error (..) , EvalError (..) , LimitKind (..)+ , OperandIssue (..) , OperatorsError (..) , ParseError (..)+ , errorKind , errorLocation , renderError , renderEvalError , renderParseError ) where +import Control.DeepSeq (NFData (..))+import Control.Exception (Exception (..))+import Data.Aeson (ToJSON (..), Value, object, (.=))+import Data.Scientific (FPFormat (..), Scientific, base10Exponent, formatScientific)+import Data.String (IsString (..)) import Data.Text (Text) import qualified Data.Text as Text +import JsonLogic.Core.Config (ConfigError (..)) import JsonLogic.Core.Location (Location, renderLocation) import JsonLogic.Core.Operator (OperatorName (..)) @@ -36,6 +48,34 @@ | Between Int Int deriving (Eq, Show) +-- | Why a custom operator failed, in a form a program can act on: a stable+-- code to match on, a message for people, and optional structured details.+-- With @OverloadedStrings@ a string literal is a failure with the code+-- @\"failed\"@, so @Left \"expected one number\"@ works.+data CustomError = CustomError+ { errorCode :: !Text+ , errorMessage :: !Text+ , errorDetails :: !(Maybe Value)+ }+ deriving (Eq, Show)++instance IsString CustomError where+ fromString = customFailure . Text.pack++-- | A failure with the code @\"failed\"@ and a message.+customFailure :: Text -> CustomError+customFailure message = CustomError "failed" message Nothing++-- | Which operand an operator could not work with, what it needed and what+-- it got.+data OperandIssue = OperandIssue+ { operandIndex :: !Int+ -- ^ Zero-based position among the operands.+ , operandExpected :: !Text+ , operandActual :: !Text+ }+ deriving (Eq, Show)+ -- | Why a JSON value could not be read as a rule. data ParseError = -- | The rule, or a literal inside it, nests deeper than the configured@@ -45,6 +85,18 @@ -- the operator, what it accepts, and how many it was given. Raised in -- strict arity mode only. ArityMismatch OperatorName Arity Int+ | -- | The rule's JSON has more nodes than the configured limit (carried+ -- here). Raised before anything is built.+ NodeLimitExceeded Int+ | -- | The rule names an operator that is neither builtin nor registered:+ -- the name, and the nearest known names (possibly none). Raised when+ -- the configuration refuses unknown operators at compile time.+ UnknownOperatorName OperatorName [OperatorName]+ | -- | The 'JsonLogic.Config' was refused.+ InvalidConfig ConfigError+ | -- | A number literal in the rule is not exactly a double (see+ -- 'JsonLogic.RejectLossy').+ LossyNumberLiteral Scientific deriving (Eq, Show) -- | Which resource limit stopped an evaluation, with the configured@@ -55,10 +107,14 @@ StepLimit Int | -- | A string result longer than allowed, in UTF-16 code units. StringLimit Int- | -- | An array result, or an array to iterate, longer than allowed.+ | -- | An array result longer than allowed. ArrayLimit Int+ | -- | An array to iterate longer than allowed.+ IterationLimit Int | -- | A value a custom operator returned nests deeper than allowed. ValueDepthLimit Int+ | -- | The data nests deeper than allowed (reported by 'JsonLogic.checkData').+ DataDepthLimit Int deriving (Eq, Show) -- | Why a well-formed rule could not be evaluated. JavaScript semantics@@ -68,15 +124,18 @@ data EvalError = -- | The rule reached an operator that is neither builtin nor supplied. UnknownOperator OperatorName- | -- | A supplied operator reported failure, with its reason.- CustomOperatorFailed OperatorName Text+ | -- | A supplied operator reported failure.+ CustomOperatorFailed OperatorName CustomError | -- | An operand the reference implementation throws a @TypeError@ on: -- @missing_some@ with a @null@ or missing option list, and @*@ with no -- operands at all (reached in lenient arity mode only; strict mode -- rejects it as an 'ArityMismatch' before evaluating).- InvalidOperand OperatorName+ InvalidOperand OperatorName OperandIssue | -- | A configured resource limit was exceeded. LimitExceeded LimitKind+ | -- | A number that is not exactly a double reached evaluation under+ -- 'JsonLogic.RejectLossy'.+ LossyNumber Scientific deriving (Eq, Show) -- | Why a registry of custom operators was refused. Raised when the@@ -86,6 +145,9 @@ ReservedOperatorName OperatorName | -- | The name was given more than once. DuplicateOperatorName OperatorName+ | -- | The name is empty, or has leading or trailing whitespace, so no+ -- rule key could match it as intended.+ InvalidOperatorName OperatorName deriving (Eq, Show) -- | A failure of either stage, and where in the rule it happened.@@ -125,21 +187,50 @@ "the rule nests deeper than the limit of " <> shown limit renderParseError (ArityMismatch (OperatorName name) accepted given) = "operator " <> quoted name <> " takes " <> renderArity accepted <> ", but was given " <> shown given+renderParseError (NodeLimitExceeded limit) =+ "the rule has more than the limit of " <> shown limit <> " nodes"+renderParseError (UnknownOperatorName (OperatorName name) near) =+ "unknown operator " <> quoted name <> didYouMean near+renderParseError (InvalidConfig (NegativeLimit field)) =+ "the configuration is invalid: " <> field <> " is negative"+renderParseError (LossyNumberLiteral n) =+ "the number " <> showNumber n <> " is not exactly representable as a double" -- | A one-line description of an evaluation error, without its location. renderEvalError :: EvalError -> Text renderEvalError (UnknownOperator (OperatorName name)) = "unknown operator " <> quoted name renderEvalError (CustomOperatorFailed (OperatorName name) reason) =- "custom operator " <> quoted name <> " failed: " <> reason-renderEvalError (InvalidOperand (OperatorName name)) =- "operator " <> quoted name <> " was given an operand it cannot work with"+ "custom operator " <> quoted name <> " failed: " <> errorMessage reason+renderEvalError (InvalidOperand (OperatorName name) issue) =+ "operator "+ <> quoted name+ <> ": operand "+ <> shown (operandIndex issue + 1)+ <> " must be "+ <> operandExpected issue+ <> ", but is "+ <> operandActual issue+renderEvalError (LossyNumber n) =+ "the number " <> showNumber n <> " is not exactly representable as a double" renderEvalError (LimitExceeded kind) = case kind of StepLimit n -> "evaluation exceeded the limit of " <> shown n <> " steps" StringLimit n -> "a string result exceeded the limit of " <> shown n <> " code units"- ArrayLimit n -> "an array exceeded the limit of " <> shown n <> " elements"+ ArrayLimit n -> "an array result exceeded the limit of " <> shown n <> " elements"+ IterationLimit n -> "an array to iterate exceeded the limit of " <> shown n <> " elements" ValueDepthLimit n -> "a value nests deeper than the limit of " <> shown n+ DataDepthLimit n -> "the data nests deeper than the limit of " <> shown n +-- | A number as it was written, in plain digits unless that would be absurdly long.+showNumber :: Scientific -> Text+showNumber n+ | abs (base10Exponent n) <= 30 = Text.pack (formatScientific Fixed Nothing n)+ | otherwise = Text.pack (formatScientific Exponent Nothing n)++didYouMean :: [OperatorName] -> Text+didYouMean [] = ""+didYouMean near = "; did you mean " <> Text.intercalate " or " [quoted name | OperatorName name <- near] <> "?"+ renderArity :: Arity -> Text renderArity (Exactly n) = "exactly " <> shown n <> plural n renderArity (AtLeast n) = "at least " <> shown n <> plural n@@ -154,3 +245,124 @@ quoted :: Text -> Text quoted name = "\"" <> name <> "\""++-- | A stable, machine-readable tag for each kind of error: the constructor+-- name in @snake_case@. Programs should match on this, not on messages.+errorKind :: Error -> Text+errorKind (ParseFailure _ problem) = case problem of+ DepthExceeded _ -> "depth_exceeded"+ ArityMismatch{} -> "arity_mismatch"+ NodeLimitExceeded _ -> "node_limit_exceeded"+ UnknownOperatorName{} -> "unknown_operator"+ InvalidConfig _ -> "invalid_config"+ LossyNumberLiteral _ -> "lossy_number"+errorKind (EvalFailure _ problem) = case problem of+ UnknownOperator _ -> "unknown_operator"+ CustomOperatorFailed{} -> "custom_operator_failed"+ InvalidOperand{} -> "invalid_operand"+ LimitExceeded _ -> "limit_exceeded"+ LossyNumber _ -> "lossy_number"++-- | @{"kind": ..., "stage": "parse" | "eval", "pointer": RFC 6901,+-- "message": ..., "detail": {...}}@.+instance ToJSON Error where+ toJSON e =+ object+ [ "kind" .= errorKind e+ , "stage" .= (stage :: Text)+ , "pointer" .= renderLocation (errorLocation e)+ , "message" .= renderError e+ , "detail" .= detail+ ]+ where+ (stage, detail) = case e of+ ParseFailure _ problem -> ("parse", parseDetail problem)+ EvalFailure _ problem -> ("eval", evalDetail problem)++parseDetail :: ParseError -> Value+parseDetail problem = case problem of+ DepthExceeded n -> object ["limit" .= n]+ ArityMismatch (OperatorName name) accepted given ->+ object ["operator" .= name, "accepts" .= arityJson accepted, "given" .= given]+ NodeLimitExceeded n -> object ["limit" .= n]+ UnknownOperatorName (OperatorName name) near ->+ object ["operator" .= name, "suggestions" .= [n | OperatorName n <- near]]+ InvalidConfig (NegativeLimit field) -> object ["field" .= field]+ LossyNumberLiteral n -> object ["number" .= n]++evalDetail :: EvalError -> Value+evalDetail problem = case problem of+ UnknownOperator (OperatorName name) -> object ["operator" .= name]+ CustomOperatorFailed (OperatorName name) reason ->+ object ["operator" .= name, "code" .= errorCode reason, "message" .= errorMessage reason, "details" .= errorDetails reason]+ InvalidOperand (OperatorName name) issue ->+ object+ [ "operator" .= name+ , "operand" .= operandIndex issue+ , "expected" .= operandExpected issue+ , "actual" .= operandActual issue+ ]+ LimitExceeded kind -> case kind of+ StepLimit n -> limit "steps" n+ StringLimit n -> limit "string_length" n+ ArrayLimit n -> limit "array_length" n+ IterationLimit n -> limit "iterations" n+ ValueDepthLimit n -> limit "value_depth" n+ DataDepthLimit n -> limit "data_depth" n+ LossyNumber n -> object ["number" .= n]+ where+ limit name n = object ["limit" .= (name :: Text), "value" .= n]++arityJson :: Arity -> Value+arityJson (Exactly n) = object ["exactly" .= n]+arityJson (AtLeast n) = object ["at_least" .= n]+arityJson (Between low high) = object ["between" .= [low, high]]++-- | So that an 'Error' can be thrown, for callers that prefer exceptions.+-- Its 'displayException' is 'renderError', so an uncaught error reads as a+-- sentence and not as a constructor tree.+instance Exception Error where+ displayException = Text.unpack . renderError++instance NFData Arity where+ rnf (Exactly n) = rnf n+ rnf (AtLeast n) = rnf n+ rnf (Between low high) = rnf low `seq` rnf high++instance NFData CustomError where+ rnf (CustomError code message details) = rnf code `seq` rnf message `seq` rnf details++instance NFData OperandIssue where+ rnf (OperandIssue index expected actual) = rnf index `seq` rnf expected `seq` rnf actual++instance NFData ParseError where+ rnf (DepthExceeded n) = rnf n+ rnf (ArityMismatch name arity given) = rnf name `seq` rnf arity `seq` rnf given+ rnf (NodeLimitExceeded n) = rnf n+ rnf (UnknownOperatorName name near) = rnf name `seq` rnf near+ rnf (InvalidConfig e) = rnf e+ rnf (LossyNumberLiteral n) = rnf n++instance NFData LimitKind where+ rnf (StepLimit n) = rnf n+ rnf (StringLimit n) = rnf n+ rnf (ArrayLimit n) = rnf n+ rnf (IterationLimit n) = rnf n+ rnf (ValueDepthLimit n) = rnf n+ rnf (DataDepthLimit n) = rnf n++instance NFData EvalError where+ rnf (UnknownOperator name) = rnf name+ rnf (CustomOperatorFailed name reason) = rnf name `seq` rnf reason+ rnf (InvalidOperand name issue) = rnf name `seq` rnf issue+ rnf (LimitExceeded kind) = rnf kind+ rnf (LossyNumber n) = rnf n++instance NFData OperatorsError where+ rnf (ReservedOperatorName name) = rnf name+ rnf (DuplicateOperatorName name) = rnf name+ rnf (InvalidOperatorName name) = rnf name++instance NFData Error where+ rnf (ParseFailure location problem) = rnf location `seq` rnf problem+ rnf (EvalFailure location problem) = rnf location `seq` rnf problem
src/JsonLogic/Core/Eval.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-} -- | -- Module : JsonLogic.Core.Eval@@ -15,11 +16,9 @@ -- choosing each node's code) happens during the fold, so running a compiled -- rule many times pays for it once. ----- Evaluation runs in 'Run', a small state-passing monad whose state is the--- remaining step budget. It is pure: the budget is threaded through the--- evaluation, never held in a global or in 'IO'. A failure carries the--- location of the node that failed. See "JsonLogic.Core.Config" for the--- limits.+-- Evaluation runs in @Run@ (see "JsonLogic.Core.Run"), a small+-- state-passing monad whose state is the remaining step budget. See+-- "JsonLogic.Core.Config" for the limits. -- -- Operand evaluation order follows the reference: every operand is evaluated -- before its operator runs, except where the reference evaluates lazily@@ -29,7 +28,6 @@ ( Program , compileRule , runProgram- , evaluate ) where import Control.Monad (foldM, when)@@ -42,126 +40,181 @@ import Data.Maybe (fromMaybe) import Data.Text (Text) import qualified Data.Text as Text+import Data.Text.Unsafe (lengthWord8) import Data.Vector (Vector) import qualified Data.Vector as Vector -import JsonLogic.Core.Config (Config (..), defaultConfig)-import JsonLogic.Core.Custom (Operators, lookupOperator, noOperators)-import JsonLogic.Core.Errors (EvalError (..), LimitKind (..))-import JsonLogic.Core.Location (Location)+import JsonLogic.Core.Config (Config (..), NumericSafety (..))+import JsonLogic.Core.Custom (CustomOperator (..), Operand (..), Operators, lookupOperator, runStep)+import JsonLogic.Core.Errors (EvalError (..), LimitKind (..), OperandIssue (..))+import JsonLogic.Core.Location (Location, root) import JsonLogic.Core.Number (maximumJs, minimumJs, remainderJs) import JsonLogic.Core.Operator (Builtin (..), builtinOperatorName)-import JsonLogic.Core.Rule (Node (..), Rule, RuleF (..))-import JsonLogic.Core.Utf16 (utf16CharAt, utf16Length, utf16Slice)+import JsonLogic.Core.Parse (buildBuiltin)+import JsonLogic.Core.Rule (Node (..), RuleF (..), RuleTree)+import JsonLogic.Core.Run (At (..), Result (..), Run (..), exceeded, failAt, spend)+import JsonLogic.Core.Utf16+ ( Units+ , fromUnits+ , textIsInfixOf+ , toUnits+ , unitsIsInfixOf+ , unitsLength+ , unitsSlice+ , utf16CharAtExact+ , utf16Length+ , utf16SliceExact+ ) import JsonLogic.Core.Value -- ------------------------------------------------------------------------ The evaluation monad+-- Costs -- --------------------------------------------------------------------- --- | The outcome of a step: its value and the budget left, or where and why--- it failed. One constructor per outcome, strict, so the budget cannot pile--- up as a chain of thunks and a step allocates one cell.-data Result a- = Done !a {-# UNPACK #-} !Int- | Failed !Location !EvalError---- | A computation that may fail, at a location in the rule, and that spends--- steps from a budget.-newtype Run a = Run {unRun :: Int -> Result a}--instance Functor Run where- fmap f (Run m) = Run $ \budget -> case m budget of- Done a left -> Done (f a) left- Failed location e -> Failed location e- {-# INLINE fmap #-}--instance Applicative Run where- pure a = Run (Done a)- {-# INLINE pure #-}- Run mf <*> Run ma = Run $ \budget -> case mf budget of- Failed location e -> Failed location e- Done f left -> case ma left of- Failed location e -> Failed location e- Done a left' -> Done (f a) left'- {-# INLINE (<*>) #-}+-- | Spend steps for converting an operand to a string, which costs as many+-- steps as an array operand has elements, at any depth. Every other value+-- converts for free.+spendOnConversion :: At -> Val -> Run ()+spendOnConversion at value = case value of+ VArr _ -> Run $ \budget -> unRun (spend at (valWeightUpTo (saturatingSucc budget) value)) budget+ _ -> pure () -instance Monad Run where- Run m >>= k = Run $ \budget -> case m budget of- Failed location e -> Failed location e- Done a left -> unRun (k a) left- {-# INLINE (>>=) #-}+-- | How many bytes of a string one step pays for when an operator only+-- /scans/ it (compares, searches, slices): the cost of a scan is its length,+-- whatever the rule around it looks like, so a string is charged by length,+-- from a length that is known in constant time. Short strings cost nothing+-- extra.+bytesPerScanStep :: Int+bytesPerScanStep = 64 --- | What every node's code knows about itself: the configuration it was--- compiled with and where it is in the rule.-data At = At !Config !Location+-- | The same when an operator may /read a string as a number/, which is+-- about ten times the work per byte of a scan.+bytesPerReadStep :: Int+bytesPerReadStep = 8 --- | Fail here.-failAt :: At -> EvalError -> Run a-failAt (At _ location) e = Run (const (Failed location e))+-- | Spend steps for an operand an operator scans: an array by its elements,+-- a string by its length.+spendOnScan :: At -> Val -> Run ()+spendOnScan at value = case value of+ VStr _ -> spendOnString at value+ VWtf _ -> spendOnString at value+ _ -> spendOnConversion at value --- | Fail here because a limit was exceeded.-exceeded :: At -> (Config -> LimitKind) -> Run a-exceeded at@(At config _) kind = failAt at (LimitExceeded (kind config))+-- | Spend steps for a string an operator scans, and nothing for any other+-- operand.+spendOnString :: At -> Val -> Run ()+spendOnString at (VStr s) = spend at (lengthWord8 s `quot` bytesPerScanStep)+spendOnString at (VWtf u) = spend at (2 * unitsLength u `quot` bytesPerScanStep)+spendOnString _ _ = pure () --- | Spend @n@ steps, or fail here if fewer than @n@ remain.-spend :: At -> Int -> Run ()-spend (At config location) n = Run $ \budget ->- if n > budget- then Failed location (LimitExceeded (StepLimit (maxSteps config)))- else Done () (budget - n)-{-# INLINE spend #-}+-- | Spend steps for an operand an operator may read as a number: an array+-- by its elements, a string by its length at the reading rate.+spendOnReading :: At -> Val -> Run ()+spendOnReading at value = case value of+ VStr s -> spend at (lengthWord8 s `quot` bytesPerReadStep)+ VWtf u -> spend at (2 * unitsLength u `quot` bytesPerReadStep)+ _ -> spendOnConversion at value --- | Spend steps for converting an operand to a string or number, which--- costs as many steps as an array operand has elements, at any depth.--- Every other value converts for free.-spendOnConversion :: At -> Val -> Run ()-spendOnConversion at value = case value of- VArr _ -> Run $ \budget -> unRun (spend at (valWeightUpTo (budget + 1) value)) budget- _ -> pure ()+-- | Spend steps for two operands that are compared or equated. If both are+-- strings (arrays and objects compare as the strings they convert to) the+-- comparison scans them; otherwise a string is read as a number.+spendOnComparison :: At -> Val -> Val -> Run ()+spendOnComparison at a b+ | stringlike a && stringlike b = spendOnScan at a >> spendOnScan at b+ | otherwise = spendOnReading at a >> spendOnReading at b+ where+ stringlike v = case v of+ VStr _ -> True+ VWtf _ -> True+ VArr _ -> True+ VObj _ -> True+ _ -> False -- --------------------------------------------------------------------- -- Compiling and running -- --------------------------------------------------------------------- +-- | The datum a node is evaluated against: the value, and the same datum as+-- JSON, which a custom operator is handed. The JSON is built the first time+-- it is asked for and then shared by every node evaluated against this+-- datum, so an operator that reads one field of a large datum does not+-- rebuild the whole of it on every call. At the root it is the input itself.+data Env = Env+ { envValue :: !Val+ , envJson :: Aeson.Value+ , envSlots :: [Val]+ -- ^ The values of the operands of an 'Applied' call, which its operator+ -- reads instead of evaluating them again. Empty everywhere else.+ }++-- | A datum that came from evaluation: its JSON is built when needed.+mkEnv :: Val -> Env+mkEnv value = Env value (toValue value) []+ -- | A rule compiled to a function of the data.-type Eval = Val -> Run Val+type Eval = Env -> Run Val -- | A compiled node: its code, and its value if it is a literal (so that a -- parent can do work ahead of time, such as splitting a @var@ path once).+-- Strict, so that compiling a rule builds all of it, not just its root. data Compiled = Compiled- { compiledLiteral :: Maybe Val- , compiledEval :: Eval+ { compiledLiteral :: !(Maybe Val)+ , compiledEval :: !Eval } -- | A compiled rule, with the configuration it was compiled with.-data Program = Program !Config Eval+data Program = Program !Config !Eval -- | Compile a rule once: convert its literals, resolve its custom operators--- against the registry, and build each node's code.-compileRule :: Config -> Operators -> Rule -> Program-compileRule config operators rule =- Program config (compiledEval (foldFix (compileNode config operators) rule))+-- against the registry, and build each node's code. All of the work is done+-- when the result is first demanded, not spread over the first run.+compileRule :: Config -> Operators -> RuleTree -> Program+compileRule config operators rule = case foldFix (compileNode config operators) rule of+ Compiled _ eval -> Program config eval -- | Run a compiled rule against some data, with the configured step budget.+-- Under 'RejectLossy' the data is first checked for numbers a double cannot+-- carry, which costs one walk of it; under the other policies it is not+-- walked at all. runProgram :: Program -> Aeson.Value -> Either (Location, EvalError) Aeson.Value-runProgram (Program config eval) input =- case unRun (eval (fromValue input)) (maxSteps config) of+runProgram (Program config eval) input = case lossyInput of+ Just n -> Left (root, LossyNumber n)+ Nothing -> case unRun (eval (Env (fromValueWith (numericSafety config) input) input [])) (maxSteps config) of Failed location e -> Left (location, e)- Done result _ -> Right (toValue result)+ Done result _+ | resultTooLarge (maxSteps config) input result ->+ Left (root, LimitExceeded (StepLimit (maxSteps config)))+ | otherwise -> Right (toValue result)+ where+ lossyInput+ | numericSafety config == RejectLossy = firstLossyNumber input+ | otherwise = Nothing --- | Compile and run with 'defaultConfig' and no custom operators.-evaluate :: Rule -> Aeson.Value -> Either (Location, EvalError) Aeson.Value-evaluate = runProgram . compileRule defaultConfig noOperators+-- | Is a result's tree larger than the budget could have built, plus the data+-- it may simply hold? Arrays are shared, not copied, so a @reduce@ whose body+-- is @[acc, acc]@ builds a result whose /tree/ doubles on every iteration+-- while each iteration costs a few steps. Nothing else walks a result, so its+-- consumer would. Checked once, at the end, in work bounded by the budget plus+-- the size of the data; only the first, cheap comparison runs unless the+-- result is large.+resultTooLarge :: Int -> Aeson.Value -> Val -> Bool+resultTooLarge budget input result =+ valWeightUpTo (saturatingSucc budget) result > budget+ && valWeightUpTo (saturatingSucc allowance) result > allowance+ where+ allowance = saturatingAdd budget (valWeightUpTo maxBound (fromValue input))+ saturatingAdd a b = if a > maxBound - b then maxBound else a + b -- | One layer of the fold: given each child already compiled, compile this -- node. Evaluating a node costs one step, before its own work. compileNode :: Config -> Operators -> Node Compiled -> Compiled-compileNode config operators (Node location node) = Compiled literal (\env -> spend at 1 >> body env)+compileNode config operators (Node location node) =+ -- every child, then this node's own code, is built before the node is+ foldr seq () node `seq` body `seq` Compiled literal (\env -> spend at 1 >> body env) where at = At config location literal = case node of- Lit value -> Just (fromValue value)+ Lit value -> Just (fromValueWith (numericSafety config) value) _ -> Nothing body = case node of -- the path of a @var@ is almost always a literal: read it once, here@@ -175,29 +228,29 @@ compileBody at@(At config _) operators node = case node of Lit literal -> -- converted once, when the rule is compiled, and shared by every run- let converted = fromValue literal in const (pure converted)+ let converted = fromValueWith (numericSafety config) literal in const (pure converted) Arr items -> let elements = Vector.fromList items in \env -> VArr <$> Vector.mapM ($ env) elements Var path fallback -> variable at path fallback (pure . pathOf) Missing keys -> \env -> do names <- evalAll keys env mapM_ (spendOnConversion at) names- let (work, absent) = missingKeys (workCap config) names env+ let (work, absent) = missingKeys (workCap config) names (envValue env) spend at work pure (VArr (Vector.fromList absent)) MissingSome needed options -> \env -> do count <- needed env listed <- options env- missingSome at count listed env+ missingSome at count listed (envValue env) If branches -> evalIf branches And operands -> evalAnd operands Or operands -> evalOr operands Not operand -> fmap (VBool . not . truthy) . operand DoubleNot operand -> fmap (VBool . truthy) . operand LooseEq x y -> coercing at (\a b -> VBool (looseEquals a b)) x y- StrictEq x y -> binary (\a b -> VBool (strictEquals a b)) x y+ StrictEq x y -> binary at (\a b -> VBool (strictEquals a b)) x y LooseNeq x y -> coercing at (\a b -> VBool (not (looseEquals a b))) x y- StrictNeq x y -> binary (\a b -> VBool (not (strictEquals a b))) x y+ StrictNeq x y -> binary at (\a b -> VBool (not (strictEquals a b))) x y Lt x y z -> between at lessThan x y z Lte x y z -> between at lessOrEqual x y z Gt x y -> coercing at (\a b -> VBool (lessThan b a)) x y@@ -209,37 +262,39 @@ Sub x y -> \env -> do a <- x env b <- definedOperand <$> traverse ($ env) y- spendOnConversion at a- mapM_ (spendOnConversion at) b+ spendOnReading at a+ mapM_ (spendOnReading at) b pure (VNum (maybe (negate (toNumber a)) (\v -> toNumber a - toNumber v) b))- Mul [] -> const (failAt at (InvalidOperand (builtinOperatorName BMul)))+ Mul [] -> const (failAt at (InvalidOperand (builtinOperatorName BMul) (OperandIssue 0 "at least one operand" "none"))) Mul (first : rest) -> \env -> do -- the reference folds without a seed: a single operand is returned as -- it is, not converted to a number a <- first env bs <- evalAll rest env- mapM_ (spendOnConversion at) (a : bs)+ mapM_ (spendOnReading at) (a : bs) pure (List.foldl' (\acc v -> VNum (parseFloat acc * parseFloat v)) a bs) Div x y -> coercing at (\a b -> VNum (toNumber a / toNumber b)) x y Mod x y -> coercing at (\a b -> VNum (remainderJs (toNumber a) (toNumber b))) x y Map collection logic ->- withCollection collection (VArr Vector.empty) $ \items -> do- guardInput at items- VArr <$> Vector.mapM logic items+ withCollection at collection (VArr Vector.empty) $ \items -> do+ if Vector.length items > maxArrayLength config+ then exceeded at (ArrayLimit . maxArrayLength)+ else VArr <$> Vector.mapM (logic . mkEnv) items Filter collection logic ->- withCollection collection (VArr Vector.empty) $ \items -> do- guardInput at items- VArr <$> Vector.filterM (fmap truthy . logic) items- Reduce collection logic initial -> reduceRule collection logic initial+ withCollection at collection (VArr Vector.empty) $ \items -> do+ kept <- Vector.filterM (fmap truthy . logic . mkEnv) items+ guardBuilt at (Vector.length kept)+ pure (VArr kept)+ Reduce collection logic initial -> reduceRule at collection logic initial All collection logic ->- withCollection collection (VBool False) $ \items ->- if Vector.null items then pure (VBool False) else VBool <$> allTruthy logic (Vector.toList items)+ withCollection at collection (VBool False) $ \items ->+ if Vector.null items then pure (VBool False) else VBool <$> allTruthy (logic . mkEnv) (Vector.toList items) None collection logic ->- withCollection collection (VBool True) $ \items ->- if Vector.null items then pure (VBool True) else VBool . not <$> anyTruthy logic (Vector.toList items)+ withCollection at collection (VBool True) $ \items ->+ if Vector.null items then pure (VBool True) else VBool . not <$> anyTruthy (logic . mkEnv) (Vector.toList items) Some collection logic ->- withCollection collection (VBool False) $ \items ->- if Vector.null items then pure (VBool False) else VBool <$> anyTruthy logic (Vector.toList items)+ withCollection at collection (VBool False) $ \items ->+ if Vector.null items then pure (VBool False) else VBool <$> anyTruthy (logic . mkEnv) (Vector.toList items) Merge operands -> \env -> do values <- evalAll operands env let pieces = map flattenOnce values@@ -247,44 +302,80 @@ when (size > maxArrayLength config) $ exceeded at (ArrayLimit . maxArrayLength) spend at size pure (VArr (Vector.concat pieces))- In needle haystack -> coercing at (\a b -> VBool (contains a b)) needle haystack+ In needle haystack -> scanning at (\a b -> VBool (contains a b)) needle haystack Cat operands -> \env -> do values <- evalAll operands env mapM_ (spendOnConversion at) values- let pieces = map toJoinText values+ let pieces = map joinPiece values total <- foldM (addLength at) 0 pieces spend at total- pure (VStr (Text.concat pieces))+ pure (jsStrVal (joinJsStr "" pieces)) Substr source start len -> \env -> do text <- source env from <- start env limit <- definedOperand <$> traverse ($ env) len- spendOnConversion at text- pure (VStr (substring (toJsString text) from limit))+ spendOnScan at text+ pure (jsStrVal (substring (toJsStr text) from limit)) Log operand -> operand- Discard inner extras -> \env -> do- result <- inner env- mapM_ ($ env) extras- pure result+ Applied builtin used extras ->+ let count = length used+ slots = [pure . slotAt i | i <- [0 .. count - 1]]+ in case buildBuiltin builtin slots of+ Nothing -> const (failAt at (UnknownOperator (builtinOperatorName builtin)))+ Just inner ->+ let apply = compileBody at operators inner+ in \env -> do+ -- every operand, left to right, then the operator on the+ -- first few: the reference's order+ values <- evalAll (used ++ extras) env+ apply env{envSlots = take count values} CustomOp name operands -> case lookupOperator operators name of Nothing -> \env -> evalAll operands env >> failAt at (UnknownOperator name)- Just implementation -> \env -> do+ Just (Eager _ implementation) -> \env -> do arguments <- evalAll operands env- case implementation (toValue env) (map toValue arguments) of+ case implementation (envJson env) (map toValue arguments) of Left reason -> failAt at (CustomOperatorFailed name reason)- Right result -> do- when (nestsDeeperThan (maxDepth config) result) $- exceeded at (ValueDepthLimit . maxDepth)- spend at (jsonWeightUpTo (maxSteps config + 1) result)- pure (fromValue result)+ Right result -> acceptResult at result+ Just (Lazy _ implementation) -> \env ->+ let unevaluated = [Operand (operand env) | operand <- operands]+ in runStep (implementation (envJson env) unevaluated) at name >>= acceptResult at +-- | The value of the operand in a slot. The slots are filled with exactly as+-- many values as the operator has operands, so the default is never used; it+-- keeps the lookup total.+slotAt :: Int -> Env -> Val+slotAt i env = case drop i (envSlots env) of+ value : _ -> value+ [] -> VUndefined++-- | A custom operator's result, held to the depth and step limits and (under+-- 'RejectLossy') to the number policy, then converted to a value.+acceptResult :: At -> Aeson.Value -> Run Val+acceptResult at@(At config _) result = do+ when (nestsDeeperThan (maxDepth config) result) $+ exceeded at (ValueDepthLimit . maxDepth)+ spend at (jsonWeightUpTo (saturatingSucc (maxSteps config)) result)+ case firstLossy of+ Just n -> failAt at (LossyNumber n)+ Nothing -> pure (fromValueWith (numericSafety config) result)+ where+ firstLossy+ | numericSafety config == RejectLossy = firstLossyNumber result+ | otherwise = Nothing++-- | A piece of a @cat@: null and undefined join as nothing.+joinPiece :: Val -> JsStr+joinPiece VNull = Plain Text.empty+joinPiece VUndefined = Plain Text.empty+joinPiece value = toJsStr value+ -- | @var@: evaluate the path (for its step and its failures), turn its value -- into a 'Path' (ahead of time, when it is a literal), and look it up. variable :: At -> Eval -> Maybe Eval -> (Val -> Run Path) -> Eval variable at@(At config _) path fallback toPath env = do key <- path env >>= toPath notFound <- maybe (pure VNull) ($ env) fallback- let (work, found) = lookupPath (workCap config) env key notFound+ let (work, found) = lookupPath (workCap config) (envValue env) key notFound spend at work pure found @@ -292,28 +383,43 @@ -- Combinators over compiled operands -- --------------------------------------------------------------------- -evalAll :: [Eval] -> Val -> Run [Val]+evalAll :: [Eval] -> Env -> Run [Val] evalAll operands env = traverse ($ env) operands --- | Two operands, no conversion cost (the combiner never walks an array).-binary :: (Val -> Val -> Val) -> Eval -> Eval -> Eval-binary combine x y env = combine <$> x env <*> y env+-- | Two operands the combiner compares without converting: no cost for an+-- array (it is never walked), and a string costs by its length.+binary :: At -> (Val -> Val -> Val) -> Eval -> Eval -> Eval+binary at combine x y env = do+ a <- x env+ b <- y env+ spendOnString at a+ spendOnString at b+ pure (combine a b) --- | Two operands that the combiner may convert to a string or number,--- which costs as many steps as an array operand has elements.+-- | Two operands that the combiner may convert to a string or number, or+-- compare or search ('spendOnComparison'). coercing :: At -> (Val -> Val -> Val) -> Eval -> Eval -> Eval coercing at combine x y env = do a <- x env b <- y env- spendOnConversion at a- spendOnConversion at b+ spendOnComparison at a b pure (combine a b) +-- | Two operands the combiner scans, a string by its length and an array by+-- its elements.+scanning :: At -> (Val -> Val -> Val) -> Eval -> Eval -> Eval+scanning at combine x y env = do+ a <- x env+ b <- y env+ spendOnScan at a+ spendOnScan at b+ pure (combine a b)+ -- | Operands about to be converted to numbers, charged for the conversion.-numeric :: At -> [Eval] -> Val -> Run [Val]+numeric :: At -> [Eval] -> Env -> Run [Val] numeric at operands env = do values <- evalAll operands env- mapM_ (spendOnConversion at) values+ mapM_ (spendOnReading at) values pure values -- | @x op y@, or the chained @x op y && y op z@ when a third operand is@@ -323,14 +429,14 @@ a <- x env b <- y env c <- definedOperand <$> traverse ($ env) z- mapM_ (spendOnConversion at) [a, b]- mapM_ (spendOnConversion at) c+ spendOnComparison at a b+ mapM_ (spendOnComparison at b) c pure (VBool (maybe (holds a b) (\third -> holds a b && holds b third) c)) -- | Condition/consequent pairs, then an optional else; no branch means null. -- -- Hand-written recursion (Standard 4.1): a search that stops at the first--- condition that holds, in 'Run'. It is a right fold with early exit, and+-- condition that holds, in @Run@. It is a right fold with early exit, and -- @base@ has no monadic combinator for that shape. evalIf :: [Eval] -> Eval evalIf (condition : consequent : rest) env = do@@ -364,46 +470,62 @@ -- | Evaluate a collection operand; run @onItems@ if it is an array, -- otherwise answer @fallback@.-withCollection :: Eval -> Val -> (Vector Val -> Run Val) -> Eval-withCollection collection fallback onItems env = do+--+-- An array longer than the iteration limit is refused before any of the+-- work, whichever of the six operators it is given to.+{-# INLINE withCollection #-}+withCollection :: At -> Eval -> Val -> (Vector Val -> Run Val) -> Eval+withCollection at@(At config _) collection fallback onItems env = do evaluated <- collection env case evaluated of- VArr items -> onItems items+ VArr items+ -- a branch, not a step run before the work: a monadic action in front+ -- of the traversal keeps GHC from optimising it, which costs a third+ -- of the time of a short body+ | Vector.length items > maxIterations config -> exceeded at (IterationLimit . maxIterations)+ | otherwise -> onItems items _ -> pure fallback --- | Refuse to iterate an array longer than the array limit, before doing--- any of the work.-guardInput :: At -> Vector Val -> Run ()-guardInput at@(At config _) items =- when (Vector.length items > maxArrayLength config) $ exceeded at (ArrayLimit . maxArrayLength)+-- | Refuse to build an array longer than the array limit.+guardBuilt :: At -> Int -> Run ()+guardBuilt at@(At config _) size =+ when (size > maxArrayLength config) $ exceeded at (ArrayLimit . maxArrayLength) -- | Add a piece's length (in UTF-16 code units) to a running total, -- failing as soon as the total passes the string limit.-addLength :: At -> Int -> Text -> Run Int+addLength :: At -> Int -> JsStr -> Run Int addLength at@(At config _) total piece | total' > maxStringLength config = exceeded at (StringLimit . maxStringLength) | otherwise = pure total' where- total' = total + utf16Length piece+ total' = total + jsStrLength piece +-- | JavaScript's @length@ of a string.+jsStrLength :: JsStr -> Int+jsStrLength (Plain t) = utf16Length t+jsStrLength (Wtf u) = unitsLength u+ -- | Fold the array with the sub-rule, evaluated against an object holding -- the current element and the accumulator.-reduceRule :: Eval -> Eval -> Eval -> Eval-reduceRule collection logic initial env = do+{-# INLINE reduceRule #-}+reduceRule :: At -> Eval -> Eval -> Eval -> Eval+reduceRule at@(At config _) collection logic initial env = do evaluated <- collection env start <- initial env case evaluated of- VArr items -> Vector.foldM' step start items+ VArr items+ | Vector.length items > maxIterations config -> exceeded at (IterationLimit . maxIterations)+ | otherwise -> Vector.foldM' step start items _ -> pure start where step accumulator item =- logic (VObj (KeyMap.fromList [("current", item), ("accumulator", accumulator)]))+ logic (mkEnv (VObj (KeyMap.fromList [("current", item), ("accumulator", accumulator)]))) -- | Does the sub-rule hold for every item? Stops at the first that does not. -- -- Hand-written recursion (Standard 4.1): a monadic @all@, which @base@ does--- not provide, in 'Run'.-allTruthy :: Eval -> [Val] -> Run Bool+-- not provide, in @Run@.+allTruthy :: (Val -> Run Val) -> [Val] -> Run Bool allTruthy _ [] = pure True allTruthy logic (item : rest) = do value <- logic item@@ -413,7 +535,7 @@ -- -- Hand-written recursion (Standard 4.1): a monadic @any@, the dual of -- 'allTruthy'.-anyTruthy :: Eval -> [Val] -> Run Bool+anyTruthy :: (Val -> Run Val) -> [Val] -> Run Bool anyTruthy _ [] = pure False anyTruthy logic (item : rest) = do value <- logic item@@ -433,10 +555,21 @@ -- A falsy container (including the empty string) contains nothing. contains :: Val -> Val -> Bool contains _ (VStr s) | Text.null s = False-contains needle (VStr s) = Text.isInfixOf (toJsString needle) s+contains needle (VStr s) = case toJsStr needle of+ Plain text -> plainInfix text s+ Wtf units -> unitsIsInfixOf units (toUnits s)+contains needle (VWtf units) = unitsIsInfixOf (jsStrUnits (toJsStr needle)) units contains needle (VArr items) = Vector.any (strictEquals needle) items contains _ _ = False +-- | Substring search on well-formed text. The text library's search is the+-- faster one for a short needle, where its worst case is bounded by the+-- needle's length; a long needle takes the linear-time search.+plainInfix :: Text -> Text -> Bool+plainInfix needle haystack+ | lengthWord8 needle < 32 = Text.isInfixOf needle haystack+ | otherwise = textIsInfixOf needle haystack+ -- | Which of the keys have no value, or an empty-string one. If the first -- argument is itself an array, it is the list of keys. --@@ -476,8 +609,8 @@ -- returned. missingSome :: At -> Val -> Val -> Val -> Run Val missingSome at@(At config _) count options env = case options of- VNull -> failAt at (InvalidOperand (builtinOperatorName BMissingSome))- VUndefined -> failAt at (InvalidOperand (builtinOperatorName BMissingSome))+ VNull -> invalid "null"+ VUndefined -> invalid "undefined" _ -> do spendOnConversion at options let names = case options of@@ -490,16 +623,19 @@ Nothing -> 0 / 0 pure (if lessOrEqual count (VNum have) then VArr Vector.empty else VArr (Vector.fromList absent)) where+ invalid actual =+ failAt at (InvalidOperand (builtinOperatorName BMissingSome) (OperandIssue 1 "a list of keys" actual)) optionLength = case options of VArr items -> Just (fromIntegral (Vector.length items)) VStr s -> Just (fromIntegral (utf16Length s))+ VWtf u -> Just (fromIntegral (unitsLength u)) VObj fields -> toNumber <$> KeyMap.lookup "length" fields _ -> Nothing -- | The most work a lookup is followed for: one more than the whole budget, -- so a lookup that cannot be paid for is cut short rather than completed. workCap :: Config -> Int-workCap config = maxSteps config + 1+workCap config = saturatingSucc (maxSteps config) -- | A @var@ path, read: the data itself, or the property names to follow. data Path = WholeData | Steps [Text]@@ -581,11 +717,22 @@ | key == "length" = (size, Just (VNum (fromIntegral (utf16Length s)))) | otherwise = case arrayIndex key of Nothing -> (0, Nothing)- Just i -> (size, VStr <$> utf16CharAt i s)+ Just i -> (size, exactVal <$> utf16CharAtExact i s) where size = min cap (Text.length s)+property cap (VWtf u) key+ | key == "length" = (size, Just (VNum (fromIntegral (unitsLength u))))+ | otherwise = case arrayIndex key of+ Just i | i < unitsLength u -> (size, Just (exactVal (fromUnits (unitsSlice i 1 u))))+ _ -> (0, Nothing)+ where+ size = min cap (unitsLength u) property _ _ _ = (0, Nothing) +-- | A slice as a value: a string, or one that holds a lone surrogate.+exactVal :: Either Units Text -> Val+exactVal = either VWtf VStr+ -- | A canonical array index: digits, no leading zero, below 10^9. arrayIndex :: Text -> Maybe Int arrayIndex key@@ -597,21 +744,24 @@ -- | @substr@: JavaScript's @substr@, plus the reference's PHP-style -- twist that a negative third argument means "stop that many characters -- before the end" rather than a negative length.-substring :: Text -> Val -> Maybe Val -> Text+substring :: JsStr -> Val -> Maybe Val -> JsStr substring source start end = case end of Just limit | lessThan limit (VNum 0) -> negativeEnd limit _ -> substrJs source (toNumber start) (fmap toNumber end) where tailText = substrJs source (toNumber start) Nothing- negativeEnd (VNum n) =- substrJs tailText 0 (Just (fromIntegral (utf16Length tailText) + n))- negativeEnd _ = ""+ negativeEnd value+ | Just n <- numberOf value = substrJs tailText 0 (Just (fromIntegral (jsStrLength tailText) + n))+ | otherwise = Plain Text.empty --- | @String.prototype.substr(start, length)@, in UTF-16 code units.-substrJs :: Text -> Double -> Maybe Double -> Text-substrJs source start len = utf16Slice from count source+-- | @String.prototype.substr(start, length)@, in UTF-16 code units. A slice+-- through a surrogate pair keeps the severed half as itself.+substrJs :: JsStr -> Double -> Maybe Double -> JsStr+substrJs source start len = case source of+ Plain text -> either Wtf Plain (utf16SliceExact from count text)+ Wtf units -> either Wtf Plain (fromUnits (unitsSlice from count units)) where- size = utf16Length source+ size = jsStrLength source relative = toClampedInt (negate size, size) start from = if relative < 0 then size + relative else relative available = size - from
src/JsonLogic/Core/Location.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-} -- | -- Module : JsonLogic.Core.Location@@ -24,6 +25,8 @@ , renderLocation ) where +import Control.DeepSeq (NFData (..))+import Data.Ord (comparing) import Data.Text (Text) import qualified Data.Text as Text @@ -35,10 +38,24 @@ Index !Int deriving (Eq, Ord, Show) +instance NFData Segment where+ rnf (Key key) = rnf key+ rnf (Index i) = rnf i+ -- | A path from the root of a rule. Held innermost-first, so that stepping -- into a child while reading a rule is constant time. newtype Location = Location [Segment]- deriving (Eq, Ord)+ deriving (Eq)++-- | Locations are ordered by their position in the rule's text: segment by+-- segment from the root, so a parent sorts before its children and siblings+-- sort by key (or index). The stored list is innermost-first, so the order+-- is taken from 'locationSegments', never from the representation.+instance Ord Location where+ compare = comparing locationSegments++instance NFData Location where+ rnf (Location segments) = rnf segments -- | Shown as the 'fromSegments' call that rebuilds it. instance Show Location where
src/JsonLogic/Core/Number.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-} -- | -- Module : JsonLogic.Core.Number@@ -17,6 +18,7 @@ ( -- * Reading decimalToDouble , scientificToDouble+ , printsAsSource , stringToNumber , parseFloatString , isJsSpace@@ -24,8 +26,7 @@ -- * Writing , numberToString , doubleToScientific- , shortestDigits- , shortestDigitsExact+ , shortestDecimal -- * Arithmetic , remainderJs@@ -37,13 +38,12 @@ import Data.Bits (shiftL, shiftR, (.&.)) import Data.Char (digitToInt, isDigit, isHexDigit) import Data.Int (Int64)-import Data.List (dropWhileEnd, sortOn, stripPrefix)+import Data.List (dropWhileEnd, stripPrefix) import qualified Data.List as List-import Data.Maybe (fromMaybe, listToMaybe, mapMaybe) import Data.Scientific (Scientific, base10Exponent, coefficient, scientific) import Data.Text (Text) import qualified Data.Text as Text-import Numeric (floatToDigits)+import GHC.Num.Integer (integerLog2) import JsonLogic.Core.Ryu (shortestDecimalRyu) @@ -72,6 +72,16 @@ scientificToDouble :: Scientific -> Double scientificToDouble s = decimalToDouble (coefficient s) (toInteger (base10Exponent s)) +-- | Whether a JSON number survives the round trip through a double: the+-- double it reads as prints (shortest digits, as JavaScript prints it) as+-- the same decimal. False for an integer above 2^53 that is not exactly a+-- shortest-digit decimal, and for any decimal with more digits than a double+-- distinguishes.+printsAsSource :: Scientific -> Bool+printsAsSource n = not (isInfinite d) && doubleToScientific d == n+ where+ d = scientificToDouble n+ -- | @mantissa * 10 ^ exponent10@ as the nearest double (ties to even). -- -- When the mantissa is below 2^53 and the exponent within 22 of zero, both@@ -94,7 +104,9 @@ | exponent10 >= 0 = roundRatio (mantissa * 10 ^ exponent10) 1 | otherwise = roundRatio mantissa (10 ^ negate exponent10) where- magnitude = exponent10 + toInteger (length (show mantissa))+ -- the digit count, to within one: enough to decide overflow and+ -- underflow, whose thresholds have far more room than that+ magnitude = exponent10 + decimalDigits mantissa -- | @numerator / denominator@, both positive, as the nearest double, ties to -- even, including the subnormal range and overflow to infinity.@@ -123,15 +135,20 @@ roundsUp = below > half || (below == half && (remainder /= 0 || odd kept)) rounded = if roundsUp then kept + 1 else kept --- | The number of bits in a positive integer.+-- | The number of bits in a positive integer, in constant time for a+-- machine-sized one and linear in its size otherwise. (Peeling 64 bits at a+-- time copies the whole integer on every step, which is quadratic: a+-- million-digit number took seconds.) bitLength :: Integer -> Int-bitLength = go 0- where- go acc v- | v >= 18446744073709551616 = go (acc + 64) (v `shiftR` 64)- | v == 0 = acc- | otherwise = go (acc + 1) (v `shiftR` 1)+bitLength v+ | v <= 0 = 0+ | otherwise = fromIntegral (integerLog2 v) + 1 +-- | The number of decimal digits of a positive integer, or one fewer or+-- more, from its bit length (log10 2 is 0.30103).+decimalDigits :: Integer -> Integer+decimalDigits v = (toInteger (bitLength v) * 30103) `quot` 100000 + 1+ -- | ECMAScript's @WhiteSpace@ and @LineTerminator@ code points, which is what -- string-to-number conversion trims. Listed explicitly rather than taken from -- @Data.Char.isSpace@ because the two differ: U+FEFF, U+2028 and U+2029 are@@ -330,15 +347,6 @@ where whole = truncate d --- | The digits ECMAScript prints for a positive finite double, as--- @(digits, pointPosition)@ in the convention of 'floatToDigits': the value--- is @0.d1d2...dn * 10^pointPosition@.-shortestDigits :: Double -> ([Int], Int)-shortestDigits d = (map digitToInt digits, length digits + exponent10)- where- (coefficientDigits, exponent10) = shortestDecimal d- digits = show coefficientDigits- -- | The decimal ECMAScript prints for a positive finite double, as -- @(significand, exponent)@ with the value @significand * 10^exponent@ and no -- trailing zeros in the significand.@@ -356,43 +364,6 @@ stripZeros m e | m /= 0 && m `rem` 10 == 0 = stripZeros (m `quot` 10) (e + 1) | otherwise = (m, e)---- | 'shortestDigits' computed exactly, for every positive finite double.------ GHC's 'floatToDigits' only accepts digit strings strictly inside the--- rounding interval of the double. ECMAScript also accepts the exact--- halfway point when the double's significand is even, because--- round-half-even reads it back to the same double. For doubles of 2^53 and--- above those points are whole numbers, so a shorter string can exist where--- GHC needs one more digit: @2.2531e21@, not @2.2531000000000001e21@. Below--- 2^53 the halfway points have too many digits to matter, so GHC's answer--- stands, except that when two candidates of the shortest length are equally--- close (@9007199254740993 / 10@ is halfway between @...099.2@ and @...099.3@)--- ECMAScript takes the even one, and 'floatToDigits' does not.-shortestDigitsExact :: Double -> ([Int], Int)-shortestDigitsExact d- | d < twoTo53 =- -- A tie between two equally short candidates needs 16 or more digits:- -- below that, decimal spacing is wider than the spacing of doubles.- if length digits >= 16 then fromMaybe generated (shorter (length digits)) else generated- | otherwise = fromMaybe generated (listToMaybe (mapMaybe shorter [1 .. length digits]))- where- generated@(digits, pointPosition) = floatToDigits 10 d- exact = toRational d- shorter k =- case sortOn rank (filter readsBack [lower, upper]) of- best : _ -> Just (digitsOf best k)- [] -> Nothing- where- scale = 10 ^^ (pointPosition - k) :: Rational- scaled = exact / scale- lower = floor scaled :: Integer- upper = ceiling scaled :: Integer- readsBack m = fromRational (fromInteger m * scale) == d- rank m = (abs (fromInteger m * scale - exact), odd m)- digitsOf m k = (map digitToInt (dropWhileEnd (== '0') text), pointPosition + length text - k)- where- text = show m -- | @layoutDigits ds k n@: @k@ significant digits @ds@ whose decimal -- point sits @n@ places to the right of their start, laid out as
src/JsonLogic/Core/Operator.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-} -- | -- Module : JsonLogic.Core.Operator@@ -19,6 +20,7 @@ , lookupBuiltin ) where +import Control.DeepSeq (NFData (..)) import qualified Data.Map.Strict as Map import Data.Text (Text) @@ -28,6 +30,9 @@ newtype OperatorName = OperatorName Text deriving (Eq, Ord, Show) +instance NFData OperatorName where+ rnf (OperatorName name) = rnf name+ -- | The operators of the classic JsonLogic specification -- (<https://jsonlogic.com/operations.html>), as implemented by the reference, -- json-logic-js 2.0.5. @?:@ is the reference's alias of @if@ and has its own@@ -113,7 +118,7 @@ BSubstr -> "substr" BLog -> "log" --- | 'builtinName' as an 'OperatorName'.+-- | 'builtinName' as an @OperatorName@. builtinOperatorName :: Builtin -> OperatorName builtinOperatorName = OperatorName . builtinName
src/JsonLogic/Core/Parse.hs view
@@ -1,9 +1,10 @@ {-# LANGUAGE LambdaCase #-}+{-# OPTIONS_HADDOCK hide #-} -- | -- Module : JsonLogic.Core.Parse ----- Reads a JSON 'Value' into a 'Rule'. Reading is an unfold+-- Reads a JSON 'Value' into a 'RuleTree'. Reading is an unfold -- ('unfoldFixM'): a seed is a piece of JSON still to read, with how deeply it -- is nested and where it is, and each step produces one node whose children -- are further seeds.@@ -19,11 +20,13 @@ -- here, exactly as the reference behaves: missing operands become -- @undefined@ (@null@ for the initial value of @reduce@), and surplus ones are -- dropped, after being evaluated for their failures where the reference--- evaluates them ('Discard'). How each builtin treats its operands is stated+-- evaluates them ('Applied'). How each builtin treats its operands is stated -- once, in @shapeOf@. module JsonLogic.Core.Parse- ( parseRule- , parseRuleWith+ ( parseRuleWith+ , parseRuleChecked+ , parseProblems+ , buildBuiltin ) where import Data.Aeson (Value (..))@@ -33,27 +36,58 @@ import Data.Foldable (toList) import Data.Text (Text) -import JsonLogic.Core.Config (ArityMode (..), Config (..), defaultConfig)+import JsonLogic.Core.Check (customProblem)+import JsonLogic.Core.Config (ArityMode (..), Config (..), NumericSafety (..), validateConfig)+import JsonLogic.Core.Custom (Operators) import JsonLogic.Core.Errors (Arity (..), ParseError (..)) import JsonLogic.Core.Location (Location, Segment (..), child, root)+import JsonLogic.Core.Number (printsAsSource) import JsonLogic.Core.Operator ( Builtin (..) , OperatorName (..) , builtinOperatorName , lookupBuiltin )-import JsonLogic.Core.Rule (Node (..), Rule, RuleF (..))-import JsonLogic.Core.Value (nestsDeeperThan)+import JsonLogic.Core.Rule (Node (..), RuleF (..), RuleTree)+import JsonLogic.Core.Value (firstLossyNumber, jsonWeightUpTo, nestsDeeperThan, saturatingSucc) --- | Read a rule with 'defaultConfig'.-parseRule :: Value -> Either (Location, ParseError) Rule-parseRule = parseRuleWith defaultConfig+-- | Read a rule with the configured depth limit, node limit and arity mode.+-- A failure says where in the rule it happened. A rule with too many nodes+-- is refused before any of it is read.+parseRuleWith :: Config -> Value -> Either (Location, ParseError) RuleTree+parseRuleWith config = parseRuleChecked config Nothing --- | Read a rule with the configured depth limit and arity mode. A failure--- says where in the rule it happened.-parseRuleWith :: Config -> Value -> Either (Location, ParseError) Rule-parseRuleWith config value = unfoldFixM (step config) (Seed 0 root (Json value))+-- | 'parseRuleWith', and, given the registry of custom operators, also+-- refusing a call to an operator that is not registered (when the+-- configuration rejects those) or that is given the wrong number of+-- operands (in strict arity mode). The first problem in document order is+-- the one reported.+parseRuleChecked :: Config -> Maybe Operators -> Value -> Either (Location, ParseError) RuleTree+parseRuleChecked config operators value = case preliminary config value of+ Just problem -> Left problem+ Nothing -> unfoldFixM (step config operators) (Seed 0 root (Json value)) +-- | Every problem 'parseRuleChecked' would find, not only the first, in+-- document order. A node that cannot be read is reported once and its+-- insides are not looked at; the rest of the rule still is.+parseProblems :: Config -> Maybe Operators -> Value -> [(Location, ParseError)]+parseProblems config operators value = case preliminary config value of+ Just problem -> [problem]+ Nothing -> go (Seed 0 root (Json value))+ where+ go seed = case step config operators seed of+ Left problem -> [problem]+ Right (Node _ node) -> concatMap go node++-- | The checks made before any of the rule is read.+preliminary :: Config -> Value -> Maybe (Location, ParseError)+preliminary config value+ | Left problem <- validateConfig config = Just (root, InvalidConfig problem)+ | jsonWeightUpTo (saturatingSucc limit) value > limit = Just (root, NodeLimitExceeded limit)+ | otherwise = Nothing+ where+ limit = maxNodes config+ -- | Something still to read: how many levels deep it is, where it is, and -- what it is. data Seed = Seed !Int !Location !Source@@ -64,16 +98,14 @@ | -- | An operand the rule leaves out, which the reference reads as -- @undefined@ or, in two places, @null@. Absent Absence- | -- | An operator call whose operand count has already been repaired.- Repaired Builtin [Seed] data Absence = AbsentUndefined | AbsentNull -- | One layer of the unfold.-step :: Config -> Seed -> Either (Location, ParseError) (Node Seed)-step config (Seed depth location source)+step :: Config -> Maybe Operators -> Seed -> Either (Location, ParseError) (Node Seed)+step config operators (Seed depth location source) | depth > limit = Left (location, DepthExceeded limit)- | otherwise = Node location <$> layer+ | otherwise = Node location <$> (layer >>= checked) where limit = maxDepth config layer = case source of@@ -86,12 +118,21 @@ -- @{"and": []}@ is how the reference's @undefined@ is written as a rule Absent AbsentUndefined -> Right (And []) Absent AbsentNull -> Right (Lit Null)- Repaired builtin operands -> build location builtin operands+ checked node = case (node, operators) of+ (CustomOp name seeds, Just registry)+ | Just problem <- customProblem config registry name (length seeds) -> Left (location, problem)+ _ -> Right node -- A literal's own nesting counts towards the limit, so a deeply nested -- object cannot be smuggled past it inside a rule. literal value | nestsDeeperThan (limit - depth) value = Left (location, DepthExceeded limit)+ | numericSafety config == RejectLossy+ , Just n <- lossy value =+ Left (location, LossyNumberLiteral n) | otherwise = Right (Lit value)+ lossy value = case value of+ Number n | not (printsAsSource n) -> Just n+ _ -> firstLossyNumber value -- | An operator call: a builtin, read to its shape, or a custom operator. operator :: Config -> Int -> Location -> Text -> Value -> Either (Location, ParseError) (RuleF Seed)@@ -118,7 +159,7 @@ Just most | length full > most -> case shapeSurplus shape of NeverEvaluated -> build location builtin (take most full)- Evaluated -> Right (Discard (Seed depth location (Repaired builtin (take most full))) (drop most full))+ Evaluated -> Right (Applied builtin (take most full) (drop most full)) _ -> build location builtin full where shape = shapeOf builtin :: Shape Seed@@ -142,6 +183,12 @@ absence BVar 0 = AbsentNull absence BReduce 2 = AbsentNull absence _ _ = AbsentUndefined++-- | The node for a builtin applied to operands, if the count is one its+-- constructor can hold. Used to rebuild an operator over operands that are+-- already evaluated.+buildBuiltin :: Builtin -> [a] -> Maybe (RuleF a)+buildBuiltin builtin = shapeBuild (shapeOf builtin) -- | Build a call whose operand count the shape admits. build :: Location -> Builtin -> [Seed] -> Either (Location, ParseError) (RuleF Seed)
src/JsonLogic/Core/Rule.hs view
@@ -1,11 +1,12 @@ {-# LANGUAGE DeriveTraversable #-}+{-# OPTIONS_HADDOCK hide #-} -- | -- Module : JsonLogic.Core.Rule -- -- The rule tree: one layer of it ('RuleF', the base functor), and the -- recursive tree whose every node records where in the rule's JSON it came--- from ('Rule').+-- from ('RuleTree'). -- -- Recursion over the tree is never written by hand: the parser builds it -- with an unfold ('Data.Fix.unfoldFixM') and the evaluator consumes it with a@@ -23,19 +24,17 @@ module JsonLogic.Core.Rule ( RuleF (..) , Node (..)- , Rule- , Term- , stripLocations+ , RuleTree ) where import Data.Aeson (Value)-import Data.Fix (Fix (..), foldFix)+import Data.Fix (Fix (..)) import Data.Foldable (toList) import Data.Functor (void) import Data.Functor.Classes (Eq1 (..), Show1 (..)) import JsonLogic.Core.Location (Location)-import JsonLogic.Core.Operator (OperatorName)+import JsonLogic.Core.Operator (Builtin, OperatorName) -- | One layer of a JsonLogic rule, with its sub-rules at type @a@. Each -- constructor's comment states what the reference implementation does, which@@ -130,12 +129,15 @@ | -- | @log@: its operand, unchanged. The reference also prints it; this -- library does no I/O. Log a- | -- | @Discard inner extras@: the value of @inner@, after evaluating each- -- of @extras@ for its failures only. Built in lenient arity mode only,- -- for the surplus operands of an operator the reference evaluates in- -- full before applying it, so that a surplus operand that fails still- -- fails the rule, as in the reference.- Discard a [a]+ | -- | @Applied builtin used extras@: a builtin operator that was given+ -- more operands than it takes, in lenient arity mode. The reference+ -- evaluates every operand, left to right, and only then applies the+ -- operator to the first few; so the @used@ operands and then the+ -- @extras@ are evaluated, and the operator is applied to the values of+ -- the @used@ ones. Built only for operators that evaluate all their+ -- operands, so that a surplus operand that fails still fails the rule,+ -- at the point where the reference fails it.+ Applied Builtin [a] [a] | -- | An operator outside the builtin set, applied to its operands. Its -- behaviour is supplied by the caller. CustomOp OperatorName [a]@@ -167,15 +169,9 @@ instance Show1 Node where liftShowsPrec showsChild _ d = showsPrec d . fmap (Shown . flip showsChild) --- | A rule as read from JSON: every node carries its 'Location'.-type Rule = Fix Node---- | A rule tree without locations, for comparing shapes.-type Term = Fix RuleF---- | Forget where every node came from.-stripLocations :: Rule -> Term-stripLocations = foldFix (Fix . nodeRule)+-- | A rule as read from JSON: every node carries its 'Location'. (Not to be+-- confused with 'JsonLogic.Rule', the compiled, opaque rule.)+type RuleTree = Fix Node -- | A value shown by a function, so that a derived 'Show' can be reused to -- write 'Show1' instances.
+ src/JsonLogic/Core/Run.hs view
@@ -0,0 +1,75 @@+{-# OPTIONS_HADDOCK hide #-}++-- |+-- Module : JsonLogic.Core.Run+--+-- The evaluation monad: a small state-passing monad whose state is the+-- remaining step budget. It is pure: the budget is threaded through the+-- evaluation, never held in a global or in 'IO'. A failure carries the+-- location of the node that failed. See "JsonLogic.Core.Config" for the+-- limits.+module JsonLogic.Core.Run+ ( Result (..)+ , Run (..)+ , At (..)+ , failAt+ , exceeded+ , spend+ ) where++import JsonLogic.Core.Config (Config (..))+import JsonLogic.Core.Errors (EvalError (..), LimitKind (..))+import JsonLogic.Core.Location (Location)++-- | The outcome of a step: its value and the budget left, or where and why+-- it failed. One constructor per outcome, strict, so the budget cannot pile+-- up as a chain of thunks and a step allocates one cell.+data Result a+ = Done !a {-# UNPACK #-} !Int+ | Failed !Location !EvalError++-- | A computation that may fail, at a location in the rule, and that spends+-- steps from a budget.+newtype Run a = Run {unRun :: Int -> Result a}++instance Functor Run where+ fmap f (Run m) = Run $ \budget -> case m budget of+ Done a left -> Done (f a) left+ Failed location e -> Failed location e+ {-# INLINE fmap #-}++instance Applicative Run where+ pure a = Run (Done a)+ {-# INLINE pure #-}+ Run mf <*> Run ma = Run $ \budget -> case mf budget of+ Failed location e -> Failed location e+ Done f left -> case ma left of+ Failed location e -> Failed location e+ Done a left' -> Done (f a) left'+ {-# INLINE (<*>) #-}++instance Monad Run where+ Run m >>= k = Run $ \budget -> case m budget of+ Failed location e -> Failed location e+ Done a left -> unRun (k a) left+ {-# INLINE (>>=) #-}++-- | What every node's code knows about itself: the configuration it was+-- compiled with and where it is in the rule.+data At = At !Config !Location++-- | Fail here.+failAt :: At -> EvalError -> Run a+failAt (At _ location) e = Run (const (Failed location e))++-- | Fail here because a limit was exceeded.+exceeded :: At -> (Config -> LimitKind) -> Run a+exceeded at@(At config _) kind = failAt at (LimitExceeded (kind config))++-- | Spend @n@ steps, or fail here if fewer than @n@ remain.+spend :: At -> Int -> Run ()+spend (At config location) n = Run $ \budget ->+ if n > budget+ then Failed location (LimitExceeded (StepLimit (maxSteps config)))+ else Done () (budget - n)+{-# INLINE spend #-}
src/JsonLogic/Core/Ryu.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE BangPatterns #-}+{-# OPTIONS_HADDOCK hide #-} -- | -- Module : JsonLogic.Core.Ryu@@ -26,6 +27,7 @@ import qualified Data.Vector.Unboxed as Unboxed import Data.Word (Word64) import GHC.Float (castDoubleToWord64)+import GHC.Num.Integer (integerLog2) -- | For a positive, finite, non-zero double, @(digits, exponent)@ with the -- double's shortest decimal equal to @digits * 10^exponent@. The digits may@@ -297,9 +299,8 @@ highWord :: Integer -> Word64 highWord = fromInteger . (`shiftR` 64) +-- | The number of bits in a positive integer. bitLength :: Integer -> Int-bitLength = go 0- where- go n v- | v == 0 = n- | otherwise = go (n + 1) (v `shiftR` 1)+bitLength v+ | v <= 0 = 0+ | otherwise = fromIntegral (integerLog2 v) + 1
src/JsonLogic/Core/Utf16.hs view
@@ -1,3 +1,6 @@+{-# LANGUAGE BangPatterns #-}+{-# OPTIONS_HADDOCK hide #-}+ -- | -- Module : JsonLogic.Core.Utf16 --@@ -9,33 +12,51 @@ -- U+D800 to U+DBFF. -- -- This module is the one place those semantics are defined, over--- 'Text'. A 'Text' cannot hold a lone surrogate, so a slice that cuts--- through a surrogate pair yields U+FFFD for the severed half. That is the--- single accepted deviation from the reference here, and it is exactly what--- @String.prototype.toWellFormed()@ would make of the reference's answer.+-- 'Text'. Nothing here builds a list of code units: skipping and slicing+-- walk the text once, without allocating per code unit, so the cost of an+-- operation is its scan of the string and nothing more.+--+-- A 'Text' cannot hold a lone surrogate, so a slice that cuts through a+-- surrogate pair cannot be a 'Text'. 'utf16Slice' and 'utf16CharAt' answer+-- such a slice with U+FFFD for the severed half (what+-- @String.prototype.toWellFormed()@ makes of the reference's answer). The+-- evaluator does not use them for that: it uses 'utf16SliceExact', which+-- answers a @Units@ value when the slice is not well formed, so that the+-- halves keep their identity: they compare unequal, and joining them again+-- gives the original character, as in JavaScript. module JsonLogic.Core.Utf16 ( utf16Length , utf16Slice , utf16CharAt , compareUtf16- , utf16Units- , fromUtf16Units++ -- * Strings that 'Text' cannot hold+ , Units+ , toUnits+ , fromUnits+ , unitsText+ , unitsLength+ , unitsSlice+ , unitsAppend+ , unitsIsInfixOf+ , textIsInfixOf+ , utf16SliceExact+ , utf16CharAtExact ) where import Data.Bits (shiftL, shiftR, (.&.), (.|.))-import Data.Char (chr, ord)+import qualified Data.ByteString as ByteString+import Data.Char (ord) import Data.Text (Text) import qualified Data.Text as Text+import qualified Data.Text.Encoding as Encoding+import qualified Data.Vector.Unboxed as Unboxed import Data.Word (Word16) -- | The number of UTF-16 code units: JavaScript's @s.length@. utf16Length :: Text -> Int utf16Length = Text.foldl' (\n c -> if ord c > 0xFFFF then n + 2 else n + 1) 0 --- | The UTF-16 code units of a text.-utf16Units :: Text -> [Word16]-utf16Units = concatMap charUnits . Text.unpack- charUnits :: Char -> [Word16] charUnits c | n <= 0xFFFF = [fromIntegral n]@@ -47,26 +68,6 @@ where n = ord c --- | Rebuild a text from UTF-16 code units. A surrogate with no partner--- becomes U+FFFD.-fromUtf16Units :: [Word16] -> Text-fromUtf16Units = Text.pack . go- where- go [] = []- go (hi : lo : rest)- | isHigh hi && isLow lo = pair hi lo : go rest- go (u : rest)- | isHigh u || isLow u = '\xFFFD' : go rest- | otherwise = chr (fromIntegral u) : go rest- isHigh u = u >= 0xD800 && u <= 0xDBFF- isLow u = u >= 0xDC00 && u <= 0xDFFF- pair hi lo =- chr- ( 0x10000- + ((fromIntegral hi - 0xD800) `shiftL` 10)- + (fromIntegral lo - 0xDC00)- )- -- | @slice from count@: the @count@ code units starting at code unit -- @from@, both already clamped into range by the caller. Cutting through a -- surrogate pair gives U+FFFD for the severed half.@@ -74,7 +75,14 @@ utf16Slice from count text | count <= 0 = Text.empty | Text.all isBmp text = Text.take count (Text.drop from text)- | otherwise = fromUtf16Units (take count (drop from (utf16Units text)))+ | otherwise =+ let (rest, severedStart) = dropUnits from text+ -- a severed low half is one code unit of the slice, written U+FFFD+ budget = if severedStart then count - 1 else count+ (whole, severedEnd) = fitUnits budget rest+ in (if severedStart then replacement else Text.empty)+ <> Text.take whole rest+ <> (if severedEnd then replacement else Text.empty) -- | The code unit at an index, as a one-unit string, or 'Nothing' past the -- end. A lone surrogate half is returned as U+FFFD.@@ -84,10 +92,48 @@ | Text.all isBmp text = let picked = Text.take 1 (Text.drop i text) in if Text.null picked then Nothing else Just picked- | otherwise = case drop i (utf16Units text) of- [] -> Nothing- unit : _ -> Just (fromUtf16Units [unit])+ | otherwise =+ let (rest, severed) = dropUnits i text+ in if severed+ then Just replacement+ else case Text.uncons rest of+ Nothing -> Nothing+ Just (c, _)+ | isBmp c -> Just (Text.singleton c)+ | otherwise -> Just replacement +-- | U+FFFD, what a severed half of a surrogate pair becomes.+replacement :: Text+replacement = Text.singleton '\xFFFD'++-- | Code units a character takes.+width :: Char -> Int+width c = if isBmp c then 1 else 2++-- | Skip @n@ code units. The flag says the skip ended inside a surrogate+-- pair: the rest starts after that character, and its low half is owed.+dropUnits :: Int -> Text -> (Text, Bool)+dropUnits n text+ | n <= 0 = (text, False)+ | otherwise = case Text.uncons text of+ Nothing -> (text, False)+ Just (c, rest)+ | width c <= n -> dropUnits (n - width c) rest+ | otherwise -> (rest, True)++-- | How many whole characters fit in @n@ code units, and whether the next+-- character would be cut after its high half.+fitUnits :: Int -> Text -> (Int, Bool)+fitUnits = go 0+ where+ go !whole n text+ | n <= 0 = (whole, False)+ | otherwise = case Text.uncons text of+ Nothing -> (whole, False)+ Just (c, rest)+ | width c <= n -> go (whole + 1) (n - width c) rest+ | otherwise -> (whole, True)+ isBmp :: Char -> Bool isBmp c = ord c <= 0xFFFF @@ -95,13 +141,154 @@ -- -- It differs from ordering by code point only when an astral character -- (first unit U+D800 to U+DBFF) meets a BMP character in U+E000 to U+FFFF:--- by code unit the astral one is smaller.+-- by code unit the astral one is smaller. The common prefix is skipped+-- without allocating, so only the first pair of characters that differ is+-- ever looked at. compareUtf16 :: Text -> Text -> Ordering-compareUtf16 a b = go (Text.unpack a) (Text.unpack b)+compareUtf16 a b = case Text.commonPrefixes a b of+ Nothing -> firstDifference a b+ Just (_, restA, restB) -> firstDifference restA restB where- go [] [] = EQ- go [] _ = LT- go _ [] = GT- go (x : xs) (y : ys)- | x == y = go xs ys- | otherwise = compare (charUnits x) (charUnits y)+ firstDifference x y = case (Text.uncons x, Text.uncons y) of+ (Nothing, Nothing) -> EQ+ (Nothing, Just _) -> LT+ (Just _, Nothing) -> GT+ (Just (p, _), Just (q, _))+ | p == q -> EQ+ | otherwise -> compare (charUnits p) (charUnits q)++-- ---------------------------------------------------------------------+-- Strings with lone surrogates+-- ---------------------------------------------------------------------++-- | A JavaScript string as its UTF-16 code units. Used only for the rare+-- string that is not well formed (it holds a lone surrogate), which a+-- 'Text' cannot; every other string stays a 'Text'.+newtype Units = Units (Unboxed.Vector Word16)+ deriving (Eq, Ord, Show)++isHigh, isLow :: Word16 -> Bool+isHigh u = u >= 0xD800 && u <= 0xDBFF+isLow u = u >= 0xDC00 && u <= 0xDFFF++-- | The code units of a 'Text'.+toUnits :: Text -> Units+toUnits = Units . Unboxed.fromList . concatMap charUnits . Text.unpack++-- | The characters of a unit sequence, with each lone surrogate written+-- U+FFFD, and whether there were none.+decode :: [Word16] -> ([Char], Bool)+decode (high : low : rest)+ | isHigh high && isLow low =+ let (chars, ok) = decode rest+ cp = 0x10000 + ((fromIntegral high - 0xD800) `shiftL` 10) + (fromIntegral low - 0xDC00)+ in (toEnum cp : chars, ok)+decode (unit : rest)+ | isHigh unit || isLow unit = let (chars, _) = decode rest in ('\xFFFD' : chars, False)+ | otherwise = let (chars, ok) = decode rest in (toEnum (fromIntegral unit) : chars, ok)+decode [] = ([], True)++-- | A 'Text' if the units are well formed, otherwise the units themselves.+fromUnits :: Units -> Either Units Text+fromUnits units@(Units v) = case decode (Unboxed.toList v) of+ (chars, True) -> Right (Text.pack chars)+ (_, False) -> Left units++-- | The units as text, each lone surrogate written U+FFFD. This is the form+-- used where a string is read as a number or a path, and in the JSON a rule+-- returns, where a lone surrogate cannot appear.+unitsText :: Units -> Text+unitsText (Units v) = Text.pack (fst (decode (Unboxed.toList v)))++-- | JavaScript's @length@.+unitsLength :: Units -> Int+unitsLength (Units v) = Unboxed.length v++-- | @unitsSlice from count@, both already clamped into range.+unitsSlice :: Int -> Int -> Units -> Units+unitsSlice from count (Units v) = Units (Unboxed.slice from count v)++-- | Concatenation: halves of a pair that meet become the pair again.+unitsAppend :: [Units] -> Units+unitsAppend pieces = Units (Unboxed.concat [v | Units v <- pieces])++-- | @haystack.indexOf(needle) !== -1@, in linear time (Knuth-Morris-Pratt),+-- so a hostile needle cannot make a search quadratic.+unitsIsInfixOf :: Units -> Units -> Bool+unitsIsInfixOf (Units needle) (Units haystack)+ | m == 0 = True+ | otherwise = go 0 0+ where+ m = Unboxed.length needle+ n = Unboxed.length haystack+ failure :: Unboxed.Vector Int+ failure = Unboxed.constructN m step+ where+ step prefix+ | i == 0 = 0+ | otherwise = extend (prefix Unboxed.! (i - 1))+ where+ i = Unboxed.length prefix+ extend k+ | needle Unboxed.! k == needle Unboxed.! i = k + 1+ | k == 0 = 0+ | otherwise = extend (prefix Unboxed.! (k - 1))+ go !i !k+ | k == m = True+ | i == n = False+ | haystack Unboxed.! i == needle Unboxed.! k = go (i + 1) (k + 1)+ | k == 0 = go (i + 1) 0+ | otherwise = go i (failure Unboxed.! (k - 1))++-- | @haystack.indexOf(needle) !== -1@ on well-formed text, in linear time+-- (Knuth-Morris-Pratt over the UTF-8 bytes). UTF-8 is self-synchronising, so+-- the bytes of a well-formed needle occur in those of a well-formed haystack+-- only at character boundaries, and a byte search is a character search.+-- The text library's own search is fast, but quadratic in the worst case+-- (a long needle that matches almost everywhere before it fails), which a+-- hostile rule could use to do far more work than the steps it is charged.+textIsInfixOf :: Text -> Text -> Bool+textIsInfixOf needleText haystackText+ | m == 0 = True+ | m > n = False+ | otherwise = go 0 0+ where+ needle = Encoding.encodeUtf8 needleText+ haystack = Encoding.encodeUtf8 haystackText+ m = ByteString.length needle+ n = ByteString.length haystack+ failure :: Unboxed.Vector Int+ failure = Unboxed.constructN m step+ where+ step prefix+ | i == 0 = 0+ | otherwise = extend (prefix Unboxed.! (i - 1))+ where+ i = Unboxed.length prefix+ extend k+ | ByteString.index needle k == ByteString.index needle i = k + 1+ | k == 0 = 0+ | otherwise = extend (prefix Unboxed.! (k - 1))+ go !i !k+ | k == m = True+ | i == n = False+ | ByteString.index haystack i == ByteString.index needle k = go (i + 1) (k + 1)+ | k == 0 = go (i + 1) 0+ | otherwise = go i (failure Unboxed.! (k - 1))++-- | 'utf16Slice' that keeps a severed half as itself: 'Right' a 'Text' when+-- the slice is well formed (the common case, with no allocation per code+-- unit when the text has no astral character), 'Left' its units when it+-- cuts a surrogate pair. Both arguments are already clamped into range.+utf16SliceExact :: Int -> Int -> Text -> Either Units Text+utf16SliceExact from count text+ | count <= 0 = Right Text.empty+ | Text.all isBmp text = Right (Text.take count (Text.drop from text))+ | otherwise = fromUnits (unitsSlice from count (toUnits text))++-- | The code unit at an index as a one-unit string, or 'Nothing' past the+-- end. A surrogate half is itself, not U+FFFD.+utf16CharAtExact :: Int -> Text -> Maybe (Either Units Text)+utf16CharAtExact i text+ | i < 0 || i >= utf16Length text = Nothing+ | otherwise = Just (utf16SliceExact i 1 text)
src/JsonLogic/Core/Value.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-} -- | -- Module : JsonLogic.Core.Value@@ -19,11 +20,23 @@ -- Recorded deviations (docs/COMPATIBILITY.md): arrays and objects are never -- equal to one another under @==@ / @===@ (the reference compares them by -- identity, which JSON values do not have). Strings are measured and ordered--- by UTF-16 code unit, as in JavaScript (see "JsonLogic.Core.Utf16").+-- by UTF-16 code unit, as in JavaScript (see "JsonLogic.Core.Utf16"). A+-- string that holds a lone surrogate (only a slice through a surrogate pair+-- makes one) is a 'VWtf', so that it behaves as in JavaScript: its halves+-- are unequal and re-join into the original character. It becomes U+FFFD+-- only where JSON cannot carry it, in the result. module JsonLogic.Core.Value ( Val (..)+ , numberOf+ , JsStr (..) , fromValue+ , fromValueWith+ , firstLossyNumber , toValue+ , toJsStr+ , jsStrVal+ , jsStrUnits+ , joinJsStr , truthy , strictEquals , looseEquals@@ -36,40 +49,83 @@ , nestsDeeperThan , jsonWeightUpTo , valWeightUpTo+ , saturatingSucc ) where import qualified Data.Aeson as Aeson import qualified Data.Aeson.KeyMap as KeyMap+import Data.Foldable (toList)+import Data.List (intersperse)+import Data.Scientific (Scientific) import Data.Text (Text) import qualified Data.Text as Text import Data.Vector (Vector) import qualified Data.Vector as Vector +import JsonLogic.Core.Config (NumericSafety (..)) import JsonLogic.Core.Number ( doubleToScientific , numberToString , parseFloatString+ , printsAsSource , scientificToDouble , stringToNumber )-import JsonLogic.Core.Utf16 (compareUtf16)+import JsonLogic.Core.Utf16 (Units, compareUtf16, fromUnits, toUnits, unitsAppend, unitsText) -- | A value during evaluation.+-- The constructors are in this order on purpose. GHC tags a pointer with+-- the constructor only for the first six of a type with more than seven, and+-- finds the others by reading the object, so the six that most evaluations+-- inspect come first and the rare ones last. data Val = VNull- | -- | JavaScript's @undefined@, which an empty @and@ or @or@ yields. It- -- is not 'VNull': it converts to @NaN@ (not 0) and to the string- -- @"undefined"@ (not @"null"@), and @undefined === null@ is false.- -- Written back as JSON @null@, and left out of objects.- VUndefined | VBool !Bool | -- | Any JavaScript number, including @NaN@, the infinities and @-0@. VNum {-# UNPACK #-} !Double | VStr !Text | VArr !(Vector Val) | VObj !(KeyMap.KeyMap Val)- deriving (Eq, Show)+ | -- | JavaScript's @undefined@, which an empty @and@ or @or@ yields. It+ -- is not 'VNull': it converts to @NaN@ (not 0) and to the string+ -- @\"undefined\"@ (not @\"null\"@), and @undefined === null@ is false.+ -- Written back as JSON @null@, and left out of objects.+ VUndefined+ | -- | A string with a lone surrogate, as its UTF-16 code units. Never+ -- well formed, so never equal to a 'VStr'; built only by 'fromUnits'+ -- through 'jsStrVal'.+ VWtf !Units+ | -- | A JSON number that a double cannot carry, when the configuration+ -- preserves such numbers: the double it is read as, and its own digits.+ -- It behaves as that double everywhere, and is written back as its own+ -- digits if it reaches the result unchanged. Arithmetic builds 'VNum',+ -- so the digits do not survive it. Kept apart from 'VNum' so that+ -- ordinary numbers carry nothing extra.+ VBig {-# UNPACK #-} !Double !Scientific+ deriving (Show) +-- | The double a number value stands for.+numberOf :: Val -> Maybe Double+numberOf (VNum d) = Just d+numberOf (VBig d _) = Just d+numberOf _ = Nothing++-- | Structural equality, in which @NaN@ equals @NaN@, so that equality is+-- reflexive. (This is not JavaScript's @==@, which is 'looseEquals', nor its+-- @===@, which is 'strictEquals'; it compares evaluation results.)+instance Eq Val where+ VNull == VNull = True+ VUndefined == VUndefined = True+ VBool a == VBool b = a == b+ VNum a == VNum b = a == b || (isNaN a && isNaN b)+ a@(VBig _ _) == b | Just x <- numberOf a, Just y <- numberOf b = x == y || (isNaN x && isNaN y)+ a == b@(VBig _ _) | Just x <- numberOf a, Just y <- numberOf b = x == y || (isNaN x && isNaN y)+ VStr a == VStr b = a == b+ VWtf a == VWtf b = a == b+ VArr a == VArr b = a == b+ VObj a == VObj b = a == b+ _ == _ = False+ -- --------------------------------------------------------------------- -- Conversion to and from JSON -- ---------------------------------------------------------------------@@ -85,6 +141,38 @@ fromValue (Aeson.Array items) = VArr (Vector.map fromValue items) fromValue (Aeson.Object fields) = VObj (KeyMap.map fromValue fields) +-- | 'fromValue' under a numeric policy: with 'PreserveSource' (and+-- 'RejectLossy', whose input has already been screened) a number whose+-- double does not print as its digits keeps them. The default policy is+-- plain 'fromValue', which the optimiser fuses into its consumers; the+-- others pay for the exactness check.+fromValueWith :: NumericSafety -> Aeson.Value -> Val+fromValueWith JsNumbers = fromValue+fromValueWith _ = go+ where+ go Aeson.Null = VNull+ go (Aeson.Bool flag) = VBool flag+ go (Aeson.Number n)+ | printsAsSource n = VNum (scientificToDouble n)+ | otherwise = VBig (scientificToDouble n) n+ go (Aeson.String s) = VStr s+ go (Aeson.Array items) = VArr (Vector.map go items)+ go (Aeson.Object fields) = VObj (KeyMap.map go fields)++-- | The first number in a JSON value, in document order, that a double+-- cannot carry (see 'printsAsSource'). Walks the whole value.+firstLossyNumber :: Aeson.Value -> Maybe Scientific+firstLossyNumber value = case value of+ Aeson.Number n | not (printsAsSource n) -> Just n+ Aeson.Array items -> firstJust (Vector.toList items)+ Aeson.Object fields -> firstJust (KeyMap.elems fields)+ _ -> Nothing+ where+ firstJust [] = Nothing+ firstJust (x : xs) = case firstLossyNumber x of+ Nothing -> firstJust xs+ found -> found+ -- | Write a result back as JSON, as @JSON.stringify@ would: @NaN@, the -- infinities and @undefined@ become @null@, negative zero becomes @0@, and an -- object property whose value is @undefined@ is left out.@@ -92,16 +180,24 @@ toValue VNull = Aeson.Null toValue VUndefined = Aeson.Null toValue (VBool flag) = Aeson.Bool flag+toValue (VBig _ n) = Aeson.Number n toValue (VNum d) | isNaN d || isInfinite d = Aeson.Null | otherwise = Aeson.Number (doubleToScientific d) toValue (VStr s) = Aeson.String s+toValue (VWtf units) = Aeson.String (unitsText units) toValue (VArr items) = Aeson.Array (Vector.map toValue items) toValue (VObj fields) = Aeson.Object (KeyMap.map toValue (KeyMap.filter (not . isUndefined) fields)) where isUndefined VUndefined = True isUndefined _ = False +-- | One more, except at 'maxBound', where it stays: a limit of 'maxBound'+-- means "no limit", and a bound written as @limit + 1@ must not wrap round+-- to 'minBound' and refuse everything.+saturatingSucc :: Int -> Int+saturatingSucc n = if n == maxBound then n else n + 1+ -- | Does a JSON value nest more than @n@ levels? An array or object that is -- not empty is one level; a scalar is none. Stops as soon as it knows, so -- the cost is bounded by @n@ along any path.@@ -151,8 +247,10 @@ truthy VNull = False truthy VUndefined = False truthy (VBool flag) = flag+truthy (VBig d _) = truthy (VNum d) truthy (VNum d) = not (d == 0 || isNaN d) truthy (VStr s) = not (Text.null s)+truthy (VWtf _) = True truthy (VArr items) = not (Vector.null items) truthy (VObj _) = True @@ -166,8 +264,10 @@ toJsString VUndefined = "undefined" toJsString (VBool True) = "true" toJsString (VBool False) = "false"+toJsString (VBig d _) = numberToString d toJsString (VNum d) = numberToString d toJsString (VStr s) = s+toJsString (VWtf units) = unitsText units toJsString (VArr items) = Text.intercalate "," (map toJoinText (Vector.toList items)) toJsString (VObj _) = "[object Object]" @@ -183,8 +283,10 @@ toNumber VNull = 0 toNumber VUndefined = 0 / 0 toNumber (VBool flag) = boolToNumber flag+toNumber (VBig d _) = d toNumber (VNum d) = d toNumber (VStr s) = stringToNumber s+toNumber (VWtf units) = stringToNumber (unitsText units) toNumber value@(VArr _) = stringToNumber (toJsString value) toNumber (VObj _) = 0 / 0 @@ -196,6 +298,7 @@ -- @NaN@ if there is none. A number is itself, except that negative zero -- becomes zero (@String(-0)@ is @"0"@). parseFloat :: Val -> Double+parseFloat (VBig d _) = d parseFloat (VNum d) | d == 0 = 0 | otherwise = d@@ -213,7 +316,10 @@ strictEquals (VBool a) (VBool b) = a == b strictEquals (VNum a) (VNum b) = a == b strictEquals (VStr a) (VStr b) = a == b-strictEquals _ _ = False+strictEquals (VWtf a) (VWtf b) = a == b+strictEquals a b+ | Just x <- numberOf a, Just y <- numberOf b = x == y+ | otherwise = False -- | JavaScript's @==@ (the abstract equality comparison). looseEquals :: Val -> Val -> Bool@@ -225,20 +331,29 @@ looseEquals VNull VNull = True looseEquals VNull _ = False looseEquals _ VNull = False+looseEquals (VBig d _) y = looseEquals (VNum d) y+looseEquals x (VBig d _) = looseEquals x (VNum d) looseEquals (VBool a) y = looseEquals (VNum (boolToNumber a)) y looseEquals x (VBool b) = looseEquals x (VNum (boolToNumber b)) looseEquals (VNum a) (VNum b) = a == b looseEquals (VStr a) (VStr b) = a == b+looseEquals (VWtf a) (VWtf b) = a == b+-- a string with a lone surrogate is never equal to a well-formed one, and+-- read as a number it is NaN+looseEquals (VWtf _) (VStr _) = False+looseEquals (VStr _) (VWtf _) = False+looseEquals (VWtf units) y@(VNum _) = looseEquals (VStr (unitsText units)) y+looseEquals x@(VNum _) (VWtf units) = looseEquals x (VStr (unitsText units)) looseEquals (VNum a) (VStr b) = a == stringToNumber b looseEquals (VStr a) (VNum b) = stringToNumber a == b looseEquals (VArr _) (VArr _) = False looseEquals (VArr _) (VObj _) = False looseEquals (VObj _) (VArr _) = False looseEquals (VObj _) (VObj _) = False-looseEquals x y@(VArr _) = looseEquals x (VStr (toJsString y))-looseEquals x y@(VObj _) = looseEquals x (VStr (toJsString y))-looseEquals x@(VArr _) y = looseEquals (VStr (toJsString x)) y-looseEquals x@(VObj _) y = looseEquals (VStr (toJsString x)) y+looseEquals x y@(VArr _) = looseEquals x (jsStrVal (toJsStr y))+looseEquals x y@(VObj _) = looseEquals x (jsStrVal (toJsStr y))+looseEquals x@(VArr _) y = looseEquals (jsStrVal (toJsStr x)) y+looseEquals x@(VObj _) y = looseEquals (jsStrVal (toJsStr x)) y -- --------------------------------------------------------------------- -- Ordering@@ -246,19 +361,75 @@ -- | Arrays and objects compare as the strings they convert to. toPrimitive :: Val -> Val-toPrimitive value@(VArr _) = VStr (toJsString value)+toPrimitive value@(VArr _) = jsStrVal (toJsStr value) toPrimitive value@(VObj _) = VStr (toJsString value) toPrimitive value = value +-- | A string value, if it is one.+stringOf :: Val -> Maybe JsStr+stringOf (VStr s) = Just (Plain s)+stringOf (VWtf units) = Just (Wtf units)+stringOf _ = Nothing+ -- | JavaScript's @<@: two strings compare by UTF-16 code unit, anything -- else numerically (so any @NaN@ makes it false). lessThan :: Val -> Val -> Bool lessThan x y = case (toPrimitive x, toPrimitive y) of- (VStr a, VStr b) -> compareUtf16 a b == LT- (a, b) -> toNumber a < toNumber b+ (a, b)+ | Just sa <- stringOf a, Just sb <- stringOf b -> compareStr sa sb == LT+ | otherwise -> toNumber a < toNumber b -- | JavaScript's @<=@. lessOrEqual :: Val -> Val -> Bool lessOrEqual x y = case (toPrimitive x, toPrimitive y) of- (VStr a, VStr b) -> compareUtf16 a b /= GT- (a, b) -> toNumber a <= toNumber b+ (a, b)+ | Just sa <- stringOf a, Just sb <- stringOf b -> compareStr sa sb /= GT+ | otherwise -> toNumber a <= toNumber b++-- ---------------------------------------------------------------------+-- Strings, exactly+-- ---------------------------------------------------------------------++-- | A JavaScript string: a 'Text' when it is well formed, which is nearly+-- always, and its code units when it holds a lone surrogate.+data JsStr+ = Plain !Text+ | Wtf !Units++-- | The code units of a string.+jsStrUnits :: JsStr -> Units+jsStrUnits (Plain t) = toUnits t+jsStrUnits (Wtf u) = u++-- | A string as a value.+jsStrVal :: JsStr -> Val+jsStrVal (Plain t) = VStr t+jsStrVal (Wtf u) = VWtf u++-- | Concatenate strings. Halves of a surrogate pair that meet become the+-- pair, so the result is a 'Plain' again.+joinJsStr :: Text -> [JsStr] -> JsStr+joinJsStr separator parts+ | all isPlain parts = Plain (Text.intercalate separator [t | Plain t <- parts])+ | otherwise = case fromUnits (unitsAppend (intersperse (toUnits separator) (map jsStrUnits parts))) of+ Right t -> Plain t+ Left u -> Wtf u+ where+ isPlain (Plain _) = True+ isPlain _ = False++-- | JavaScript's @String(value)@, exactly: an array holding a lone surrogate+-- converts to a string that holds it.+toJsStr :: Val -> JsStr+toJsStr (VStr s) = Plain s+toJsStr (VWtf u) = Wtf u+toJsStr (VArr items) = joinJsStr "," (map joined (toList items))+ where+ joined VNull = Plain ""+ joined VUndefined = Plain ""+ joined v = toJsStr v+toJsStr v = Plain (toJsString v)++compareStr :: JsStr -> JsStr -> Ordering+compareStr (Plain a) (Plain b) = compareUtf16 a b+compareStr a b = compare (jsStrUnits a) (jsStrUnits b)
+ test/AuditSpec.hs view
@@ -0,0 +1,529 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Behaviour that a forensic engineering audit found wrong, pinned so it+-- stays fixed. Each group names the finding (F-nn) it covers.+module AuditSpec (spec) where++import Control.Concurrent (forkIO, killThread, newEmptyMVar, putMVar, takeMVar, threadDelay)+import Control.Exception (AsyncException (..), Exception, fromException, throw, try)+import qualified Control.Exception+import Control.Monad (forM, forM_)+import Data.Aeson (Value (..), object, (.=))+import qualified Data.Aeson as Aeson+import qualified Data.Aeson.Key as Key+import Data.Either (isLeft, isRight)+import Data.Maybe (isNothing)+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Vector as Vector+import System.Timeout (timeout)+import Test.Hspec+import Test.QuickCheck++import Gen (genData, genRule)+import JsonLogic+import JsonLogic.Core.Value (firstLossyNumber)+import Support (at, json)++-- ---------------------------------------------------------------------+-- Helpers+-- ---------------------------------------------------------------------++call :: Text -> [Value] -> Value+call operator operands = object [Key.fromText operator .= operands]++registry :: [(Text, CustomOperator)] -> Operators+registry entries =+ either (error . show) id (operatorsFromList [(OperatorName name, implementation) | (name, implementation) <- entries])++anyArity :: (Value -> [Value] -> Either CustomError Value) -> CustomOperator+anyArity = pureOperator (AtLeast 0)++lenientConfig, lazyConfig, preserve, rejectLossy :: Config+lenientConfig = defaultConfig{arityMode = Lenient}+lazyConfig = defaultConfig{unknownOperators = FailWhenReached}+preserve = defaultConfig{numericSafety = PreserveSource}+rejectLossy = defaultConfig{numericSafety = RejectLossy}++withRule :: Operators -> Value -> (Rule -> IO ()) -> IO ()+withRule operators rule test = case compile defaultConfig operators rule of+ Left e -> expectationFailure ("did not compile: " ++ Text.unpack (renderError e))+ Right ready -> test ready++spinner :: Operators+spinner = registry [("spin", anyArity (\_ _ -> seq (length [1 :: Integer ..]) (Right Null)))]++data Boom = Boom+ deriving (Show)++instance Exception Boom++-- | The result of a rule as a value, with the error reduced to its kind.+kind :: Either Error Value -> Either Text Value+kind = either (Left . errorKind) Right++spec :: Spec+spec = describe "audit findings" $ do+ f01+ f02+ f03+ f04+ f05+ f06+ f07+ f10+ f11+ f13+ f15+ concurrency++-- ---------------------------------------------------------------------+-- F-01: tryRun and asynchronous exceptions+-- ---------------------------------------------------------------------++f01 :: Spec+f01 = describe "F-01 tryRun never swallows an asynchronous exception" $ do+ it "a timeout around tryRun fires, instead of becoming a Left" $+ withRule spinner (call "spin" []) $ \ready -> do+ outcome <- timeout 100000 (tryRun ready Null)+ isNothing outcome `shouldBe` True+ it "killThread reaches the thread running tryRun" $+ withRule spinner (call "spin" []) $ \ready -> do+ done <- newEmptyMVar+ thread <- forkIO (try (tryRun ready Null) >>= putMVar done)+ threadDelay 50000+ killThread thread+ result <- timeout 3000000 (takeMVar done)+ case result of+ Just (Left e) -> fromException e `shouldBe` Just ThreadKilled+ Just (Right _) -> expectationFailure "tryRun swallowed ThreadKilled and finished normally"+ Nothing -> expectationFailure "the killed thread never finished"+ it "runWithTimeout reports TimedOut" $+ withRule spinner (call "spin" []) $ \ready -> do+ outcome <- runWithTimeout 100000 ready Null+ case outcome of+ Left TimedOut -> pure ()+ other -> expectationFailure ("expected TimedOut, got " ++ show other)+ it "a synchronous exception from an operator is still reported, as OperatorThrew" $+ withRule (registry [("boom", anyArity (\_ _ -> throw Boom))]) (call "boom" []) $ \ready -> do+ outcome <- tryRun ready Null+ case outcome of+ Left (OperatorThrew e) -> fromException e `shouldSatisfy` \case Just Boom -> True; Nothing -> False+ other -> expectationFailure ("expected OperatorThrew, got " ++ show other)+ it "a rejection stays a value, apart from the exceptions" $+ withRule (registry [("fail", anyArity (\_ _ -> Left "no"))]) (call "fail" []) $ \ready -> do+ outcome <- tryRun ready Null+ case outcome of+ Left (Rejected (EvalFailure _ (CustomOperatorFailed _ _))) -> pure ()+ other -> expectationFailure ("expected Rejected, got " ++ show other)+ it "an ordinary answer is returned unchanged" $+ withRule noOperators (call "+" [Number 1, Number 2]) $ \ready -> do+ outcome <- tryRun ready Null+ either (const Nothing) Just outcome `shouldBe` Just (Number 3)++-- ---------------------------------------------------------------------+-- F-02: unknown operators+-- ---------------------------------------------------------------------++f02 :: Spec+f02 = describe "F-02 unknown operators are found when the rule is compiled" $ do+ let typo = call "if" [Bool True, call "nope" [Number 1]]+ it "are refused by default, with their location" $+ case compile defaultConfig noOperators typo of+ Left (ParseFailure loc (UnknownOperatorName name _)) -> do+ loc `shouldBe` at [Left "if", Right 1]+ name `shouldBe` OperatorName "nope"+ other -> expectationFailure ("expected UnknownOperatorName, got " ++ either show (const "a rule") other)+ it "name the nearest known operators" $+ case compile defaultConfig noOperators (call "missing_sone" []) of+ Left (ParseFailure _ (UnknownOperatorName _ near)) -> near `shouldBe` [OperatorName "missing_some"]+ other -> expectationFailure ("expected a suggestion, got " ++ either show (const "a rule") other)+ it "suggest registered operators too" $+ case compile defaultConfig (registry [("starts_with", anyArity (\_ _ -> Right Null))]) (call "start_with" []) of+ Left (ParseFailure _ (UnknownOperatorName _ near)) -> near `shouldBe` [OperatorName "starts_with"]+ other -> expectationFailure ("expected a suggestion, got " ++ either show (const "a rule") other)+ it "suggest nothing when nothing is close" $+ case compile defaultConfig noOperators (call "xyzzy" []) of+ Left (ParseFailure _ (UnknownOperatorName _ near)) -> near `shouldBe` []+ other -> expectationFailure ("expected no suggestion, got " ++ either show (const "a rule") other)+ it "are accepted when the configuration says they fail only when reached, as the reference does" $ do+ apply typo Null `shouldSatisfy` isLeft+ applyWithConfig lazyConfig noOperators (call "or" [Bool True, call "nope" []]) Null `shouldBe` Right (Bool True)+ applyWithConfig lazyConfig noOperators typo Null+ `shouldBe` Left (EvalFailure (at [Left "if", Right 1]) (UnknownOperator (OperatorName "nope")))+ it "follow the arity mode by default: lenient mode keeps the reference's laziness" $+ applyWithConfig lenientConfig noOperators (call "or" [Bool True, call "nope" []]) Null `shouldBe` Right (Bool True)+ it "can be refused in lenient mode too" $+ applyWithConfig lenientConfig{unknownOperators = RejectAtCompile} noOperators (call "nope" []) Null+ `shouldSatisfy` \case Left (ParseFailure _ (UnknownOperatorName _ _)) -> True; _ -> False+ it "are listed by unresolvedOperators when they are accepted" $+ case compile lazyConfig noOperators (call "and" [call "a" [], call "b" []]) of+ Right ready -> unresolvedOperators ready `shouldBe` [(at [Left "and", Right 0], OperatorName "a"), (at [Left "and", Right 1], OperatorName "b")]+ Left e -> expectationFailure (Text.unpack (renderError e))+ it "are not reported for a registered operator" $+ case compile defaultConfig (registry [("known", anyArity (\_ _ -> Right Null))]) (call "known" []) of+ Right ready -> unresolvedOperators ready `shouldBe` []+ Left e -> expectationFailure (Text.unpack (renderError e))+ it "the declared arity of a custom operator is checked in strict mode" $+ case compile defaultConfig (registry [("two", pureOperator (Exactly 2) (\_ _ -> Right Null))]) (call "two" [Number 1]) of+ Left (ParseFailure _ (ArityMismatch (OperatorName "two") (Exactly 2) 1)) -> pure ()+ other -> expectationFailure ("expected ArityMismatch, got " ++ either show (const "a rule") other)+ it "the declared arity is not checked in lenient mode" $+ applyWithConfig lenientConfig (registry [("two", pureOperator (Exactly 2) (\_ _ -> Right (Number 7)))]) (call "two" [Number 1]) Null+ `shouldBe` Right (Number 7)+ it "apply and compile-then-run agree, for any rule, including those that are refused" $+ property $+ forAll (genRule 5) $ \rule -> forAll (genData 3) $ \dat ->+ case compile defaultConfig noOperators rule of+ Left e -> apply rule dat === Left e+ Right ready -> run ready dat === apply rule dat++-- ---------------------------------------------------------------------+-- F-03: numbers a double cannot hold+-- ---------------------------------------------------------------------++f03 :: Spec+f03 = describe "F-03 numbers a double cannot hold" $ do+ let ident = json "{\"var\":\"id\"}"+ dat = json "{\"id\":9007199254740993}"+ it "are rounded by default, as in the reference" $+ apply ident dat `shouldBe` Right (Number 9007199254740992)+ it "keep their digits when passed through, under PreserveSource" $+ applyWithConfig preserve noOperators ident dat `shouldBe` Right (Number 9007199254740993)+ it "keep their digits through map, if and a literal rule" $ do+ applyWithConfig preserve noOperators (json "{\"map\":[{\"var\":\"xs\"},{\"var\":\"\"}]}") (json "{\"xs\":[9007199254740993,1]}")+ `shouldBe` Right (json "[9007199254740993,1]")+ applyWithConfig preserve noOperators (json "{\"if\":[true,9007199254740993,0]}") Null `shouldBe` Right (Number 9007199254740993)+ it "are used as doubles in arithmetic and comparison, whatever the policy" $ do+ applyWithConfig preserve noOperators (json "{\"+\":[{\"var\":\"id\"},0]}") dat `shouldBe` Right (Number 9007199254740992)+ applyWithConfig preserve noOperators (json "{\"==\":[{\"var\":\"id\"},9007199254740992]}") dat `shouldBe` Right (Bool True)+ it "are refused under RejectLossy: in the data, in the rule, and from an operator" $ do+ applyWithConfig rejectLossy noOperators ident dat+ `shouldBe` Left (EvalFailure (fromSegments []) (LossyNumber 9007199254740993))+ applyWithConfig rejectLossy noOperators (Number 9007199254740993) Null+ `shouldBe` Left (ParseFailure (fromSegments []) (LossyNumberLiteral 9007199254740993))+ applyWithConfig rejectLossy (registry [("big", anyArity (\_ _ -> Right (Number 9007199254740993)))]) (call "big" []) Null+ `shouldBe` Left (EvalFailure (fromSegments []) (LossyNumber 9007199254740993))+ it "are not confused with numbers that print back as written" $+ forM_ ["0", "1", "-1", "0.1", "0.5", "1e22", "9007199254740992", "1.7976931348623157e308", "5e-324", "123.456"] $ \text ->+ applyWithConfig rejectLossy noOperators ident (object ["id" .= json text]) `shouldBe` Right (json text)+ it "checkData screens the data once, for depth and (under RejectLossy) for lossy numbers" $ do+ checkData defaultConfig dat `shouldBe` Right ()+ checkData rejectLossy dat `shouldBe` Left (EvalFailure (fromSegments []) (LossyNumber 9007199254740993))+ checkData defaultConfig{maxDataDepth = 3} (json "[[[[1]]]]")+ `shouldBe` Left (EvalFailure (fromSegments []) (LimitExceeded (DataDepthLimit 3)))+ checkData defaultConfig{maxDataDepth = 4} (json "[[[[1]]]]") `shouldBe` Right ()+ it "PreserveSource changes nothing for numbers a double holds" $+ property $+ forAll (genRule 4) $ \rule -> forAll (genData 3) $ \d ->+ isNothing (firstLossyNumber rule) && isNothing (firstLossyNumber d) ==>+ applyWithConfig preserve noOperators rule d === apply rule d++-- ---------------------------------------------------------------------+-- F-04: a string with a lone surrogate+-- ---------------------------------------------------------------------++f04 :: Spec+f04 = describe "F-04 severed surrogate halves keep their identity" $ do+ let emoji = String "\x1F600"+ hi = call "substr" [emoji, Number 0, Number 1]+ lo = call "substr" [emoji, Number 1, Number 1]+ run1 rule = apply rule Null+ it "the two halves are not equal" $ do+ run1 (call "==" [hi, lo]) `shouldBe` Right (Bool False)+ run1 (call "===" [hi, lo]) `shouldBe` Right (Bool False)+ run1 (call "!=" [hi, lo]) `shouldBe` Right (Bool True)+ it "a half is equal to itself" $+ run1 (call "===" [hi, call "substr" [call "cat" [hi, String "x"], Number 0, Number 1]]) `shouldBe` Right (Bool True)+ it "the halves re-join into the character" $ do+ run1 (call "cat" [hi, lo]) `shouldBe` Right emoji+ run1 (call "===" [call "cat" [hi, lo], emoji]) `shouldBe` Right (Bool True)+ it "the halves order by code unit" $ do+ run1 (call "<" [hi, lo]) `shouldBe` Right (Bool True)+ run1 (call "<" [lo, hi]) `shouldBe` Right (Bool False)+ it "a half is found in the character it came from, and not in another" $ do+ run1 (call "in" [hi, emoji]) `shouldBe` Right (Bool True)+ run1 (call "in" [lo, emoji]) `shouldBe` Right (Bool True)+ run1 (call "in" [hi, String "x"]) `shouldBe` Right (Bool False)+ run1 (call "in" [call "cat" [lo, hi], String "\x1F600\x1F600"]) `shouldBe` Right (Bool True)+ it "a half has one code unit, and slicing it again works" $ do+ run1 (call "substr" [hi, Number 0, Number 5]) `shouldBe` run1 hi+ run1 (call "cat" [call "substr" [call "cat" [hi, String "ab"], Number 1, Number 2]]) `shouldBe` Right (String "ab")+ it "turns into U+FFFD only where JSON cannot carry it, in the result" $+ run1 hi `shouldBe` Right (String "\xFFFD")+ it "a half is not a number and is truthy" $ do+ run1 (call "!!" [hi]) `shouldBe` Right (Bool True)+ run1 (call "+" [hi, Number 1]) `shouldBe` Right Null+ it "an array holding a half converts to a string that holds it" $+ do+ run1 (call "===" [call "cat" [Array (Vector.fromList [hi]), lo], emoji]) `shouldBe` Right (Bool True)+ -- a null element joins as nothing, but the comma between elements stays+ run1 (call "===" [call "cat" [Array (Vector.fromList [hi, Null]), lo], emoji]) `shouldBe` Right (Bool False)+ it "splitting a string anywhere and joining the parts gives it back" $+ property $+ forAll genEmojiText $ \s -> forAll (choose (0, utf16Len s)) $ \k ->+ apply+ (call "cat" [call "substr" [String s, Number 0, Number (fromIntegral k)], call "substr" [String s, Number (fromIntegral k)]])+ Null+ === Right (String s)++utf16Len :: Text -> Int+utf16Len s = sum [if fromEnum c > 0xFFFF then 2 else 1 | c <- Text.unpack s]++genEmojiText :: Gen Text+genEmojiText = Text.concat <$> listOf (elements ["a", "b", "\xE9", "\x1F600", "\x1F680", "\x4E2D"])++-- ---------------------------------------------------------------------+-- F-05: limits+-- ---------------------------------------------------------------------++f05 :: Spec+f05 = describe "F-05 one limit model" $ do+ let cfg = defaultConfig{maxIterations = 3}+ body = Bool True+ items :: Int -> Value+ items n = Array (Vector.fromList (map (Number . fromIntegral) [1 .. n]))+ overData rule n = applyWithConfig cfg noOperators (call rule [object ["var" .= ("" :: Text)], body]) (items n)+ forM_ ["map", "filter", "all", "none", "some"] $ \name -> do+ it (Text.unpack name ++ " refuses an array longer than the iteration limit") $+ overData name 4 `shouldBe` Left (EvalFailure root' (LimitExceeded (IterationLimit 3)))+ it (Text.unpack name ++ " accepts an array at the iteration limit") $+ overData name 3 `shouldSatisfy` isRight+ it "reduce refuses an array longer than the iteration limit, like the others" $ do+ let reduceRule = call "reduce" [object ["var" .= ("" :: Text)], object ["var" .= ("accumulator" :: Text)], Number 0]+ applyWithConfig cfg noOperators reduceRule (items 4) `shouldBe` Left (EvalFailure root' (LimitExceeded (IterationLimit 3)))+ applyWithConfig cfg noOperators reduceRule (items 3) `shouldSatisfy` isRight+ it "the iteration limit and the build limit are separate" $ do+ let wide = defaultConfig{maxIterations = 10, maxArrayLength = 2}+ keep n = call "filter" [object ["var" .= ("" :: Text)], call "<" [object ["var" .= ("" :: Text)], Number n]]+ -- keeps one of five: builds one element, so within the build limit+ applyWithConfig wide noOperators (keep 2) (items 5) `shouldBe` Right (json "[1]")+ -- keeps four of five: builds more than the build limit+ applyWithConfig wide noOperators (keep 5) (items 5) `shouldBe` Left (EvalFailure root' (LimitExceeded (ArrayLimit 2)))+ -- map builds as many as it reads+ applyWithConfig wide noOperators (call "map" [object ["var" .= ("" :: Text)], Number 1]) (items 5)+ `shouldBe` Left (EvalFailure root' (LimitExceeded (ArrayLimit 2)))+ it "a negative limit is refused, by name" $ do+ validateConfig defaultConfig{maxSteps = -1} `shouldBe` Left (NegativeLimit "maxSteps")+ validateConfig defaultConfig{maxIterations = -5, maxNodes = -1} `shouldBe` Left (NegativeLimit "maxIterations")+ validateConfig defaultConfig{maxNodes = -1} `shouldBe` Left (NegativeLimit "maxNodes")+ apply' defaultConfig{maxDepth = -1} (Number 1)+ `shouldBe` Left (ParseFailure root' (InvalidConfig (NegativeLimit "maxDepth")))+ it "unlimited is accepted everywhere" $+ applyWithConfig+ defaultConfig{maxSteps = unlimited, maxDepth = unlimited, maxNodes = unlimited, maxStringLength = unlimited, maxArrayLength = unlimited, maxIterations = unlimited}+ noOperators+ (call "+" [Number 1, Number 2])+ Null+ `shouldBe` Right (Number 3)+ it "zero is a limit, not a switch: it refuses everything it counts" $+ applyWithConfig defaultConfig{maxSteps = 0} noOperators (Number 1) Null+ `shouldBe` Left (EvalFailure root' (LimitExceeded (StepLimit 0)))+ where+ root' = fromSegments []+ apply' config rule = applyWithConfig config noOperators rule Null++-- ---------------------------------------------------------------------+-- F-06: custom operators+-- ---------------------------------------------------------------------++f06 :: Spec+f06 = describe "F-06 the custom operator contract" $ do+ let coalesce = lazyOperator (AtLeast 1) go+ where+ go _ [] = pure Null+ go datum (operand : rest) = do+ value <- force operand+ if value == Null then go datum rest else pure value+ failing = anyArity (\_ _ -> Left (CustomError "boom" "it broke" (Just (Number 1))))+ ops = registry [("coalesce", coalesce), ("fail", failing)]+ fails = call "fail" []+ it "a lazy operator does not evaluate the operands it does not need" $ do+ applyWithConfig defaultConfig ops (call "coalesce" [Number 1, fails]) Null `shouldBe` Right (Number 1)+ applyWithConfig defaultConfig ops (call "coalesce" [Null, Number 2, fails]) Null `shouldBe` Right (Number 2)+ it "a lazy operator evaluates the operands it asks for, and their failures stop it" $+ kind (applyWithConfig defaultConfig ops (call "coalesce" [Null, fails]) Null) `shouldBe` Left "custom_operator_failed"+ it "forcing an operand spends steps from the same budget" $ do+ let rule = call "coalesce" [Null, Null, Null, Number 5]+ applyWithConfig defaultConfig{maxSteps = 100} ops rule Null `shouldBe` Right (Number 5)+ applyWithConfig defaultConfig{maxSteps = 3} ops rule Null+ `shouldSatisfy` \case Left (EvalFailure _ (LimitExceeded (StepLimit 3))) -> True; _ -> False+ it "a failure carries its code, message and details unchanged, at the operator" $+ applyWithConfig defaultConfig ops (call "if" [Bool True, fails, Null]) Null+ `shouldBe` Left (EvalFailure (at [Left "if", Right 1]) (CustomOperatorFailed (OperatorName "fail") (CustomError "boom" "it broke" (Just (Number 1)))))+ it "stepFail stops a lazy operator the same way" $ do+ let stopper = lazyOperator (Exactly 0) (\_ _ -> stepFail (CustomError "stop" "stopped" Nothing))+ applyWithConfig defaultConfig (registry [("stop", stopper)]) (call "stop" []) Null+ `shouldBe` Left (EvalFailure (fromSegments []) (CustomOperatorFailed (OperatorName "stop") (CustomError "stop" "stopped" Nothing)))+ it "a lazy operator is handed the datum in scope, and its operands see the same datum" $ do+ let echo = lazyOperator (Exactly 0) (\datum _ -> pure datum)+ firstOf = lazyOperator (Exactly 1) (\_ operands -> case operands of (o : _) -> force o; [] -> pure Null)+ scoped = registry [("echo", echo), ("first_of", firstOf)]+ applyWithConfig defaultConfig scoped (call "map" [json "[1,2]", call "echo" []]) Null `shouldBe` Right (json "[1,2]")+ applyWithConfig defaultConfig scoped (call "map" [json "[[7],[8]]", call "first_of" [object ["var" .= ("0" :: Text)]]]) Null+ `shouldBe` Right (json "[7,8]")+ it "a string literal is a failure with the code \"failed\"" $+ (Left "x" :: Either CustomError ()) `shouldBe` Left (CustomError "failed" "x" Nothing)++-- ---------------------------------------------------------------------+-- F-07: errors+-- ---------------------------------------------------------------------++f07 :: Spec+f07 = describe "F-07 errors" $ do+ let unknown = EvalFailure (at [Left "if", Right 1]) (UnknownOperator (OperatorName "x"))+ it "an uncaught error reads as a sentence" $+ displayException' unknown `shouldBe` "at /if/1: unknown operator \"x\""+ it "an error has a stable JSON form" $+ Aeson.toJSON unknown+ `shouldBe` json "{\"kind\":\"unknown_operator\",\"stage\":\"eval\",\"pointer\":\"/if/1\",\"message\":\"at /if/1: unknown operator \\\"x\\\"\",\"detail\":{\"operator\":\"x\"}}"+ it "every kind has its own tag" $ do+ let errs =+ [ ParseFailure root' (DepthExceeded 1)+ , ParseFailure root' (ArityMismatch (OperatorName "a") (Exactly 1) 0)+ , ParseFailure root' (NodeLimitExceeded 1)+ , ParseFailure root' (UnknownOperatorName (OperatorName "a") [])+ , ParseFailure root' (InvalidConfig (NegativeLimit "x"))+ , ParseFailure root' (LossyNumberLiteral 1)+ , EvalFailure root' (CustomOperatorFailed (OperatorName "a") (customFailure "x"))+ , EvalFailure root' (InvalidOperand (OperatorName "a") (OperandIssue 0 "x" "y"))+ , EvalFailure root' (LimitExceeded (StepLimit 1))+ , EvalFailure root' (LossyNumber 1)+ , EvalFailure root' (UnknownOperator (OperatorName "a"))+ ]+ -- a kind is unique within a stage (a parse and an eval error may share a name)+ let tagged e = (errorKind e, case e of ParseFailure{} -> True; EvalFailure{} -> False)+ length (uniq (map tagged errs)) `shouldBe` length errs+ forM_ errs $ \e -> Aeson.toJSON e `shouldSatisfy` \case Object _ -> True; _ -> False+ it "an invalid operand says which, what was needed, and what was given" $ do+ let r = applyWithConfig lenientConfig noOperators (call "missing_some" [Number 1, Null]) Null+ either (Left . renderError) Right r+ `shouldBe` Left "at the root of the rule: operator \"missing_some\": operand 2 must be a list of keys, but is null"+ it "validate reports every problem, in document order" $ do+ let rule = call "and" [call "nope" [], call "==" [Number 1], call "if" [Bool True, call "mox" []]]+ map errorLocation (validate defaultConfig noOperators rule)+ `shouldBe` [at [Left "and", Right 0], at [Left "and", Right 1], at [Left "and", Right 2, Left "if", Right 1]]+ it "validate is empty exactly when compile succeeds, and starts with compile's error" $+ property $+ forAll (genRule 5) $ \rule -> forAll (elements [defaultConfig, lenientConfig, lazyConfig]) $ \cfg ->+ case compile cfg noOperators rule of+ Right _ -> validate cfg noOperators rule === []+ Left e -> take 1 (validate cfg noOperators rule) === [e]+ it "validate sees problems in custom operators too" $ do+ let ops = registry [("two", pureOperator (Exactly 2) (\_ _ -> Right Null))]+ map errorKind (validate defaultConfig ops (call "or" [call "two" [Number 1], call "three" []]))+ `shouldBe` ["arity_mismatch", "unknown_operator"]+ where+ root' = fromSegments []+ displayException' = Control.Exception.displayException+ uniq = foldr (\x acc -> if x `elem` acc then acc else x : acc) []++-- ---------------------------------------------------------------------+-- F-10: ordering of locations+-- ---------------------------------------------------------------------++f10 :: Spec+f10 = describe "F-10 locations order by position in the rule" $ do+ it "a key sorts by its own name before a later segment" $+ (fromSegments [Key "a", Key "z"] < fromSegments [Key "b", Key "a"]) `shouldBe` True+ it "a parent sorts before its children, and siblings by index" $ do+ (fromSegments [Key "a"] < fromSegments [Key "a", Index 0]) `shouldBe` True+ (fromSegments [Key "a", Index 1] < fromSegments [Key "a", Index 2]) `shouldBe` True+ (fromSegments [Key "a", Index 9] < fromSegments [Key "b"]) `shouldBe` True+ it "the order is that of the segment lists, whatever they are" $+ property $+ forAll (listOf genSegment) $ \xs -> forAll (listOf genSegment) $ \ys ->+ compare (fromSegments xs) (fromSegments ys) === compare xs ys+ it "a parent is smaller than every extension of it" $+ property $+ forAll (listOf genSegment) $ \xs -> forAll genSegment $ \s ->+ fromSegments xs < fromSegments (xs ++ [s])+ where+ genSegment = oneof [Key <$> elements ["a", "b", "if", "var"], Index <$> choose (0, 5)]++-- ---------------------------------------------------------------------+-- F-11: registries+-- ---------------------------------------------------------------------++f11 :: Spec+f11 = describe "F-11 operator registries" $ do+ let one = anyArity (\_ _ -> Right Null)+ it "refuse an empty name and a padded one" $ do+ operatorsFromList' [("", one)] `shouldBe` Just (InvalidOperatorName (OperatorName ""))+ operatorsFromList' [(" x", one)] `shouldBe` Just (InvalidOperatorName (OperatorName " x"))+ operatorsFromList' [("x ", one)] `shouldBe` Just (InvalidOperatorName (OperatorName "x "))+ it "combine disjoint registries, and refuse a name defined by both" $ do+ let a = registry [("f", one)]+ b = registry [("g", one)]+ isRight (combineOperators a b) `shouldBe` True+ either Just (const Nothing) (combineOperators a a) `shouldBe` Just (DuplicateOperatorName (OperatorName "f"))+ isRight (combineOperators a noOperators) `shouldBe` True+ where+ operatorsFromList' entries = either Just (const Nothing) (operatorsFromList [(OperatorName n, o) | (n, o) <- entries])++-- ---------------------------------------------------------------------+-- F-13: lenient mode evaluates every operand before applying the operator+-- ---------------------------------------------------------------------++f13 :: Spec+f13 = describe "F-13 lenient surplus operands, in the reference's order" $ do+ it "a surplus operand that fails is reported before the operator's own failure" $+ applyWithConfig lenientConfig noOperators (call "missing_some" [Number 1, Null, call "nope" []]) Null+ `shouldBe` Left (EvalFailure (at [Left "missing_some", Right 2]) (UnknownOperator (OperatorName "nope")))+ it "the operator's own failure is still reported when the surplus is harmless" $+ applyWithConfig lenientConfig noOperators (call "missing_some" [Number 1, Null, Number 3]) Null+ `shouldSatisfy` \case Left (EvalFailure _ (InvalidOperand _ _)) -> True; _ -> False+ it "surplus operands are still evaluated, and discarded" $ do+ applyWithConfig lenientConfig noOperators (call "!" [Number 1, Number 2]) Null `shouldBe` Right (Bool False)+ applyWithConfig lenientConfig noOperators (call "!" [Number 1, call "nope" []]) Null `shouldSatisfy` isLeft+ it "the data a rule reads is still found when a var has surplus operands" $+ case compile lenientConfig noOperators (call "var" [String "a", Null, object ["var" .= ("b" :: Text)]]) of+ Right ready -> usedPaths (dataUse ready) `shouldBe` ["a", "b"]+ Left e -> expectationFailure (Text.unpack (renderError e))+ it "lenient and strict agree wherever strict accepts the rule" $+ property $+ forAll (genRule 5) $ \rule -> forAll (genData 3) $ \d ->+ case apply rule d of+ Left _ -> property True+ Right r -> applyWithConfig lenientConfig noOperators rule d === Right r++-- ---------------------------------------------------------------------+-- F-15: JSON text in and out+-- ---------------------------------------------------------------------++f15 :: Spec+f15 = describe "F-15 applyBytes" $ do+ it "applies a rule to data, both as JSON text" $+ applyBytes "{\"+\":[{\"var\":\"a\"},1]}" "{\"a\":2}" `shouldSatisfy` \r -> either (const False) (== "3") r+ it "says which of the two is not JSON" $ do+ applyBytes "{" "{}" `shouldSatisfy` \case Left (MalformedRule _) -> True; _ -> False+ applyBytes "{}" "}" `shouldSatisfy` \case Left (MalformedData _) -> True; _ -> False+ it "reports a refusal as an Error" $+ applyBytes "{\"nope\":[]}" "null" `shouldSatisfy` \case Left (Refused (ParseFailure _ _)) -> True; _ -> False+ it "agrees with apply" $+ property $+ forAll (genRule 4) $ \rule -> forAll (genData 3) $ \d ->+ case (apply rule d, applyBytes (Aeson.encode rule) (Aeson.encode d)) of+ (Right v, Right bytes) -> Aeson.decode bytes === Just v+ (Left e, Left (Refused e')) -> e === e'+ (a, b) -> counterexample (show (a, b)) False++-- ---------------------------------------------------------------------+-- Sharing a compiled rule+-- ---------------------------------------------------------------------++concurrency :: Spec+concurrency = describe "a compiled rule shared by several threads" $+ it "gives each the answer it would have got alone" $ do+ let rule = json "{\"map\":[{\"var\":\"xs\"},{\"*\":[{\"var\":\"\"},2]}]}"+ inputs = [object ["xs" .= [n .. n + 20]] | n <- [1 .. 40 :: Int]]+ case compile defaultConfig noOperators rule of+ Left e -> expectationFailure (Text.unpack (renderError e))+ Right ready -> do+ boxes <- forM inputs $ \input -> do+ box <- newEmptyMVar+ _ <- forkIO (putMVar box $! run ready input)+ pure box+ results <- mapM takeMVar boxes+ results `shouldBe` map (run ready) inputs
test/CompatSpec.hs view
@@ -16,6 +16,7 @@ import JsonLogic import JsonLogic.Core.Location (root) import JsonLogic.Core.Utf16+import Oracle (fromUtf16Units, utf16Units) import Support (Problem (..), at, json, problem) -- | A registry that the test expects to be accepted.@@ -52,15 +53,15 @@ it "strict rejects * with no operands before evaluating anything" $ strict "{\"*\":[]}" "null" `shouldBe` Left (ParseProblem (ArityMismatch (OperatorName "*") (AtLeast 1) 0)) it "lenient throws on * with no operands only when it is evaluated, as the reference does" $ do- lenient "{\"*\":[]}" "null" `shouldBe` Left (EvalProblem (InvalidOperand (OperatorName "*")))+ lenient "{\"*\":[]}" "null" `shouldBe` Left (EvalProblem (InvalidOperand (OperatorName "*") (OperandIssue 0 "at least one operand" "none"))) lenient "{\"if\":[true,1,{\"*\":[]}]}" "null" `shouldBe` Right (Number 1) lenient "{\"or\":[1,{\"*\":[]}]}" "null" `shouldBe` Right (Number 1) lenient "{\"and\":[0,{\"*\":[]}]}" "null" `shouldBe` Right (Number 0) lenient "{\"map\":[[],{\"*\":[]}]}" "null" `shouldBe` Right (toJSON ([] :: [Int]))- lenient "{\"and\":[1,{\"*\":[]}]}" "null" `shouldBe` Left (EvalProblem (InvalidOperand (OperatorName "*")))+ lenient "{\"and\":[1,{\"*\":[]}]}" "null" `shouldBe` Left (EvalProblem (InvalidOperand (OperatorName "*") (OperandIssue 0 "at least one operand" "none"))) it "locates the empty * that was reached" $ applyWithConfig defaultConfig{arityMode = Lenient} noOperators (json "{\"and\":[1,{\"*\":[]}]}") Null- `shouldBe` Left (EvalFailure (at [Left "and", Right 1]) (InvalidOperand (OperatorName "*")))+ `shouldBe` Left (EvalFailure (at [Left "and", Right 1]) (InvalidOperand (OperatorName "*") (OperandIssue 0 "at least one operand" "none"))) it "strict success implies the same lenient answer" $ forAll (genRuleForArity 4) $ \rule -> case apply rule Null of Right v -> applyWithConfig defaultConfig{arityMode = Lenient} noOperators rule Null === Right v@@ -148,7 +149,7 @@ strict "{\"missing_some\":[2,\"ab\"]}" "{}" `shouldBe` Right (json "[\"ab\"]") it "throws where the reference throws on a null option list" $ strict "{\"missing_some\":[1,null]}" "{}"- `shouldBe` Left (EvalProblem (InvalidOperand (OperatorName "missing_some")))+ `shouldBe` Left (EvalProblem (InvalidOperand (OperatorName "missing_some") (OperandIssue 1 "a list of keys" "null"))) it "returns the missing keys when the options have no length" $ strict "{\"missing_some\":[0,0]}" "{}" `shouldBe` Right (json "[0]") @@ -160,13 +161,21 @@ it "still finds an own property of that name" $ strict "{\"var\":\"constructor\"}" "{\"constructor\":7}" `shouldBe` Right (Number 7) + describe "arrays and objects are never equal (DEV-IDENTITY)" $ do+ it "two reads of the same array are not equal, where the reference compares references" $ do+ strict "{\"===\":[{\"var\":\"l\"},{\"var\":\"l\"}]}" "{\"l\":[1]}" `shouldBe` Right (Bool False)+ strict "{\"!==\":[{\"var\":\"o\"},{\"var\":\"o\"}]}" "{\"o\":{\"a\":1}}" `shouldBe` Right (Bool True)+ it "an accumulator holding an array is not equal to itself (the reference says it is)" $+ lenient "{\"reduce\":[[1],{\"!==\":[{\"var\":\"accumulator\"},{\"var\":\"accumulator\"}]},[0]]}" "null"+ `shouldBe` Right (Bool True)+ describe "undefined" $ do it "an object property that is undefined is left out, as JSON.stringify does" $- strict "{\"reduce\":[[0],{\"var\":\"\"},{\"and\":[]}]}" "null" `shouldBe` Right (json "{\"current\":0}")+ lenient "{\"reduce\":[[0],{\"var\":\"\"},{\"and\":[]}]}" "null" `shouldBe` Right (json "{\"current\":0}") describe "custom operators" $ do let double :: CustomOperator- double _ args = case args of+ double = pureOperator (Exactly 1) $ \_ args -> case args of [Number n] -> Right (Number (n * 2)) _ -> Left "expected one number" it "are refused when named like a builtin, instead of being ignored" $@@ -177,19 +186,25 @@ case operatorsFromList [(OperatorName "double", double), (OperatorName "double", double)] of Left e -> e `shouldBe` DuplicateOperatorName (OperatorName "double") Right _ -> expectationFailure "a duplicate name was accepted"- it "compose left-biased" $ do- let a = registry [(OperatorName "f", \_ _ -> Right (toJSON (1 :: Int)))]- b = registry [(OperatorName "f", \_ _ -> Right (toJSON (2 :: Int))), (OperatorName "g", \_ _ -> Right (toJSON (3 :: Int)))]- both = a <> b- applyWith both (object ["f" .= ([] :: [Int])]) Null `shouldBe` Right (Number 1)- applyWith both (object ["g" .= ([] :: [Int])]) Null `shouldBe` Right (Number 3)+ it "combine when their names are disjoint, and refuse a name both define" $ do+ let a = registry [(OperatorName "f", pureOperator (AtLeast 0) (\_ _ -> Right (toJSON (1 :: Int))))]+ b = registry [(OperatorName "f", pureOperator (AtLeast 0) (\_ _ -> Right (toJSON (2 :: Int))))]+ c = registry [(OperatorName "g", pureOperator (AtLeast 0) (\_ _ -> Right (toJSON (3 :: Int))))]+ case combineOperators a c of+ Right both -> do+ applyWith both (object ["f" .= ([] :: [Int])]) Null `shouldBe` Right (Number 1)+ applyWith both (object ["g" .= ([] :: [Int])]) Null `shouldBe` Right (Number 3)+ Left e -> expectationFailure ("disjoint registries were refused: " <> show e)+ either Just (const Nothing) (combineOperators a b) `shouldBe` Just (DuplicateOperatorName (OperatorName "f")) it "a custom failure inside map stops the evaluation" $ do let ops = registry [(OperatorName "double", double)] applyWith ops (json "{\"map\":[[1,\"x\"],{\"double\":[{\"var\":\"\"}]}]}") Null `shouldBe` Left (EvalFailure (at [Left "map", Right 1]) (CustomOperatorFailed (OperatorName "double") "expected one number")) it "combining with the empty registry changes nothing" $ do let ops = registry [(OperatorName "double", double)]- applyWith (ops <> noOperators) (json "{\"double\":[2]}") Null `shouldBe` Right (Number 4)+ case combineOperators ops noOperators of+ Right same -> applyWith same (json "{\"double\":[2]}") Null `shouldBe` Right (Number 4)+ Left e -> expectationFailure (show e) describe "renderError" $ do it "describes each constructor, after the location" $ do
test/EvalSpec.hs view
@@ -10,10 +10,10 @@ import Test.Hspec import Test.QuickCheck (Gen, choose, forAll, listOf, oneof) -import JsonLogic hiding (Rule)-import JsonLogic.Core.Eval (evaluate)+import JsonLogic import JsonLogic.Core.Location (root)-import JsonLogic.Core.Rule (Node (..), Rule, RuleF (..))+import JsonLogic.Core.Rule (Node (..), RuleF (..), RuleTree)+import Oracle (evaluate) import Support (Problem (..), at, problem) -- | Test cases are written with single quotes so the JSON stays readable.@@ -21,10 +21,19 @@ q = LBS.map (\byte -> if byte == 39 then 34 else byte) -- | @evaluates rule input expected@+-- | The reference's own reading of a rule: lenient arity, and an operator+-- nobody supplied fails only if it is reached.+reference :: Config+reference = defaultConfig{arityMode = Lenient}++-- | Strict arity, but an unknown operator fails only when reached.+lazyUnknown :: Config+lazyUnknown = defaultConfig{unknownOperators = FailWhenReached}+ evaluates :: LBS.ByteString -> LBS.ByteString -> LBS.ByteString -> Expectation evaluates rule input expected = case (decode (q rule), decode (q input), decode (q expected)) of- (Just r, Just i, Just e) -> apply r i `shouldBe` Right e+ (Just r, Just i, Just e) -> applyWithConfig reference noOperators r i `shouldBe` Right e _ -> expectationFailure "test case contains invalid JSON" -- | (rule, data, expected result). Every one of these is behaviour of the@@ -162,7 +171,7 @@ nested n = foldr (\_ inner -> object ["!" .= inner]) (Number 0) [1 .. n] doubling :: Operators-doubling = either (error . show) id (operatorsFromList [(OperatorName "double", implementation)])+doubling = either (error . show) id (operatorsFromList [(OperatorName "double", pureOperator (Exactly 1) implementation)]) where implementation _ [Number n] = Right (Number (n * 2)) implementation _ _ = Left "expected one number"@@ -183,13 +192,13 @@ ] -- | A node built by hand, at the root (the laws do not look at locations).-node :: RuleF Rule -> Rule+node :: RuleF RuleTree -> RuleTree node = Fix . Node root -lit :: Value -> Rule+lit :: Value -> RuleTree lit = node . Lit -result :: Rule -> Either EvalError Value+result :: RuleTree -> Either EvalError Value result rule = either (Left . snd) Right (evaluate rule Null) spec :: Spec@@ -200,13 +209,13 @@ describe "errors" $ do it "reports an unknown operator, where it is" $ withJson "{'nope':[1]}" $ \rule ->- apply rule Null `shouldBe` Left (EvalFailure root (UnknownOperator (OperatorName "nope")))+ applyWithConfig lazyUnknown noOperators rule Null `shouldBe` Left (EvalFailure root (UnknownOperator (OperatorName "nope"))) it "evaluates arguments before the operator, so a bad one still fails" $ withJson "{'+':[1,{'nope':[]}]}" $ \rule ->- apply rule Null `shouldBe` Left (EvalFailure (at [Left "+", Right 1]) (UnknownOperator (OperatorName "nope")))+ applyWithConfig lazyUnknown noOperators rule Null `shouldBe` Left (EvalFailure (at [Left "+", Right 1]) (UnknownOperator (OperatorName "nope"))) it "locates a failure inside an iteration body" $ withJson "{'map':[[1],{'nope':[]}]}" $ \rule ->- apply rule Null `shouldBe` Left (EvalFailure (at [Left "map", Right 1]) (UnknownOperator (OperatorName "nope")))+ applyWithConfig lazyUnknown noOperators rule Null `shouldBe` Left (EvalFailure (at [Left "map", Right 1]) (UnknownOperator (OperatorName "nope"))) it "surfaces parse errors, with their location" $ withJson "{'!':{'==':[1]}}" $ \rule -> apply rule Null
test/LimitsSpec.hs view
@@ -16,6 +16,7 @@ import Gen (genData, genRule) import JsonLogic+import JsonLogic.Core.Utf16 (textIsInfixOf) import Support (Problem (..), isRight', json, problem) run' :: Config -> String -> Value -> Either Problem Value@@ -30,6 +31,10 @@ nestedMap :: Int -> Value nestedMap levels = foldr (\_ inner -> object ["map" .= [toJSON [1 .. 10 :: Int], inner]]) (object ["var" .= ("" :: String)]) [1 .. levels] +-- | Short strings over a small alphabet, so that matches and near-matches are common.+smallText :: Gen Data.Text.Text+smallText = Data.Text.pack <$> listOf (elements "aab\955\128512")+ spec :: Spec spec = describe "resource limits" $ do describe "steps" $ do@@ -99,7 +104,7 @@ `shouldBe` Left (ParseProblem (DepthExceeded 5)) it "holds a custom operator's result to the same depth" $ do let deep n = foldr (\_ inner -> toJSON [inner]) (toJSON (0 :: Int)) [1 .. n :: Int]- ops = either (error . show) id (operatorsFromList [(OperatorName "deep", \_ _ -> Right (deep 10))])+ ops = either (error . show) id (operatorsFromList [(OperatorName "deep", pureOperator (AtLeast 0) (\_ _ -> Right (deep 10)))]) call limit = problem (applyWithConfig defaultConfig{maxDepth = limit} ops (object ["deep" .= ([] :: [Int])]) Null) call 10 `shouldSatisfy` isRight' call 9 `shouldBe` Left (EvalProblem (LimitExceeded (ValueDepthLimit 9)))@@ -123,10 +128,21 @@ \{\"merge\":[{\"var\":\"accumulator\"},{\"var\":\"accumulator\"}]},[1,2]]}" r <- within10s (run' defaultConfig rule Null) r `shouldBe` Left (EvalProblem (LimitExceeded (ArrayLimit 100000)))+ it "a reduce that nests its accumulator in itself (shared, never copied)" $ do+ let rule =+ "{\"reduce\":[[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40],\+ \[{\"var\":\"accumulator\"},{\"var\":\"accumulator\"}],0]}"+ r <- within10s (run' defaultConfig rule Null)+ r `shouldSatisfy` isStepLimit it "a very wide rule" $ do+ -- within the node limit, so it is read and then stopped by the step limit+ let wide = object ["+" .= replicate 900000 (1 :: Int)]+ r <- within10s (problem (applyWithConfig defaultConfig{maxSteps = 500000} noOperators wide Null))+ r `shouldSatisfy` isStepLimit+ it "a rule wider than the node limit is refused before it is read" $ do let wide = object ["+" .= replicate 2000000 (1 :: Int)] r <- within10s (problem (applyWithConfig defaultConfig noOperators wide Null))- r `shouldSatisfy` isStepLimit+ r `shouldBe` Left (ParseProblem (NodeLimitExceeded 1000000)) it "a deeply nested datum is only read, never recursed into by the evaluator" $ do let deepData = foldr (\_ inner -> toJSON [inner]) Null [1 .. 20000 :: Int] r <- within10s (problem (applyWithConfig defaultConfig noOperators (object ["var" .= ("" :: String)]) deepData))@@ -146,6 +162,18 @@ rule = object ["+" .= replicate 2000 (object ["==" .= [object ["var" .= ("x" :: String)], toJSON (1 :: Int)]])] r <- within10s (problem (applyWithConfig defaultConfig noOperators rule (object ["x" .= big]))) r `shouldSatisfy` isStepLimit++ describe "string search" $ do+ it "textIsInfixOf agrees with Data.Text.isInfixOf" $+ forAll smallText $ \needle -> forAll smallText $ \haystack ->+ textIsInfixOf needle haystack === Data.Text.isInfixOf needle haystack+ it "a long needle that almost matches everywhere is searched in linear time" $ do+ let n = 400000+ needle = Data.Text.replicate n "a" <> "b" <> Data.Text.replicate n "a"+ rule = object ["in" .= [String needle, object ["var" .= ("h" :: String)]]]+ dat = object ["h" .= Data.Text.replicate (4 * n) "a"]+ r <- within10s (applyWithConfig defaultConfig noOperators rule dat)+ r `shouldBe` Right (Bool False) describe "properties" $ do it "evaluation always terminates, within a constant factor of the budget" $
test/LocationSpec.hs view
@@ -41,7 +41,7 @@ ParseFailure _ (ArityMismatch name _ _) -> Just name EvalFailure _ (UnknownOperator name) -> Just name EvalFailure _ (CustomOperatorFailed name _) -> Just name- EvalFailure _ (InvalidOperand name) -> Just name+ EvalFailure _ (InvalidOperand name _) -> Just name _ -> Nothing modes :: [Config]@@ -60,10 +60,10 @@ Left e | Just name <- operatorOf e -> counterexample (show e) (operatorAt (errorLocation e) rule === Just name) _ -> property True it "follow bare operands, which have no index" $- apply (json "{\"!\":{\"!\":{\"nope\":1}}}") Null+ applyWithConfig defaultConfig{unknownOperators = FailWhenReached} noOperators (json "{\"!\":{\"!\":{\"nope\":1}}}") Null `shouldBe` Left (EvalFailure (at [Left "!", Left "!"]) (UnknownOperator (OperatorName "nope"))) it "point into literals' own arrays" $- apply (json "{\"merge\":[[{\"nope\":[]}]]}") Null+ applyWithConfig defaultConfig{unknownOperators = FailWhenReached} noOperators (json "{\"merge\":[[{\"nope\":[]}]]}") Null `shouldBe` Left (EvalFailure (at [Left "merge", Right 0, Right 0]) (UnknownOperator (OperatorName "nope"))) it "put an operand the rule leaves out at the operator call, which exists" $ -- five steps: the and, its true, the ==, its 1, and the undefined that
test/NumberSpec.hs view
@@ -15,6 +15,7 @@ import Test.QuickCheck hiding ((.&.)) import JsonLogic.Core.Number+import Oracle (shortestDigits, shortestDigitsExact) -- | Any positive finite double, from its bit pattern. genAnyDouble :: Gen Double
+ test/Oracle.hs view
@@ -0,0 +1,167 @@+-- |+-- Module : Oracle+--+-- Slow, simple or test-only definitions that the tests hold the library to.+-- They used to live in the library, where nothing but the tests used them.+module Oracle+ ( -- * Numbers+ shortestDigits+ , shortestDigitsExact++ -- * UTF-16+ , utf16Units+ , fromUtf16Units+ , sliceOracle+ , charAtOracle++ -- * Rules+ , Term+ , stripLocations+ , parseRule+ , evaluate+ ) where++import Data.Aeson (Value)+import Data.Bits (shiftL, shiftR, (.&.), (.|.))+import Data.Char (chr, digitToInt, ord)+import Data.Fix (Fix (..), foldFix)+import Data.List (dropWhileEnd, sortOn)+import Data.Maybe (fromMaybe, listToMaybe, mapMaybe)+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word16)+import Numeric (floatToDigits)++import JsonLogic.Core.Config (defaultConfig)+import JsonLogic.Core.Custom (noOperators)+import JsonLogic.Core.Errors (EvalError, ParseError)+import JsonLogic.Core.Eval (compileRule, runProgram)+import JsonLogic.Core.Location (Location)+import JsonLogic.Core.Number (shortestDecimal)+import JsonLogic.Core.Parse (parseRuleWith)+import JsonLogic.Core.Rule (Node (..), RuleF, RuleTree)++twoTo53 :: Double+twoTo53 = 9007199254740992++-- ---------------------------------------------------------------------+-- Numbers+-- ---------------------------------------------------------------------++-- | The digits ECMAScript prints for a positive finite double, as+-- @(digits, pointPosition)@ in the convention of 'floatToDigits': the value+-- is @0.d1d2...dn * 10^pointPosition@.+shortestDigits :: Double -> ([Int], Int)+shortestDigits d = (map digitToInt digits, length digits + exponent10)+ where+ (coefficientDigits, exponent10) = shortestDecimal d+ digits = show coefficientDigits++-- | 'shortestDigits' computed exactly, for every positive finite double.+--+-- GHC's 'floatToDigits' only accepts digit strings strictly inside the+-- rounding interval of the double. ECMAScript also accepts the exact+-- halfway point when the double's significand is even, because+-- round-half-even reads it back to the same double. For doubles of 2^53 and+-- above those points are whole numbers, so a shorter string can exist where+-- GHC needs one more digit: @2.2531e21@, not @2.2531000000000001e21@. Below+-- 2^53 the halfway points have too many digits to matter, so GHC's answer+-- stands, except that when two candidates of the shortest length are equally+-- close (@9007199254740993 / 10@ is halfway between @...099.2@ and @...099.3@)+-- ECMAScript takes the even one, and 'floatToDigits' does not.+shortestDigitsExact :: Double -> ([Int], Int)+shortestDigitsExact d+ | d < twoTo53 =+ -- A tie between two equally short candidates needs 16 or more digits:+ -- below that, decimal spacing is wider than the spacing of doubles.+ if length digits >= 16 then fromMaybe generated (shorter (length digits)) else generated+ | otherwise = fromMaybe generated (listToMaybe (mapMaybe shorter [1 .. length digits]))+ where+ generated@(digits, pointPosition) = floatToDigits 10 d+ exact = toRational d+ shorter k =+ case sortOn rank (filter readsBack [lower, upper]) of+ best : _ -> Just (digitsOf best k)+ [] -> Nothing+ where+ scale = 10 ^^ (pointPosition - k) :: Rational+ scaled = exact / scale+ lower = floor scaled :: Integer+ upper = ceiling scaled :: Integer+ readsBack m = fromRational (fromInteger m * scale) == d+ rank m = (abs (fromInteger m * scale - exact), odd m)+ digitsOf m k = (map digitToInt (dropWhileEnd (== '0') text), pointPosition + length text - k)+ where+ text = show m++-- ---------------------------------------------------------------------+-- UTF-16, as lists of code units+-- ---------------------------------------------------------------------++-- | The UTF-16 code units of a text.+utf16Units :: Text -> [Word16]+utf16Units = concatMap charUnits . Text.unpack++charUnits :: Char -> [Word16]+charUnits c+ | n <= 0xFFFF = [fromIntegral n]+ | otherwise =+ let m = n - 0x10000+ in [ fromIntegral (0xD800 .|. (m `shiftR` 10))+ , fromIntegral (0xDC00 .|. (m .&. 0x3FF))+ ]+ where+ n = ord c++-- | Rebuild a text from UTF-16 code units. A surrogate with no partner+-- becomes U+FFFD.+fromUtf16Units :: [Word16] -> Text+fromUtf16Units = Text.pack . go+ where+ go [] = []+ go (hi : lo : rest)+ | isHigh hi && isLow lo = pair hi lo : go rest+ go (u : rest)+ | isHigh u || isLow u = '\xFFFD' : go rest+ | otherwise = chr (fromIntegral u) : go rest+ isHigh u = u >= 0xD800 && u <= 0xDBFF+ isLow u = u >= 0xDC00 && u <= 0xDFFF+ pair hi lo =+ chr+ ( 0x10000+ + ((fromIntegral hi - 0xD800) `shiftL` 10)+ + (fromIntegral lo - 0xDC00)+ )++-- | The slice the library computes, by way of a list of code units.+sliceOracle :: Int -> Int -> Text -> Text+sliceOracle from count text+ | count <= 0 = Text.empty+ | otherwise = fromUtf16Units (take count (drop from (utf16Units text)))++-- | The code unit at an index, by way of a list of code units.+charAtOracle :: Int -> Text -> Maybe Text+charAtOracle i text+ | i < 0 = Nothing+ | otherwise = case drop i (utf16Units text) of+ [] -> Nothing+ unit : _ -> Just (fromUtf16Units [unit])++-- ---------------------------------------------------------------------+-- Rules+-- ---------------------------------------------------------------------++-- | A rule tree without locations, for comparing shapes.+type Term = Fix RuleF++-- | Forget where every node came from.+stripLocations :: RuleTree -> Term+stripLocations = foldFix (Fix . nodeRule)++-- | Read a rule with 'defaultConfig'.+parseRule :: Value -> Either (Location, ParseError) RuleTree+parseRule = parseRuleWith defaultConfig++-- | Compile and run with 'defaultConfig' and no custom operators.+evaluate :: RuleTree -> Value -> Either (Location, EvalError) Value+evaluate = runProgram . compileRule defaultConfig noOperators
test/ParseSpec.hs view
@@ -15,9 +15,10 @@ import JsonLogic.Core.Config (ArityMode (..), Config (..), defaultConfig) import JsonLogic.Core.Errors (Arity (..), ParseError (..)) import JsonLogic.Core.Location (Location, root)-import JsonLogic.Core.Operator (OperatorName (..), allBuiltins, builtinName, lookupBuiltin)-import JsonLogic.Core.Parse (parseRule, parseRuleWith)-import JsonLogic.Core.Rule (Node (..), Rule, RuleF (..), Term, stripLocations)+import JsonLogic.Core.Operator (Builtin (..), OperatorName (..), allBuiltins, builtinName, lookupBuiltin)+import JsonLogic.Core.Parse (parseRuleWith)+import JsonLogic.Core.Rule (Node (..), RuleF (..), RuleTree)+import Oracle (Term, parseRule, stripLocations) import Support (at, json) lit :: Value -> Term@@ -38,13 +39,13 @@ lenientShape = either (Left . snd) (Right . stripLocations) . parseRuleWith defaultConfig{arityMode = Lenient} -- | The location of every node, outermost first.-locations :: Rule -> [Location]+locations :: RuleTree -> [Location] locations = foldFix (\(Node location node) -> location : concat node) parsedLocations :: Value -> [Location] parsedLocations = either (const []) locations . parseRule -withDepth :: Int -> Value -> Either (Location, ParseError) Rule+withDepth :: Int -> Value -> Either (Location, ParseError) RuleTree withDepth limit = parseRuleWith defaultConfig{maxDepth = limit} spec :: Spec@@ -96,7 +97,7 @@ `shouldBe` Right (Fix (Reduce (lit (String "xs")) (lit (int 2)) (lit Null))) it "keeps surplus operands of an ordinary operator to be evaluated" $ lenientShape (object ["!" .= [int 1, int 2]])- `shouldBe` Right (Fix (Discard (Fix (Not (lit (int 1)))) [lit (int 2)]))+ `shouldBe` Right (Fix (Applied BNot [lit (int 1)] [lit (int 2)])) it "drops surplus operands of map, which the reference never looks at" $ lenientShape (object ["map" .= [int 1, int 2, int 3]]) `shouldBe` Right (Fix (Map (lit (int 1)) (lit (int 2))))
+ test/RegressionSpec.hs view
@@ -0,0 +1,196 @@+{-# LANGUAGE OverloadedStrings #-}++-- | Behaviour that a forensic review found missing, pinned so it stays+-- fixed: limits that wrap round at 'maxBound', work that the step budget did+-- not see, a rule size that was not bounded, a quadratic number reader, and+-- the contract of the exception and deepseq instances.+module RegressionSpec (spec) where++import Control.DeepSeq (force)+import Control.Exception (Exception, evaluate, fromException, throw, throwIO, try)+import Data.Aeson (Value (..), encode, object, toJSON, (.=))+import qualified Data.Aeson.Key as Key+import qualified Data.ByteString.Lazy.Char8 as Char8+import Data.Either (fromRight)+import Data.Scientific (Scientific, scientific)+import Data.Text (Text)+import qualified Data.Text as Text+import System.Timeout (timeout)+import Test.Hspec+import Test.QuickCheck++import Gen (genData, genRule, genText)+import JsonLogic hiding (force)+import JsonLogic.Core.Number (scientificToDouble)+import JsonLogic.Core.Utf16 (compareUtf16, utf16CharAt, utf16Slice)+import Oracle (charAtOracle, sliceOracle, utf16Units)+import Support (Problem (..), json, problem)++call :: Text -> [Value] -> Value+call operator operands = object [Key.fromText operator .= operands]++variable :: Text -> Value+variable path = object ["var" .= path]++-- | Force the answer; fail the test if it takes more than the given seconds.+withinSeconds :: Int -> Either e Value -> IO (Either e Value)+withinSeconds seconds result = do+ outcome <- timeout (seconds * 1000000) (evaluate (Char8.length (encode (fromRight Null result)) `seq` result))+ maybe (expectationFailure ("did not finish in " ++ show seconds ++ " seconds") >> pure result) pure outcome++-- | A registry of custom operators. The names used here are all valid; if+-- one were not, the registry is empty and the test that uses it fails on an+-- unknown operator.+registry :: [(Text, Value -> [Value] -> Either CustomError Value)] -> Operators+registry entries =+ fromRight noOperators (operatorsFromList [(OperatorName name, pureOperator (AtLeast 0) implementation) | (name, implementation) <- entries])++-- | Compile a rule and hand it to the test, which fails if it does not compile.+-- | What a custom operator throws in the tests below.+data Boom = Boom+ deriving (Eq, Show)++instance Exception Boom++withRule :: Operators -> Value -> (Rule -> IO ()) -> IO ()+withRule operators rule test = case compile defaultConfig operators rule of+ Left e -> expectationFailure ("did not compile: " ++ Text.unpack (renderError e))+ Right ready -> test ready++-- | Hand the test the error of an application, which fails if it succeeded.+withFailure :: Either Error Value -> (Error -> IO ()) -> IO ()+withFailure result test = either test (const (expectationFailure "expected a failure")) result++isStepLimit :: Either Problem Value -> Bool+isStepLimit (Left (EvalProblem (LimitExceeded (StepLimit _)))) = True+isStepLimit _ = False++spec :: Spec+spec = describe "regressions" $ do+ describe "a limit of maxBound means no limit" $ do+ let dat = json "{\"a\":1,\"s\":\"hello\",\"xs\":[1,2]}"+ rules =+ [ ("var", variable "a", Number 1)+ , ("var into a string", variable "s.length", Number 5)+ , ("arithmetic on a var", call "+" [variable "a", Number 1], Number 2)+ , ("missing", call "missing" ["a"], toJSON ([] :: [Int]))+ , ("map", call "map" [variable "xs", call "+" [variable "", Number 1]], toJSON [2, 3 :: Int])+ , ("a string used as a number", call "+" ["12"], Number 12)+ , ("an array converted to a string", call "cat" [variable "xs"], String "1,2")+ ]+ mapM_+ ( \(name, rule, expected) ->+ it name $ do+ problem (applyWithConfig defaultConfig{maxSteps = maxBound} noOperators rule dat) `shouldBe` Right expected+ problem (applyWithConfig defaultConfig{maxSteps = maxBound - 1} noOperators rule dat) `shouldBe` Right expected+ )+ rules+ it "gives the answer a large finite limit gives, for any rule" $+ forAll (genRule 5) $ \rule -> forAll (genData 3) $ \dat' ->+ let withoutLimit = applyWithConfig defaultConfig{maxSteps = maxBound, arityMode = Lenient} noOperators rule dat'+ large = applyWithConfig defaultConfig{maxSteps = 100000000, arityMode = Lenient} noOperators rule dat'+ in withoutLimit === large+ it "holds for the other limits too" $ do+ let config = defaultConfig{maxStringLength = maxBound, maxArrayLength = maxBound, maxDepth = maxBound, maxNodes = maxBound}+ problem (applyWithConfig config noOperators (call "cat" ["a", "b"]) Null) `shouldBe` Right (String "ab")++ describe "the size of the rule" $ do+ -- [1,2] is three nodes: the array and its two elements+ it "is held to maxNodes, exactly" $ do+ let rule = json "[1,2]"+ problem (applyWithConfig defaultConfig{maxNodes = 3} noOperators rule Null) `shouldBe` Right (toJSON [1, 2 :: Int])+ problem (applyWithConfig defaultConfig{maxNodes = 2} noOperators rule Null) `shouldBe` Left (ParseProblem (NodeLimitExceeded 2))+ it "refuses a huge rule before building any of it, at the root" $ do+ let wide = object ["+" .= replicate 1500000 (1 :: Int)]+ case compile defaultConfig noOperators wide of+ Left (ParseFailure location (NodeLimitExceeded 1000000)) -> renderLocation location `shouldBe` ""+ other -> expectationFailure ("expected NodeLimitExceeded, got " ++ either (Text.unpack . renderError) (const "a rule") other)++ describe "work on strings is paid for" $ do+ let big = String (Text.replicate 1000000 "a")+ dat = object ["big" .= big, "big2" .= big]+ repeated operator n = call "+" (replicate n operator)+ it "a comparison of long strings" $ do+ r <- withinSeconds 10 (problem (applyWithConfig defaultConfig noOperators (repeated (call "<" [variable "big", variable "big2"]) 1000) dat))+ r `shouldSatisfy` isStepLimit+ it "a substring of a long string" $ do+ r <- withinSeconds 10 (problem (applyWithConfig defaultConfig noOperators (repeated (call "substr" [variable "big", Number 0, Number 1]) 1000) dat))+ r `shouldSatisfy` isStepLimit+ it "a search of a long string" $ do+ r <- withinSeconds 10 (problem (applyWithConfig defaultConfig noOperators (repeated (call "in" ["b", variable "big"]) 1000) dat))+ r `shouldSatisfy` isStepLimit+ it "a long string read as a number" $ do+ let digits = String (Text.replicate 1000000 "7")+ r <- withinSeconds 10 (problem (applyWithConfig defaultConfig noOperators (repeated (call "+" [variable "digits"]) 1000) (object ["digits" .= digits])))+ r `shouldSatisfy` isStepLimit+ it "strict equality of long strings" $ do+ r <- withinSeconds 10 (problem (applyWithConfig defaultConfig noOperators (repeated (call "===" [variable "big", variable "big2"]) 1000) dat))+ r `shouldSatisfy` isStepLimit+ it "does not charge short strings anything extra" $+ problem (applyWithConfig defaultConfig{maxSteps = 8} noOperators (call "<" ["abc", "abd"]) Null) `shouldBe` Right (Bool True)+ it "still lets one use of a long string through" $ do+ r <- withinSeconds 10 (problem (applyWithConfig defaultConfig noOperators (call "<" [variable "big", variable "big2"]) dat))+ r `shouldBe` Right (Bool False)++ describe "UTF-16 strings" $ do+ it "slicing agrees with the list-of-code-units definition" $+ forAll genText $ \t -> forAll (choose (-2, 24)) $ \from -> forAll (choose (-2, 24)) $ \count ->+ utf16Slice from count t === sliceOracle from count t+ it "indexing agrees with the list-of-code-units definition" $+ forAll genText $ \t -> forAll (choose (-2, 24)) $ \i ->+ utf16CharAt i t === charAtOracle i t+ it "ordering agrees with comparing code-unit lists" $+ forAll genText $ \a -> forAll genText $ \b ->+ compareUtf16 a b === compare (utf16Units a) (utf16Units b)+ it "ordering is right when the strings share a long prefix and differ in a character's last byte" $ do+ compareUtf16 "\233" "\232" `shouldBe` GT+ compareUtf16 (Text.replicate 100 "a" <> "\x1F600") (Text.replicate 100 "a" <> "\xFFFF") `shouldBe` LT++ describe "numbers" $ do+ -- 77...7, built in linear time+ let digitsOf n = 7 * ((10 ^ n - 1) `div` 9) :: Integer+ decimal :: Int -> Int -> Scientific+ decimal digits = scientific (digitsOf digits)+ it "a long JSON number reads as the nearest double" $+ mapM_+ (\(digits, power) -> scientificToDouble (decimal digits power) `shouldBe` fromRational (toRational (decimal digits power)))+ [(30, -30), (400, -405), (800, -790), (2000, -2005), (5000, -4990), (3000, 100), (2000, -2400), (600, -1000)]+ it "a million-digit JSON number is read in linear time" $ do+ let number = decimal 1000000 (-1000000)+ outcome <- timeout 10000000 (evaluate (scientificToDouble number))+ outcome `shouldSatisfy` (/= Nothing)++ describe "evaluation as a value" $ do+ it "a custom operator is handed the root datum as it came" $ do+ let operators = registry [("echo", \datum _ -> Right datum)]+ dat' = json "{\"k\":[1,2,{\"z\":null}]}"+ applyWith operators (call "echo" []) dat' `shouldBe` Right dat'+ it "a custom operator inside map is handed the current element" $ do+ let operators = registry [("echo", \datum _ -> Right datum)]+ applyWith operators (call "map" [toJSON [1, 2 :: Int], call "echo" []]) Null `shouldBe` Right (toJSON [1, 2 :: Int])+ it "compile then run equals apply, and a compiled rule is already in normal form" $+ forAll (genRule 5) $ \rule -> forAll (genData 3) $ \dat' ->+ case compile defaultConfig noOperators rule of+ Left e -> apply rule dat' === Left e+ Right ready -> force ready `seq` (run ready dat' === apply rule dat')++ describe "exceptions and instances" $ do+ it "tryRun catches an exception thrown by a custom operator" $ do+ let operators = registry [("boom", \_ _ -> throw Boom)]+ withRule operators (call "boom" []) $ \ready -> do+ r <- tryRun ready Null+ case r of+ Left (OperatorThrew e) -> fromException e `shouldBe` Just Boom+ Left other -> expectationFailure ("unexpected failure: " <> show other)+ Right _ -> expectationFailure "the exception escaped tryRun's result"+ it "tryRun returns an ordinary answer unchanged" $ do+ withRule noOperators (call "+" [Number 1, Number 2]) $ \ready -> do+ r <- tryRun ready Null+ either (const Nothing) Just r `shouldBe` Just (Number 3)+ it "an Error can be thrown and caught" $ do+ withFailure (apply (call "nope" []) Null) $ \e -> do+ r <- try (throwIO e) :: IO (Either Error ())+ r `shouldBe` Left e+ it "an Error can be forced" $ do+ withFailure (apply (call "nope" []) Null) $ \e ->+ force e `shouldBe` e
test/Spec.hs view
@@ -3,12 +3,14 @@ import Test.Hspec (hspec) import qualified AnalysisSpec+import qualified AuditSpec import qualified CompatSpec import qualified EvalSpec import qualified LimitsSpec import qualified LocationSpec import qualified NumberSpec import qualified ParseSpec+import qualified RegressionSpec import qualified ValueSpec main :: IO ()@@ -21,3 +23,5 @@ LimitsSpec.spec LocationSpec.spec AnalysisSpec.spec+ RegressionSpec.spec+ AuditSpec.spec
test/community/expected.json view
@@ -18,9 +18,9 @@ "comparison/softNotEquals.json": {"cases":34,"lenient":23,"strict":25}, "comparison/strictEquals.json": {"cases":31,"lenient":26,"strict":28}, "comparison/strictNotEquals.json": {"cases":30,"lenient":26,"strict":28},- "control/and.json": {"cases":25,"lenient":23,"strict":23},- "control/if.json": {"cases":44,"lenient":42,"strict":42},- "control/or.json": {"cases":24,"lenient":22,"strict":22},+ "control/and.json": {"cases":25,"lenient":23,"strict":20},+ "control/if.json": {"cases":44,"lenient":42,"strict":38},+ "control/or.json": {"cases":24,"lenient":22,"strict":19}, "control/not.json": {"cases":23,"lenient":23,"strict":22}, "control/doublebang.json": {"cases":23,"lenient":23,"strict":22}, "string/in.json": {"cases":8,"lenient":8,"strict":8},
tutorial/Tutorial.hs view
@@ -19,8 +19,9 @@ json = fromMaybe Null . decode . Char8.pack startsWith :: CustomOperator-startsWith _ [String prefix, String s] = Right (Bool (prefix `Text.isPrefixOf` s))-startsWith _ _ = Left "starts_with takes two strings"+startsWith = pureOperator (Exactly 2) $ \_ arguments -> case arguments of+ [String prefix, String s] -> Right (Bool (prefix `Text.isPrefixOf` s))+ _ -> Left "starts_with takes two strings" operators :: Either OperatorsError Operators operators = operatorsFromList [(OperatorName "starts_with", startsWith)]@@ -54,11 +55,19 @@ ((\rule -> map (run rule) [json "{\"price\": 10}", json "{\"price\": 2.5}"]) <$> compile defaultConfig noOperators (json "{\"*\": [{\"var\": \"price\"}, 1.2]}")) , check "4 location"- (Left (EvalFailure (fromSegments [Key "if", Index 1]) (UnknownOperator (OperatorName "nope"))))+ (Left (ParseFailure (fromSegments [Key "if", Index 1]) (UnknownOperatorName (OperatorName "nope") [OperatorName "none"]))) (apply (json "{\"if\": [true, {\"nope\": [1]}]}") Null)- , check "4 render" ("at /if/1: unknown operator \"nope\"" :: Text) (either renderError (const "") (apply (json "{\"if\": [true, {\"nope\": [1]}]}") Null))+ , check+ "4 suggestion"+ (Left (ParseFailure (fromSegments []) (UnknownOperatorName (OperatorName "missing_sone") [OperatorName "missing_some"])))+ (apply (json "{\"missing_sone\": [1, [\"a\"]]}") Null)+ , check+ "4 validate"+ [fromSegments [Key "and", Index 0], fromSegments [Key "and", Index 1]]+ (map errorLocation (validate defaultConfig noOperators (json "{\"and\": [{\"nope\": []}, {\"mox\": []}]}")))+ , check "4 render" ("at /if/1: unknown operator \"nope\"; did you mean \"none\"?" :: Text) (either renderError (const "") (apply (json "{\"if\": [true, {\"nope\": [1]}]}") Null)) , check "4 describe" "rule error at \"\": \"==\" given 1" (describe (apply (json "{\"==\": [1]}") Null))- , check "4 lazy" (Right (Bool True)) (apply (json "{\"or\": [true, {\"nope\": []}]}") Null)+ , check "4 lazy" (Right (Bool True)) (applyWithConfig defaultConfig{unknownOperators = FailWhenReached} noOperators (json "{\"or\": [true, {\"nope\": []}]}") Null) , check "5 strict" (Left (ParseFailure (fromSegments []) (ArityMismatch (OperatorName "==") (Exactly 2) 1)))@@ -80,7 +89,7 @@ , check "7 custom failure" (Right (Left (EvalFailure (fromSegments []) (CustomOperatorFailed (OperatorName "starts_with") "starts_with takes two strings"))))- ((\ops -> applyWith ops (json "{\"starts_with\": [1]}") Null) <$> operators)+ ((\ops -> applyWith ops (json "{\"starts_with\": [1, 2]}") Null) <$> operators) , check "8 dataUse" (Right (DataUse ["orders", "user.age"] False))