#!/bin/sh
# restart -*-Tcl-*- \
exec tclsh $0 $@

# conflicts -
#
# The 'conflicts' script processes annotated emake output to give a
# human-readable conflicts report.
#
# Copyright (c) 2003-2026 Electric Cloud, Inc.
# All rights reserved.

package require xml
package require textutil
package require math

namespace import textutil::*

array set gParse {};                    # has stacks (lists) and counters
                                        # Keys include:
                                        #   stack_job - job stack
                                        #   stack_make - make stack
                                        #   counter_make - make counter
array set gJob {};                      # job elements, keyed by id
array set gMake {};                     # make element, keyed by number
set gConflicts {};                      # List of conflict element attrs


# ------------------------------------------------------------------------
# indent
#
#      Splits the given text into lines and prepend a prefix.
#
# Arguments:
#      prefix          - (string) prefix each line with this string
#      text            - (string) text to indent
# ------------------------------------------------------------------------

proc indent {prefix text} {
    set result ""
    foreach line [split $text \n] {
        append result "\t\t$line\n"
    }
    return $result
}

# ------------------------------------------------------------------------
# isJob
# isMake
#
#      Returns true if the given id is for a job or make element, 
#      respectively.
#
# Arguments:
#      id          - (string) element id
# ------------------------------------------------------------------------

proc isJob {id} {
    return [expr {[string index $id 0] == "J"}]
}
proc isMake {id} {
    return [expr {[string index $id 0] == "M"}]
}

# ------------------------------------------------------------------------
# attrget
#
#      Query a Tcl alist for a value. If not found, return empty string
#      or the specified default, if provided.
#
# Arguments:
#      attrList       - (alist) Tcl alist to query
#      name           - (string) key to return
#      defaultValue   - (optional string) value to return if name not found
# ------------------------------------------------------------------------

proc attrget {attrList name {defaultValue {}}} {
    foreach {key value} $attrList {
        if {$key == $name} {
            return $value
        }
    }
    return $defaultValue
}

# ------------------------------------------------------------------------
# lprepend
#
#      Prepend the arguments to the specfied list. Returns the new list.
# ------------------------------------------------------------------------

proc lprepend {listVar args} {
    upvar $listVar l
    set l [concat $args $l]
    return $l
}

# ------------------------------------------------------------------------
# getName
#
#      Given an id for a job or make element, returns a name for the
#      element. It's the job name for a job, or the command line for a
#      make. Return "name not available" if the id doesn't exist or is
#      invalid.
# ------------------------------------------------------------------------

proc getName {id {showType 0}} {

    if {$id == ""} {
        return
    }

    set result "\[name/desc not available\]"

    if {[isJob $id]} {

        # Job id. If we know about this job, return its name.
        
        if {[info exist ::gJob($id)]} {
            set result [attrget $::gJob($id) name]
        } else {
            puts stderr "WARNING: dangling job reference: \"$id\""
        }

    } elseif {[isMake $id]} {

        # Make id. If we know about this make, return its command.
        
        set prefix [expr {$showType ? "\[NEW MAKE INSTANCE\]\n" : ""}]
        if {[info exist ::gMake($id)]} {
            set result $prefix[attrget $::gMake($id) cmd]
        } else {
            puts stderr "WARNING: dangling make reference: \"$id\""
        }
    } else {
        puts stderr "WARNING: invalid job/make reference: \"$id\""
    }

    return $result
}

# ------------------------------------------------------------------------
# getParents
#
#      Given an id for a job or make element, returns a list of ids of 
#      the parent job and make elements. Returns empty if the job
#      ancestry is broken (dangling neededby, for example).
# ------------------------------------------------------------------------

