CpmLogic.icl 17.9 KB
Newer Older
1
2
implementation module CpmLogic

3
4
5
/**
 * Clean libraries imports
 */
6
import StdEnv,StdStrictLists
7
from StdOverloadedList import ++|,Last,Init,RemoveAt,SplitAt,instance length [!!]
8
import set_return_code,Directory
9

10
11
12
/**
 * CPM imports
 */
13
import AbsSyn,CpmPaths
14
15
16
17

/**
 * CleanIDE imports
 */
18
import UtilIO,IdeState,Platform,PmPath,PmEnvironment,PmProject,PmDriver
19
20
21
22

/**
 * Execute a general CPM action
 */
23
doCpmAction :: String String !CpmAction !*World -> *World
24
25
26
27
28
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 =
29
30
  help  "cpm <target>"
    [  "Where <target> is one of the following:"
31
32
33
34
35
36
37
    ,  "  <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"
38
39
40
    ,  ""
    ,  "Execute `cpm <target> help` to get help for specific actions."] world

41
42
43
/**
 * Find all project files in the current working directory and build them
 */
44
doMake :: String !String !*World -> *World
45
doMake cleanhome pwd world
46
47
48
49
50
51
52
53
54
55
56
  # ((ok,pwd_path),world) = pd_StringToPath pwd world
  | not ok
 	= error "Failed to read current directory" world
  # ((err,entries), world) = getDirectoryContents pwd_path world
  | err<>NoDirError
 	= error "Failed to read current directory" world
 	# xs = [e \\ {fileName=e}<-entries
 			| size e>=4 && e.[size e-4]=='.' && e.[size e-3]=='p' && e.[size e-2]=='r' && e.[size e-1]=='j']
 	| isEmpty xs
		= error ("No project file found in " +++ pwd) world
		= foldr (\pn -> doProjectAction cleanhome pwd pn (BuildProject False EnvsFileName)) world xs
57

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
  # (exists,world)  = accFiles (FExists mainmodule) world
79
80
81
  | 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
  mainmodule   = MakeImpPathname pn
87

88
89
90
91
  mkMainAndProject world
    # world = doModuleAction "" mainmodule (CreateModule ApplicationModule) world
    = mkProject world
  mkProject world
92
93
94
95
96
    # 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
97
    # projectfile    = MakeImpPathname pn
98
    = saveProject cleanhome pwd project projectfile world
99
100

doProjectAction cleanhome pwd  pn  ShowProject world
101
102
103
104
  # (proj_path, project, ok, world) = openProject pwd pn cleanhome world
  | not ok
	= world
  = showLines  [  "Content of " +++ proj_path +++ ":"
105
106
107
108
109
110
111
112
               ,  "ProjectRoot..: " +++ PR_GetRelativeRootDir project
               ,  "Target.......: " +++ PR_GetTarget project
               ,  "Executable...: " +++ PR_GetExecPath project
               ,  "Paths........:"
               :  showPaths project
               ] world

doProjectAction cleanhome pwd  pn  (BuildProject force ideenvs) world
113
114
115
116
117
118
119
  # (envs, world)                = readIDEEnvs cleanhome ideenvs world
  # (proj_path, proj, ok, world) = openProject pwd pn cleanhome world
  | not ok
	= 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}
120
  = gst_world
121
122
  where
  pinit force_rebuild gst = BringProjectUptoDate force_rebuild cleanup gst
123
  cleanup exepath bool1 bool2 ps = abortLog (not bool2) "" ps
124

125
126
127
128
129
doProjectAction cleanhome pwd pn  (ProjectPath pa) world
  # (proj_path, project, ok, world) = openProject pwd pn cleanhome world
  | not ok
	= world
  = doProjectPathAction cleanhome pwd pn project pa world
130

131
132
doProjectAction cleanhome pwd pn (SetRelativeRoot relroot) world
  = withProject pwd pn cleanhome (uncurry (change_root_directory_of_project relroot) o PR_GetRootPathName) world
133

