CpmLogic.icl 17.3 KB
Newer Older
1 2 3 4 5
implementation module CpmLogic

/**
 * CPM imports
 */
6
import AbsSyn, CpmPaths
7 8 9 10 11 12 13 14 15

/**
 * CleanIDE imports
 */
import IdeState, logfile, PmDriver, PmEnvironment, PmProject, set_return_code, UtilIO, UtilStrictLists

/**
 * Clean Platform imports
 */
16
import Text
Bas Lijnse's avatar
Bas Lijnse committed
17
import Data.Func, Data.Error, Data.List
18
import System.Directory, System.File, System.FilePath
19 20 21 22

/**
 * Clean libraries imports
 */
23
import StdBool, StdEnum, StdMisc, StdTuple, StdArray
24 25 26 27

/**
 * Execute a general CPM action
 */
28
doCpmAction :: String String !CpmAction !*World -> *World
29 30 31 32 33
doCpmAction cleanhome  pwd  CpmMake           world = doMake cleanhome pwd world
doCpmAction cleanhome  pwd  (Project pn pa)   world = doProjectAction cleanhome pwd pn pa world
doCpmAction cleanhome  pwd  (Module mn ma)    world = doModuleAction cleanhome mn ma world
doCpmAction cleanhome  pwd  (Environment ea)  world = doEnvironmentAction cleanhome pwd ea world
doCpmAction _          _    _                 world =
34 35
  help  "cpm <target>"
    [  "Where <target> is one of the following:"
36 37 38 39 40 41 42
    ,  "  <projectname> [--force] [--envs=filename] : build project <projectname>."
    ,  "                                              Optionally force build (default: 'false')"
    ,  "                                              Optionally specify the environments file (default: 'IDEEnvs')"
    ,  "  project <projectfile>                     : project actions"
    ,  "  module <modulename>                       : module actions"
    //,  "  environment                               : environment actions"
    ,  "  make                                      : build all projects in the current directory"
43 44 45
    ,  ""
    ,  "Execute `cpm <target> help` to get help for specific actions."] world

46 47 48
/**
 * Find all project files in the current working directory and build them
 */
49
doMake :: String !String !*World -> *World
50 51 52 53 54 55 56 57
doMake cleanhome pwd world
  # (mbErr, world) = readDirectory pwd world
  = case mbErr of
      Error _     -> error "Failed to read current directory" world
      Ok entries  -> case filter (\entry -> endsWith ".prj" entry) entries of
                       []  -> error ("No project file found in " +++ pwd) world
                       xs  -> foldr (\pn -> doProjectAction cleanhome pwd pn (BuildProject False EnvsFileName)) world xs

58 59 60 61 62 63 64
/**
 * Default compiler options. Currently it is a simple alias for
 * forwards-compatibility.
 */
compilerOptions :: CompilerOptions
compilerOptions = DefaultCompilerOptions

65 66 67 68 69 70 71
getLine :: *World -> *(String, *World)
getLine world
  # (console, world)  = stdio world
  # (line, console)   = freadline console
  # (_, world)        = fclose console world
  = (line, world)

72 73 74
/**
 * Execute project-specific actions
 */
75
doProjectAction :: String String String ProjectAction *World -> *World
76 77
doProjectAction cleanhome pwd  pn  CreateProject world
  //Check if main module exists
78 79 80 81
  # (exists,world)  = fileExists mainmodule world
  | not exists //       = error ("Main module " +++ mainmodule +++ " does not exist.") world
    # world         = showLines ["Main module " +++ mainmodule +++ " does not exist. Create it? [y/n]"] world
    # (line, world) = getLine world
82 83
    | line.[0] == 'y' = mkMainAndProject world
    | otherwise       = error ("Failed to create project. Need " +++ mainmodule) world
84
  | otherwise       = mkProject world
85
  where
86 87 88
  basefilename = dropExtension pn
  mainmodule   = addExtension basefilename "icl"

