blob: c6330b3d1a45142e9325d70222bb66f83471a6d2 [file] [log] [blame]
mkk91ada922020-12-02 09:08:26 -08001#!/bin/sh
2# Copyright (C) 2014, 2015, 2020 efabless Corporation. All Rights Reserved.
3# send a very-first -T FILE to magic's startup, hide all other args from magic-startup
4# for-bash\
5 export _M0= ;\
6 for i in "$@" ; do _M0="$_M0${_M0:+ }\"${i//\"/\\\"}\""; done ;\
7 case "$1" in -T) tch="$2"; shift; shift; _MARGS="$*" exec magic -dnull -noconsole -T "$tch" <"$0" ;; esac
8# hide next line from magic(tclsh):\
9_MARGS="$*" exec magic -dnull -noconsole <"$0"
10#
11# magicDRC: run magic-DRC in batch on a GDS file, tabulate/pareto the error counts.
12#
13# rb@ef 2014-08-28 author
14# rb 2020-02-19 embed some library functions, to standalone from efabless-opengalaxy env, test via magic-8.2.188
15#
16# todo: support "-" as GDS file arg, to mean GDS from stdin
17#
18
19set ::Prog "magicGdrc"
20set argv [eval "list $env(_M0)"] ;# orig. mix of native plus custom args, for logging all args to script
21# set argv [split $env(_MARGS)] ;# (currently unused)
22
23proc usage {args} {
24 if {[llength $args] > 0} {
25 puts "ERROR: ${::Prog}: [join $args]"
26 }
27 puts {usage: [ -T techfilePath ] [-S <drcStyleName>] [-I <cifIStyleName>] [-km FILE_NAME] [-l FILE_NAME] [-L FILE_NAME] gdsFileName [topCellName]}
28 puts " -T if given, must be very first"
29 puts " -S if given, changes from techfile's default/1st drc style (perhaps \"drc(fast)\") to named style, for example: -S \"drc(full)\""
30 puts " -I if given, changes from techfile's default/1st cifinput style (perhaps \"vendorimport\" or \"import(exact)\") to named style, for example: -I \"import(magic)\""
31 puts " -path-sub do 'gds path subcell yes' (default:no). Make unique subcell for each path: cut #tiles cost of angles."
32 puts " -poly-sub do 'gds polygon subcell yes' (default:no). Make unique subcell for each polygon: cut #tiles cost of angles."
33# gds polygon subcell [yes|no]
34 puts " -pps Short hand, equivalent to giving both: -path-sub -poly-sub"
35 puts ""
36 puts " Error tabulation: By default (slowest, most detail): Report table of counts-by-errorString for all cells."
37 puts " Stdout logs a pareto of error-type by count unless disabled for some/all cells by below; topcell last."
38 puts " -tt Table of counts-by-errorString for ONLY topcell; and just lumped total error count per subcell."
39 puts " -tc Just lumped error counts per cell including topcell (fastest, least detail)."
40 puts " Cells NOT tabulating count-by-errorString can't appear in other output error files: feedback(*.drtcl), -l, -km."
41 puts " For lumped error counts, overlapped error shapes from unique error-types are merged further reducing count."
42 puts ""
43 puts " cell-type +-- (default) --+-- option -tt --+-- option -tc"
44 puts " subcell | count-by-errorString | lumped-error-count | lumped-error-count"
45 puts " topcell | count-by-errorString | count-by-errorString | lumped-error-count"
46 puts ""
47 puts " -km if given, write to FILE_NAME EVERY individual error bbox (MICRONS) in klayout Marker database(XML) format (suggest *.lyrdb)"
48 puts " -l if given, enumerates EVERY individual error bbox (MICRONS) to FILE_NAME, emulates $::CAD_ROOT/magic/tcl/drc.tcl"
49 puts " -L same as -l above, but outputs bbox-es in LAMBDA coordinates, not microns"
50 puts " -nf Do NOT write *.drtcl per-cell feedback files. Can be source-ed in magic and step thru: feedback find."
51 puts ""
52 puts " NOTES: Without explicit tech-file option: the ./.magicrc or ./magic_setup and ~/.magicrc may load a default tech-file."
53 puts " Therefore the tech-file used CAN depend on whether your CWD is ~/design/<CURRENT_DESIGN>/mag when running this script."
54 puts " Since no *.mag are loaded by this script: the cell search path defined by any init files has no impact."
55 puts " Since about 8.3.68, magic may generate error-type \"See error definition in the subcell\". There typically are"
56 puts " redundancies of errors across the hierarchy anyway (but with tech-file err-strings), this seems another form."
57 puts ""
58 puts "example, just list all styles: by causing an error which provokes usage report:"
59 puts " magicGdrc -T /ef/tech/XFAB/EFXH035B/libs.tech/magic/current/EFXH035B.tech"
60 puts "example, same but run in a ~/design/*/mag/ dir, so techfile set by ./.magicrc (else magic's builtin minimum.tech):"
61 puts " magicGdrc"
62 puts "example, run GDS drc, explicit: tech, cif-istyle, drc-style:"
63 puts " magicGdrc -T /ef/tech/SW/EFS8A/libs.tech/magic/current/EFS8A.tech -I vendorimport -S 'drc(full)' /tmp/mytop.gds mytopcell"
64 puts "example, run GDS drc, default tech & styles, write klayout marker database, no per-cell *.drtcl feedback files:"
65 puts " magicGdrc -km /tmp/mytop.lyrdb -nf /tmp/mytop.gds mytopcell"
66 puts "example, same but make subcells for paths & polygons"
67 puts " magicGdrc -km /tmp/mytop.lyrdb -nf -pps /tmp/mytop.gds mytopcell"
68 puts "example, run GDS drc, no feedback (*.drtcl), only lumped/merged err-count for all cells"
69 puts " magicGdrc -tc /tmp/mytop.gds mytopcell"
70 puts "example, run GDS drc, no feedback (*.drtcl), lumped/merged err-count for subcells, detail errors for topcell"
71 puts " magicGdrc -nf -tt /tmp/mytop.gds mytopcell"
72 puts ""
73
74 reportTechFile
75 reportAllStyles
76 puts ""
77
78 if {[llength $args] > 0} {
79 puts "ERROR: ${::Prog}: [join $args]"
80 }
81}
82proc gdsChk {file} {
83 foreach suffix {"" ".gds" ".gds2" ".strm"} {
84 if {[file readable "${file}${suffix}"]} {return 1}
85 }
86 puts "ERROR: ${::Prog}: Cannot open (as-is or with .gds, .gds2, or .strm) to read GDS-II stream from: $file"
87 exit 1
88}
89
90proc reportTechFile {} {
91 puts "${::Prog}: tech-name: [tech name] -version: [tech version] -filename: [tech filename] -lambda [tech lambda]"
92}
93
94# query currently loaded tech-file for styles the user might need for -I -S options
95# Suggest a bad tech-file if none are found or errors thrown.
96# Used after finding error in -I -S options, and probably should add it to the usage.
97proc reportAllStyles {} {
98 set errs {}
99 if {[catch {set allstyle [cif listall istyle]} msg]} {
100 lappend errs "ERROR: ${::Prog}: bad tech-file? failed to 'cif listall istyle', $msg"
101 } elseif {$allstyle == {}} {
102 lappend errs "ERROR: ${::Prog}: bad tech-file? no cifinput styles found by 'cif listall istyle'"
103 } else {
104 puts "info: ${::Prog}: cifinput styles available: $allstyle"
105 }
106 if {[catch {set allstyle [drc listall style]} msg]} {
107 lappend errs "ERROR: ${::Prog}: bad tech-file? failed to 'drc listall style', $msg"
108 } elseif {$allstyle == {}} {
109 lappend errs "ERROR: ${::Prog}: bad tech-file? no drc styles found by 'drc listall style'"
110 } else {
111 puts "info: ${::Prog}: drc styles available: $allstyle"
112 }
113 if {$errs != {}} {
114
115 }
116 return [llength $errs]
117}
118
119# optionally hardcode library proc-s (part of site-wide extensions - always available - in context of efabless/open-galaxy)
120# This is to make the script more standalone from efabless environment; but these capabilities should be native to magic.
121
122if {[info command unbounds] == {}} {
123 puts "${::Prog}: hardcoding library proc-s..."
124# Replacement for 'cellname list exists CELLNAME', to fix ambiguity for cell "0".
125# For cell "0" test for membership in 'cellname list allcells'.
126#
127# Instead of returning 0 for (non-existent) and cellname for exists,
128# returns regular 0/1 instead for non-existent/exists.
129#
130# Therefore NOT direct replacement for uses of 'cellname list exists CELL'.
131# Requires code changes.
132proc cellnameExists {cell} {
133 expr {$cell ne "0" && [cellname list exists $cell] eq $cell ||
134 $cell eq "0" && [lsearch -exact [cellname list allcells] $cell] > -1}
135}
136
137# Walk allcells to get/return list of cellNames that are unbound.
138# Only use this after: 'select top cell; expand' to expand whole hierarchy.
139#
140# foreach CELL in 'cellname list allcells':
141# if flags says available : it's Bound, goto next cell.
142# if filepath is "default", try to expand the cell.
143# if still "default"**: cell made by "cellname create", never saved, goto next.
144# if filepath is CELL.mag, check for "available" flags, if none: Unbound.
145# else cell is bound.
146# **: should never get there
147proc unbounds {} {
148 set allcells [cellname list allcells]
149 # filter (UNNAMED)
150 set allcells [lsearch -exact -not -all -inline $allcells "(UNNAMED)"]
151 # set nbrAllCells [llength $allcells]
152 set ercell {}
153 foreach cell $allcells {
154 # filter (without recording as skipped) non-existent cells.
155 if {![cellnameExists $cell]} { continue }
156
157 # filepath = "default": unexpanded (not loaded from disk),
158 # or created in-mem and never saved (is writable already
159 # though flags won't say so): skip both.
160 # TODO: use a combo of filepath & flags likely can detect created in-mem
161 set tmppath [cellname list filepath $cell]
162 if {$tmppath eq "default"} {
163 lappend skipped $cell
164 continue
165 }
166
167 # flags not meaningful, until expanded or expand attempted.
168 # After expand attempt (filepath != "default"), and flags
169 # can now be used to determine cell unbound: not available.
170 set flags [cellname list flags $cell]
171 if {[lsearch -exact $flags available] < 0} {
172 lappend ercell $cell
173 continue
174 }
175 }
176 set ercell ;# return list of unbound cells, if any
177}
178}
179
180# without top-level proc around bulk of script, intermediate error statements don't abort script.
181proc main {argv} {
182
183set mlen [llength $argv]
184
185# process name-value pair options, if any
186set nbrErr 0
187set ndx 0
188set max [llength $argv]
189set extTechOpt {} ;# -T ... but not used here
190set enumFilel {} ;# -l ... enum output file
191set enumFileL {} ;# -L ... enum output file
192set enumFileKm {} ;# -km ... enum output file
193set variant {} ;# -S ... non-default drc style
194set istyle {} ;# -I ... non-default cifinput style
195set doFeedback 1 ;# -nf sets to 0: Do not write *.drtcl per-cell feedback files.
196set pathSub 0 ;# -path-sub ... do 'gds path subcell yes'
197set polySub 0 ;# -poly-sub ... do 'gds polygon subcell yes'
198set subcellTab 1 ;# -tt, -tc both turn OFF subcell count-by-error report
199set topcellTab 1 ;# -tc turns OFF topcell count-by-error report
200set flatten 0
201while {$ndx < $max && [string match "-*" [lindex $argv $ndx]]} {
202 set opt [lindex $argv $ndx]
203 incr ndx
204 switch -exact -- $opt {
205 -T {
206 if {$ndx != 1} {
207 usage "-T option must very 1st (here was #$ndx)"
208 exit 1
209 }
210 if {$ndx == $max} {
211 usage "missing tech-file argument for -T option"
212 exit 1
213 }
214 set extTechOpt [lindex $argv $ndx] ;# unused
215 incr ndx
216 }
217 -S {
218 if {$ndx == $max} {
219 usage "missing drcStyle argument for -S option"
220 exit 1
221 }
222 set variant [lindex $argv $ndx]
223 incr ndx
224 }
225 -I {
226 if {$ndx == $max} {
227 usage "missing cifinput-style argument for -I option"
228 exit 1
229 }
230 set istyle [lindex $argv $ndx]
231 incr ndx
232 }
233 -F { set flatten 1}
234 -nf { set doFeedback 0 }
235 -path-sub { set pathSub 1}
236 -poly-sub { set polySub 1}
237 -pps { set pathSub 1; set polySub 1}
238 -tt { set subcellTab 0 ; set topcellTab 1}
239 -tc { set subcellTab 0 ; set topcellTab 0 }
240 -km {
241 if {$ndx == $max} {
242 usage "missing outputFile argument for -km option"
243 exit 1
244 }
245 set enumFileKm [lindex $argv $ndx]
246 incr ndx
247 }
248 -l {
249 if {$ndx == $max} {
250 usage "missing outputFile argument for -l option"
251 exit 1
252 }
253 set enumFilel [lindex $argv $ndx]
254 incr ndx
255 if {[catch {set enumOut [open $enumFilel w]} msg]} {
256 error "ERROR: ${::Prog}: failed to open-for-write '$enumFilel' threw error, $msg"
257 }
258 puts "${::Prog}: enumerating each error bbox to: $enumFilel"
259 }
260 -L {
261 if {$ndx == $max} {
262 usage "missing outputFile argument for -L option"
263 exit 1
264 }
265 set enumFileL [lindex $argv $ndx]
266 incr ndx
267 if {[catch {set enumOutL [open $enumFileL w]} msg]} {
268 error "ERROR: ${::Prog}: failed to open-for-write '$enumFileL' threw error, $msg"
269 }
270 puts "${::Prog}: enumerating each error bbox to: $enumFileL"
271 }
272 default {
273 usage "unknown option: $opt"
274 exit 1
275 }
276 }
277}
278
279if {$ndx == $max} {
280 usage {Insufficient number of arguments, need gdsFileName [topCellName]}
281 exit 1
282}
283
284set gdsf [lindex $argv $ndx] ; incr ndx
285set topc {}
286set topcStr "(AUTO)"
287if {$ndx < $max} {
288 set topc [lindex $argv $ndx] ; incr ndx
289 set topcStr $topc
290}
291# error if extra options (not understood, something is wrong):
292if {$ndx < $max} {
293 error "ERROR: ${::Prog}: after gdsFile=\"$gdsf\", topcell=\"$topc\" found unsupported extra arguments: [lrange $argv $ndx end]"
294}
295# ndx no longer used for argv position from here
296
297gdsChk $gdsf
298
299# warning on combo of -tc & -km. If -km ok, open its output file.
300if {$enumFileKm ne {}} {
301 if {! $topcellTab} {
302 puts "WARNING: ${::Prog}: with -tc cannot (-km) write klayout-marker-db"
303 } else {
304 if {[catch {set enumOutKm [open $enumFileKm w]} msg]} {
305 error "ERROR: ${::Prog}: failed to open-for-write '$enumFileKm' threw error, $msg"
306 }
307 puts "${::Prog}: enumerating each error bbox to: $enumFileKm"
308 }
309}
310
311# write a line with timestamp and all arguments to stdout (log)
312# (magic renames the TCL clock command)
313set clockp clock
314if {[info command $clockp] == {} && [info command orig_clock] != {}} {
315 set clockp orig_clock
316}
317set nowSec [$clockp seconds]
318set timestamp [$clockp format $nowSec -format "%Y-%m-%d.%T.%Z"]
319# TODO: quote logged argv here as needed so it's machine readable for replay purposes.
320puts "${::Prog}: timestamp: $timestamp, arguments: $argv"
321
322# just Manhattan is default, turn on euclidean, and log new mode
323drc euclidean on
324drc euclidean
325
326# 8.1.83 this worked:
327# drc off; gds drccheck no; gds read ... ; load topcell; select top cell; expand; drc check; drc update; drc listall count
328# By 8.2.64, that fails, the 'drc listall count' reports errors only in the top-cell, no subcells.
329# 8.1.83 & 8.2.193 this works (gds drccheck defaults to on anyway):
330# drc off; gds drccheck yes; gds read ... ; load topcell; select top cell; expand; drc check; drc update; drc listall count
331#
332# But are we properly avoiding redundant drc runs?
333#
334# turn off background checker. We'll invoke checks explicitly.
335drc off
336gds drccheck yes
337puts "drc status (whether background checking enabled) is: [drc status]"
338puts "gds drccheck (whether gds-read marks new cells as need-drc) is: [gds drccheck]"
339
340# set user's drc style; set user's cifinput istyle
341# These are back-to-back without intervening status messages.
342# If both wrong their errors are back-to-back.
343set res {}
344set res [drc list style]
345if {$variant != {}} {
346 set allstyle [drc listall style]
347 set ndx [lsearch -exact $allstyle $variant]
348 if {$ndx < 0} {
349 puts "ERROR: ${::Prog}: drc style '$variant' not one of those available: $allstyle"
350 incr nbrErr
351 } else {
352 set res [drc list style $variant]
353 }
354}
355set res2 [cif list istyle]
356if {$istyle != {}} {
357 set allstyle [cif listall istyle]
358 set ndx [lsearch -exact $allstyle $istyle]
359 if {$ndx < 0} {
360 puts "ERROR: ${::Prog}: istyle '$istyle' not one of those available: $allstyle"
361 incr nbrErr
362 } else {
363 set res2 [cif istyle $istyle]
364 }
365}
366if {$res != {}} {
367 puts "drc style reports:\n$res"
368}
369if {$res2 != {}} {
370 puts "cif istyle reports:\n$res2"
371}
372
373# gds {path,polygon} subcell yes
374if {$pathSub != 0} { gds path subcells yes }
375puts "gds path subcells: [gds path subcells]"
376if {$polySub != 0} { gds polygon subcells yes }
377puts "gds polygon subcells: [gds polygon subcells]"
378
379# todo: this catch never happens. Need nicer error check of 'gds read' somehow. Can check for zero-sized file?
380# if use /dev/null for example, it prints its own error message, but no throw, no useful return value.
381puts "doing: gds read $gdsf ..."
382if {[catch {set res [gds read $gdsf]} msg]} {
383 puts "ERROR: ${::Prog}: 'gds read $gdsf' threw error, $msg"
384 incr nbrErr
385}
386# nothing useful:
387# puts "gds-read res: $res"
388
389set topcells [cellname list top]
390set allcells [cellname list allcells]
391# puts "cellname-list-top from GDS is: $topcells"
392# puts "cellname-list-allcells from GDS are: $allcells"
393# filter (UNNAMED)
394set topcells [lsearch -exact -not -all -inline $topcells "(UNNAMED)"]
395set allcells [lsearch -exact -not -all -inline $allcells "(UNNAMED)"]
396set nbrAllCells [llength $allcells]
397
398if {$topcells == {}} {
399 puts "ERROR: ${::Prog}: GDS-read did not report any useful cell name(s) found."
400 incr nbrErr
401}
402
403if {$nbrErr > 0} {
404 return $nbrErr ;# outside of main, we print termination with errors message
405}
406
407if {$topc == {}} {
408 # try and infer topcell from cellname-list-top.
409 # presume its list of cells not placed anywhere else.
410 # todo: test with "library" GDS having more than one topcell
411 # here we just take the last entry
412 set topc [lindex $topcells end]
413 set topcStr $topc
414 puts "WARNING: auto-picked top-cell \"$topc\"; the topcells inferred from GDS are: $topcells"
415} else {
416 # verify input topc argument exists in GDS read result
417 set ndx [lsearch -exact $allcells $topc]
418 if {$ndx < 0} {
419 puts "ERROR: ${::Prog}: top-cell name: $topc, not found in GDS"
420 puts "info: top cells inferred from GDS are: $topcells"
421 puts "info: all cells inferred from GDS are: $allcells"
422 return [incr nbrErr] ;# outside of main, we print termination with errors message
423 }
424}
425
426puts "${::Prog}: running drc on -gds: $gdsf -topcell: $topcStr"
427reportTechFile
428
429# todo: need to error check load command somehow (no useful return value).
430# it can fail with error message (in log) like:
431# File dne.mag couldn't be found
432# Creating new cell
433if {[catch {set res [load $topc]} msg]} {
434 puts "ERROR: ${::Prog}: 'load $topc' threw error (maybe cellName not found in GDS?), $msg"
435 return [incr nbrErr] ;# outside of main, we print termination with errors message
436}
437# nothing useful:
438# puts "load $topc res: $res"
439
440if {$flatten} {
441 # delete (UNNAMED) if any.
442 set trg "(UNNAMED)"
443 if {[cellnameExists $trg]} {cellname delete $trg}
444
445 # rename top cell to (UNNAMED)
446 cellname rename $topc $trg
447
448 # now Edit Cell contents are original top cell, but under name (UNNAMED)
449 # flatten Edit-Cell into original top cell name
450 puts "${::Prog}: flattening..."
451 flatten $topc
452
453 # load and edit new version of top cell
454 load $topc
455
456 # crude way even in batch to determine the "current" cell; perhaps not yet the "Edit" cell
457 # WARNING, if topcell locked elsewhere or not writable, it can't become the "Edit" cell.
458 set topcw [cellname list window]
459 if {$topcw ne $topc} {
460 puts "ERROR: ${::Prog}: assertion failed, post-flatten, $topc, is not the current cell, 'cellname list window'=$topcw"
461 return [incr nbrErr] ;# outside of main, we print termination with errors message
462 }
463
464 # should not be necessary:
465 select top cell
466 edit
467
468 # crude way even in batch to determine the "current" cell; perhaps not yet the "Edit" cell
469 # WARNING, if topcell locked elsewhere or not writable, it can't become the "Edit" cell.
470 set topcw [cellname list window]
471 if {$topcw ne $topc} {
472 puts "ERROR: ${::Prog}: assertion-2 failed, post-flatten, $topc, is not the current cell, 'cellname list window'=$topcw"
473 return [incr nbrErr] ;# outside of main, we print termination with errors message
474 }
475}
476
477# Erase all preexisting *.drtcl first. Else when cell transitions from
478# dirty in previous run (leaving *.drtcl), to clean, the old *.drtcl
479# remains.
480# TODO: only delete *.drtcl of cells in 'cellname list allcells'?
481if {$doFeedback} {
482 set files [glob -nocomplain -types {f} -- ./*.drtcl]
483 if {$flatten} {
484 # only delete topcell's .drtcl in flatten mode, if there is one
485 set files [lsearch -all -inline -exact $files ./$topc.drtcl]
486 }
487 if {$files != {}} {
488 # TODO: detect/report failure details better here?
489 puts "${::Prog}: deleting preexisting *.drtcl"
490 set msg {}
491 set delfail [catch {eval {file delete} $files} msg]
492 set files [glob -nocomplain -types {f} -- ./*.drtcl]
493 if {$delfail || $files != {}} {
494 puts "ERROR: ${::Prog}: failed to clean old ./*.drtcl files. $msg"
495 incr nbrErr
496 }
497 }
498}
499
500# 1st "select top cell": without it drc-list-count is blank, and error count reduced.
501select top cell
502
503set bbox0 [view bbox]
504set outScale [cif scale out]
505
506# set bbox1 [view bbox]
507
508# "select top cell" and box [view bbox] should be equivalent in
509# placing a box around whole cell extent.
510# The box cmd ALSO prints lambda and micron user-friendly box data,
511# but it prints microns with not enough resolution,
512# (and no option to disable that flawed print out).
513#
514# todo: emulate box output in full, except for higher resolution,
515# here we only scale/print the overall bbox in microns.
516set bbs {}
517foreach oord $bbox0 {
518 lappend bbs [format "%.3f" [expr {$outScale * $oord}]]
519}
520puts "info: outScale: [format "%.6f" $outScale], view-bbox: $bbox0"
521puts "info: Root cell box: ([lindex $bbs 0] [lindex $bbs 1]), ([lindex $bbs 2] [lindex $bbs 3])"
522
523drc check
524drc catchup
525drc statistics
526drc rulestats
527# puts "doing plain: drc count"
528drc count
529
530# 2nd select top cell needed else error count may be reduced (why? bbox does not change due to DRC)
531select top cell
532
533set celllist [drc listall count]
534set drcListCountTot [drc list count total]
535# puts stdout "(drc listall count) is << " nonewline; puts stdout [list $celllist] nonewline; puts " >>"
536# puts stdout "(drc list count) is << " nonewline; puts stdout [list [drc list count]] nonewline; puts " >>"
537# puts stdout "(drc list count total) is << " nonewline; puts stdout [list $drcListCountTot] nonewline; puts " >>"
538# puts stdout "(drc listall count total) is << " nonewline; puts stdout [list [drc listall count total]] nonewline; puts " >>"
539# puts stdout "(drc list why) is << " nonewline; puts stdout [list [drc list why]] nonewline; puts " >>"
540# puts stdout "(drc listall why) is << " nonewline; puts stdout [list [drc listall why]] nonewline; puts " >>"
541
542set bbox2 [view bbox]
543if {$bbox2 != $bbox0} {
544 set bbs {}
545 foreach oord $bbox2 {
546 lappend bbs [format "%.3f" [expr {$outScale * $oord}]]
547 }
548 puts "info: outScale: [format "%.6f" $outScale], view-bbox: $bbox2"
549 puts "info: Root cell box2: ([lindex $bbs 0] [lindex $bbs 1]), ([lindex $bbs 2] [lindex $bbs 3])"
550}
551
552
553# canonicalize order of celllist, move topc to last (if present whatsoever).
554# force our own artificial entry for topc (zero errors) if not present (was clean)
555# puts "celllist before: $celllist"
556set nbrErrCells [llength $celllist]
557set topcPair [lsearch -inline -index 0 -exact $celllist $topc]
558set celllist [lsearch -not -all -inline -index 0 -exact $celllist $topc]
559set celllist [lsort -index 0 -dictionary $celllist]
560if {$topcPair == {}} {
561 # puts "info: ${::Prog}: $topc clean, forcing celllist entry for it"
562 set topcPair [list $topc 0]
563}
564lappend celllist $topcPair
565# puts stdout "adjusted celllist(drc list count) is << " nonewline; puts stdout $celllist nonewline; puts " >>"
566
567array set kmErr2catNm {}
568array set kmErr2catDesc {}
569array set kmCell2item {}
570if {$celllist != {} && [info exists enumOutKm]} {
571 # Header example of .lyrdb klayout Marker format
572 # <?xml version="1.0" encoding="utf-8"?>
573 # <report-database>
574 # <description>Diff of 'x.gds, Cell RINGO' vs. 'x.gds[1], Cell INV2'</description>
575 # <original-file/>
576 # <generator/>
577 # <top-cell>RINGO</top-cell>
578 # <tags>
579 # <tag>
580 # <name>red</name>
581 # <description>Red flag</description>
582 # </tag>
583 # ...
584 # </tags>
585
586 puts $enumOutKm {<?xml version="1.0" encoding="utf-8"?><report-database>}
587 puts $enumOutKm "<description>$topc DRC timestamp: $timestamp, arguments: $argv</description>"
588 puts $enumOutKm {<original-file/><generator/>}
589 puts $enumOutKm "<top-cell>$topc</top-cell>"
590 puts $enumOutKm {<tags/>}
591 puts $enumOutKm {<cells>}
592
593 # multiple <cells>...</cells> sections do accumulate, but cells and categories need
594 # to be defined before use in an item (specific error), and we know cell names here,
595 # so declare all cells to klayout here.
596 #
597 # Cell-specific header of klayout marker file
598 # <cell>
599 # <name>CELLNAME1</name>
600 # <variant>1</variant> (don't need)
601 # </cell>
602 #
603 foreach pair $celllist {
604 set acell [lindex $pair 0]
605
606 # for -tt, no subcell error-detail: don't write subcells in <cells>...</cells> section.
607 if {$acell ne $topc && ! $subcellTab} { continue }
608
609 puts $enumOutKm " <cell><name>$acell</name></cell>"
610 set kmCell2item($acell) {}
611 }
612 puts $enumOutKm {</cells>}
613}
614
615# loop over celllist
616set gtotal 0
617set gcells 0
618set lumpedHeader 0
619foreach pair $celllist {
620 set acell [lindex $pair 0]
621 set acount [lindex $pair 1]
622
623 if {$acell ne $topc && ! $subcellTab} {
624 if {! $lumpedHeader} {
625 puts "--- #err|cell, lumped total counts"
626 set lumpedHeader 1
627 }
628 puts "[format {%8d} $acount] $acell"
629 incr gcells
630 incr gtotal $acount
631 continue
632 }
633 if {$acell eq $topc && ! $topcellTab} {
634 if {! $lumpedHeader} {
635 puts "--- #err|cell, lumped total counts"
636 set lumpedHeader 1
637 }
638 puts "[format {%8d} $acount] $acell"
639 incr gcells
640 incr gtotal $acount
641 continue
642 }
643 puts ""
644
645 # todo: need useful error check of load command
646 if {[catch {set res [load $acell]} msg]} {
647 puts "ERROR: ${::Prog}: 'load $acell' threw error, $msg"
648 return [incr nbrErr] ;# outside of main, we print termination with errors message
649 }
650
651 # instead use quiet version for per-cell selects
652 select top cell
653
654 set drcListCountTot [drc listall count total]
655
656 # enumerate errors under box, plain "drc why" only reports unique types, no quantities
657 # as-yet-undocumented "drc listall why" will give: {errStr1 {errBox1 ...} errStr2 {errBox1 ...} ... }
658 set pareto {}
659 set total 0
660 set enumTotal 0
661 set types 0
662 set typeDup 0
663 set dups 0
664
665 set fbOut {}
666 if {$acount != 0} {
667 # file path for feedback, keep in CWD
668 if {$doFeedback && $fbOut == {}} {
669 set fbOut "./$acell.drtcl"
670 if {![file writable $fbOut] &&
671 ([file exists $fbOut] || ![file writable [file dir $fbOut]])} {
672 puts stderr "ERROR: ${::Prog}: feedback output not writable, $fbOut"
673 incr nbrErr
674 set fbOut {}
675 } elseif {[catch {set outfb [open $fbOut w]} msg]} {
676 puts stderr "ERROR: ${::Prog}: failed to truncate previous feedback output, $fbOut : $msg"
677 incr nbrErr
678 set fbOut {}
679 }
680 }
681
682 foreach {str boxes} [drc listall why] {
683 # sort errors
684 set boxes [lsort -dictionary $boxes]
685 # for our pareto, gather data
686 set this [llength $boxes]
687 incr total $this
688 incr types
689 lappend pareto [list $this $str]
690
691 # for enumOut, emulate formatting of $CAD_ROOT/magic/tcl/drc.tcl, which is
692 # not tk pure: fails with complaint about winfo
693 # note: we walk these errors also in order to count/report stats on duplicates, even if not outputing enumerations
694 if {[info exists enumOut]} {
695 if {$types == 1} {
696 puts $enumOut "[join $pair]\n----------------------------------------"
697 }
698 puts $enumOut "${str}\n----------------------------------------"
699 }
700 if {[info exists enumOutL]} {
701 if {$types == 1} {
702 puts $enumOutL "[join $pair]\n----------------------------------------"
703 }
704 puts $enumOutL "${str}\n----------------------------------------"
705 }
706 if {[info exists enumOutKm]} {
707 # category names must be declared all together up front before use in items
708 # so we only store their names (error strings) and error detail (items)
709 # to dump after all cells and errors are processed.
710 # TODO: Only quote catName in item if embeds dot, instead of full-time
711 # TODO: test klayout handles literal (non-entity) single-quote in double-quoted name
712 set strKmNm $str
713 set strKmDesc $str
714 regsub -all -- {&} $strKmDesc {\&amp;} strKmDesc ;# perhaps not needed; just in case
715 regsub -all -- {<} $strKmDesc {\&lt;} strKmDesc ;# description does not have such bug, so use correct entity
716 regsub -all -- {>} $strKmDesc {\&gt;} strKmDesc ;# perhaps not needed; just in case
717 regsub -all -- {&} $strKmNm {-and-} strKmNm ;# perhaps not needed; just in case
718 regsub -all -- {>} $strKmNm {-gt-} strKmNm ;# perhaps not needed; just in case
719 regsub -all -- {<} $strKmNm {-lt-} strKmNm ;# catName klayout bug: info win truncates at '<' as &lt; entity
720 regsub -all -- "\"" $strKmNm {'} strKmNm ;# we dqoute each catNm in item, so change embedded double to single
721 set kmErr2catNm($str) $strKmNm
722 set kmErr2catDesc($str) $strKmDesc
723 #
724 # example klayout Marker format, header of one item (one error instance)
725 # <item>
726 # <tags/> (don't need?)
727 # <image/> (don't need?)
728 # <category>'DRC-MSG-STR'</category> (cat1.cat2 path delimit by dot: names with dot need single|double quotes)
729 # <cell>RINGO:1</cell> (don't need :N variant suffix)
730 # <visited>false</visited> (optional? start with false?)
731 # <multiplicity>1</multiplicity> (not boolean, if error "represents" more that are NOT enumerated)
732 # <values> ... </values>
733 # </item>
734
735 set itemStr "<item><category>\"$strKmNm\"</category><cell>$acell</cell><values>"
736 }
737 set lastq {}
738 set thisDup 0
739 foreach quad $boxes {
740 set quadUM {}
741 set kmBoxUM {}
742 foreach coord $quad {
743 set valum [expr {$coord * $outScale}]
744 set valumf [format "%.3f" $valum]
745 lappend quadUM "${valumf}um"
746 lappend kmBoxUM ${valumf}
747 }
748 set dup [expr {$quad == $lastq}]
749 incr thisDup $dup
750 set line $quadUM
751 if {[info exists enumOut]} {
752 if {$dup} {
753 puts $enumOut "[join $line] #dup"
754 } else {
755 puts $enumOut [join $line]
756 }
757 }
758 if {[info exists enumOutL]} {
759 if {$dup} {
760 puts $enumOutL "$quad #dup"
761 } else {
762 puts $enumOutL $quad
763 }
764 }
765 if {[info exists enumOutKm]} {
766 # <value>text: 'item: polygon'</value> (text is optional? Repeat the box coordinates here in um?)
767 # <value>polygon: (1.4,1.8;-1.4,1.8;-1.4,3.8;1.4,3.8)</value>
768 # <value>box: (1.4,1.8;-1.4,3.8)</value>
769 # </values>
770 set kmItem $itemStr
771 append kmItem " <value>box: ([lindex $kmBoxUM 0],[lindex $kmBoxUM 1];[lindex $kmBoxUM 2],[lindex $kmBoxUM 3])</value>"
772 if {$dup} {
773 append kmItem " <value>text: 'dup'</value>"
774 }
775 append kmItem " </values></item>"
776 lappend kmCell2item($acell) $kmItem
777 }
778 if {$fbOut != {}} {
779 set line [join $quadUM]
780 regsub -all -- "(\[\[\"\$\\\\])" $str {\\\1} strdq
781 puts $outfb "[concat box $line]" nonewline
782 puts $outfb " ; feedback add \"$strdq\" medium" nonewline
783 if {$dup} {
784 puts $outfb " ;#dup"
785 } else {
786 puts $outfb ""
787 }
788 }
789
790 incr enumTotal
791 set lastq $quad
792 }
793 if {$thisDup} {
794 incr typeDup
795 incr dups $thisDup
796 }
797 if {[info exists enumOut]} {
798 puts $enumOut "----------------------------------------\n"
799 }
800 if {[info exists enumOutL]} {
801 puts $enumOutL "----------------------------------------\n"
802 }
803 }
804 }
805
806 if {$fbOut != {}} {
807 close $outfb
808 set outfb {}
809 }
810
811 set pareto [lsort -integer -decreasing -index 0 $pareto]
812 if {$total > 0} {
813 puts "--- #err|description, table for cell: $acell"
814 }
815 foreach pair $pareto {
816 puts "[format {%8d} [lindex $pair 0]] [lindex $pair 1]"
817 }
818 if {$typeDup} {
819 puts "[format {%8d} $dups] total duplicate error(s) among $typeDup error type(s), cell: $acell"
820 }
821 puts "[format {%8d} $total] total error(s) among $types error type(s), cell: $acell"
822 # add to grand-totals
823 incr gcells
824 incr gtotal $total
825
826 # always compare the total from the enum to the pareto as error check
827 if {$total != $enumTotal} {
828 puts "ERROR: ${::Prog}: cell: $acell, internal error, pareto vs enum count mismatch: $total != $enumTotal"
829 incr nbrErr
830 }
831 # wish to compare the drc-list-count-total to the pareto total.
832 # Per te 2014-08-27 : it is not an error.
833 if {$total != $drcListCountTot} {
834 # puts "info: ${::Prog}: cell: $acell, drc-list-count-total vs drc-listall-why mismatch {drc list count total} gave $drcListCountTot, but {drc listall why} gave $total"
835 }
836}
837
838# grand totals
839puts "[format {%8d} $nbrErrCells] of $nbrAllCells cell(s) report error(s)"
840puts "[format {%8d} $gtotal] grand-total error(s) across $gcells cell(s)"
841
842if {[info exists enumOut]} {
843 close $enumOut
844}
845if {[info exists enumOutL]} {
846 close $enumOutL
847}
848if {[info exists enumOutKm]} {
849 # declare all category names and descriptions, note '<' in name vs description are represented differently
850 #
851 # <categories><category><name>layerN width -lt- 1.0um</name>
852 # <description>layerN width &lt; 1.0um</description></category>
853 # <category> ... </category></categories>
854 #
855 puts $enumOutKm "<categories>"
856 foreach errStr [array names kmErr2catNm] {
857 set nm $kmErr2catNm($errStr)
858 set desc $kmErr2catDesc($errStr)
859 puts $enumOutKm " <category><name>$nm</name><description>$desc</description></category>"
860 }
861 puts $enumOutKm "</categories>"
862
863 # dump all items (after all cells and all categories have been defined up front)
864 puts $enumOutKm "<items>"
865 foreach {acell items} [array get kmCell2item] {
866 foreach item $items {
867 puts $enumOutKm $item
868 }
869 }
870 puts $enumOutKm "</items>"
871
872 # footer example .lyrdb klayout Marker file
873 # </report-database>
874 puts $enumOutKm {</report-database>}
875 close $enumOutKm
876}
877# todo: implement super-pareto, ranked table of SUM of all DRC errs/counts from ALL cells.
878# (It still would not reflect as-if-flat hierarchical expansion due to repetition of instances).
879
880set nbrErr ;# return value
881} ;# end main
882
883# non-zero exit-status on errors, either if thrown by main, or counted and returned by main
884set nbrErr 0
885if {[catch {set nbrErr [main $argv]} msg]} {
886 puts stderr $msg
887 set nbrErr 1
888} elseif {$nbrErr > 0} {
889 puts "ERROR: ${::Prog}: script terminated with errors reported above."
890}
891exit $nbrErr
892
893# for emacs syntax-mode:
894# Local Variables:
895# mode:tcl
896# End: