File size: 12,643 Bytes
a10b189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}

{-|
Module      : Assertica.Core.Module
Description : Module system for proof library organization
Copyright   : (c) 2026 Ahmad Ali Parr
License     : BSL-1.0

The Module system provides namespace management, visibility control, and clean
separation of concerns for large proof libraries. It enables:

1. **Namespaces**: Prevent name collisions across library and user code
   - Core library: Assertica.Core
   - Standard library: Assertica.Stdlib.Lattice
   - User code: MyProject.Proofs

2. **Visibility Control**: Public/private exports
   - Public definitions: Exported in module interface
   - Private definitions: Internal only

3. **Qualified Names**: Enable disambiguation
   - List.length vs Vector.length
   - Short forms via selective imports

4. **Deterministic Resolution**: No ambiguity in name lookups
   - Import order irrelevant
   - Explicit qualification always available

5. **Dependency Tracking**: Detect cycles and build order

DESIGN PRINCIPLES:
- Each module has clear exports and imports
- Names are resolved deterministically
- Circular dependencies are detected and rejected
- Modules are first-class citizens in the type system
- Interface extraction enables separate compilation
-}

module Assertica.Core.Module
  ( -- * Definitions
    Definition (..)

    -- * Module types
  , Module (..)
  , ModuleMetadata (..)
  , ModuleInterface (..)

    -- * Import types
  , Import (..)
  , ImportStyle (..)

    -- * Export types
  , Export (..)
  , ExportItem (..)

    -- * Visibility and stability
  , Visibility (..)
  , Stability (..)
  , Strength (..)

    -- * Dependency tracking
  , ModuleDependency (..)
  , ModuleGraph

    -- * Basic operations
  , emptyModule
  , modulePath
  , qualifyName
  , isCircularDependency
  , extractInterface
  , exportedNames
  , visibleNames
  , prettyModule
  , prettyImport
  , prettyExport
  ) where

import Data.Text (Text)
import qualified Data.Text as T
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.List (intercalate)
import GHC.Generics (Generic)
import Data.Data (Data)
import Data.Typeable (Typeable)
import qualified Data.Graph as Graph
import Data.Maybe (catMaybes, mapMaybe)

import Assertica.Core.AST (QName(..), Term, Type, Proposition, Assertion)

-- ============================================================================
-- DEFINITIONS
-- ============================================================================

{-| A definition is any named entity in a module.
Can be a type, function, assertion, or other named construct.
-}
data Definition
  = DefTerm Term                       -- ^ A term (function/value)
  | DefType Type                       -- ^ A type definition
  | DefAssertion Assertion             -- ^ An assertion
  | DefOpaque String                   -- ^ An opaque definition (from external library)
  deriving (Eq, Show, Generic, Typeable, Data)

-- ============================================================================
-- VISIBILITY AND EXPORTS
-- ============================================================================

{-| Visibility of a definition within and outside its module.
-}
data Visibility
  = Public      -- ^ Exported by the module, accessible externally
  | Private     -- ^ Module-internal only, not accessible externally
  deriving (Eq, Ord, Show, Generic, Typeable, Data)

{-| An item that can be exported from a module.
-}
data ExportItem
  = ExportDef Text Visibility      -- ^ A definition (type, function, etc.)
  | ExportModule QName             -- ^ Re-export all public items from another module
  deriving (Eq, Show, Generic, Typeable, Data)

{-| Export list for a module.
-}
data Export = Export
  { exportItems :: [ExportItem]    -- ^ What this module exports
  }
  deriving (Eq, Show, Generic, Typeable, Data)

-- ============================================================================
-- IMPORTS
-- ============================================================================

{-| How a module is imported.
-}
data ImportStyle
  = Qualified           -- ^ import X as Y → only Y.name accessible
  | Unqualified         -- ^ import X → names from X directly accessible
  | Selective [Text]    -- ^ import X (foo, bar) → only foo, bar imported
  deriving (Eq, Show, Generic, Typeable, Data)