89 90 91 92
  mkMainAndProject world
    # world = doModuleAction "" mainmodule (CreateModule ApplicationModule) world
    = mkProject world
  mkProject world
93 94 95 96 97 98 99 100
    # edit_options   = {eo={newlines=NewlineConventionUnix},pos_size=NoWindowPosAndSize}
    //Create project file using the Clean IDE libraries
    # prj            = PR_NewProject mainmodule edit_options compilerOptions DefCodeGenOptions
                         DefApplicationOptions [!!] DefaultLinkOptions
    # project        = PR_SetRoot mainmodule edit_options compilerOptions prj
    # projectfile    = mkProjectFile basefilename //addExtension basefilename "prj"
    # (prjok, world) = accFiles (SaveProjectFile projectfile project cleanhome) world
    | not prjok      = error ("Could not create project file " +++ projectfile) world
101
    = world
102 103

doProjectAction cleanhome pwd  pn  ShowProject world
104
  # projectfile       = mkProjectFile pn
105 106 107 108 109 110 111 112 113 114
  # (project, world)  = openProject cleanhome projectfile world
  = showLines  [  "Content of " +++ projectfile +++ ":"
               ,  "ProjectRoot..: " +++ PR_GetRelativeRootDir project
               ,  "Target.......: " +++ PR_GetTarget project
               ,  "Executable...: " +++ PR_GetExecPath project
               ,  "Paths........:"
               :  showPaths project
               ] world

doProjectAction cleanhome pwd  pn  (BuildProject force ideenvs) world
115
  # (envs, world)            = readIDEEnvs cleanhome ideenvs world
116
  # proj_path                = GetLongPathName (pwd </> pn)
117 118 119 120 121
  # ((proj, ok, err), world) = accFiles (ReadProjectFile proj_path cleanhome) world
  | not ok || err <> ""      = error ("CPM failed while opening project: " +++ err +++ "\n") world
  # (console, world)         = stdio world
  # iniGeneral               = initGeneral True compilerOptions cleanhome proj_path proj envs console
  # {ls, gst_world}          = pinit force {ls=iniGeneral,gst_world=world,gst_continue_or_stop=False}
122
  = gst_world
123 124 125
  where
  pinit force_rebuild gst = BringProjectUptoDate force_rebuild cleanup gst
  cleanup exepath bool1 bool2 ps = abortLog False "" ps
126 127

doProjectAction cleanhome  _  pn  (ProjectPath pa) world
128
  # projectfile       = mkProjectFile pn
129 130 131
  # (project, world)  = openProject cleanhome projectfile world
  = doProjectPathAction cleanhome projectfile project pa world

132 133 134
doProjectAction cleanhome pwd pn (SetRelativeRoot target) world =
  withProject cleanhome pn (PR_SetRelativeRootDir target) world

135 136 137 138 139 140
doProjectAction cleanhome pwd pn (SetTarget target) world =
  withProject cleanhome pn (PR_SetTarget target) world

doProjectAction cleanhome pwd pn (SetExec exec) world =
  withProject cleanhome pn (PR_SetExecPath exec) world

141 142 143 144 145 146 147 148 149 150 151 152 153
doProjectAction cleanhome pwd pn (SetProjectOptions project_options) world
	= withProject cleanhome pn (set_project_options project_options) world
where
	set_project_options [project_option:project_options] project
		# project = set_project_option project_option project
		= set_project_options project_options project
	set_project_options [] project
		= project

	set_project_option DynamicsOn project
		= PR_SetApplicationOptions {PR_GetApplicationOptions project & dynamics = True} project
	set_project_option DynamicsOff project
		= PR_SetApplicationOptions {PR_GetApplicationOptions project & dynamics = False} project
