Hog v10.58.0
flow.tcl
Go to the documentation of this file.
1 
2 namespace eval Flow {
3 
4  # A top-level command may NOT claim any of these
5  # names/aliases, even if no flow currently uses them — this protects the core
6  # project workflow from being shadowed by a stray command.
7  variable ReservedFlowNames {
8  CREATE CREATEWORKFLOW WORKFLOW
9  SYNTHESIS SYNTH IMPLEMENTATION IMPL IMPLEMENT
10  SIMULATION SIMULATE BITSTREAM
11  }
12 
13  foreach _reserved_name $Flow::ReservedFlowNames {
14  Commands::AddNameGuard $_reserved_name \
15  "'$_reserved_name' is a reserved project-flow verb; a top-level command\
16  would shadow the same-named flow on every tool. Rename it, or reach\
17  the flow via 'tool <tool> flow $_reserved_name <project>'."
18  }
19  unset _reserved_name
20 
21 
22 
23  # Registers a flow for 'tool' (name/alias or namespace) as the command node <TOOL>.FLOW.<NAME>.
24  proc RegisterFlow {tool key raw_dict args} {
25  set tool_ns [expr {[namespace exists $tool] ? $tool : [Tools::ResolveAlias $tool]}]
26  if {$tool_ns eq ""} {
27  Msg Warning "Skipping flow '$key': unknown tool '$tool'"
28  return
29  }
30  set tool_key [string toupper [namespace tail $tool_ns]]
31  set tool_short [string tolower [namespace tail $tool_ns]]
32 
33  set norm {}
34  dict for {k v} $raw_dict { dict set norm [string tolower $k] $v }
35  set raw_dict $norm
36 
37  dict set raw_dict requires_proj true
38  dict set raw_dict ide $tool_short
39 
40  set flow_group "TOOL.$tool_key.FLOW"
41  if {[Commands::GetCommand $flow_group] eq {}} {
42  Commands::RegisterCommand $flow_group [dict create description \
43  "Flows provided by [namespace tail $tool_ns].\
44  Usage: $tool_short flow <flow> <project>"]
45  }
46  Commands::RegisterCommand "TOOL.$tool_key.FLOW.[string toupper $key]" $raw_dict {*}$args
47  }
48 
49  proc RegisterCustomFlows {flow_dir} {
50  if {![file isdirectory $flow_dir]} { return }
51  foreach f [lsort [glob -nocomplain -directory $flow_dir *.tcl]] {
52  Hog::SourceFile $f 1
53  }
54  }
55 
56 }
57 
58 
59 # File-backed store for whatever FlowControl::Produce records while a stage
60 # runs. One file per name, holding a bare Tcl dict
61 # stored in Project/<Project>/.hog/tokens/
62 # {
63 # producer <>
64 # describe <>
65 # mtime <>
66 # path <>
67 # file_mtime <>
68 # }
69 #
70 # path and file_mtime only exist if the token is backed by a file generated elsewhere
71 namespace eval Artifact {
72 
73  # "" when no project is current - callers must treat that as "no store".
74  proc _dir {} {
75  if {![CurrentProject::Exists project_name]} { return "" }
76  return [file join [CurrentProject::Get build_dir] .hog tokens]
77  }
78 
79  proc Write {name record} {
80  set dir [_dir]
81  if {$dir eq ""} {
82  Msg Warning "Artifact::Write $name: no project is current, nothing persisted"
83  return
84  }
85  file mkdir $dir
86  set fh [open [file join $dir "$name.tcl"] w]
87  puts $fh $record
88  close $fh
89  }
90 
91  proc Read {name} {
92  set dir [_dir]
93  if {$dir eq ""} { return {} }
94  set path [file join $dir "$name.tcl"]
95  if {![file exists $path]} { return {} }
96  set fh [open $path r]
97  set record [read $fh]
98  close $fh
99  return $record
100  }
101 
102  proc Exists {name} {
103  set dir [_dir]
104  if {$dir eq ""} { return 0 }
105  return [file exists [file join $dir "$name.tcl"]]
106  }
107 
108  proc Remove {name} {
109  set dir [_dir]
110  if {$dir eq ""} { return }
111  file delete -force [file join $dir "$name.tcl"]
112  }
113 }
114 
115 namespace eval FlowControl {
116  variable _state
117  if {![info exists _state]} {
118  set _state [tdict create \
119  stages [tlist create] \
120  status [tstr continue] \
121  reason [tstr ""] \
122  tokens [tlist create] \
123  stage [tstr ""] \
124  ]
125  }
126  variable _i 0
127 
128  proc _stages {} {
129  variable _state
130  set r {}
131  tlist foreachval s [tdict get $_state stages] { lappend r $s }
132  return $r
133  }
134  proc _set_stages {lst} {
135  variable _state
136  tdict set _state stages [tlist create {*}$lst]
137  }
138  proc _tokens {} {
139  variable _state
140  set r {}
141  tlist foreachval t [tdict get $_state tokens] { lappend r $t }
142  return $r
143  }
144 
145 
146  ################################################################################
147  # Stage Dependency Management
148  ################################################################################
149 
150  # True only while a real stage is running (inside Run's loop):
151  # gates artifacts from being stored without a current project or from within a stage
152  proc _stage_context {} {
153  variable _state
154  return [expr {[tdict getval $_state stage] ne "" && [CurrentProject::Exists project_name]}]
155  }
156 
157  # Creates a persitant artifact
158  # 'mtime' is call-time ([clock seconds])
159  # - used for cross token comparisions
160  # 'file_mtime' is the payload's own filesystem mtime at write time,
161  # - used only to detect an out of hog modification
162  proc _persist {name path} {
163  variable _state
164  set producer [StageProc [tdict getval $_state stage]]
165  if {$producer eq ""} { set producer [tdict getval $_state stage] }
166  set record [dict create producer $producer describe [Repo::Get Tag] mtime [clock seconds]]
167  if {$path ne ""} {
168  if {![file exists $path]} {
169  return -code error "Produce $name: no file at '$path' - the stage claimed to have\
170  written it, but it isn't there."
171  }
172  dict set record path $path
173  dict set record file_mtime [file mtime $path]
174  }
175  Artifact::Write $name $record
176  }
177 
178  # Walks the whole ancestor chain (each producer's declared 'requires'); Warns only;
179  proc _check_freshness {name {_seen {}}} {
180  if {$name in $_seen} { return }
181  lappend _seen $name
182  set record [Artifact::Read $name]
183  if {[dict size $record] == 0} { return }
184  set my_mtime [dict get $record mtime]
185  foreach producer_canon [Commands::ProducersOf $name] {
186  set pnode [Commands::GetCommand $producer_canon]
187  if {$pnode eq {}} continue
188  set upstream [tdict getobjor $pnode requires [tlist create]]
189  tlist foreachval up_name $upstream {
190  set up_record [Artifact::Read $up_name]
191  # A required artifact that was never produced is normal (conditional
192  # artifacts), not something to warn about.
193  if {[dict size $up_record] == 0} continue
194  if {[dict get $up_record mtime] > $my_mtime} {
195  Msg Warning "'$name' (produced by $producer_canon) is older than '$up_name',\
196  which it requires - '$up_name' was produced more recently. Consider rebuilding\
197  '$name'."
198  }
199  _check_freshness $up_name $_seen
200  }
201  }
202  }
203 
204  # Produce name ?path? - given a path, always persists (the artifact is the
205  # payload). Given none, it's a plain in-memory token that never persists on
206  # its own - a per-process fact (e.g. VIVADO_INITIALIZED) must not leak into
207  # a later process via a stale record.
208  proc Produce {name {path {}}} {
209  variable _state
210  set tok [_tokens]
211  if {$name ni $tok} {
212  lappend tok $name
213  tdict set _state tokens [tlist create {*}$tok]
214  }
215  if {$path ne "" && [_stage_context]} { _persist $name $path }
216  }
217 
218  # Opt-in for a bare token that's a durable fact about the filesystem, not
219  # the live interpreter, and should be checkable from a later process.
220  proc ProducePersistent {name} {
221  Produce $name
222  if {[_stage_context]} { _persist $name {} }
223  }
224 
225  # The membership check Require/RequireOr delegate to: in-memory list first,
226  # then - if stage-attributed - the on-disk store. A stale record (file
227  # gone, or its mtime changed since recorded) is dropped and reported absent.
228  proc Has {args} {
229  variable _state
230  set tok [_tokens]
231  set can_check_disk [_stage_context]
232  foreach token $args {
233  if {$token in $tok} { continue }
234  if {!$can_check_disk || ![Artifact::Exists $token]} { return 0 }
235  set record [Artifact::Read $token]
236  if {[dict exists $record path]} {
237  set path [dict get $record path]
238  if {![file exists $path]} {
239  Msg Warning "Artifact '$token' was recorded (by [dict get $record producer]) but its\
240  file is missing: $path - dropping the stale record."
241  Artifact::Remove $token
242  return 0
243  }
244  if {[dict exists $record file_mtime] && [file mtime $path] != [dict get $record file_mtime]} {
245  Msg Warning "Artifact '$token' at $path has changed on disk since it was recorded (by\
246  [dict get $record producer]) - dropping the stale record."
247  Artifact::Remove $token
248  return 0
249  }
250  }
251  _check_freshness $token
252  }
253  return 1
254  }
255 
256  proc Require {args} {
257  variable _state
258  foreach token $args {
259  if {[Has $token]} continue
260  set producers [Commands::ProducersOf $token]
261  set by [expr {[llength $producers] > 0 ? " (produced by [join $producers {, }])" : ""}]
262  tdict set _state status abort
263  tdict set _state reason "Required token '$token' not found$by while executing proc [lindex [info level -1] 0]. "
264 
265  set _flow_run_level -1
266  for {set i 1} {$i < [info level]} {incr i} {
267  if {[lindex [info level $i] 0] eq "FlowControl::Run"} {
268  set _flow_run_level $i
269  break
270  }
271  }
272 
273  if {$_flow_run_level < 0} {
274  Msg Warning "Require called outside of FlowControl::Run. Don't know what to do... returning..."
275  return
276  }
277  return -level [expr {[info level] - $_flow_run_level}]
278  }
279  }
280 
281  # If missing, run 'script' as if it were written directly at the call site
282  # - a bare 'return' inside it terminates the *calling stage*
283  proc RequireOr {token script} {
284  if {[Has $token]} { return }
285  set _code [catch {uplevel 1 $script} _res _opts]
286  if {$_code == 0} { return }
287  if {$_code != 2} { return -options $_opts $_res }
288 
289  set _flow_run_level -1
290  for {set i 1} {$i < [info level]} {incr i} {
291  if {[lindex [info level $i] 0] eq "FlowControl::Run"} {
292  set _flow_run_level $i
293  break
294  }
295  }
296  if {$_flow_run_level < 0} { return -options $_opts $_res }
297  return -level [expr {[info level] - $_flow_run_level}] $_res
298  }
299 
300  # On-disk path of a produced artifact - "" if none was recorded.
301  proc ArtifactPath {name} {
302  set record [Artifact::Read $name]
303  if {![dict exists $record path]} { return "" }
304  return [dict get $record path]
305  }
306 
307  proc ClearTokens {} {
308  variable _state
309  tdict set _state tokens [tlist create]
310  }
311 
312  ################################################################################
313  # Flow Control Management
314  ################################################################################
315 
316  proc AppendStages {new} {
317  set stages [_stages]
318  lappend stages {*}$new
319  _set_stages $stages
320  }
321 
322  proc InsertStagesAfter {anchor new} {
323  set stages [_stages]
324  set idx [lsearch -exact $stages $anchor]
325  if {$idx >= 0} {
326  set stages [linsert $stages [expr {$idx + 1}] {*}$new]
327  } else {
328  Msg Warning "FlowControl InsertStagesAfter: '$anchor' not found... skipping..."
329  }
330  _set_stages $stages
331  }
332 
333  proc InsertStagesBefore {anchor new} {
334  set stages [_stages]
335  set idx [lsearch -exact $stages $anchor]
336  if {$idx >= 0} {
337  set stages [linsert $stages $idx {*}$new]
338  } else {
339  Msg Warning "FlowControl InsertStagesBefore: '$anchor' not found... skipping..."
340  }
341  _set_stages $stages
342  }
343 
344  proc InsertStages {new} {
345  variable _i
346  set stages [_stages]
347  _set_stages [linsert $stages [expr {$_i + 1}] {*}$new]
348  }
349 
350  proc RemoveStages {to_remove} {
351  set stages [_stages]
352  foreach s $to_remove {
353  set idx [lsearch -exact $stages $s]
354  while {$idx >= 0} {
355  set stages [lreplace $stages $idx $idx]
356  set idx [lsearch -exact $stages $s]
357  }
358  }
359  _set_stages $stages
360  }
361 
362  proc ReplaceStage {old new_stages} {
363  set stages [_stages]
364  set idx [lsearch -exact $stages $old]
365  if {$idx >= 0} {
366  _set_stages [lreplace $stages $idx $idx {*}$new_stages]
367  } else {
368  Msg Warning "FlowControl ReplaceStage: '$old' not found"
369  }
370  }
371 
372  # Stage name -> fully-qualified proc. "::Foo::Bar" is used verbatim (cross-
373  # tool stages); a bare name resolves against the <TOOL>.STAGE node if
374  # registered (aliases, artifact contract), else a plain proc in the active
375  # tool's namespace. Returns "" when there is no active tool to resolve against.
376  proc StageProc {stage} {
377  if {[string match "::*" $stage]} { return $stage }
378  set tool_ns [ActiveTool::CurrentTool]
379  if {$tool_ns eq "" || $tool_ns eq "tclsh"} { return "" }
380  set node [Commands::GetCommand "TOOL.[string toupper [namespace tail $tool_ns]].STAGE.$stage"]
381  if {$node ne {}} { return [tdict getval $node script] }
382  return ${tool_ns}::${stage}
383  }
384 
385  proc ClearRemaining {} {
386  variable _i
387  _set_stages [lrange [_stages] 0 $_i]
388  }
389 
390  proc Exit {{reason ""}} {
391  variable _state
392  tdict set _state status [tstr exit]
393  tdict set _state reason [tstr $reason]
394 
395  set _flow_run_level -1
396  for {set i 1} {$i < [info level]} {incr i} {
397  if {[lindex [info level $i] 0] eq "FlowControl::Run"} {
398  set _flow_run_level $i
399  break
400  }
401  }
402 
403  if {$_flow_run_level < 0} {
404  Msg Warning "Require called outside of FlowControl::Run. Don't know what to do... returning..."
405  return
406  }
407 
408  return -level [expr {[info level] - $_flow_run_level}]
409  }
410 
411  proc Run {stages flow} {
412  variable _state
413  variable _i
414 
415  # Catches a flow with no stages, or every @ref unresolved (FlattenStages
416  # already warned) - otherwise the loop below just silently no-ops.
417  if {[llength $stages] == 0} {
418  Msg Error "Flow $flow has no stages to run - it either declares none, or\
419  every stage it @references failed to resolve."
420  return -code error "flow '$flow' has no stages"
421  }
422 
423  tdict set _state stages [tlist create {*}$stages]
424  tdict set _state status [tstr continue]
425  tdict set _state reason [tstr ""]
426  set _i 0
427 
428  Msg Info "Running flow $flow: $stages"
429 
430  while {$_i < [llength [_stages]]} {
431  set stage [lindex [_stages] $_i]
432  tdict set _state stage [tstr $stage]
433  set prev [_stages]
434 
435  Msg Info "Flow $flow: Running stage $stage..."
436 
437  # Resolved per iteration - a stage may insert more stages, or a tool
438  # may define its proc lazily.
439  set _proc [StageProc $stage]
440  if {$_proc eq "" || [info commands $_proc] eq ""} {
441  tdict set _state status [tstr abort]
442  tdict set _state reason [tstr "stage '$stage' has no implementation\
443  ([expr {$_proc eq "" ? "no active tool to resolve it against" : "no proc $_proc"}])"]
444  } else {
445  set _ns [namespace qualifiers $_proc]
446  if {[info commands ${_ns}::@PRE_$stage] ne ""} { ${_ns}::@PRE_$stage }
447  Msg Debug "Flow $flow: stage '$stage' -> $_proc"
448  $_proc
449  if {[info commands ${_ns}::@POST_$stage] ne ""} { ${_ns}::@POST_$stage }
450  }
451 
452  if {[_stages] ne $prev} {
453  Msg Info "Flow $flow updated: [_stages]"
454  }
455 
456  set status [tdict getval $_state status]
457  set reason [tdict getval $_state reason]
458  switch $status {
459  abort {
460  tdict set _state stage [tstr ""]
461  Msg Error "Flow $flow aborted at '$stage': $reason"
462  return -code error $reason
463  }
464  exit {
465  tdict set _state stage [tstr ""]
466  if {$reason ne ""} { Msg Info "Flow \[$flow:$stage\] exiting: $reason" }
467  return
468  }
469  }
470 
471  incr _i
472  }
473  # Cleared here too, so a call between flows doesn't inherit this stage.
474  tdict set _state stage [tstr ""]
475  }
476 
477 }