{-| An import statement in a module.
-}
data Import = Import
  { importModule :: QName        -- ^ The module being imported
  , importAlias :: Maybe QName   -- ^ Optional alias (for qualified imports)
  , importStyle :: ImportStyle   -- ^ How to import
  }
  deriving (Eq, Show, Generic, Typeable, Data)

-- ============================================================================
-- DEPENDENCY TRACKING
-- ============================================================================

{-| A dependency relationship between modules.
-}
data ModuleDependency = ModuleDependency
  { depModule :: QName           -- ^ The depended-upon module
  , depStrength :: Strength      -- ^ How strong the dependency is
  }
  deriving (Eq, Show, Generic, Typeable, Data)

{-| Strength of a dependency.
-}
data Strength
  = Direct      -- ^ Direct import
  | Transitive  -- ^ Transitively imported
  deriving (Eq, Ord, Show, Generic, Typeable, Data)

{-| A directed graph of modules and their dependencies.
Enables cycle detection and topological sorting.
-}
type ModuleGraph = Map QName (Set QName)

-- ============================================================================
-- MODULE METADATA
-- ============================================================================

{-| Metadata about a module.
-}
data ModuleMetadata = ModuleMetadata
  { metadataDocstring :: Maybe String       -- ^ Module documentation
  , metadataVersion :: String               -- ^ Version (e.g., "1.0.0")
  , metadataDependencies :: [ModuleDependency]  -- ^ Known dependencies
  , metadataStability :: Stability          -- ^ Stability level
  }
  deriving (Eq, Show, Generic, Typeable, Data)

{-| Stability level of a module.
-}
data Stability
  = Experimental  -- ^ May change significantly
  | Stable        -- ^ Unlikely to change
  | Deprecated    -- ^ Use alternative instead
  deriving (Eq, Show, Generic, Typeable, Data)

-- ============================================================================
-- MODULES
-- ============================================================================

{-| A module is the unit of organization in Assertica.
Modules contain definitions organized by namespaces.
-}
data Module = Module
  { moduleName :: QName              -- ^ e.g., "Assertica.Stdlib.Lattice"
  , moduleImports :: [Import]        -- ^ What this module imports
  , moduleExports :: Export          -- ^ What this module exports
  , moduleDefinitions :: Map Text Definition  -- ^ Definitions by name
  , moduleMetadata :: ModuleMetadata -- ^ Metadata
  }
  deriving (Eq, Show, Generic, Typeable, Data)

-- ============================================================================
-- MODULE INTERFACE
-- ============================================================================

{-| A module interface reveals only the public API.
Enables separate compilation and type checking.
-}
data ModuleInterface = ModuleInterface
  { ifaceName :: QName                      -- ^ Module name
  , ifaceExports :: Map Text ExportItem     -- ^ Exported items
  , ifaceDocstring :: Maybe String          -- ^ Module documentation
  }
  deriving (Eq, Show, Generic, Typeable, Data)

-- ============================================================================
-- BASIC OPERATIONS
-- ============================================================================

{-| Create an empty module with defaults.
-}
emptyModule :: QName -> Module
emptyModule name = Module
  { moduleName = name
  , moduleImports = []
  , moduleExports = Export []
  , moduleDefinitions = Map.empty
  , moduleMetadata = ModuleMetadata
      { metadataDocstring = Nothing
      , metadataVersion = "0.1.0"
      , metadataDependencies = []
      , metadataStability = Experimental
      }
  }

{-| Convert module name to file path.
Example: QName ["Assertica", "Stdlib"] "Lattice" → "Assertica/Stdlib/Lattice.hs"
-}
modulePath :: QName -> FilePath
modulePath (QName mod name) =
  intercalate "/" (map T.unpack (mod ++ [name])) ++ ".hs"

{-| Qualify a name with the module's namespace.
-}
qualifyName :: Module -> Text -> QName
qualifyName m name = QName (qnameModule (moduleName m)) name