134
135
doProjectAction cleanhome pwd pn (SetTarget target) world
  = withProject pwd pn cleanhome (PR_SetTarget target) world
136

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

140
doProjectAction cleanhome pwd pn (SetProjectOptions project_options) world
141
	= withProject pwd pn cleanhome (set_project_options project_options) world
142
143
144
145
146
147
148
149
150
151
152
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
153
154
155
156
	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
157
158
159
160
	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
161
162
163
	set_project_option (HeapSize hs) project
		= PR_SetApplicationOptions {PR_GetApplicationOptions project & hs = hs} project
	set_project_option (StackSize ss) project
164
		= PR_SetApplicationOptions {PR_GetApplicationOptions project & ss = ss} project
165
166
	set_project_option (Output output) project
		= PR_SetApplicationOptions {PR_GetApplicationOptions project & o = output} project
167
168
169
170
	set_project_option LinkerGenerateSymbolsOn project
		= PR_SetLinkOptions project {PR_GetLinkOptions project & generate_symbol_table=True}
	set_project_option LinkerGenerateSymbolsOff project
		= PR_SetLinkOptions project {PR_GetLinkOptions project & generate_symbol_table=False}
171

172
doProjectAction _          _  _   _    world             =
173
  help "cpm project <projectfile> <action>"
174
    [  "Where <action> is one of the following"
175
176
177
178
179
    ,  "  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"
180
181
    ,  "  root .[.]                         : set the project root relative to the project file."
    ,  "                                    :  . is the same dir, .. the parent, ... the grandparent, etc."
182
183
184
185
186
187
188
189
190
191
    ,  "  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"
192
193
194
    ,  "                                    : -b,-nr,-nc,-sc"
    ,  "                                    :     Set the output option to BasicValuesOnly, NoReturnType,"
    ,  "                                    :     NoConsole or ShowConstructors respectively"
195
196
    ] world

197
198
199
/**
 * Execute environment-specific actions
 */
200
doEnvironmentAction :: String String EnvironmentAction *World -> *World
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
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

224
225
226
/**
 * Modify a project
 */
227
228
229
230
231
232
withProject :: !String !String !String (Project -> Project) *World -> *World
withProject pwd pn cleanhome f world
  # (project_path, project, ok, world) = openProject pwd pn cleanhome world
  | not ok
	= world
  = saveProject cleanhome pwd (f project) project_path world
233
234
235
236

/**
 * Execute path-related project actions
 */
237
238
doProjectPathAction :: String String String Project PathAction *World -> *World
doProjectPathAction cleanhome pwd pn project (AddPathAction path) world
239
  = doModPaths cleanhome pwd pn project (\t -> [!GetLongPathName path:t!]) world
240

241
doProjectPathAction cleanhome pwd pn project (RemovePathAction i) world
242
  = doModPaths cleanhome pwd pn project (RemoveAt i) world
243

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

247
248
doProjectPathAction cleanhome pwd pn project (MovePathAction i pdir) world
  = doModPaths cleanhome pwd pn project (moveStrictListIdx i pdir) world
249

250
251
doProjectPathAction _          _ _   _     _  world
  = help "cpm project <projectname.prj> path <action>"