proc getParents {id} {

    set result $id

    set done 0
    while {! $done} {

        # Is the current id a Make or a Job?

        if {[isJob $id]} {

            # Job. If we don't know about this job, return empty.
            
            if {! [info exist ::gJob($id)]} {
                puts stderr "ERROR: dangling reference to \"$id\""
                return
            }

            # Do we have a 'neededby' attribute on this job?

            set neededby [attrget $::gJob($id) neededby]
            if {$neededby != ""} {

                # Yes, that's our parent.

                lprepend result $neededby
                set id $neededby

            } else {

                # No 'neededby' attribute, this is a goal. Parent
                # is the enclosing make instance.

                set make [attrget $::gJob($id) make]
                lprepend result $make
                set id $make
            }
        } elseif {[isMake $id]} {
            
            # Make. If we don't know about this make, return empty.
            
            if {! [info exist ::gMake($id)]} {
                puts stderr "ERROR: dangling reference to \"$id\""
                return
            }

            # Are we the toplevel make instance?

            set job [attrget $::gMake($id) job]
            if {$job == "root"} {
                
                # Yes, we're done.

                set done 1

            } else {

                # No, there's a job above us. That's our parent.

                lprepend result $job
                set id $job
            }
        } else {

            # Invalid id; doesn't start with 'J' or 'M'.

            puts stderr "ERROR: not a job or make id: \"$id\""
            return
        }
    }
    
    return $result
}

# ------------------------------------------------------------------------
# reportConflicts
#
#      Process the ::gConflicts array, displaying details and suggested
#      resolutions for each conflict logged.
# ------------------------------------------------------------------------