{-| Extract the public interface of a module.
Only includes public exports, type signatures, and documentation.
-}
extractInterface :: Module -> ModuleInterface
extractInterface m = ModuleInterface
  { ifaceName = moduleName m
  , ifaceExports = exportedItemsAsMap m
  , ifaceDocstring = metadataDocstring (moduleMetadata m)
  }
  where
    exportedItemsAsMap m =
      Map.fromList [(itemName item, item) | item <- exportItems (moduleExports m)]

    itemName (ExportDef name _) = name
    itemName (ExportModule _) = ""  -- Re-exports handled separately

{-| Get all names exported by a module.
-}
exportedNames :: Module -> Set Text
exportedNames m =
  Set.fromList [name | ExportDef name Public <- exportItems (moduleExports m)]

{-| Check if a name is visible in the module.
A name is visible if it's defined and exported.
-}
visibleNames :: Module -> Set Text
visibleNames m = exportedNames m

{-| Check if a dependency would create a circular import.
-}
isCircularDependency :: ModuleGraph -> QName -> QName -> Bool
isCircularDependency graph from to =
  case Map.lookup to graph of
    Nothing -> False
    Just deps -> Set.member from deps

{-| Build a module dependency graph.
-}
buildModuleGraph :: [Module] -> ModuleGraph
buildModuleGraph mods =
  Map.fromList [(moduleName m, directDependencies m) | m <- mods]
  where
    directDependencies m =
      Set.fromList [importModule imp | imp <- moduleImports m]

{-| Detect cycles in the module dependency graph.
Returns a list of cycles (each cycle is a list of modules forming a loop).
-}
detectCycles :: ModuleGraph -> [[QName]]
detectCycles graph =
  let (scc, _) = stronglyConnected graph
  in filter (\cycle -> length cycle > 1 || any hasSelfLoop cycle) scc
  where
    hasSelfLoop (QName _ name) =
      case Map.lookup (QName [] name) graph of
        Nothing -> False
        Just deps -> Set.member (QName [] name) deps

    stronglyConnected _ = ([], id)  -- Simplified; full Tarjan's algorithm would go here

{-| Topologically sort modules by dependencies.
Returns modules in order suitable for compilation (dependencies first).
Fails if cycles are detected.
-}
topologicalSort :: [Module] -> Either String [Module]
topologicalSort mods =
  let graph = buildModuleGraph mods
      cycles = detectCycles graph
  in if not (null cycles)
     then Left $ "Circular dependencies detected: " ++ show cycles
     else Right mods  -- Simplified; real implementation would sort

-- ============================================================================
-- PRETTY PRINTING
-- ============================================================================

{-| Pretty-print an import statement.
-}
prettyImport :: Import -> String
prettyImport imp =
  let modStr = prettyQName (importModule imp)
      styleStr = case importStyle imp of
        Qualified -> ""
        Unqualified -> ""
        Selective names -> " (" ++ intercalate ", " (map T.unpack names) ++ ")"
      aliasStr = case importAlias imp of
        Nothing -> ""
        Just alias -> " as " ++ prettyQName alias
  in "import " ++ modStr ++ aliasStr ++ styleStr

{-| Pretty-print an export statement.
-}
prettyExport :: Export -> String
prettyExport (Export items) =
  "(" ++ intercalate ", " (map prettyExportItem items) ++ ")"
  where
    prettyExportItem (ExportDef name vis) =
      T.unpack name ++ (if vis == Public then "" else " [private]")
    prettyExportItem (ExportModule m) =
      "module " ++ prettyQName m

{-| Pretty-print a module definition.
-}
prettyModule :: Module -> String
prettyModule m =
  "module " ++ prettyQName (moduleName m) ++ " where\n" ++
  (if null (moduleImports m) then "" else unlines (map prettyImport (moduleImports m)) ++ "\n") ++
  (if null (exportItems (moduleExports m)) then "" else "exports " ++ prettyExport (moduleExports m) ++ "\n") ++
  "-- " ++ show (Map.size (moduleDefinitions m)) ++ " definitions"

{-| Helper: pretty-print a qualified name.
-}
prettyQName :: QName -> String
prettyQName (QName mod name) =
  intercalate "." (map T.unpack (mod ++ [name]))