252
253
254
255
256
257
258
259
260
    [  "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
 */
261
showPaths :: !Project -> [String]
262
showPaths project = ["  [" +++ toString n +++ "]  " +++ p \\ p<|-PR_GetPaths project & n<-[0..]]
263
264
265
266
267
268

/**
 * 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.
 */
269
270
doModPaths :: !String !String !String !Project ([!String!] -> [!String!]) *World -> *World
doModPaths cleanhome pwd pn project f world
271
272
  # paths = PR_GetPaths project
  # prj   = PR_SetPaths False paths (f paths) project
273
  # world = saveProject cleanhome pwd prj pn world
274
275
  = showLines ["Successfully modified project paths"] world

276
277
278
279
280
281
append_dir_separator :: !{#Char} -> {#Char}
append_dir_separator s
	| size s>0 && s.[size s-1]==DirSeparator
		= s
		= s+++DirSeparatorString

282
283
284
/**
 * Open a project file
 */
285
286
openProject :: !FilePath !FilePath !FilePath !*World -> (!FilePath, !Project, Bool, !*World)
openProject pwd pn cleanhome world
287
  # proj_path                = GetLongPathName (append_dir_separator pwd +++ pn)
288
289
290
291
  # ((prj, ok, err), world)  = accFiles (ReadProjectFile proj_path cleanhome) world
  | not ok || err <> ""
	= (proj_path, prj, ok, error err world)
  = (proj_path, prj, ok, world)
292
293
294
295

/**
 * Save a project back to its project file
 */
296
297
298
299
300
301
302
saveProject :: !FilePath !FilePath !Project !FilePath !*World -> *World
saveProject cleanhome pwd prj projectfile world
  # proj_path = GetLongPathName projectfile
  # (ok, world) = accFiles (SaveProjectFile proj_path prj cleanhome) world
  | not ok
	= error "Error saving project" world
  = world
303
304
305
306
307

/**
 * Move a path at a given index up or down the list of paths. Abort execution
 * if the index is out of bounds.
 */
308
moveStrictListIdx :: !Int PathDirection [!a!] -> [!a!]
309
moveStrictListIdx i dir xs
310
311
312
313
314
315
316
317
318
319
320
321
  | i < 0 || i > length xs - 1 = abort ("Index " +++ toString i +++ " out of bounds")
  | otherwise                  = msl dir (SplitAt i xs)
  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!]
322
323
324
325

/**
 * Execute module-related actions
 */
326
doModuleAction :: String !String !ModuleAction !*World -> *World
327
doModuleAction _ mn  (CreateModule mt) world
328
  # (dclexists, world)  = accFiles (FExists dclnm) world
329
  | dclexists           = error ("Definition module '" +++ dclnm +++ "' already exists.") world
330
  # (iclexists, world)  = accFiles (FExists iclnm) world
331
  | iclexists           = error ("Implementation module '" +++ iclnm +++ "' already exists.") world
332
  = writeMods mt world
333
  where
334
335
336
  dclnm      = MakeDefPathname mn
  iclnm      = MakeImpPathname mn
  basenm     = iclnm % (0,size iclnm-5)
337

338
  mkmod mty  = mty +++ "module " +++ basenm
339

340
341
342
343
  writeMods ApplicationModule world = writeicl ApplicationModule world
  writeMods LibraryModule world
    # world = writeicl ApplicationModule world
    = writedcl world
344

345
346
  writeicl ApplicationModule  world = writeicl` "" world
  writeicl LibraryModule      world = writeicl` "implementation " world
347

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

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

352
  writemod nm pref errmsg world
353
354
355
356
357
358
359
360
  	# (ok,file,world) = fopen nm FWriteText world
  	| not ok
  		= error errmsg world
  	# file = fwrites (mkmod pref) file
  	  (ok,world) = fclose file world
  	| not ok
  		= error errmsg world
	    = world
361
362
363
364

doModuleAction _ _   _  world                =
  help "cpm module <modulename> <action>"
    [  "Where <action> is one of the following"
365
366
367
368
    ,  "  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
369
370
371
372

/**
 * Show an error message
 */
373
error :: !String !*World -> *World
374
error message world
375
376
  # stderr     = fwrites message stderr
  # (ok,world) = fclose stderr world
377
378
379
380
381
382
  = set_return_code_world (-1) world

/**
 * Show a help message
 */
help :: !String ![String] !*World -> *World
383
384
385
386
387
388
help cmd lines world
  # lines` = [ "CPM: Clean Project Manager"
             : ""
             : "Usage: " +++ cmd
             : lines]
  = showLines lines` world
389
390
391
392
393
394
395

/**
 * 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
396
  # (console, world) = stdio world
397
398
  # console = foldl (\file s -> fwritec '\n' (fwrites s file)) console lines
  = snd (fclose console world)