154 155 156 157
	set_project_option GenericFusionOn project
		= PR_SetApplicationOptions {PR_GetApplicationOptions project & generic_fusion = True} project
	set_project_option GenericFusionOff project
		= PR_SetApplicationOptions {PR_GetApplicationOptions project & generic_fusion = False} project
158 159 160 161
	set_project_option DescExLOn project
		= PR_SetApplicationOptions {PR_GetApplicationOptions project & desc_exl = True} project
	set_project_option DescExLOff project
		= PR_SetApplicationOptions {PR_GetApplicationOptions project & desc_exl = False} project
162 163 164
	set_project_option (HeapSize hs) project
		= PR_SetApplicationOptions {PR_GetApplicationOptions project & hs = hs} project
	set_project_option (StackSize ss) project
165
		= PR_SetApplicationOptions {PR_GetApplicationOptions project & ss = ss} project
166

167
doProjectAction _          _  _   _    world             =
168
  help "cpm project <projectfile> <action>"
169
    [  "Where <action> is one of the following"
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    ,  "  create                            : create a new project"
    ,  "  show                              : show project information"
    ,  "  build [--force] [--envs=filename] : build the project. Optionally force build (default: 'false')"
    ,  "                                      Optionally specify the environments file (default: 'IDEEnvs')"
    ,  "  path                              : manage project paths"
    ,  "  target <env>                      : set target environment to <env>"
    ,  "  exec <execname>                   : set executable name to <execname>"
    ,  "  set option [option]               : Set one or more of the following options:"
    ,  "                                    : -generic_fusion,-ngeneric_fusion"
    ,  "                                    :     Enable or disable generic fusion"
    ,  "                                    : -dynamics,-ndynamics"
    ,  "                                    :     Enable or disable dynamics"
    ,  "                                    : -descexl,-descexl"
    ,  "                                    :     Enable or disable descriptor generation and label exporting"
    ,  "                                    :     This translates to passing -desc and -exl to cocl"
185 186
    ] world

187 188 189
/**
 * Execute environment-specific actions
 */
