Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

lustrec / src / plugins / scopes / scopes.ml @ 70be4acf

History | View | Annotate | Download (14.1 KB)

1
open Lustre_types 
2
open Corelang 
3
open Machine_code_types
4
open Machine_code_common
5

    
6
(* (variable, node name, node instance) *)
7
type scope_t = (var_decl * string * string option) list * var_decl
8

    
9
(* Scope to string list *)
10
let scope_to_sl ((sl, v) : scope_t) : string list=
11
  List.fold_right (
12
    fun (v, nodename, _) accu -> 
13
      v.var_id :: nodename :: accu
14
  ) sl [v.var_id]
15

    
16

    
17
let rec compute_scopes ?(first=true) prog root_node : scope_t list =
18
  let compute_scopes = compute_scopes ~first:false in
19
  (* Format.eprintf "Compute scope of %s@." main_node; *)
20
  try
21
    let node =  get_node root_node prog in    
22
    let all_vars = node.node_inputs @ node.node_locals @  node.node_outputs in
23
    let local_vars = if first then
24
                       node.node_locals
25
                     else
26
                       node.node_inputs @ node.node_locals in
27
    let local_scopes = List.map (fun x -> [], x) local_vars  in
28
    let sub_scopes =
29
      let sub_nodes =
30
	List.fold_left 
31
	  (fun res s -> 
32
	    match s with 
33
	    | Eq ({ eq_rhs ={ expr_desc = Expr_appl (nodeid, _, _); _}; _ } as eq) -> 
34
	      (* Obtaining the var_del associated to the first var of eq_lhs *)
35
	      (
36
		try
37
		  let query v = v.var_id = List.hd eq.eq_lhs in
38
		  let vid = List.find query all_vars in
39
		  (nodeid, vid)::res
40
		with Not_found -> Format.eprintf "eq=%a@.local_vars=%a@." Printers.pp_node_eq eq (Utils.fprintf_list ~sep:"," Printers.pp_var) local_vars; assert false 
41
	      )
42
	    | Eq _ -> res
43
	    | _ -> assert false (* TODO deal with Automaton *)
44
	  ) [] node.node_stmts
45
      in
46
      List.map (fun (nodeid, vid) ->
47
	let scopes = compute_scopes prog nodeid in
48
	List.map (fun (sl,v) -> (vid, nodeid, None)::sl, v) scopes (* instances are not yet known, hence the None *)
49
      ) sub_nodes
50
    in
51
    local_scopes @ (List.flatten sub_scopes) 
52
  with Not_found ->  []
53

    
54

    
55
let print_scopes =
56
  Utils.fprintf_list ~sep:"@ " 
57
    (fun fmt ((_, v) as s) -> Format.fprintf fmt "%a: %a" 
58
      (Utils.fprintf_list ~sep:"." Format.pp_print_string )(scope_to_sl s)
59
      Types.print_ty v.var_type)
60
    
61
     
62
    
63

    
64
(* let print_path fmt p =  *)
65
(*   Utils.fprintf_list ~sep:"." (fun fmt (id, _) -> Format.pp_print_string fmt id) fmt p *)
66

    
67
let get_node_vdecl_of_name name node =
68
  try
69
    List.find 
70
      (fun v -> v.var_id = name) 
71
      (node.node_inputs  @ node.node_outputs  @ node.node_locals ) 
72
  with Not_found -> 
73
    Format.eprintf "Cannot find variable %s in node %s@." name node.node_id;
74
    assert false
75

    
76
let rec get_path prog machines node id_list accu =
77
  let get_path = get_path prog machines in
78
  match id_list, accu with
79
  | [flow], [] ->  (* Special treatment of first level flow: node is here main_node *)
80
     let flow_var = get_node_vdecl_of_name flow node in
81
     [], flow_var, node.node_id
