aboutsummaryrefslogtreecommitdiff
path: root/sucl/clean.icl
blob: 6f4964f46f56ed65e8ab0a912710c541c38f53a9 (plain) (blame)
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
implementation module clean

// $Id$

/*

clean.lit - Clean core language
===============================

Description
-----------

This script contains  the  implementation  of  the  core  of  the  Clean
language.

------------------------------------------------------------

Interface
---------

Exported identifiers:

>   %export            ||  law.lit cli.lit test.lit

>       cleanpart      ||     +       +        -
>       node           ||     +       +        +
>       symbol         ||     +       +        +
>       typenode       ||     +       +        +
>       typesymbol     ||     +       +        +

>       cleantyperule  ||     -       +        -
>       corecomplete   ||     +       +        -
>       coretypeinfo
>       coretyperule   ||     -       +        -
>       readcleanparts ||     -       +        -
>       showcleanpart
>       shownode       ||     -       -        +
>       showsymbol     ||     +       +        +
>       showtypenode   ||     -       +        -
>       showtypesymbol ||     -       +        -
>       symbolmodule
>       typesymbolmodule
>       usersym

>       cleanalias
>       cleanmacro
>       cleantype
>       cleanrule

>       heap     ||  Infinite list of anonymous nodes
>       typeheap ||  Infinite list of anonymous type nodes

------------------------------------------------------------

Includes
--------

>   %include "basic.lit"
>   %include "hunt.lit"
>   %include "graph.lit" -extgraph
>   %include "rule.lit"

------------------------------------------------------------

Implementation
--------------

Implementation of identifier

>   typesymbol
>   ::= INT              | ||  Integer
>       BOOL             | ||  Boolean
>       CHAR             | ||  Character
>       STRING           | ||  String
>       REAL             | ||  Real
>       FILE             | ||  File
>       FN               | ||  Function
>       LIST             | ||  List
>       TUPLE num        | ||  Tuple of specific arity
>       USER [char] [char] ||  User-defined type <module.ident>

>   typenode
>   ::= NAMED [char] | ||  A type node with an explicit nodeid
>       ANONYMOUS num  ||  A type node without an explicit nodeid

>   symbol
>   ::= Int num          | ||  A specific integer
>       Bool bool        | ||  A specific boolean
>       Char char        | ||  A specific character
>       String [char]    | ||  A specific string
>       Real num         | ||  A specific real
>       Tuple num        | ||  The tuple constructor of specific arity
>       Cons             | ||  The list constructor
>       Nil              | ||  The empty list
>       Apply            | ||  The curried function application symbol
>       If               | ||  The predefined if symbol
>       Select num num   | ||  The tuple element selector for tuple arity and element number
>       User [char] [char] ||  A user-defined symbol <module.ident>

>   node
>   ::= Named [char] | ||  A node with an explicit nodeid
>       Anonymous num  ||  A node without an explicit nodeid

>   cleanpart
>   ::= Typeexport typesymbol |
>       Alias typesymbol [typenode] typenode [(typenode,(typesymbol,[typenode]))] |
>       Algebra typesymbol [symbol] |
>       Export symbol |
>       Macro symbol [node] node [(node,(symbol,[node]))] |
>       Type symbol [typenode] typenode [(typenode,(typesymbol,[typenode]))] [char] |
>       Rules symbol |
>       Rule symbol [node] node [(node,(symbol,[node]))] |
>       Constructor symbol

>   showcleanpart :: cleanpart -> [char]
>   showcleanpart = show

>   ct = printrule show show.coretyperule

>   coreconstructor :: symbol -> bool

>   coreconstructor (Int    i) = True
>   coreconstructor (Bool   b) = True
>   coreconstructor (Char   c) = True
>   coreconstructor (String s) = True
>   coreconstructor (Real   r) = True
>   coreconstructor (Tuple  a) = True
>   coreconstructor (Cons    ) = True
>   coreconstructor (Nil     ) = True
>   coreconstructor (Apply   ) = True
>   coreconstructor (If      ) = False
>   coreconstructor (Select a i) = False
>   coreconstructor (User m n) = False

>   coreexports :: [symbol]

>   coreexports = []

>   coreimported :: symbol -> bool

>   coreimported (Int    i) = False
>   coreimported (Bool   b) = False
>   coreimported (Char   c) = False
>   coreimported (String s) = False
>   coreimported (Real   r) = False
>   coreimported (Tuple  a) = False
>   coreimported (Cons    ) = False
>   coreimported (Nil     ) = False
>   coreimported (Apply   ) = True
>   coreimported (If      ) = False
>   coreimported (Select a i) = False
>   coreimported (User m n) = False

>   corerules :: symbol -> [rule symbol node]

>   corerules (Int    i) = []
>   corerules (Bool   b) = []
>   corerules (Char   c) = []
>   corerules (String s) = []
>   corerules (Real   r) = []
>   corerules (Tuple  a) = []
>   corerules (Cons    ) = []
>   corerules (Nil     ) = []
>   corerules (Apply   ) = []
>   corerules (If      )
>   =   [   mkrule [Named "cond",Named "then",Named "else"] (Named "else") (updategraph (Named "cond") (Bool False,[]) emptygraph)
>       ,   mkrule [Named "cond",Named "then",Named "else"] (Named "then") (updategraph (Named "cond") (Bool True ,[]) emptygraph)
>       ]
>   corerules (Select a i) = [mkrule [Named "tuple"] (Anonymous i) (updategraph (Named "tuple") (Tuple a,map Anonymous [1..a]) emptygraph)]
>   corerules (User m n) = []

    coresymbols :: [symbol]

    coresymbols = [If,Select a i]

>   coretyperule (Int    i) = mkrule [] (NAMED "int"   ) (updategraph (NAMED "int"   ) (INT   ,[]) emptygraph)
>   coretyperule (Bool   b) = mkrule [] (NAMED "bool"  ) (updategraph (NAMED "bool"  ) (BOOL  ,[]) emptygraph)
>   coretyperule (Char   c) = mkrule [] (NAMED "char"  ) (updategraph (NAMED "char"  ) (CHAR  ,[]) emptygraph)
>   coretyperule (String s) = mkrule [] (NAMED "string") (updategraph (NAMED "string") (STRING,[]) emptygraph)
>   coretyperule (Real   r) = mkrule [] (NAMED "real"  ) (updategraph (NAMED "real"  ) (REAL  ,[]) emptygraph)
>   coretyperule (Tuple  a)
>   =   mkrule args (NAMED "tuple") (updategraph (NAMED "tuple") (TUPLE a,args) emptygraph)
>       where args = take a (map ANONYMOUS [1..])
>   coretyperule Cons = mkrule [NAMED "element",NAMED "list"] (NAMED "list") (updategraph (NAMED "list") (LIST,[NAMED "element"]) emptygraph)
>   coretyperule Nil = mkrule [] (NAMED "list") (updategraph (NAMED "list") (LIST,[NAMED "element"]) emptygraph)
>   coretyperule Apply = mkrule [NAMED "fn",NAMED "arg"] (NAMED "res") (updategraph (NAMED "fn") (FN,[NAMED "arg",NAMED "res"]) emptygraph)
>   coretyperule If = mkrule [NAMED "bool",NAMED "res",NAMED "res"] (NAMED "res") (updategraph (NAMED "bool") (BOOL,[]) emptygraph)
>   coretyperule (Select a i) = mkrule [NAMED "tuple"] (ANONYMOUS i) (updategraph (NAMED "tuple") (TUPLE a,map ANONYMOUS [1..a]) emptygraph)
>   coretyperule (User m n) = error ("coretyperule: untyped user symbol "++m++'.':n)

>   coretypeinfo :: symbol -> (rule typesymbol typenode,[bool])
>   coretypeinfo sym
>   =   (trule,corestricts sym)
>       where corestricts Apply = [True,False]
>             corestricts If    = [True,False,False]
>             corestricts (Select a i) = [True]
>             corestricts sym = map (const False) (lhs trule)
>             trule = coretyperule sym

>   readcleanparts :: [char] -> [cleanpart]
>   readcleanparts = readvals.findclean

>   findclean :: [char] -> [char]
>   findclean base
>   =   foldr const (error ("findclean: "++show base++" not found.")) files
>       where files = findfiles readable ["",".cli"] (getpath ["."] "CLIPATH") base

>   corecomplete :: typesymbol -> [symbol] -> bool

>   corecomplete INT = const False
>   corecomplete BOOL = superset (map Bool [False,True])
>   corecomplete CHAR = superset (map (Char.decode) [0..255])
>   corecomplete STRING = const False
>   corecomplete REAL = const False
>   corecomplete FILE = const False
>   corecomplete FN = const False
>   corecomplete LIST = superset [Nil,Cons]
>   corecomplete (TUPLE arity) = superset [Tuple arity]
>   corecomplete (USER module identifier) = const False

>   showtypesymbol INT = "INT"
>   showtypesymbol BOOL = "BOOL"
>   showtypesymbol CHAR = "CHAR"
>   showtypesymbol STRING = "STRING"
>   showtypesymbol REAL = "REAL"
>   showtypesymbol FILE = "FILE"
>   showtypesymbol FN = "=>"
>   showtypesymbol LIST = "_LIST"
>   showtypesymbol (TUPLE a) = "_TUPLE"++shownum a
>   showtypesymbol (USER module ident) = ident

>   showtypenode (NAMED ident) = ident
>   showtypenode (ANONYMOUS n) = "type"++shownum n

>   showtypenodedef :: typesymbol -> [([char],[char])] -> ([char],[char])
>   showtypenodedef (TUPLE a) [] = issafe "()"
>   showtypenodedef (TUPLE a) [arg] = arg
>   showtypenodedef (TUPLE a) ((safearg,unsafearg):args)
>   =   issafe ('(':unsafearg++f args)
>       where f [] = ")"
>             f ((safearg,unsafearg):args) = ',':unsafearg++f args
>   showtypenodedef LIST [(safearg,unsafearg)] = issafe ('[':unsafearg++"]")
>   showtypenodedef symbol [] = issafe (showtypesymbol symbol)
>   showtypenodedef symbol args = showappl (showtypesymbol symbol) args

>   showsymbol :: symbol -> [char]
>   showsymbol (Int i) = shownum i
>   showsymbol (Bool False) = "FALSE"
>   showsymbol (Bool True) = "TRUE"
>   showsymbol (Char c) = show c
>   showsymbol (String s) = show s
>   showsymbol (Real r) = show (r+0.0)
>   showsymbol (Tuple a) = "_Tuple"++show a
>   showsymbol Cons = "_CONS"
>   showsymbol Nil = "[]"
>   showsymbol Apply = "_AP"
>   showsymbol If = "IF"
>   showsymbol (Select a i) = "_Select"++show a++'.':show i
>   showsymbol (User module ident) = ident

>   shownode (Named ident) = ident
>   shownode (Anonymous n) = "node"++shownum n

>   shownodedef :: symbol -> [([char],[char])] -> ([char],[char])
>   shownodedef (Tuple a) [] = issafe "()"
>   shownodedef (Tuple a) [arg] = arg
>   shownodedef (Tuple a) ((safearg,unsafearg):args)
>   =   issafe ('(':unsafearg++f args)
>       where f [] = ")"
>             f ((safearg,unsafearg):args) = ',':unsafearg++f args
>   shownodedef Cons [(safehead,unsafehead),(safetail,unsafetail)]
>   =   issafe ('[':unsafehead++f unsafetail)
>       where f "[]" = "]"
>             f ('[':ttail) = ',':ttail
>             f unsafetail = '|':unsafetail++"]"
>   shownodedef Apply [fn] = fn
>   shownodedef Apply ((safefn,unsafefn):args) = showappl unsafefn args
>   shownodedef symbol [] = issafe (showsymbol symbol)
>   shownodedef symbol args = showappl (showsymbol symbol) args

>   showappl sym args = mksafe (sym++concat (map ((' ':).fst) args))
>   mksafe unsafe = ('(':unsafe++")",unsafe)
>   issafe safe = (safe,safe)

>   cleantyperule :: symbol -> (rule typesymbol typenode,[bool]) -> [char]

>   cleantyperule sym (trule,tstricts)
>   =   "::  "++showsymbol sym++concat (map2 printarg tstricts targs)++" -> "++snd (lookup' troot)++";"
>       where targs = lhs trule; troot = rhs trule; tgraph = rulegraph trule
>             lookup' = lookup table
>             table = map (pairwith printunraveled) (nodelist tgraph (troot:targs))
>             printunraveled tnode
>             =   showtypenodedef tsym (map lookup' targs), if tdef
>             =   issafe (showtypenode tnode), otherwise
>                 where (tdef,(tsym,targs)) = nodecontents tgraph tnode
>             printarg tstrict targ = ' ':cond tstrict ('!':) id (fst (lookup' targ))

>   prettyrule :: (**->[char]) -> (*->[([char],[char])]->([char],[char])) -> rule * ** -> [char]
>   prettyrule shownode shownodedef rule
>   =   concat (map ((++" ").fst) (init shownnodes))++"-> "++snd (last shownnodes)
>       where shownnodes = foldgraph prettydef (issafe.shownode) shownodedef graph (args++[root])
>             prettydef node (saferef,unsaferef) = issafe (shownode node++':':saferef)
>             graph = rulegraph rule
>             args = lhs rule
>             root = rhs rule

>   usersym :: symbol -> bool
>   usersym (User module name) = True
>   usersym sym = False

>   symbolmodule :: symbol -> optional [char]
>   symbolmodule (User module ident) = Present module
>   symbolmodule symbol = Absent

>   typesymbolmodule :: typesymbol -> optional [char]
>   typesymbolmodule (USER module ident) = Present module
>   typesymbolmodule symbol = Absent

========================================================================

Get the Select nodes from a graph.

>   getselectnodes :: graph symbol ** -> ** -> [((**,num),(num,**))]

>   getselectnodes graph root
>   =   foldr (withmeta (nodecontents graph) addselectnode) [] (nodelist graph [root])
>       where addselectnode (True,(Select arity index,[tuplenode])) selectnode
>             =   (((tuplenode,arity),(index,selectnode)):)
>             addselectnode contents node = id

Distribute the Select nodes over their indexes.

>   splitselectnodes :: ((**,num),[(num,**)]) -> (**,[[**]])

>   splitselectnodes ((tuplenode,arity),selects)
>   =   (tuplenode,foldr dist (rep arity []) selects)
>       where dist (1,selectnode) (ns:nss) = (selectnode:ns):nss
>             dist (index,selectnode) (ns:nss) = ns:dist (index-1,selectnode) nss

Make left hand sides.

>   makelhss :: [**] -> [[**]] -> ([**],[[**]])

>   makelhss heap nss
>   =   (heap,[]), if empty
>   =   (heap'',ns':nss''), otherwise
>       where (heap'',nss'') = makelhss heap' nss'
>             (empty,ns',heap',nss') = heads heap nss
>             heads heap [] = (True,[],heap,[])
>             heads (node:heap) ([]:nss)
>             =   (empty,node:ns',heap',[]:nss')
>                 where (empty,ns',heap',nss') = heads heap nss
>             heads heap ((n:ns):nss)
>             =   (False,n:ns',heap',ns:nss')
>                 where (empty,ns',heap',nss') = heads heap nss

>   maketuplenodedefs :: [**] -> [(**,[[**]])] -> [([**],**)]

>   maketuplenodedefs heap []
>   =   []
>   maketuplenodedefs heap ((tuplenode,nss):rest)
>   =   map (converse pair tuplenode) lhss++tuplenodedefs
>       where (heap',lhss) = makelhss heap nss
>             tuplenodedefs = maketuplenodedefs heap' rest

>   printtree :: graph symbol node -> node -> ([char],[char])
>   printtree = unravelwith (issafe.shownode) shownodedef

>   cleanalias sym = indent "::  ".totalpretty typeheap (const (const [])) showtypesymbol showtypenodedef showtypenode sym
>   cleanmacro sym = indent "    ".totalpretty heap (const (const [])) showsymbol shownodedef shownode sym
>   cleantype sym = indent "::  ".totalpretty typeheap (const (const [])) showsymbol showtypenodedef showtypenode sym
>   cleanrule sym = indent "    ".totalpretty heap getselectnodes showsymbol shownodedef shownode sym

>   heap = map Anonymous [0..]
>   typeheap = map ANONYMOUS [0..]

>   totalpretty
>   ::  [***] ->
>       (graph ** ***->***->[((***,num),(num,***))]) ->
>       (*->[char]) ->
>       (**->[([char],[char])]->([char],[char])) ->
>       (***->[char]) ->
>       * ->
>       rule ** *** ->
>       [[char]]

>   totalpretty heap getselectnodes showlhssymbol shownodedef shownode lhssymbol rule
>   =   punctuate "" "," "    " "" lhsheader lhsbody++
>       punctuate "->  " "," "    " ";" rhsheader rhsbody

>       where

>             args = lhs rule; root = rhs rule; graph = rulegraph rule
>             selectnodes = getselectnodes graph root
>             prunedgraph = foldr prunegraph graph (map (snd.snd) selectnodes)
>             tuplenodedefs
>             =   (   maketuplenodedefs (heap--nodelist graph (root:args)).
>                     map splitselectnodes.
>                     partition fst snd
>                 ) selectnodes
>             tuplenodes = map snd tuplenodedefs
>             count = refcount prunedgraph (args++root:tuplenodes)
>             sharednodes = [node|node<-nodelist prunedgraph (args++root:tuplenodes);count node>1;fst (nodecontents prunedgraph node)]
>             reprunedgraph = foldr prunegraph prunedgraph sharednodes
>             (argreprs:[rootrepr]:tuplereprs:sharedargreprs)
>             =   map (map (unravelwith (issafe.shownode) shownodedef reprunedgraph)) (args:[root]:tuplenodes:map (snd.snd.nodecontents prunedgraph) sharednodes)

>             showtupledef (selectnodes,tuplenode) tuplerepr
>             =   '(':join ',' (map shownode selectnodes)++"): "++snd tuplerepr
>             showshareddef (node,argreprs)
>             =   mapfst addline, if patnode node
>             =   mapsnd addline, otherwise
>                 where addline = ((shownode node++": "++snd (shownodedef (fst cont) argreprs)):)
>                       (True,cont) = nodecontents prunedgraph node

>             patnode = member (nodelist graph args)

>             lhsheader = showlhssymbol lhssymbol++concat (map ((' ':).fst) argreprs)
>             rhsheader = snd rootrepr
>             (lhslines,rhslines) = foldr showshareddef ([],[]) (zip2 sharednodes sharedargreprs)
>             lhsbody = lhslines
>             rhsbody = map2 showtupledef tuplenodedefs tuplereprs++rhslines

>   punctuate :: [char] -> [char] -> [char] -> [char] -> [char] -> [[char]] -> [[char]]

>   punctuate open endline beginline close l ls
>   =   (open++l++end):ls'
>       where (end,ls') = f ls
>             f [] = (close,[])
>             f (l:ls) = (endline,punctuate beginline endline beginline close l ls)

------------------------------------------------------------------------
Useful (higher order) functions.

>   withmeta :: (*->**) -> (**->*->***) -> * -> ***
>   withmeta meta f x = f (meta x) x

>   pair :: * -> ** -> (*,**)
>   pair x y = (x,y)

>   unravelwith :: (**->***) -> (*->[***]->***) -> graph * ** -> ** -> ***
>   unravelwith foldopen foldclosed graph
>   =   unravel
>       where unravel node
>             =   foldclosed sym (map unravel args), if def
>             =   foldopen node, otherwise
>                 where (def,(sym,args)) = nodecontents graph node

*/