190
doEnvironmentAction :: String String EnvironmentAction *World -> *World
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
doEnvironmentAction cleanhome  pwd  ListEnvironments                world = error ("Not implemented") world
doEnvironmentAction cleanhome  pwd  (ImportEnvironment ef)          world = error ("Not implemented") world
doEnvironmentAction cleanhome  pwd  (RemoveEnvironment en)          world = error ("Not implemented") world
doEnvironmentAction cleanhome  pwd  (ShowEnvironment en)            world = error ("Not implemented") world
doEnvironmentAction cleanhome  pwd  (ExportEnvironment en)          world = error ("Not implemented") world
doEnvironmentAction cleanhome  pwd  (CreateEnvironment en)          world = error ("Not implemented") world
doEnvironmentAction cleanhome  pwd  (RenameEnvironment en en`)      world = error ("Not implemented") world
doEnvironmentAction cleanhome  pwd  (SetEnvironmentCompiler en cp)  world = error ("Not implemented") world
doEnvironmentAction cleanhome  pwd  (SetEnvironmentCodeGen en cp)   world = error ("Not implemented") world
doEnvironmentAction _          _    _                               world =
  help "cpm environment <action>"
    [  "Where <action> is one of the following"
    ,  "  list                                  : list all available environments"
    ,  "  import <filepath>                     : import an environement from file <filepath>"
    ,  "  create <envname>                      : create a new environment with name <envname>"
    ,  "  remove <envname>                      : remove evironment <envname>"
    ,  "  show <envname>                        : show environment <envname>"
    ,  "  export <envname>                      : export environment <envname>"
    ,  "  rename <envname> <envname`>           : rename environment <envname> to <envname`>"
    ,  "  setcompiler <envname> <compilername>  : set compiler for <envname> to <compilername>"
    ,  "  setcodegen <envname> <codegenname>    : set codegen for <envname> to <codegenname>"
    ] world

/**
 * Turn a project name into a project filename
 */
mkProjectFile :: !String -> String
mkProjectFile pn = addExtension (dropExtension pn) "prj"

220 221 222
/**
 * Modify a project
 */
223
withProject :: !String !String (Project -> Project) *World -> *World
224
withProject cleanhome pn f world
225 226
  # projectfile      = mkProjectFile pn
  # (project, world) = openProject cleanhome projectfile world
227 228 229 230 231
  = saveProject cleanhome (f project) projectfile world

/**
 * Execute path-related project actions
 */
232
doProjectPathAction :: String String Project PathAction *World -> *World
233 234 235 236 237 238 239 240 241 242 243 244
doProjectPathAction cleanhome pn project (AddPathAction path) world =
  doModPaths cleanhome pn project ((:!) path) world

doProjectPathAction cleanhome pn project (RemovePathAction i) world =
  doModPaths cleanhome pn project (rmStrictListIdx i) world

doProjectPathAction _ _ project ListPathsAction world = showLines ["Paths for project:" : showPaths project] world

doProjectPathAction cleanhome pn project (MovePathAction i pdir) world =
  doModPaths cleanhome pn project (moveStrictListIdx i pdir) world

doProjectPathAction _         _   _     _  world =
245
  help "cpm project <projectname.prj> path <action>"
246 247 248 249 250 251 252 253 254
    [  "Where <action> is one of the following"
    ,  "  add <path>          : add a path to the project"
    ,  "  list                : list all project paths and their index"
    ,  "  remove <i>          : remove path <i> from the list of projects"
    ,  "  move <i> <up|down>  : move path <i> up or down one position" ] world

/**
 * Collect all project paths in a list with an index prefixed
 */
255
showPaths :: !Project -> [String]
256 257 258 259 260 261 262 263
showPaths project = map f (zip2 [0..] (StrictListToList (PR_GetPaths project)))
  where f (n, p)  = "  [" +++ toString n +++ "]  " +++ p

/**
 * Modify the list of paths in a project given a modification function which
 * takes a strict list of project paths and returns a strict list of project
 * paths.
 */
264
doModPaths :: !String !String !Project ([!String!] -> [!String!]) *World -> *World
265
doModPaths cleanhome pn project f world
266 267 268
  # paths = PR_GetPaths project
  # prj   = PR_SetPaths False paths (f paths) project
  # world = saveProject cleanhome prj pn world
269 270 271 272 273 274 275 276
  = showLines ["Successfully modified project paths"] world

/**
 * Open a project file
 */
openProject :: !FilePath !FilePath !*World -> (!Project, !*World)
openProject cleanhome projectfile world
  # ((prj, ok, err), world) = accFiles (ReadProjectFile projectfile cleanhome) world
277 278
  | ok        = (prj, world)
  | otherwise = (prj, error err world)
279 280 281 282 283 284 285

/**
 * Save a project back to its project file
 */
saveProject :: !FilePath !Project !FilePath !*World -> *World
saveProject cleanhome prj projectfile world
  # (ok, world) = accFiles (SaveProjectFile projectfile prj cleanhome) world
286 287
  | not ok    = error "Error saving project" world
  | otherwise = world
288 289 290 291 292

/**
 * Remove an item from a strict list at a given index. Abort execution if the
 * index is out of bounds.
 */
293
rmStrictListIdx :: !Int [!a!] -> [!a!]
294 295 296 297 298 299 300 301
rmStrictListIdx 0  (_ :! t)          = t
rmStrictListIdx n  (h :! t) | n > 0  = h :! (rmStrictListIdx (n - 1) t)
rmStrictListIdx n  _                 = abort ("Index " +++ toString n +++ " out of bounds")

/**
 * Move a path at a given index up or down the list of paths. Abort execution
 * if the index is out of bounds.
 */
302
moveStrictListIdx :: !Int PathDirection [!a!] -> [!a!]
303 304 305
moveStrictListIdx i dir xs
  | i < 0 || i > (LLength xs - 1)  = abort ("Index " +++ toString i +++ " out of bounds")
  | otherwise                      = ListToStrictList (msl dir (splitAt i (StrictListToList xs)))
306 307 308 309 310 311 312 313 314 315
  where  msl MovePathUp      ([], xs)        = xs
         msl MovePathUp      (xs, [x:ys])    = (init xs) ++ [x : (last xs) : ys]
         msl MovePathDown    ([], [x:y:ys])  = [y:x:ys]
         msl MovePathDown    (xs, [])        = xs
         msl MovePathDown    (xs, [y])       = xs ++ [y]
         msl MovePathDown    (xs, [x:y:ys])  = xs ++ [y:x:ys]
         msl MovePathTop     (xs, [])        = xs
         msl MovePathTop     (xs, [y:ys])    = [y:xs] ++ ys
         msl MovePathBottom  (xs, [])        = xs
         msl MovePathBottom  (xs, [y:ys])    = xs ++ ys ++ [y]
316 317 318 319

/**
 * Execute module-related actions
 */
320
doModuleAction :: String !String !ModuleAction !*World -> *World
321
doModuleAction _ mn  (CreateModule mt) world
322
  # (dclexists, world)  = fileExists dclnm world
323
  | dclexists           = error ("Definition module '" +++ dclnm +++ "' already exists.") world
324
  # (iclexists, world)  = fileExists iclnm world
325
  | iclexists           = error ("Implementation module '" +++ iclnm +++ "' already exists.") world
326
  = writeMods mt world
327 328 329 330
  where
  basenm     = dropExtension mn
  dclnm      = addExtension basenm "dcl"
  iclnm      = addExtension basenm "icl"
331

332
  mkmod mty  = mty +++ "module " +++ basenm
333

334 335 336 337
  writeMods ApplicationModule world = writeicl ApplicationModule world
  writeMods LibraryModule world
    # world = writeicl ApplicationModule world
    = writedcl world
338

339 340
  writeicl ApplicationModule  world = writeicl` "" world
  writeicl LibraryModule      world = writeicl` "implementation " world
341

342
  writeicl` pref world = writemod iclnm pref ("Failed to write implementation module '" +++ basenm +++ "'") world
343

344
  writedcl world = writemod dclnm "definition " ("Failed to write definition module '" +++ basenm +++ "'") world
345

346 347 348 349
  writemod nm pref errmsg world
    # (me, world)  = writeFile nm (mkmod pref) world
    | isError me   = error errmsg world
    = world
350 351 352 353

doModuleAction _ _   _  world                =
  help "cpm module <modulename> <action>"
    [  "Where <action> is one of the following"
354 355 356 357
    ,  "  create [application|library]  : create a new module. Optionally specify module type (default: 'library')"
    //,  "  check <projectname.prj>       : type-check module in the context of project <projectname.prj>"
    //,  "  compile <projectname.prj>     : compile module in the context of project <projectname.prj>"
    ] world
358 359 360 361

/**
 * Show an error message
 */
362
error :: !String !*World -> *World
363
error message world
364 365
  # stderr     = fwrites message stderr
  # (ok,world) = fclose stderr world
366 367 368 369 370 371
  = set_return_code_world (-1) world

/**
 * Show a help message
 */
help :: !String ![String] !*World -> *World
372 373 374 375 376 377
help cmd lines world
  # lines` = [ "CPM: Clean Project Manager"
             : ""
             : "Usage: " +++ cmd
             : lines]
  = showLines lines` world
378 379 380 381 382 383 384

/**
 * Given a list of strings, concatenate them to a single string with newlines
 * in between, then print that new string to console.
 */
showLines :: ![String] !*World -> *World
showLines lines world
385 386
  # (console, world) = stdio world
  # console          = seqSt (\s -> fwrites (s +++ "\n")) lines console
387
  = snd $ fclose console world