proc reportConflicts {} {
    set count 1
    foreach conflictAttrs $::gConflicts {
        set type cascade
        foreach {key val} $conflictAttrs {
            set $key $val
        }
        
        puts "Conflict #$count"
        puts "\tConflict Type: $type"
        puts "\tReader Job:"
        puts "\t\tid: $readjob"
        set rType [attrget $::gJob($readjob) type]
        puts "\t\ttype: $rType"
        
        # Interesting hack. If this is a conflict on a parse job, the
        # "reader" is really the rerun job (since it's in a different make
        # instance).

        if {$rType == "parse"} {
            set readjob    $rerunby
        }

        array set readerMake $::gMake([attrget $::gJob($readjob) make])

        puts "\t\tname: [attrget $::gJob($readjob) name N/A]"
        puts "\t\tdir: $readerMake(cwd)"
        puts "\t\tcmd: $readerMake(cmd)\n"
        
        if {$type == "cascade"} {

            # TODO - resolution suggestions for cascade conflicts could
            # become very accurate.

            switch $rType {
                rule {   
                    set cause "This job started before a conflict was found on its prerequisite."
                    set resolution "Check and resolve conflicts on prerequisites."
                }
                parse {
                    # There is no ParseJob::hasConflict() - should always have
                    # file conflicts on ParseJobs, not cascades.

                    puts stderr "ASSERT: cascade conflict on ParseJob".
                    exit 1
                }
                end -
                remake -
                exist -
                follow {
                    set cause "<< cause of a(n) $rType job conflict >>"
                    set resolution "<< resolution for a(n) $rType job conflict >>"
                }
                default {
                    puts "no $type!"
                    exit 1
                }
            }
            puts "\tCause:\n"
            puts [indent "\t\t" [adjust $cause]]
            puts "\tResolution:\n"
            puts [indent "\t\t" [adjust $resolution]]

        } else {

            # If this is not a cascade, we should have job and file vars.
            # If we don't, skip to the next one.

            set ok 1
            foreach v {file writejob} {
                if {! [info exist $v]} {
                    puts "\tERROR: unable to suggest resolutions, \"$v\"\
                          attribute missing."
                    set ok 0
                }
            }
            if {! $ok} {
                continue
            }

            puts "\tCause:"
            set cause "Two different jobs were allowed to start in parallel, but one read the file \"$file\" before the other wrote/modified it."
            puts [indent \t\t [adjust $cause]]

            set readerParents [getParents $readjob]
            set writerParents [getParents $writejob]
            
            if {$readerParents == "" || $writerParents == ""} {
                puts "\t\tERROR: unable to show job ancestry."
                continue
            }

            # Loop over the ancestry lists, printing them out in a table
            # side-by-side. Also keep track of the first differing elements,
            # and last differing jobs.

            set seenDifference 0
            set seenLastWriteJob 0
            set seenLastReadJob 0

            set max [math::max [llength $readerParents] \
                         [llength $writerParents]]
            puts "\t\t--- SHARED: the dependency chain through last common parent:\n"
            for {set i 0} {$i < $max} {incr i} {

                # Get the parents at this level.

                set rParent [lindex $readerParents $i]
                set wParent [lindex $writerParents $i]

                # Are they the same?

                if {$rParent == $wParent} {

                    # Yes - just print the reader.

                    set r [split [adjust [getName $rParent 1] \
                                      -length 70 -strictlength 1] \n]
                    for {set j 0} {$j < [llength $r]} {incr j} {
                        if {$j == 0} {
                            set n [expr {$i + 1}].
                        } else {
                            set n ""
                        }
                        puts [format "\t\t%-4s%-70s" $n [lindex $r $j]]
                    }

                    # Hang on to the last matching parent.

                    set lastMatch $rParent

                } else {

                    # If we don't have the dissenters, record them now.

                    if {! $seenDifference} {
                        set rTop $rParent
                        set wTop $wParent
                        set seenDifference 1
                        puts "\n\t\t--- SPLIT: separate dependency chains running in parallel"
                        puts [format "\n\t\t    %-35s   %-35s" READER WRITER]\n
                    }

                    # Keep track of the last read and write jobs in the same
                    # make instance.

                    if {[isJob $rParent] && ! $seenLastReadJob} {
                        set rLastJob $rParent
                    } else {
                        set seenLastReadJob 1
                    }
                    if {[isJob $wParent] && ! $seenLastWriteJob} {
                        set wLastJob $wParent
                    } else {
                        set seenLastWriteJob 1
                    }

                    # Print both reader and writer in two columns. 

                    set r [split [adjust [getName $rParent 1] \
                                      -length 35 -strictlength 1] \n]
                    set w [split [adjust [getName $wParent 1] \
                                      -length 35 -strictlength 1] \n]
                    set m [math::max [llength $r] [llength $w]]
                    for {set j 0} {$j < $m} {incr j} {
                        if {$j == 0} {
                            set n [expr {$i + 1}].
                        } else {
                            set n ""
                        }
                        puts [format "\t\t%-4s%-35s   %-35s" $n \
                                  [lindex $r $j] [lindex $w $j]]
                    }
                }
            }

            puts "\n\tPossible Resolution: Rewrite job to avoid read."

            switch $rType {
                rule {
                    puts "\n\t\tIn file \"\", rewrite this rule:"
                    puts [indent \t\t\t "rule: pre\n\techo \$@"]
                    puts "\t\tto avoid reading the file: \"$file\"."
                }
                parse {
                    puts "\n\t\tRewrite the parse started by:"
                    puts "\t\t\t$readerMake(cmd)"
                    puts "\t\tto avoid reading the file: \"$file\"."
                }
                default {
                    puts "\n\t\t<<rewrite to avoid read of \"$file\"."
                }
            }
            
            puts "\n\tPossible Resolution: Introduce dependency."

            # How did the job ancestries differ?

            if {[isJob $rTop] && [isJob $wTop]} {

                # Different jobs. Fix is a dependency between the last
                # read job and the last write job in that make instance.

                set srcFile [attrget $::gJob($rTop) file]

                puts "\n\t\tIn file: \"$srcFile\", add the dependency:"
                puts "\t\t\t[getName $rLastJob]: [getName $wLastJob]\n"

            } elseif {[isMake $rTop] && [isMake $wTop] && [isJob $lastMatch]} {

                # Different makes started by a job. Fix is to split rule
                # for the job so that the makes are serialized.

                set srcFile [attrget $::gJob($lastMatch) file]
                set name [attrget $::gJob($lastMatch) name]
                set readerCmd [attrget $::gMake($rTop) cmd]
                set writerCmd [attrget $::gMake($wTop) cmd]

                puts "\t\tIn file: \$srcFile\", split rule for \"$name\" to\
                      serialize:"
                puts "\t\t\t$readerCmd"
                puts "\t\t\t$writerCmd"
            }
        }

        incr count
    }
}

