Hog v10.58.0
commands.tcl
Go to the documentation of this file.
1 namespace eval Commands {
2 
3  # alias_index: qualified alias -> canonical path (plain dict, string -> string)
4  # Top-level canonical: "VIVADO" -> "VIVADO"
5  # Top-level alias: "VI" -> "VIVADO"
6  # Scoped canonical: "VIVADO.FLOW" -> "VIVADO.FLOW"
7  # Scoped alias: "VIVADO.C" -> "VIVADO.FLOW.CREATE"
8  #
9  # nodes: canonical path -> Node tdict
10 
11  variable alias_index {}
12  variable nodes {}
13  variable name_guards {}
14 
15 
16  # Current Node executing:
17  variable _current_node {}
18  variable _current_path {}
19 
20  proc CurrentNode {} {
21  variable _current_node
22  return $_current_node
23  }
24 
25  proc CurrentPath {} {
26  variable _current_path
27  return $_current_path
28  }
29 
30  # Positional arguments of the running command as a plain Tcl list:
31  # every non-flag token left over after the command path resolved (see
32  # ParseArgv). Index 0 is the project by convention, also mirrored as
33  # Launcher project/project_name.
34  #
35  # Read these instead of $::argv: an inline Hog::Do has no private argv, and
36  # argv indices shift whenever the command path changes length.
37  proc Args {} {
38  set _a [Launcher::GetOr args {}]
39  if {$_a eq {}} { return {} }
40  return [tnative $_a]
41  }
42 
43  # Safe indexed accessor - out-of-range yields $default rather than an error.
44  proc Arg {index {default ""}} {
45  set _v [lindex [Args] $index]
46  if {$_v eq ""} { return $default }
47  return $_v
48  }
49 
50  # CommandNode
51  # Represents anything that can be run from cmdline, such as tool, flow, stage, command
52  # Distinguished mostly by looking at the nodes key:
53  # TOOL.<> is a tool; TOOL.<>.FLOW.<> is a flow; TOOL.<>.STAGE.<> is a stage,
54  # everything else a command
55  namespace eval Node {
56 
57  # Field table: {name type default}
58  #
59  # 'script' and 'stages' are the two mutually exclusive action fields; stages
60  # win if an author sets both (Lint reports it).
61  #
62  # 'produces'/'requires' are the per-stage artifact contract (handled by flowcontrol)
63  variable _fields {
64  { name str "" }
65  { aliases list "" }
66  { description str "" }
67  { help str "" }
68  { script str "" }
69  { stages list {} }
70  { produces list {} }
71  { requires list {} }
72  { options list {} }
73  { ide str tclsh }
74  { requires_proj bool 0 }
75  { api bool 0 }
76  { passthrough bool 0 }
77  }
78 
79 
80  proc New {key raw_dict} {
81  variable _fields
82  set norm [dict create]
83  dict for {k v} $raw_dict { dict set norm [string tolower $k] $v }
84  set raw_dict $norm
85 
86  set node [tdict create]
87  foreach field $_fields {
88  lassign $field fname ftype fdefault
89 
90  switch -- $fname {
91  name {
92  set name [expr {
93  [dict exists $raw_dict name] && [dict get $raw_dict name] ne ""
94  ? [string toupper [string trim [dict get $raw_dict name]]] : [string toupper $key]
95  }]
96  if {$name eq ""} { error "Command has no name" }
97  if {[string first "." $name] >= 0} { error "Command '$name': name may not contain '.'" }
98  tdict set node name [tstr $name]
99  continue
100  }
101 
102  aliases {
103  set aliases {}
104  foreach a [expr {[dict exists $raw_dict aliases] ? [dict get $raw_dict aliases] : {}}] {
105  set au [string toupper $a]
106  if {$au ne "" && [string first "." $au] < 0 && $au ne [tdict getval $node name] && $au ni $aliases} { lappend aliases $au }
107  }
108  tdict set node aliases [tlist create {*}$aliases]
109  continue
110  }
111  }
112 
113  if {[dict exists $raw_dict $fname] && [dict get $raw_dict $fname] ne ""} {
114  set v [dict get $raw_dict $fname]
115  } else {
116  set v $fdefault
117  }
118  switch -- $ftype {
119  str { tdict set node $fname [tstr [string trim $v]] }
120  bool { tdict set node $fname [tbool $v] }
121  list { tdict set node $fname [tlist create {*}$v] }
122  }
123  }
124 
125  return $node
126  }
127 
128  proc HasStages {node} { return [expr {[tlist length [tdict getobjor $node stages [tlist create]]] > 0}] }
129  proc IsRunnable {node} { return [expr {[tdict getval $node script] ne "" || [HasStages $node]}] }
130  proc RequiresProj {node} { return [tdict getval $node requires_proj] }
131 
132  proc IsTool {node} { return [regexp {^TOOL\.[^.]+$} [tdict getor $node canon ""]] }
133  proc IsFlow {node} { return [regexp {^TOOL\.[^.]+\.FLOW\.[^.]+$} [tdict getor $node canon ""]] }
134  proc IsStage {node} { return [regexp {^TOOL\.[^.]+\.STAGE\.[^.]+$} [tdict getor $node canon ""]] }
135 
136  # Resolve an "@<FLOW>" stage reference against the node's siblings, so a flow
137  # references a peer flow by bare name ("@CREATE", not "VIVADO.FLOW.CREATE").
138  # Goes through GetCommand, so the reference may be an alias.
139  proc _sibling {node ref} {
140  set canon [tdict getval $node canon]
141  set idx [string last "." $canon]
142  if {$idx < 0} { return {} }
143  return [::Commands::GetCommand "[string range $canon 0 [expr {$idx-1}]].$ref"]
144  }
145 
146  # Expand a node's stage list, splicing "@<FLOW>" references in place.
147  #
148  # Deliberately lazy - resolved per run/help rather than snapshotted at
149  # registration, so a flow may reference one that registers later in the file
150  # (or in another file entirely).
151  proc FlattenStages {node} { return [dict get [_walk_stages $node] stages] }
152 
153 
154  # The traversal behind both FlattenStages and Commands::Lint. Returns:
155  # stages -> the flattened stage list
156  # badrefs -> {{owner_canon @ref} ...} a reference naming no sibling flow
157  # cycles -> {{owner_canon chain} ...} a reference that closes a loop
158  #
159  # Each problem carries the canon of the node that *declared* the offending reference
160  proc _walk_stages {node {_seen {}}} {
161  set canon [tdict getval $node canon]
162  if {$canon in $_seen} {
163  return [dict create stages {} badrefs {} cycles [list [list $canon $_seen]]]
164  }
165  lappend _seen $canon
166  set stages {}
167  set badrefs {}
168  set cycles {}
169  tlist foreachval s [tdict getobjor $node stages [tlist create]] {
170  if {![string match "@*" $s]} { lappend stages $s; continue }
171  set rnode [_sibling $node [string range $s 1 end]]
172  if {$rnode eq {}} { lappend badrefs [list $canon $s]; continue }
173  set sub [_walk_stages $rnode $_seen]
174  lappend stages {*}[dict get $sub stages]
175  lappend badrefs {*}[dict get $sub badrefs]
176  lappend cycles {*}[dict get $sub cycles]
177  }
178  return [dict create stages $stages badrefs $badrefs cycles $cycles]
179  }
180 
181  # Options of a node, plus every flow it @references, plus every bare stage it names
182  proc FlattenOptions {node {_seen {}}} {
183  set canon [tdict getval $node canon]
184  if {$canon in $_seen} { return {} }
185  lappend _seen $canon
186 
187  # Self first, then each @referenced flow, then each bare stage's own options.
188  set specs {}
189  tlist foreachval o [tdict getobjor $node options [tlist create]] { lappend specs $o }
190  tlist foreachval s [tdict getobjor $node stages [tlist create]] {
191  if {[string match "@*" $s]} {
192  set rnode [_sibling $node [string range $s 1 end]]
193  if {$rnode ne {}} { lappend specs {*}[FlattenOptions $rnode $_seen] }
194  } else {
195  set snode [::Commands::GetCommand "TOOL.[::Commands::_tool_of $canon].STAGE.$s"]
196  if {$snode ne {}} {
197  tlist foreachval o [tdict getobjor $snode options [tlist create]] { lappend specs $o }
198  }
199  }
200  }
201 
202  # First spec for an option name wins, so a flow overrides an inherited default.
203  set result {}
204  set names {}
205  foreach spec $specs {
206  set n [lindex $spec 0]
207  if {$n ni $names} { lappend result $spec; lappend names $n }
208  }
209  return $result
210  }
211 
212  proc Run {node {path {}}} {
213  if {![IsRunnable $node]} {
214  error "Cannot run '[tdict getval $node name]' - no script or stages defined"
215  }
216  set _prev_node ${::Commands::_current_node}
217  set _prev_path ${::Commands::_current_path}
218  set ::Commands::_current_node $node
219  set ::Commands::_current_path $path
220 
221  # Stages and Flows must run through FlowControl
222  if {[HasStages $node]} {
223  set _code [catch {FlowControl::Run [FlattenStages $node] [tdict getval $node name]} _res _opts]
224  } elseif {[IsStage $node]} {
225  set _name [tdict getval $node name]
226  set _code [catch {FlowControl::Run [list $_name] $_name} _res _opts]
227  } else {
228  set _code [catch {uplevel #0 [tdict getval $node script]} _res _opts]
229  }
230  set ::Commands::_current_node $_prev_node
231  set ::Commands::_current_path $_prev_path
232  return -options $_opts $_res
233  }
234  }
235 
236  # Register a single reserved name and the reason it's rejected
237  proc AddNameGuard {name reason} {
238  variable name_guards
239  dict set name_guards [string toupper $name] $reason
240  }
241 
242  proc _veto {name} {
243  variable name_guards
244  set key [string toupper $name]
245  if {[dict exists $name_guards $key]} { return [dict get $name_guards $key] }
246  return ""
247  }
248 
249  # Resolves any alias - bare ("VIVADO") or dotted ("VIVADO.FLOW.CREATE") - to
250  # its real canon.
251  #
252  # Walks the dotted commande tree, resolving aliases at each level
253  # 'VIVADO.FLOW.C'
254  # 'VIVADO' -> TOOL.VIVADO
255  # 'TOOL.VIVADO.FLOW' -> TOOL.VIVADO.FLOW
256  # 'TOOL.VIVADO.FLOW.C' -> TOOL.VIVADO.FLOW.CREATE
257  proc _canon {alias} {
258  variable alias_index
259  if {$alias eq ""} { return "" }
260  set key [string toupper $alias]
261  if {[dict exists $alias_index $key]} { return [dict get $alias_index $key] }
262  set parts [split $key "."]
263  if {[llength $parts] < 2} { return "" }
264  set canon [_canon [lindex $parts 0]]
265  if {$canon eq ""} { return "" }
266  foreach part [lrange $parts 1 end] {
267  set canon [_canon_child $canon $part]
268  if {$canon eq ""} { return "" }
269  }
270  return $canon
271  }
272 
273  proc _canon_child {parent token} {
274  variable alias_index
275  set key "$parent.[string toupper $token]"
276  if {[dict exists $alias_index $key]} { return [dict get $alias_index $key] }
277  return ""
278  }
279 
280  # Registration internals
281 
282  # Registers one node: assigns its canonical path, indexes it and its aliases.
283  # node: the built Node tdict (from Node::New) to register
284  # parent: the parent's own canon, or "" for top-level
285  # is_custom: set when sourcing custom commands
286  # source: file where this was generated from
287  proc _register_at {node parent is_custom source} {
288  variable alias_index
289  variable nodes
290 
291  set bare_name [tdict getval $node name]
292  set canon [expr {$parent eq "" ? $bare_name : "$parent.$bare_name"}]
293  tdict set node custom [tbool $is_custom]
294  tdict set node canon [tstr $canon]
295  tdict set node source_path [tstr $source]
296 
297  set name $bare_name
298  set aliases {}
299  tlist foreachval a [tdict getval $node aliases] { lappend aliases $a }
300 
301  dict set nodes $canon $node
302 
303  dict set alias_index $canon $canon
304  foreach a [list $name {*}$aliases] {
305  set key [expr {$parent eq "" ? $a : "$parent.$a"}]
306  if {$key ne $canon && ![dict exists $alias_index $key]} {
307  dict set alias_index $key $canon
308  }
309  }
310  }
311 
312  # Direct children of a path, derived from nodes' keys
313  proc GetChildren {canon} {
314  variable nodes
315  set prefix "$canon."
316  set plen [string length $prefix]
317  set result {}
318  dict for {k v} $nodes {
319  if {[string equal -length $plen $prefix $k] && [string first "." $k $plen] < 0} {
320  lappend result $k
321  }
322  }
323  return $result
324  }
325 
326  proc _deregister {canon} {
327  variable alias_index
328  variable nodes
329 
330  if {![dict exists $nodes $canon]} { return }
331 
332  foreach child [GetChildren $canon] { _deregister $child }
333 
334  foreach k [dict keys [dict filter $alias_index value $canon]] {
335  dict unset alias_index $k
336  }
337 
338  dict unset nodes $canon
339  }
340 
341  # Public registration API
342 
343  # Registers 'key' at the top level, or under an existing node if 'key' is dotted (e.g. "PARENT.CHILD").
344  proc RegisterCommand {key raw_dict args} {
345  variable alias_index
346  variable nodes
347  set is_custom [expr {"-custom" in $args}]
348  set source ""
349  if {[set _si [lsearch -exact $args -source]] >= 0} { set source [lindex $args [expr {$_si+1}]] }
350 
351  set idx [string last "." $key]
352  set bare_key [expr {$idx < 0 ? $key : [string range $key [expr {$idx+1}] end]}]
353  set parent ""
354  if {$idx >= 0} {
355  set parent [_canon [string toupper [string range $key 0 [expr {$idx-1}]]]]
356  if {$parent eq "" || ![dict exists $nodes $parent]} {
357  Msg Warning "RegisterCommand: parent for '$key' not found"
358  return
359  }
360  set parent_node [dict get $nodes $parent]
361  if {"-custom" ni $args} { set is_custom [tobj value [tdict get $parent_node custom]] }
362  if {$source eq ""} { set source [tdict getval $parent_node source_path] }
363  } else {
364  # Top-level: fall back to Hog::_loading_* context
365  if {"-custom" ni $args} { set is_custom [set ::Hog::_loading_custom] }
366  if {$source eq ""} { set source [set ::Hog::_loading_source] }
367  }
368 
369  if {[catch {Node::New $bare_key $raw_dict} node]} {
370  Msg Warning "Skipping command '$key': $node"
371  return
372  }
373  set name [tdict getval $node name]
374 
375  # Name guards are top-level only - they stop a stray command shadowing a flow, not nested paths.
376  if {$parent eq "" && [set why [_veto $name]] ne ""} {
377  Msg Warning "Command '$name' rejected: $why"
378  return
379  }
380  set existing [expr {$parent eq "" ? [_canon $name] : [_canon_child $parent $name]}]
381  if {$existing ne ""} {
382  Msg Warning "Command '$name' already exists, skipping"
383  return
384  }
385 
386  # Filter conflicting aliases before registering (scoped to the same parent)
387  set clean {}
388  tlist foreachval a [tdict getval $node aliases] {
389  set a_existing [expr {$parent eq "" ? [_canon $a] : [_canon_child $parent $a]}]
390  if {$parent eq "" && [set why [_veto $a]] ne ""} {
391  Msg Warning "Alias '$a' for '$name' rejected: $why"
392  } elseif {$a_existing ne ""} {
393  Msg Warning "Alias '$a' for '$name' already exists, skipping alias"
394  } else {
395  lappend clean $a
396  }
397  }
398  tdict set node aliases [tlist create {*}$clean]
399 
400  _register_at $node $parent $is_custom $source
401  }
402 
403  # Used to manually register aliases in the aliase dict;
404  # allows us to register alias <TOOL> -> TOOL.<TOOL>
405  proc AddAlias {alias canon} {
406  variable alias_index
407  variable nodes
408  if {![dict exists $nodes $canon]} {
409  Msg Warning "AddAlias: '$canon' does not exist, skipping alias '$alias'"
410  return
411  }
412  set key [string toupper $alias]
413  if {[set why [_veto $key]] ne ""} {
414  Msg Warning "Alias '$alias' for '$canon' rejected: $why"
415  return
416  }
417  if {[dict exists $alias_index $key]} {
418  if {[dict get $alias_index $key] ne $canon} {
419  Msg Warning "Alias '$alias' already exists, skipping (wanted for '$canon')"
420  }
421  return
422  }
423  dict set alias_index $key $canon
424  }
425 
426  # Sources a command file, which must call RegisterCommand;
427  # sets the custom/source context so users don't have to
428  proc RegisterCommandsFile {f args} {
429  Hog::SourceFile $f [expr {"-custom" in $args}]
430  }
431 
432  proc RegisterCommandsDir {dir args} {
433  if {![file isdirectory $dir]} { return }
434  foreach f [lsort [glob -nocomplain -directory $dir *.tcl]] {
435  RegisterCommandsFile $f {*}$args
436  }
437  foreach sub [lsort [glob -nocomplain -type d -directory $dir *]] {
438  set name [file tail $sub]
439  set entry [file join $sub "$name.tcl"]
440  if {![file exists $entry]} { set entry [file join $sub "main.tcl"] }
441  if {![file exists $entry]} {
442  Msg Warning "Command directory '$name' has no '$name.tcl' or 'main.tcl', skipping"
443  continue
444  }
445  RegisterCommandsFile $entry {*}$args
446  }
447  }
448 
449 
450  # Replace a node's content in-place (including aliases);
451  proc UpdateCommand {key new_dict} {
452  variable nodes
453  variable alias_index
454  set canon [string toupper $key]
455  if {![dict exists $nodes $canon]} { set canon [_canon $canon] }
456  if {$canon eq "" || ![dict exists $nodes $canon]} {
457  Msg Warning "UpdateCommand: '$key' not found - use RegisterCommand to add new commands"
458  return
459  }
460  set idx [string last "." $canon]
461  set bare [expr {$idx < 0 ? $canon : [string range $canon [expr {$idx+1}] end]}]
462  set parent [expr {$idx < 0 ? "" : [string range $canon 0 [expr {$idx-1}]]}]
463  if {[catch {Node::New $bare $new_dict} node]} {
464  Msg Warning "UpdateCommand: skipping '$canon': $node"
465  return
466  }
467  set existing [dict get $nodes $canon]
468  tdict set node custom [tdict get $existing custom]
469  tdict set node canon [tdict get $existing canon]
470  tdict set node source_path [tdict get $existing source_path]
471 
472  # Drop this node's old scoped aliases, then re-add whatever the new dict specifies.
473  foreach k [dict keys $alias_index] {
474  if {$k ne $canon && [dict get $alias_index $k] eq $canon} { dict unset alias_index $k }
475  }
476  set clean {}
477  tlist foreachval a [tdict getval $node aliases] {
478  set a_existing [expr {$parent eq "" ? [_canon $a] : [_canon_child $parent $a]}]
479  if {[set why [_veto $a]] ne ""} {
480  Msg Warning "Alias '$a' for '$bare' rejected: $why"
481  } elseif {$a_existing ne "" && $a_existing ne $canon} {
482  Msg Warning "Alias '$a' for '$bare' already exists, skipping alias"
483  } else {
484  lappend clean $a
485  }
486  }
487  tdict set node aliases [tlist create {*}$clean]
488  foreach a $clean {
489  set a_key [expr {$parent eq "" ? $a : "$parent.$a"}]
490  if {$a_key ne $canon} { dict set alias_index $a_key $canon }
491  }
492 
493  dict set nodes $canon $node
494  }
495 
496  # Remove a top-level command and recursively deregister everything under it.
497  proc RemoveCommand {key} {
498  variable nodes
499  set canon [string toupper $key]
500  if {![dict exists $nodes $canon]} { set canon [_canon $canon] }
501  if {$canon eq "" || [string first "." $canon] >= 0 || ![dict exists $nodes $canon]} {
502  Msg Warning "RemoveCommand: '$key' not found"
503  return
504  }
505  _deregister $canon
506  }
507 
508 
509  proc AliasExists {alias} {
510  variable alias_index
511  return [dict exists $alias_index [string toupper $alias]]
512  }
513 
514  proc Run {cmd} {
515  set canon [_canon [string toupper $cmd]]
516  if {$canon eq ""} { Msg Error "Unknown command '$cmd'"; return }
517  variable nodes
518  Node::Run [dict get $nodes $canon]
519  }
520 
521  proc GetCommand {cmd} {
522  variable nodes
523  set canon [_canon [string toupper $cmd]]
524  if {$canon eq "" || ![dict exists $nodes $canon]} { return {} }
525  return [dict get $nodes $canon]
526  }
527 
528  # The bare tool name a canon lives under
529  proc _tool_of {canon} {
530  if {[regexp {^TOOL\.([^.]+)\.} $canon -> bare]} { return $bare }
531  return ""
532  }
533 
534  # Every flow (in the same tool) whose own, unflattened 'stages' list names this stage directly - not via @ref
535  proc _flows_naming_stage {node} {
536  set canon [tdict getval $node canon]
537  if {![Node::IsStage $node]} { return {} }
538  set stage_name [string toupper [tdict getval $node name]]
539  set result {}
540  foreach flow_canon [GetChildren "TOOL.[_tool_of $canon].FLOW"] {
541  set fnode [GetCommand $flow_canon]
542  if {$fnode eq {}} continue
543  tlist foreachval s [tdict getobjor $fnode stages [tlist create]] {
544  if {[string match "@*" $s]} continue
545  if {[string toupper $s] eq $stage_name} { lappend result $fnode; break }
546  }
547  }
548  return $result
549  }
550 
551  # Accepts either a command name string or a resolved tdict node.
552  # A node with stages inherits the options of every flow it @references, so this
553  # flattens rather than reading the raw field - both RunRequest's cmdline parse
554  # and the help page need the inherited set. A stage node has no @refs of its
555  # own, but may still need options only a referencing flow declared
556  proc GetCommandOptions {cmd_or_node} {
557  if {[tobj isobj $cmd_or_node] && [tobj type $cmd_or_node] eq "Dict"} {
558  set node $cmd_or_node
559  } else {
560  set node [GetCommand $cmd_or_node]
561  }
562  if {$node eq {}} { return {} }
563  if {[Node::HasStages $node]} { return [Node::FlattenOptions $node] }
564 
565  set result {}
566  set names {}
567  tlist foreachval o [tdict get $node options] {
568  set n [lindex $o 0]
569  if {$n ni $names} { lappend result $o; lappend names $n }
570  }
571  foreach fnode [_flows_naming_stage $node] {
572  foreach spec [Node::FlattenOptions $fnode] {
573  set n [lindex $spec 0]
574  if {$n ni $names} { lappend result $spec; lappend names $n }
575  }
576  }
577  return $result
578  }
579 
580  # Returns canon -> tdict node for every command up to 'depth' levels deep
581  # (1 = top-level only, 2 = top-level + their direct children, etc).
582  proc GetCommands {{depth 1}} {
583  variable nodes
584  set result {}
585  dict for {canon node} $nodes {
586  if {[llength [split $canon "."]] <= $depth} { dict set result $canon $node }
587  }
588  return $result
589  }
590 
591  # A stage name -> the proc that should implement it, resolved against the tool that *owns* the node.
592  proc _owning_stage_proc {canon stage} {
593  if {[string match "::*" $stage]} { return $stage }
594  set tool_bare [_tool_of $canon]
595  set snode [GetCommand "TOOL.$tool_bare.STAGE.$stage"]
596  if {$snode ne {}} { return [tdict getval $snode script] }
597  set tool_ns [Tools::ResolveAlias [string tolower $tool_bare]]
598  if {$tool_ns eq ""} { return "" }
599  return ${tool_ns}::${stage}
600  }
601 
602  # Reports declarations that contradict themselves, across the whole tree,
603  # Warns and changes nothing; HOG_STRICT=1 makes it fail the run instead
604  #
605  # This is a *report*, not a constraint. Every check here answers "did you mean this?"
606  #
607  # Several of these conditions are also caught at run time i.e.:
608  # FlowControl::Run refuses an empty stage list
609  # StageProc aborts on a missing proc
610  #
611  # Returns the problem count.
612  proc Lint {} {
613  variable nodes
614  set problems {}
615  set seen_cycles {}
616 
617  dict for {canon node} $nodes {
618  set children [GetChildren $canon]
619  set has_script [expr {[tdict getval $node script] ne ""}]
620  set has_stages [Node::HasStages $node]
621  set is_flow [Node::IsFlow $node]
622  set is_stage [Node::IsStage $node]
623 
624  if {$has_script && $has_stages} {
625  lappend problems "$canon declares both 'script' and 'stages'.\
626  Node::Run branches on 'stages' first, so the script is dead code."
627  }
628 
629  if {[tdict getval $node passthrough] && [llength $children] == 0} {
630  lappend problems "$canon is 'passthrough true' but has no children.\
631  The flag only changes how a following token is resolved against\
632  children, so it does nothing here."
633  }
634 
635  if {[Node::RequiresProj $node] && [llength $children] > 0 && \
636  ![tdict getval $node passthrough]} {
637  lappend problems "$canon requires a project and has children, but is not\
638  'passthrough true'. Its project argument will be read as a subcommand\
639  name and rejected."
640  }
641 
642  if {$is_flow && ![Node::RequiresProj $node]} {
643  lappend problems "$canon is a flow with 'requires_proj false'. Flows are\
644  project-scoped by definition; this one cannot be reached as a flow."
645  }
646 
647  # A declared stage's script is a proc name, so it is checkable. This is how
648  # a typo in 2-arg 'RegisterStage DoNothing' gets caught - the node registers
649  # happily and names a proc that was never defined.
650  if {$is_stage} {
651  set p [tdict getval $node script]
652  if {$p ne "" && [info commands $p] eq ""} {
653  lappend problems "$canon declares a stage backed by '$p', which is not\
654  a defined proc. Two-arg RegisterStage names a proc the tool must\
655  already define; three-arg RegisterStage defines it for you."
656  }
657  }
658 
659  if {$is_flow && !$has_stages} {
660  lappend problems "$canon is a flow that declares no stages.\
661  Running it would do nothing."
662  }
663  if {!$has_stages} continue
664 
665  set walk [Node::_walk_stages $node]
666 
667  # Only problems this node itself declared - every node is visited, so
668  # filtering here reports each one once, against its author, instead of once
669  # per flow that @references it.
670  foreach bad [dict get $walk badrefs] {
671  lassign $bad owner ref
672  if {$owner ne $canon} continue
673  lappend problems "$canon references unknown flow '$ref'. It will be\
674  skipped, silently shortening the stage list."
675  }
676 
677  foreach cyc [dict get $walk cycles] {
678  lassign $cyc owner chain
679  if {$owner ne $canon} continue
680  # A cycle is discovered once from each participant (A->B->A is found
681  # walking A *and* walking B), so key on the unordered set to name it once.
682  set sig [lsort -unique [concat $chain $owner]]
683  if {$sig in $seen_cycles} continue
684  lappend seen_cycles $sig
685  lappend problems "circular @reference: [join $chain { -> }] -> $owner.\
686  Flattening survives it, but the stage list is not what was intended."
687  }
688 
689  if {[llength [dict get $walk stages]] == 0} {
690  lappend problems "$canon flattens to no stages - every stage it\
691  @references is unresolvable. Running it will fail."
692  }
693 
694  # Bare names only, checked where they are written rather than where they are
695  # spliced in. A stage with its own STAGE node is checked above, at that node.
696  tlist foreachval st [tdict getobjor $node stages [tlist create]] {
697  if {[string match "@*" $st]} continue
698  set tool_bare [_tool_of $canon]
699  if {[GetCommand "TOOL.$tool_bare.STAGE.$st"] ne {}} continue
700  set p [_owning_stage_proc $canon $st]
701  if {$p eq "" || [info commands $p] eq ""} {
702  lappend problems "$canon names stage '$st', which resolves to no proc\
703  ([expr {$p eq "" ? "no tool owns '$tool_bare'" : "no proc $p"}])."
704  }
705  }
706  }
707 
708  if {[llength $problems] == 0} { return 0 }
709 
710  set strict [expr {[info exists ::env(HOG_STRICT)] &&
711  $::env(HOG_STRICT) ni {"" 0 false no}}]
712  foreach p $problems {
713  Msg [expr {$strict ? "CriticalWarning" : "Warning"}] "Lint: $p"
714  }
715  if {$strict} {
716  error "Commands::Lint found [llength $problems] problem(s) with HOG_STRICT set" \
717  "" {HOG_LINT_FAILED}
718  }
719  return [llength $problems]
720  }
721 
722 
723  # Bare tool names (e.g. {VIVADO QUARTUS}) whose FLOW subtree holds the specified flow
724  # Returns the bare tools name
725  proc ToolsWithFlow {name} {
726  variable nodes
727  set needle [string toupper $name]
728  set result {}
729  dict for {canon _n} $nodes {
730  if {![regexp {^TOOL\.([^.]+)\.FLOW$} $canon -> tool_name]} { continue }
731  if {[_canon_child $canon $needle] ne ""} { lappend result $tool_name }
732  }
733  return $result
734  }
735 
736  # Every node, anywhere in the tree, that declares producing 'name' - the
737  # reverse of a node's own 'produces' field.
738  # Used for cross-tool "who makes this" discovery and by
739  # FlowControl::_check_freshness to find an artifact's declared upstreams.
740  # Returns list of stages
741  proc ProducersOf {name} {
742  variable nodes
743  set result {}
744  dict for {canon node} $nodes {
745  if {[tlist elemExists [tdict getobjor $node produces [tlist create]] $name]} {
746  lappend result $canon
747  }
748  }
749  return $result
750  }
751 
752  # Resolution
753 
754  # Walk argv_list through the command tree.
755  # Returns: {node <tdict> path <list> remaining <list>} or {} on failure.
756  proc ResolvePath {argv_list} {
757  variable alias_index
758  variable nodes
759  if {[llength $argv_list] == 0} { return {} }
760 
761  set first [string toupper [lindex $argv_list 0]]
762  set canon [_canon $first]
763  if {$canon eq "" || ![dict exists $nodes $canon]} { return {} }
764 
765  set node [dict get $nodes $canon]
766  set path [list [lindex $argv_list 0]]
767  set remaining [lrange $argv_list 1 end]
768 
769  while {[llength [GetChildren $canon]] > 0 && [llength $remaining] > 0} {
770  set token [lindex $remaining 0]
771  set next_canon [_canon_child $canon [string toupper $token]]
772  if {$next_canon eq "" || ![dict exists $nodes $next_canon]} break
773  set canon $next_canon
774  set node [dict get $nodes $next_canon]
775  lappend path $token
776  set remaining [lrange $remaining 1 end]
777  }
778 
779  return [dict create node $node path $path remaining $remaining]
780  }
781 
782  proc _strip_top {token} {
783  return [string trimright [regsub {^(\./)?Top/} $token ""] "/ "]
784  }
785 
786  proc ParseArgv {argv top_path} {
787  if {[llength $argv] >= 2 && ![string match "-*" [lindex $argv 1]]} {
788  set argv [lreplace $argv 1 1 [_strip_top [lindex $argv 1]]]
789  }
790 
791  # Flow shorthand: <flow> <proj> -> <tool> <flow> <proj>, where <tool> is
792  # whichever tool the project's hog.conf names.
793  set directive [string toupper [lindex $argv 0]]
794  if {$directive ne "" && ![AliasExists $directive] && [llength $argv] >= 2} {
795  set proj [lindex $argv 1]
796  if {[file exists [file join $top_path $proj hog.conf]]} {
797  set tool [Tools::GetToolForProject $proj $top_path]
798  if {$tool ne ""} {
799  set tool_key [string toupper [namespace tail $tool]]
800  if {[_canon_child "TOOL.$tool_key.FLOW" $directive] ne ""} {
801  set argv [concat [list $tool_key FLOW $directive] [lrange $argv 1 end]]
802  }
803  }
804  }
805  }
806 
807  set directive [string toupper [lindex $argv 0]]
808  set resolved [ResolvePath $argv]
809  if {[llength $resolved] > 0} {
810  set node [dict get $resolved node]
811  set path [dict get $resolved path]
812  set rest [dict get $resolved remaining]
813  } else {
814  set node {}
815  set path [list $directive]
816  set rest [lrange $argv 1 end]
817  }
818 
819  # Every leading non-flag leftover is a positional argument. Stop at the first
820  # flag so option *values* ("-num 2") are never mistaken for positionals.
821  # Index 0 is the project by convention - most commands want only that, but
822  # multi-positional commands read the rest via Commands::Arg.
823  set pargs {}
824  while {[llength $rest] > 0 && ![string match "-*" [lindex $rest 0]]} {
825  lappend pargs [lindex $rest 0]
826  set rest [lrange $rest 1 end]
827  }
828  set options $rest
829 
830  # args[0] is the project, so normalize it in place rather than keeping a raw
831  # and a cooked copy that can disagree: "Top/example/" and "example" must look
832  # identical to a command reading Commands::Arg 0.
833  set project_name ""
834  if {[llength $pargs] > 0} {
835  set project_name [_strip_top [lindex $pargs 0]]
836  set pargs [lreplace $pargs 0 0 $project_name]
837  }
838 
839  return [dict create \
840  node $node \
841  typed_path $path \
842  args $pargs \
843  project [file tail $project_name] \
844  project_name $project_name \
845  options $options \
846  ]
847  }
848 
849  # True when the node's target ide is the process we're already in
850  # (tclsh at top level, or the active tool inside a booted IDE).
851  proc _InContext {ide} {
852  set here [ActiveTool::CurrentTool]
853  if {$ide eq "tclsh"} { return [expr {$here eq "tclsh"}] }
854  return [expr {[Tools::ResolveAlias $ide] eq $here}]
855  }
856 
857  # Run a resolved node inline in the current process.
858  proc _RunInContext {node full_path} {
859  cd [Repo::Get repo_path]
860  set ide [tdict getval $node ide]
861  if {$ide ne "tclsh"} {
862  set ::DataStore::inIDE 1
863  set tool [Tools::ResolveAlias $ide]
864  Launcher::Set ide $tool
865  CurrentProject::Set ide $tool
866  if {[info commands ${tool}::Initialize] ne ""} { ${tool}::Initialize }
867  }
868  Node::Run $node $full_path
869  }
870 
871  # Decides ran/usage/boot for a resolved node. Runs it inline when its ide is
872  # the current process; otherwise returns a boot verdict for the caller to launch the right IDE.
873  proc Dispatch {node typed_path project} {
874  set label [join $typed_path { }]
875  set full_path [expr {$project ne "" ? [concat $typed_path [list $project]] : $typed_path}]
876 
877  if {$node eq {}} {
878  set directive [string toupper [lindex $typed_path 0]]
879  set tools [ToolsWithFlow $directive]
880  if {[llength $tools] > 0} {
881  return -code error "Flow '$directive' requires a project\
882  (provided by [join [string tolower $tools] {, }]).\
883  Usage: ./Hog/Do $directive <project>"
884  }
885  return -code error "Unknown directive '$directive'. Run './Hog/Do HELP' for usage."
886  }
887 
888  set node_canon [tdict getval $node canon]
889  set has_children [expr {[llength [GetChildren $node_canon]] > 0}]
890  set has_action [Node::IsRunnable $node]
891 
892  if {$has_children && $project ne "" && ![tdict getval $node passthrough] && \
893  [_canon_child $node_canon [string toupper $project]] eq ""} {
894  return [list usage $typed_path "'$label' has no subcommand '[string toupper $project]'"]
895  }
896 
897  if {!$has_action} {
898  if {$has_children} { return [list help $typed_path] }
899  return -code error "Command '$label' is not executable"
900  }
901 
902  if {[tdict getval $node requires_proj] && $project eq ""} {
903  return -code error "Command '$label' requires a project. Usage: ./Hog/Do [join $typed_path { }] <project>"
904  }
905 
906  set ide [tdict getval $node ide]
907  if {[_InContext $ide]} {
908  _RunInContext $node $full_path
909  return [list ran]
910  }
911  return [list boot $ide]
912  }
913 
914  # Parse argv into a request and mirror it onto the Launcher DataStore.
915  # Does not load projects or execute - callers own that ordering.
916  proc Resolve {argv} {
917  set directive [string toupper [lindex $argv 0]]
918  set request [ParseArgv $argv [Repo::Get top_path]]
919 
920  Launcher::Set directive $directive
921  Launcher::Set cmd [expr {[dict get $request node] ne {} ? [tdict getval [dict get $request node] canon] : ""}]
922  Launcher::Set full_cmd [dict get $request typed_path]
923  Launcher::Set args [tlist createstr {*}[dict get $request args]]
924  Launcher::Set project [dict get $request project]
925  Launcher::Set project_name [dict get $request project_name]
926 
927  # Raw, unparsed flags; RunRequest replaces this with the parsed tdict.
928  Launcher::Set options [tlist createstr {*}[dict get $request options]]
929  return $request
930  }
931 
932  # Validate + parse options + Dispatch a resolved request. Returns the verdict
933  # (ran/boot/usage/help); throws on error. Never calls exit.
934  proc RunRequest {request} {
935  set node [dict get $request node]
936  set typed_path [dict get $request typed_path]
937  set project [dict get $request project]
938  set raw_opts [dict get $request options]
939 
940  if {"--help" in $raw_opts || "-help" in $raw_opts || "-h" in $raw_opts || "-?" in $raw_opts} {
941  Help::RenderPath $typed_path
942  return [list help]
943  }
944 
945  if {$project ne "" && $node ne "" && [Node::RequiresProj $node]} {
946  set _conf [file join [Repo::Get top_path] $project hog.conf]
947  if {![file exists $_conf]} {
948  return -code error "Project '$project' not found (no hog.conf at $_conf)."
949  }
950  }
951 
952  set opt_specs [GetCommandOptions $node]
953  set options $raw_opts
954  array unset _parsed
955  array set _parsed {}
956  if {[llength $opt_specs] > 0} {
957  if {[catch {array set _parsed [cmdline::getoptions options $opt_specs ""]} err]} {
958  return -code error "Option error: $err"
959  }
960  }
961  set _t [tdict create]
962  foreach k [array names _parsed] { tdict set _t $k [tinf $_parsed($k)] }
963  Launcher::Set options $_t
964 
965  set verdict [Dispatch $node $typed_path $project]
966  switch -- [lindex $verdict 0] {
967  ran { return $verdict }
968  help {
969  Help::RenderPath [lindex $verdict 1]
970  return [list help]
971  }
972  usage {
973  lassign $verdict _ path message
974  Msg Warning $message
975  catch { Help::RenderPath $path }
976  return $verdict
977  }
978  boot {
979  lassign $verdict _ ide
980  Launcher::Set ide $ide
981  Tools::Launch $ide
982  # A tool with no real IDE binary flips itself active in this process
983  # instead of spawning a child - if we're now in its context, re-dispatch
984  # so it runs inline (a real IDE already ran it in the booted child).
985  if {[_InContext $ide]} {
986  return [RunRequest $request]
987  }
988  return $verdict
989  }
990  default { return -code error "Unexpected dispatch verdict: $verdict" }
991  }
992  }
993 
994  # JSON export
995 
996  proc ToJson {{flag {}}} {
997  variable alias_index
998  variable nodes
999  set ai [tdict create]
1000  dict for {k v} $alias_index { tdict set ai $k [tstr $v] }
1001  set nd [tdict create]
1002  dict for {canon node} $nodes {
1003  # children isn't stored on the node - compute it here for export only.
1004  tdict set node children [tlist create {*}[GetChildren $canon]]
1005  tdict set nd $canon $node
1006  }
1007  set root [tdict create alias_index $ai nodes $nd]
1008  if {$flag eq "-pretty"} { return [tobj tojson $root -pretty] }
1009  return [tobj tojson $root]
1010  }
1011 
1012 }