82
  | [id], (_, last_node, _)::_ -> (* last item, it should denote a local
83
				       memory variable (local var, memory or input *)
84
     let id_vdecl = 
85
       get_node_vdecl_of_name id (get_node last_node prog) 
86
     in
87
     List.rev accu, id_vdecl, last_node
88
  | varid::nodename::id_list_tl, _ -> (
89
    let e_machine = get_machine node.node_id machines in 
90
    (* Format.eprintf "Looking for def %s in call %s in machine %a@."  *)
91
    (* 	varid nodename *)
92
    (* 	Machine_code.pp_machine e_machine; *)
93
    let find_var = (fun v -> v.var_id = varid) in
94
    let instance = 
95
      List.find 
96
	(fun i -> match get_instr_desc i with 
97
	          | MStep(p, o, _) -> List.exists find_var p 
98
	          | _ -> false
99
	) 
100
	e_machine.mstep.step_instrs 
101
    in
102
    try
103
      let variable, instance_node, instance_id = 
104
	match get_instr_desc instance with 
105
	| MStep(p, o, _) -> 
106
	   (* Format.eprintf "Looking for machine %s@.@?" o; *)
107
	   let o_fun, _ = List.assoc o e_machine.mcalls in
108
	   if node_name o_fun = nodename then
109
	     List.hd p, o_fun, o 
110
	   else 
111
	     assert false
112
	| _ -> assert false
113
      in
114
      let next_node = node_of_top instance_node in
115
      let accu = (variable, nodename, Some instance_id)::accu in
116
      (* Format.eprintf "Calling get path on %s@.@?" next_node.node_id; *)
117
      get_path next_node id_list_tl accu
118
    with Not_found -> Format.eprintf "toto@."; assert false
119
  )
120
  | _ -> assert false
121

    
122
    
123
let check_scope all_scopes  =
124
  let all_scopes_as_sl = List.map scope_to_sl all_scopes in
125
  fun prog machines main_node_name sl ->
126
  if not (List.mem sl all_scopes_as_sl) then (
127
    Format.eprintf "%s is an invalid scope.@." (String.concat "." sl);
128
    exit 1
129
  )
130
  else (
131
    (* Format.eprintf "@.@.Required path: %s@." (String.concat "." sl) ;  *)
132
    let main_node = get_node main_node_name prog in
133
    let path, flow, mid = get_path prog machines main_node sl [] in
134
    (* Format.eprintf "computed path: %a.%s@." print_path path flow.var_id; *)
135
    path, flow, mid
136
  )
137

    
138

    
139
                                                                
140
(* Build the two maps 
141
   - (scope_name, variable)
142
   - (machine_name, list of selected variables)
143
 *)
144
let check_scopes main_node_name prog machines all_scopes scopes =
145
  let check_scope = check_scope all_scopes prog machines in
146
  List.fold_left
147
    (fun (accu_sl, accu_m) sl ->
148
      let path, flow, mid = check_scope main_node_name sl in
149
      let accu_sl = (sl, (path, flow))::accu_sl in
150
      let accu_m =
151
        let flow_id = flow.var_id in
152
        if List.mem_assoc mid accu_m then
153
          (mid, flow_id::(List.assoc mid accu_m)) :: 
154
            (List.remove_assoc mid accu_m)
155
        else
156
          (mid, [flow_id])::accu_m
157
      in
158
      accu_sl, accu_m
159
    ) ([], []) scopes
160
  
161
  
162

    
163

    
164
let scope_var_name vid =  vid ^ "__scope"
165

    
166
(**********************************************************************)
167
(* The following three functions are used in the main function to print
168
   the value of the new memories, storing scopes values               *)
169
(**********************************************************************)
170

    
171
(* TODO: recuperer le type de "flow" et appeler le print correspondant 
172
   iterer sur path pour construire la suite des xx_mem._reg.yy_mem._reg......flow
173
par ex main_mem->n8->n9->_reg.flow
174
*)
175
let extract_scopes_defs scopes =
176
  let rec scope_path_name (path, flow) accu = 
177
    match path with 
178
    | [] -> accu ^ "_reg." ^ (scope_var_name flow.var_id), flow.var_type
179
    | (_, _, Some instance_id)::tl -> scope_path_name (tl, flow) ( accu ^ instance_id ^ "->" ) 
180
    | _ -> assert false
181
  in
182
  let scopes_vars = 
183
    List.map 
184
      (fun (sl, scope) -> 
185
	String.concat "." sl, scope_path_name scope "main_mem.") 
186
      scopes 
187
  in
188
  scopes_vars
189
  
190
let pp_scopes_files basename mname fmt scopes =
191
  let scopes_vars = extract_scopes_defs scopes in
192
  List.iteri (fun idx _ (* (id, (var, typ)) *) ->
193
      Format.fprintf fmt "FILE *f_out_scopes_%i;@ " (idx+1);
194
      (* we start from 1: in1, in2, ... *)
195
    Format.fprintf fmt
196
      "f_out_scopes_%i = fopen(\"%s_%s_simu.scope%i\", \"w\");@ "
197
      (idx+1) basename mname (idx+1);
198
  ) scopes_vars
199

    
200
  
201
let pp_scopes fmt scopes = 
202
  let scopes_vars = extract_scopes_defs scopes in
203
  List.iteri (fun idx (id, (var, typ)) ->
204
    Format.fprintf fmt "@ %t;" 
205
      (fun fmt -> C_backend_common.print_put_var fmt
206
                    ("_scopes_" ^ string_of_int (idx+1))
207
                    id (*var*) typ var)
208
  ) scopes_vars
209

    
210
(**********************************************************************)
211
                        
212
let update_machine main_node machine scopes =
213
  let stateassign (vdecl_mem, vdecl_orig) =
214
    mkinstr 
215
    (MStateAssign (vdecl_mem, mk_val (Var vdecl_orig) vdecl_orig.var_type))
216
  in
217
  let selection =
218
    (* We only register inputs for non root node *)
219
    (if machine.mname.node_id = main_node then
220
      []
221
    else
222
      machine.mstep.step_inputs
223
    )
224
    (* @ machine.mstep.step_outputs   *)
225
    @ machine.mmemory 
226
    @ machine.mstep.step_locals
227
  in
228
  let selection = List.filter (fun v -> List.exists (fun vid -> vid = v.var_id) scopes) selection in
229
  let new_mems = List.map (fun v ->
230
                     (* We could copy the variable but then we need to update its type 
231
                        let new_v = copy_var_decl v in
232
                      *)
233
                     let new_v = { v with var_id = scope_var_name v.var_id }  in
234
                     new_v, v
235
                   ) selection
236
  in
237
  { machine with
238
    mmemory = machine.mmemory @ (List.map fst new_mems);
239
    mstep = { 
240
      machine.mstep with 
241
        step_instrs = machine.mstep.step_instrs
242
        @ (mkinstr (MComment "Registering all flows"))::(List.map stateassign new_mems)
243
          
244
    }
245
  }
246
    
247
let rec is_valid_path path nodename prog machines =
248
  let nodescopes = compute_scopes prog nodename in
249
  let m = get_machine nodename machines in
250
  match path with
251
  | [] -> assert false
252
  | [vid] -> let res = List.exists (fun v -> v.var_id = vid) (m.mmemory @ m.mstep.step_inputs @ m.mstep.step_locals) in
253
	     (* if not res then  *)
254
	     (* 	 Format.eprintf "Variable %s cannot be found in machine %s@.Local vars are %a@." vid m.mname.node_id *)
255
	     (* 	   (Utils.fprintf_list ~sep:", " Printers.pp_var) (m.mmemory @ m.mstep.step_inputs @ m.mstep.step_locals) *)
256
	     (* ; *)
257
	     res
258
	     
259
  | inst::nodename::path' -> (* We use the scopes computed on the prog artifact *)
260
     (* Format.eprintf "Path is %a@ Local scopes: @[<v>%a@ @]@."  *)
261
     (* 	(Utils.fprintf_list ~sep:"." Format.pp_print_string) path *)
262
     (* 	(Utils.fprintf_list ~sep:";@ " *)
263
     (* 	   (fun fmt scope ->  *)
264
     (* 	     Utils.fprintf_list ~sep:"." Format.pp_print_string fmt (scope_to_sl scope)) *)
265
     (* 	)  *)
266
     (* 	nodescopes; *)
267
     if List.mem path (List.map scope_to_sl nodescopes) then (
268
       (* Format.eprintf "Valid local path, checking underneath@."; *)
269
       is_valid_path path' nodename prog machines
270
     )
271
     else
272
       false
273

    
274
      (* let instok = List.exists (fun (inst', node) -> inst' = inst) m.minstances in *)
275
      (* if not instok then Format.eprintf "inst = %s@." inst; *)
276
      (* instok &&  *)
277
      (* let instnode = fst (snd (List.find (fun (inst', node) -> inst' = inst) m.minstances)) in *)
278
      (* is_valid_path path' (Corelang.node_of_top instnode).node_id prog machines *)
279

    
280

    
281

    
282
(****************************************************)
283
      
284
let scopes_def : string list list ref = ref []
285
let inputs = ref []
286

    
287
let option_show_scopes = ref false
288
let option_scopes = ref false
289
let option_all_scopes = ref false
290
(* let option_mems_scopes = ref false 
291
 * let option_input_scopes = ref false *)
292

    
293
let scopes_map : (Lustre_types.ident list  * scope_t) list ref  = ref []
294
      
295
let process_scopes main_node prog machines =
296
  let all_scopes = compute_scopes prog !Options.main_node in
297
  let selected_scopes = if !option_all_scopes then
298
	                  List.map (fun s -> scope_to_sl s) all_scopes
299
                        else
300
	                  !scopes_def
301
  in
302
  (* Making sure all scopes are defined and were not removed by various
303
       optmizationq *)
304
  let selected_scopes = 
305
    List.filter 
306
      (fun sl -> 
307
	let res = is_valid_path sl main_node prog machines in
308
	if not res then
309
	  Format.eprintf "Scope %a is cancelled due to variable removal@." (Utils.fprintf_list ~sep:"." Format.pp_print_string) sl; 
310
	res
311
      ) 
312
      selected_scopes 
313
  in
314
  let scopes_map', machines_scopes = check_scopes main_node prog machines all_scopes selected_scopes in
315
  scopes_map := scopes_map';
316
  (* Each machine is updated with fresh memories and declared as stateful  *)
317
  let machines = List.map (fun m ->
318
                     let mid = m.mname.node_id in
319
                     if List.mem_assoc mid machines_scopes then
320
                       let machine_scopes = List.assoc mid machines_scopes in
321
                       update_machine main_node m machine_scopes
322
                     else
323
                       m) machines in
324
  machines
325

    
326
let activate () = 
327
  option_scopes := true;
328
  Options.optimization := 0; (* no optimization *)
329
  ()
330
  
331
let register_scopes s = 
332
  activate ();
333
  option_all_scopes:=false; 
334
  let scope_list = Str.split (Str.regexp ", *") s in
335
  let scope_list = List.map (fun scope -> Str.split (Str.regexp "\\.") scope) scope_list in
336
  scopes_def := scope_list
337

    
338
let register_inputs s = 
339
  activate ();
340
  let input_list = Str.split (Str.regexp "[;]") s in
341
  let input_list = List.map (fun s -> match Str.split (Str.regexp "=") s with | [v;e] -> v, e | _ -> raise (Invalid_argument ("Input list error: " ^ s))) input_list in
342
  let input_list = List.map (fun (v, e) -> v, Str.split (Str.regexp "[;]") e) input_list in
343
  inputs := input_list
344

    
345
let register_all_scopes () =
346
  activate ();
347
  option_all_scopes:= true
348
  
349
module Plugin : (
350
  sig
351
    include PluginType.PluginType
352
    val show_scopes: unit -> bool
353
    end) =
354
struct
355
  let name = "scopes"
356
  let is_active () = 
357
    !option_scopes || !option_show_scopes || !option_all_scopes
358
  (* || !option_mem_scopes || !option_input_scopes *)
359
      
360
  let show_scopes () = 
361
    !option_show_scopes && (
362
      Compiler_common.check_main ();
363
      true)
364

    
365
  let options = [
366
    "-select", Arg.String register_scopes, "specifies which variables to log";
367
    "-input", Arg.String register_inputs, "specifies the simulation input";
368
    "-show-possible-scopes", Arg.Set option_show_scopes, "list possible variables to log";
369
    "-select-all", Arg.Unit register_all_scopes, "select all possible variables to log";
370
    (* "-select-mems", Arg.Set option_mems_scopes, "select all memory variables to log";
371
     * "-select-inputs", Arg.Set option_input_scopes, "select all input variables to log"; *)
372
  ]
373

    
374
  let activate = activate
375

    
376
  let check_force_stateful () = is_active()
377

    
378
  let refine_machine_code prog machine_code =
379
    if show_scopes () then
380
      begin
381
	let all_scopes = compute_scopes prog !Options.main_node in
382
      (* Printing scopes *)
383
      if !Options.verbose_level >= 1 then
384
	Format.printf "Possible scopes are:@   ";
385
	Format.printf "@[<v>%a@ @]@.@?" print_scopes all_scopes;
386
	exit 0
387
      end;
388
    if is_active () then
389
      process_scopes !Options.main_node prog machine_code
390
    else
391
      machine_code
392
	
393

    
394

    
395
  let c_backend_main_loop_body_suffix fmt () =
396
    if is_active () then
397
      begin
398
	Format.fprintf fmt "@ %a" pp_scopes !scopes_map 
399
      end  
400

    
401
  let c_backend_main_loop_body_prefix basename mname fmt () =
402
    if is_active () then
403
      begin
404
	Format.fprintf fmt "@ %a" (pp_scopes_files basename mname) !scopes_map 
405
      end  
406

    
407

    
408
end
409
    
410
(* Local Variables: *)
411
(* compile-command:"make -C ../.." *)
412
(* End: *)