# ------------------------------------------------------------------------
# newItem
#
#      Register an element instance from the input file and returns
#      its id. Each element's attributes are saved as an alist in a global
#      array ::g<Type> keyed on the element id.
#      
#      This procedure also fills in the implied 'job' attribute on make
#      and 'make' on job.
# 
# Arguments:
#      type     - ('make'|'job') the element type
#      attrList - (list) attr/val list of the XML attributes for this element
# ------------------------------------------------------------------------

proc newItem {type attrList} {

    switch $type {
        make {
            # The make id is just a counter.

            set id M[incr ::gParse(counter_make)]

            # What job is this make instance in? If it's empty, use 'root'.

            set jobId [lindex $::gParse(stack_job) end]
            if {$jobId == ""} {
                set jobId root
            }

            # Save the attributes, including job that started us.

            set ::gMake($id) [concat $attrList job $jobId]
        }
        job {
            # The job id is given on the attributes.

            set id [attrget $attrList id]

            # What make is this job in? Look at top of make stack.

            set makeId [lindex $::gParse(stack_make) end]

            # Save the attributes, including the make instance we're in.

            set ::gJob($id) [concat $attrList make $makeId]
        }
        default {
            puts stderr "ASSERT: newItem called with unexpected type: $type"
            exit 1
        }
    }

    return $id
}

# ------------------------------------------------------------------------
# parseElement
# 
#      Called when the parser encounters an XML tag to update the global
#      parse state, ::gParse. 
#
#      Element-specific stacks are updated with ids after the element
#      is registered with 'newItem'.
# 
# Arguments:
#      state         - (bool) 1 if this is an element start, 0 if end
#      name          - (string) name of the element (make, job, etc)
#      args          - (unused) additional arguments passed by TclXML
# ------------------------------------------------------------------------

proc parseElement {state name args} {

    set attrList [lindex $args 0]

    switch $name {
        make - 
        job {

            # Update the element specific stacks for <make> and <job>.

            if {$state} {
                lappend ::gParse(stack_$name) [newItem $name $attrList]
            } else {
                set ::gParse(stack_$name) [lrange $::gParse(stack_$name) \
                                               0 end-1]
            }
        }
        conflict {

            # Record a conflict on conflict open.

            if {$state} {
                lappend ::gConflicts [concat $attrList readjob \
                                          [lindex $::gParse(stack_job) end]]
            }
        }
    }

    return
}

# ------------------------------------------------------------------------
# parseFile
# 
#      Parse the input file.
# 
# Arguments:
#      filename          - (string) XML file name to open and parse
# ------------------------------------------------------------------------

proc parseFile {fileName} {

    if {[catch {open $fileName r} f]} {
        puts stderr "conflicts: $f"
        exit 1
    }

    # Set up the default gParse global. We have separate make and job
    # stacks. We also have a make instance counter.

    foreach key {stack_make stack_job} {
        set ::gParse($key) {}
    }
    set ::gParse(counter_make) 0

    # Parse the file in one shot. 'parseElement' is called to handle a
    # begin/end of an XML element.

    set parser [::xml::parser \
                    -ignorewhitespace 1 \
                    -elementstartcommand [list parseElement 1] \
                    -elementendcommand   [list parseElement 0]]
    if {[catch {$parser parse [read $f]} result]} {
        puts stderr "WARNING: error parsing \"$fileName\": $result"
    }
    close $f
    return
}

# ------------------------------------------------------------------------
# main
# ------------------------------------------------------------------------

proc main {} {

    # Must be given name of input file.

    set fname [lindex $::argv 0]
    if {$fname == ""} {
        puts stderr "Usage: conflicts <log.xml>"
        exit 1
    }

    parseFile $fname
    reportConflicts
}

main
