aboutsummaryrefslogtreecommitdiff
path: root/snug-clean/src/Snug/Compile.icl
blob: 0dd2959ffce6d86f7264bc65582729ad7518c488 (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
implementation module Snug.Compile

import StdEnv

import Control.Monad
import Control.Monad.Fail
import Control.Monad.State
import Control.Monad.Trans
import Data.Error
import Data.Func
import Data.Functor
import Data.List
import qualified Data.Map
from Data.Map import :: Map
from Text import concat4

import MIPS.MIPS32
import Snug.Compile.ABI
import Snug.Compile.Simulate
import Snug.Syntax

:: CompileM a :== StateT CompileState (MaybeError String) a

:: CompileState =
	{ fresh_ident :: !Int
	, globals     :: !Globals
	}

:: Locals :== Map SymbolIdent LocalLocation

:: LocalLocation = FrontPtrArg !Int

instance == (Namespaced id) | == id
where
	(==) x y = x.id == y.id && x.ns == y.ns

instance < (Namespaced id) | < id
where
	(<) x y
		| x.id < y.id = True
		| x.id > y.id = False
		| otherwise = x.ns < y.ns

compile :: !Namespace ![Definition] -> MaybeError String [Line]
compile ns defs =
	flatten <$> evalStateT (mapM (compileDefinition ns) defs) init
where
	init =
		{ fresh_ident = 0
		, globals = combineGlobals [builtin, gatherGlobals ns defs]
		}

	builtin =
		{ constructors = 'Data.Map'.fromList
			[ ({ns="", id="INT"}, ConstructorDef "INT" [])
			]
		, functions = 'Data.Map'.newMap
		}

	combineGlobals :: ![Globals] -> Globals
	combineGlobals sets =
		{ constructors = 'Data.Map'.unions [g.constructors \\ g <- sets]
		, functions = 'Data.Map'.unions [g.functions \\ g <- sets]
		}

	gatherGlobals :: !Namespace ![Definition] -> Globals
	gatherGlobals ns defs =
		{ constructors = 'Data.Map'.fromList
			[ ({ns=ns, id=id}, cons)
			\\ DataDef _ _ conses <- defs
			, cons=:(ConstructorDef id _) <- conses
			]
		, functions = 'Data.Map'.fromList
			[ ({ns=ns, id=id}, {arity=length args, type=foldr TyApp ret (map snd (reverse args))})
			\\ FunDef id args ret _ <- defs
			]
		}

freshLabel :: CompileM Label
freshLabel = state \st -> ("_l" +++ toString (st.fresh_ident), {st & fresh_ident=st.fresh_ident+1})

lookupConstructor :: !Namespace !ConstructorIdent -> CompileM ConstructorDef
lookupConstructor ns id =
	gets (\s -> s.globals) >>= \globals ->
	liftT $ mb2error
		(concat4 "Unknown constructor " ns "." id)
		('Data.Map'.get {ns=ns, id=id} globals.constructors)

lookupFunction :: !Namespace !SymbolIdent -> CompileM FunctionInfo
lookupFunction ns id =
	gets (\s -> s.globals) >>= \globals ->
	liftT $ mb2error
		(concat4 "Unknown symbol " ns "." id)
		('Data.Map'.get {ns=ns, id=id} globals.functions)

compileDefinition :: !Namespace !Definition -> CompileM [Line]
compileDefinition _ (TypeDef _ _) = pure
	[]
compileDefinition ns (DataDef _ _ constructors) =
	(++) [StartSection "data"] <$>
	flatten <$> mapM (compileConstructor ns) constructors
compileDefinition ns (FunDef id args ret expr) =
	(++)
		(if (isEmpty args) [] (
			[ StartSection "data"
			, Align 2
			] ++ flatten
			[[ Label (closure_label i)
			// TODO: Ideally we would use the following here:
			//, RawByte i // pointer arity
			//, RawByte 0 // basic value arity
			//, RawByte (length args-i-1) // number of arguments that still have to be curried in minus 1
			//, RawByte 0 // reserved
			// But since SPIM does not allow .byte in the text section, we use:
			, RawWord
				(i bitor // pointer arity
				((length args-i-1) << 16)) // number of arguments that still have to be curried in minus 1
			] \\ i <- [0..length args-1]
			] ++
			[ RawWordLabel n_label
			])) <$>
	(++)
		[ StartSection "text"
		, Global n_label
		// TODO: Ideally we would use the following here:
		//, Align 1
		//, RawByte (sum [2^i \\ i <- [0..] & _ <- args]) // all strict for now, TODO change
		//, RawByte (length args) // arity
		// But since SPIM does not allow .byte in the text section, we use:
		, Align 2
		, RawWord
			(sum [2^i \\ i <- [0..] & _ <- args] bitor // all strict for now, TODO change
			(length args << 8)) // arity
		// instead... (end modification)
		, Label n_label
		] <$>
	map Instr <$> compileExpr ns globals locals expr
where
	closure_label i = closureLabel ns id i
	n_label = functionLabel ns NodeEntry id
	locals = 'Data.Map'.fromList
		[ (id, FrontPtrArg offset)
		\\ (id,_) <- args
		& offset <- [0..]
		]

compileConstructor :: !Namespace !ConstructorDef -> CompileM [Line]
compileConstructor ns (ConstructorDef id args) = pure
	[ Global label
	, Align 1
	, Label label
	, RawByte (length args) // pointer arity
	, RawByte 0 // basic value arity
	//, RawByte -1 // number of arguments still to be curried in (unused for constructors)
	]
where
	label = constructorLabel ns id

compileExpr :: !Namespace !Locals !Expression -> CompileM [Instruction]
compileExpr ns locals expr =
	case simulate [SVRegOffset FrontEvalPtr 0] expr` of
		Error e -> fail ("Compiling an expression failed: " +++ e)
		Ok instrs -> pure instrs
where
	expr` = simulator ns locals expr >>| indirectAndEval

simulator :: !Namespace !Locals !Expression -> Simulator ()
simulator _ _ (BasicValue bv) =
	pushBasicValue bv >>|
	buildCons (constructorLabel "" (label bv)) 1
where
	label (BVInt _) = "INT"
	label (BVChar _) = "CHAR"
simulator ns locals (Symbol id) =
	case 'Data.Map'.get id locals of
		?Just (FrontPtrArg i) ->
			stackSize >>= \n ->
			pushArg (n-1) i
		?None ->
			liftT (lookupFunction ns id) >>= \info -> case info.arity of
				0 ->
					buildThunk (functionLabel ns NodeEntry id) 0
				_ ->
					fail "symbol with arity > 0" // TODO implement
simulator ns locals expr=:(ExpApp _ _) =
	case f of
		Symbol id -> // TODO include locals
			liftT (lookupFunction ns id) >>= \info
				| info.arity == length args ->
					mapM_ (simulator ns locals) (reverse args) >>|
					buildThunk (functionLabel ns NodeEntry id) info.arity
				| info.arity > length args ->
					mapM_ (simulator ns locals) (reverse args) >>|
					buildCons (closureLabel ns id (length args)) (length args)
				| info.arity < length args ->
					let
						(closure_args,extra_args) = splitAt info.arity args
						closure = foldl ExpApp f closure_args
					in
					mapM_ (simulator ns locals) extra_args >>|
					simulator ns locals closure >>|
					mapM_ (\_ -> buildThunk (functionLabel "" NodeEntry "ap") 2) extra_args
		Constructor id ->
			liftT (lookupConstructor ns id) >>= \(ConstructorDef _ arg_types)
				| length arg_types == length args ->
					mapM_ (simulator ns locals) (reverse args) >>|
					buildCons (constructorLabel ns id) (length args)
				| otherwise -> fail ("arity mismatch in application of " +++ id) // TODO implement
		_ -> // TODO
			fail "unexpected lhs of function application"
where
	(f, args) = linearizeApp expr []

	linearizeApp (ExpApp f x) xs = linearizeApp f [x:xs]
	linearizeApp e xs = (e, xs)
simulator _ _ _ _ = // TODO
	pushBasicValue (BVInt 0) >>|
	buildCons (constructorLabel "" "INT") 1
//	= BasicValue !BasicValue
//	| Symbol !SymbolIdent
//	| Constructor !ConstructorIdent
//	| Case !Expression ![CaseAlternative]
//	| ExpApp !Expression !Expression