-- SPDX-FileCopyrightText: Copyright (c) 2025 Objectionary.com-- SPDX-License-Identifier: MIT-- This module provides commonly used helper functions for other modulesmodule Misc ( toDouble , fqnToAttrs , attributesFromBindings , attributesFromBindings' , attributeFromBinding , uniqueBindings , uniqueBindings' , orThrow )whereimport ASTimport Control.Exceptionimport Data.Functor ((<&>))import Data.List (intercalate)import Data.Maybe (catMaybes)import qualified Data.Set as Setimport Text.Printf (printf)-- Unwrap a pure 'Either String' in IO, throwing the built exception on 'Left'orThrow :: (Exception e) => (String -> e) -> Either String a -> IO aorThrow _ (Right value) = pure valueorThrow asException (Left err) = throwIO (asException err)-- Extract attribute from bindingattributeFromBinding :: Binding -> Maybe AttributeattributeFromBinding (BiTau attr _) = Just attrattributeFromBinding (BiVoid attr) = Just attrattributeFromBinding (BiDelta _) = Just AtDeltaattributeFromBinding (BiLambda _) = Just AtLambdaattributeFromBinding (BiMeta _) = NothingattributeFromBinding (BiAny _) = Nothing-- Extract attributes from bindingsattributesFromBindings :: [Binding] -> [Attribute]attributesFromBindings [] = []attributesFromBindings bds = catMaybes (attributesFromBindings' bds)attributesFromBindings' :: [Binding] -> [Maybe Attribute]attributesFromBindings' = map attributeFromBindinguniqueBindings' :: [Binding] -> IO [Binding]uniqueBindings' bds = case uniqueBindings bds of Left msg -> throwIO (userError msg) Right _ -> pure bds-- Check if given binding list consists of unique attributesuniqueBindings :: [Binding] -> Either String [Binding]uniqueBindings bds = case duplicated bds Set.empty of Just attr -> Left ( printf "Duplicated attribute '%s' found in %s" (show attr) (intercalate ", " (map show (attributesFromBindings bds))) ) _ -> Right bds where duplicated :: [Binding] -> Set.Set Attribute -> Maybe Attribute duplicated [] _ = Nothing duplicated (bd : rest) seen = case attributeFromBinding bd of Just attr | attr `Set.member` seen -> Just attr | otherwise -> duplicated rest (Set.insert attr seen) Nothing -> duplicated rest seen-- Transform dispatch to list of attributes-- >>> fqnToAttrs (ExDispatch (ExDispatch (ExDispatch ExRoot (AtLabel "org")) (AtLabel "eolang")) (AtLabel "number"))-- Just [org,eolang,number]-- >>> fqnToAttrs (ExFormation [])-- Nothing-- >>> fqnToAttrs ExRoot-- Just []fqnToAttrs :: Expression -> Maybe [Attribute]fqnToAttrs expr = go expr <&> reverse where go :: Expression -> Maybe [Attribute] go ExRoot = Just [] go (ExDispatch ex at) = go ex <&> (:) at go _ = Nothing-- >>> toDouble 5-- 5.0toDouble :: Int -> DoubletoDouble = fromIntegral