Showing posts with label stefan schippers. Show all posts
Showing posts with label stefan schippers. Show all posts

Wednesday, November 18, 2026

Dear Tim Edwards - Please Ensure Level-Shifters in SKY130 Don't Keep Causing Grief


Hi Tim,

A short report on an old issue that is still catching people, with a request at the end.

In December 2021 you diagnosed skywater-pdk issue #349 (and #305): the layout-extracted .spice netlists of sky130_fd_sc_hvl__lsbuflv2hv_1 and sky130_fd_sc_hvl__lsbufhv2lv_1 in google/skywater-pdk-libs-sky130_fd_sc_hvl turned the second VGND/VPWR rail of these double-height cells into internal nodes, and open_pdks sidesteps it by regenerating the standard-cell netlists from GDS at install. That is all still exactly right. What I want to add is what the fault does and how we hit it in 2026.

In lsbuflv2hv_1, net a_686_151# is the source of both LV inverter NMOS and the ground of the five HV pull-downs of a_1197_107#, and touches nothing else; a_1606_563# is the source of the cross-coupled PMOS that pulls a_504_1221# up, and appears once. So a_504 can only be pulled down and X sits at VGND for any A. In lsbufhv2lv_1, a_30_443# and VPWR each appear once. In ngspice (45.2 and a current build, open_pdks models, tt, LVPWR 1.8 V, VPWR 3.3 V) the upstream netlist gives X = 9 nV for both input levels; your open_pdks netlist gives 0 / 3.3 V with 1.2 ns / 0.7 ns delays. The cell is not mis-matching, it is dead, and it dies quietly: the file is complete, loads with no warning, and in a mixed-signal block it looks like a design bug. We lost most of a day to it.

How we got the bad file: our design environment had no open_pdks sky130 install at the time, so the 69 per-cell .spice files were pulled from the library repository on GitHub and concatenated, on the (checked, 67-of-69-true) assumption that this is what open_pdks installs. Today the same files come from git clone of skywater-pdk-libs-sky130_fd_sc_hvl (main = branch-0.0.3 = 4fd4f858), from git clone --recursive google/skywater-pdk (the latest submodule is pinned to that commit), from the googlesource mirror, and from raw downloads. The library repository is archived, so none of that will change on its own, and #349 is still open with a title that does not say "do not simulate with this file".

The request: you are the person whose word on this carries, and open_pdks is where people who got burned will look. Would any of these be reasonable?

1. A sentence in the open_pdks sky130 README (or the install log) saying that the .spice files shipped in the skywater-pdk library repositories are not the ones open_pdks installs, that the two hvl level shifters are broken upstream, and that the open_pdks-generated libs.ref/sky130_fd_sc_hvl/spice deck is the one to use.
2. A closing comment on #349 and #305 stating the same, so the search result people land on says it plainly. I am happy to post the simulation evidence there myself if that helps (I have it written up).
3. If you know who at Google or SkyWater can still touch the archived repository or skywater-pdk-docs, a README line in cells/lsbuflv2hv and cells/lsbufhv2lv pointing at open_pdks.

If a lint is of any use for the open_pdks install: inside a .subckt, any net that appears on exactly one device terminal, or that is touched only by MOSFET terminals and has no path to a port, flags both cells and nothing else in that library.

Thank you for open_pdks, magic and netgen, and for having had the right answer on this five years ago.

Best regards,
Ananth

Friday, November 13, 2026

GF180MCU Device Cheat Sheet (But Which Flavor?:)

GlobalFoundries 180 nm MCU, variant D (open_pdks gf180mcuD, BSIM4). Corner typical / res_typical; mismatch via sw_stat_mismatch=1 (per-instance ΔVT and Δβ in the fets_mm wrappers). Every number below is simulated from the vendored models with plain ngspice decks, typical corner, 27 °C; the Monte-Carlo columns use the PDK's own per-device mismatch model with 30 samples. Click a column header to sort (first click ascending, second descending); click the # header to restore the original order. Devices marked † could not be simulated at the standard 10/0.5 and 0.5/2 geometries; the geometry used is listed under the table.

FETs

#DeviceTypeLmin (µm)Wmin (µm)VDS max (V)VGS max (V)Vth (V)7gm,in (µS)1gm,mir (µS)2AVT (mV·µm)3fT (GHz)4σ ΔI/I mirror (%)5σ Vos pair (mV)6
1nfet_03v33.3 V NMOSNMOS0.280.223.603.600.711617.07.42.035.13.3
2pfet_03v33.3 V PMOSPMOS0.280.223.603.60-0.791103.56.90.992.43.2
3nfet_05v0†5 V NMOS (same model as 06v0)NMOS0.600.305.505.500.711556.519.02.466.37.5
4pfet_05v05 V PMOSPMOS0.500.305.505.50-0.821102.914.11.532.76.5
5nfet_06v0†6 V NMOSNMOS0.700.306.506.500.721446.516.81.976.36.3
6pfet_06v06 V PMOSPMOS0.500.306.506.50-0.821102.914.11.552.76.5
7nfet_06v0_nvt†6 V native NMOSNMOS1.800.806.506.50-0.09175n/an/a2.02n/an/a
8nfet_03v3_dss3.3 V NMOS, drain salicide blockNMOS0.280.223.603.600.711607.07.42.025.13.3
9pfet_03v3_dss3.3 V PMOS, drain salicide blockPMOS0.280.223.603.60-0.791103.56.90.992.43.2
10nfet_06v0_dss†6 V NMOS, drain salicide blockNMOS0.600.306.506.500.711586.519.02.566.37.5
11pfet_06v0_dss6 V PMOS, drain salicide blockPMOS0.500.306.506.50-0.821102.914.11.552.76.5

† Geometry actually simulated (W/L in µm) where the standard 10/0.5 and 0.5/2 devices are not allowed: nfet_05v0: input-pair device 10/0.6 (Lmin / Wmin); nfet_06v0: input-pair device 10/0.7 (Lmin / Wmin); nfet_06v0_nvt: input-pair device 10/1.8, mirror device 0.8/2 (Lmin / Wmin); nfet_06v0_dss: input-pair device 10/0.6 (Lmin / Wmin).

Notes

  1. gm of one input-pair device, W = 10 µm, L = 0.5 µm (the geometry listed under † where the model does not allow that), ID = 10 µA, VDS = half the nominal supply of the device's gate class (1.65 V, 2.5 V, 3 V), VSB = 0, 27 °C; dID/dVGS from a 1 mV dc sweep.
  2. gm of one current-mirror device, W = 0.5 µm, L = 2 µm (or the † geometry), diode-connected, ID = 1 µA. Blank when the device cannot work as a diode-connected mirror (zero-VT or depletion device: VDS = VGS leaves it in triode).
  3. Pelgrom coefficient for the threshold: σ(ΔVT) of two input-pair devices (geometry of note 1) times √(W·L), from 30 Monte-Carlo mismatch samples (ΔVT read from the model's operating-point vth). With 30 samples a σ carries about ±13 % (1σ) statistical error; the last section compares the samples with the model's own mismatch parameters.
  4. Transit frequency of the input-pair device at the bias of note 1: frequency where |id/ig| = 1 in a small-signal sweep (drain at fixed VDS, source and bulk on the rail).
  5. Current-mirror error: two 0.5/2 devices at 1 µA (the "gm·ΔVGS" of a mirror), master diode-connected, slave at the same VDS; σ of (Islave − Imaster) / Imaster over 30 mismatch samples.
  6. Input offset: σ(ΔVGS) of two input-pair devices at 10 µA each (geometry of note 1), the number a differential pair of this size would show as random offset.
  7. Threshold voltage as the model reports it at the operating point of note 1 (BSIM4 / PSP vth of the 10/0.5 device, VSB = 0, so it includes the model's drain-induced shift at that VDS); PMOS values are given with their negative sign, a negative NMOS value marks a depletion-mode device.

Resistors

#ResistorRsh (Ω/sq)aTC (ppm/K)fWmin (µm)Density (kΩ/µm²)bσ ΔR/R, 1×10 µm (%)cAR (%·µm)dRend (Ω)e
1nplus_uN+ diffusion, unsalicided59.613790.800.0931n/an/a3.67
2pplus_uP+ diffusion, unsalicided18714060.800.291n/an/a10.0
3npolyf_uN+ poly, unsalicided311-13270.800.486n/an/a8.03
4ppolyf_uP+ poly, unsalicided352-650.800.550n/an/a12.0
5ppolyf_u_1khigh-res poly 1k1001-8531.001.00n/an/a16.8
6ppolyf_u_2khigh-res poly 2k2002-15441.002.00n/an/a43.9
7ppolyf_u_3khigh-res poly 3k3004-15441.003.00n/an/a62.6
8nwelln-well105126151.200.730n/an/a50.3
9ppolyf_sP+ poly, salicided7.3632370.800.0115n/an/a1.00
10rm1metal 10.090633080.230.0017n/an/a0

Notes

  1. Sheet resistance from the model: R at W = 10 µm for L = 20 and 40 µm, Rsh = ΔR·W/ΔL, 27 °C, typical corner. A device at Wmin reads higher by the model's width bias (ΔW), up to +30 % for the n-well resistor.
  2. Resistance per unit body area at the minimum width: Rsh / Wmin² (ends, contacts and spacing not included). Highest = densest.
  3. Mismatch of two identical resistors, W = 1 µm (or Wmin), L = 10 µm, σ of ΔR/R over 30 Monte-Carlo mismatch samples.
  4. Area-normalised matching: the σ of note c times √(W·L), so σ(ΔR/R) ≈ AR/√(W·L) for another size. Lowest = best matching.
  5. End resistance per device from the same two lengths: R(L) ≈ Rsh·L/W + Rend (heads, contacts, salicide transitions).
  6. Span temperature coefficient of the sheet resistance, (Rsh(125 °C) − Rsh(−40 °C)) / (Rsh(27 °C) · 165 K), from the same wide devices; the models carry a quadratic term, so the local slope is lower at the cold end and higher at the hot end.

Ratings, sizes and what is not here

  • Voltages: nominal 3.3 V and 5 V / 6 V supplies with a 10 % overshoot allowance; the design manual caps the DC gate-to-any-node voltage at 3.63 V for thin oxide and 6.5 V for the thick-gate devices. The table lists nominal + 10 % (3.6 / 5.5 V) and 6.5 V for the 6 V devices.
  • Lmin/Wmin are the model binning limits (lmin/wmin in the vendored BSIM4 bins): 0.28 / 0.22 µm (3.3 V), 0.6 / 0.3 µm (5 V NMOS), 0.7 / 0.3 µm (6 V NMOS), 0.5 / 0.3 µm (5 V and 6 V PMOS), 1.8 / 0.8 µm (native). nfet_05v0/pfet_05v0 share the 6 V models (Appendix A of the design manual); they differ by the V5_XTOR mark and the shorter allowed L.
  • _dss = the same FET with a salicide-block (SAB) drain extension (3.78 µm NMOS / 2.78 µm PMOS on the drain, 0.28 µm on the source) for drain-voltage robustness; electrically identical here except the series drain resistance. The 10 V LDMOS (nfet_10v0_asym) has a symbol but no model in the vendored set and is not characterised. The native has no mismatch model, and its mirror cells are blank because a diode-connected depletion device (VT ≈ −0.1 V) sits in triode.
  • Mismatch parameters: the fets_mm wrappers put σ(VT) = par_vth/√(Leff·Weff) with Leff = L − 0.15 µm (0.4 µm for the 5 V / 6 V FETs) and Weff = W + 0.1 µm (0.5 µm), par_vth 7.1 / 6.7 mV·µm (3.3 V n / p), 11.6 / 10.5 (5 V and 6 V n / p). Normalised to drawn W·L that predicts AVT 8.5 / 7.9 (3.3 V) and 19.5 / 17.2 / 16.3 (5 V n, 6 V n, p); the 30-sample values sit 3–13 % below. The 0.4 µm length offset is why the same 6 V model reads 19.0 at L 0.6 and 16.8 at L 0.7.
  • Resistor Wmin: PRES.1 / LRES.1 = 0.8 µm (unsalicided P+/N+ poly), HRES.2 = 1.0 µm (1k/2k/3k high-res poly); for the diffusion, n-well, salicided poly and metal resistors no device rule was found and the PDK symbol default (0.8 / 1.2 / 0.8 / 0.23 µm) is used. GF180's vendored models carry no resistor mismatch model (the mis_r hook is never set), only global process σ: that column is empty.

Wednesday, November 11, 2026

In Case it Helps - Randomized Results in TT with SKY130nm and ngspice

Why my sky130 bandgap gave a different answer every run

One test in our xschem fork failed two of our last four full regression runs. On its own it always passed, so for weeks it was filed as "the known flaky one". This week we found the cause, and it is not a test problem at all. Every ordinary run of a tt_mm sky130 bench is a fresh Monte Carlo trial.

What we saw

The symptom

The test simulates the bandgap testbench that ships with the open_pdks sky130 examples. Sometimes ngspice ran for about 13 seconds, exited with code 1, and wrote no results file. The failing check moved from run to run.

It looked like a load problem, because it only failed inside a full test run. It wasn't.

The evidence

We copied the exact deck the test used and ran it with ngspice directly, 24 times. One run failed:

doAnalyses: TRAN:  Timestep too small; time = 1.63211e-07,
  timestep = 5e-20: trouble with node "v4#branch"
tran simulation(s) aborted

The surprise was earlier in the output. ngspice prints its starting solution before the transient begins, and no two runs printed the same one. Most started near 0 V, with noise from 1e-12 down to 1e-53. The failing run started at a non-physical point, with one node at −1.96×108 V.

Same deck, same binary, a different answer every time. Forcing ngspice onto one thread changed nothing, so it wasn't multithreading.

The cause

tt_mm means "typical, with mismatch"

The bench's corner symbol says corner=tt_mm. In the sky130 model library, that section sets MC_MM_SWITCH=1, so every transistor draws a random mismatch offset when the netlist is loaded. Plain tt sets it to 0.

ngspice has no separate Monte Carlo analysis. Monte Carlo in ngspice means "run again with a different seed". These runs set no seed, so ngspice used a different one every time. Every run was a new random sample of the circuit.

Seven of the bundled sky130 example benches use tt_mm, including the two bandgaps, the comparator, lvnand and srlatch.

The proof

Adding one line before the .control block:

.option seed=1

Six concurrent runs then found the same starting solution, and their results files matched byte for byte once ngspice's date line was removed.

Is ngspice broken?

No. ngspice and the sky130 models are doing what they were designed to do. The bundled sky130_mismatch example even calls setseed 12 when it wants a repeatable run.

The bug is the gap between that design and what a Cadence user expects. In Spectre, mismatch only applies inside a Monte Carlo analysis, so an ordinary run gives the same numbers every time. Our ADE-style front end, ASE-L, handed ngspice the deck without pinning a seed. So pressing Run on a tt_mm bench quietly ran one Monte Carlo trial instead of a repeatable simulation. On this bandgap, about one trial in 24 also failed to converge.

What we're changing

Ordinary runs get a fixed seed

ASE-L will pin the random seed for every run that isn't a Monte Carlo run, so a tt_mm bench gives the same answer each time you press Run.

Keep one subtlety in mind. A fixed seed gives you one particular mismatch sample, repeatably. It is not the mismatch-free typical device you get from tt. If you want typical numbers, use tt. If you want to see mismatch, run Monte Carlo.

If you use ngspice with sky130 today

Check your corner

If your corner ends in _mm and you aren't running Monte Carlo, either switch to the plain corner or put .option seed=1 in your deck. Otherwise two runs of the same schematic can disagree, and you'll chase a change you never made.

If you work with Claude Code: prompts that found this

A flaky test hides its cause until someone keeps the evidence. These are the requests that got us from "known flaky" to a root cause:

  • "Don't re-run it again. Find out why the simulator exits with error 1."
  • "Copy the exact deck the test simulates, and run ngspice on it directly, many times, keeping the output of any run that fails."
  • "Compare a failing run's output with a passing one, and tell me where they first differ."
  • "Before fixing anything, give me the background: where did this come from, and is the tool itself broken?"

The third one cracked it. The difference was before the transient even started, and that pointed straight at the models instead of at the test.

Does ngspice STB Work? Is ASE-L Geared to Use it?

HRH Claude Opus:

I didn't need any documentation, and native stb in ver_53 works. The ngspice session left a user guide (README.stb), a spec of what it built, three example decks and its review notes in the tree, and I had our own acceptance kit.

- Acceptance kit: accepted, with 323 checks passing, 0 failing and 0 skipped. Older binaries skipped the 32 native checks; on ver_53 all of them now run and pass.
- Your sky130 OTA demo: native gives the same loop gain as ASE-L's current method, to rounding (8e-14). The margins match the walkthrough: UGB 13.20 MHz, phase margin 56.3°, gain margin 44.6 dB at 267 MHz.
  - No probe element needed: naming a pin works, which is the extracted-view case you wanted. rm1:1 breaks the loop at the metal resistor's pin, and x1:inn at the OTA's own input; both give the same margins.
- Speed:
  - On the demo there is no difference, because loading the sky130 models (about 2.5 s) dominates.
  - On a large netlist, with a 20,000-node RC network added to the bench, the stb part takes about 0.2 s natively against about 1.5 s for ASE-L's two-sweep method.
- Monte Carlo: the shipped Monte Carlo example runs 100 samples cleanly, each within 0.002° of the analytic answer.
- Switching from v_52: ver_53 is ver_52 plus the stb work. ASE-L's demo suite prints identical numbers on both, so switching changes no existing ASE-L result.

What native stb doesn't do yet:

- No transistor as the probe: you name one of its pins instead.
- No differential or common-mode loops, the same as ASE-L's stb today.
- Frequency sweeps only: Monte Carlo runs through a loop in the deck.
- Not checked against another simulator: the margins have been checked against textbook closed forms and now ASE-L's own engine, but not against Spectre.

Two other findings:
- ASE-L doesn't use native stb yet. It still runs its own two-sweep method on every binary. Switching is the unbuilt plan in our private notes (CLIENT_NOTES.md §3). It would also let you pick any pin as the loop break, extracted views included.
- ver_53 isn't in your simulator list, which has only v_50 and v_52. Adding it is up to you, in Setup > Simulators.
- Unrelated to ver_53: the demo walkthrough's Monte Carlo table was measured on ver_51. On your v_52, and on ver_53, 3 of its 28 numbers differ in the last digit. The regression suite runs ver_51, so it stays green.



Tuesday, September 1, 2026

What You Need In Your WSL to Hack Xschem

 



┌────────────────────────────────────────────────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐

│                     group                      │                                                                   why                                                                    │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ build-essential pkg-config bison flex gawk     │ required by INSTALL; bison/flex regenerate expandlabel.c, eval_expr.c, parselabel.c                                                      │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ tcl-dev tk-dev                                 │ pulls 8.6.16 — inside the project's 8.4–8.6 window. Also gives you tclsh (runs the regression suites) and wish (the GUI gate panel)      │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ libx11-dev libxpm-dev                          │ required Xlib/Xpm                                                                                                                        │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ libcairo2-dev libxcb1-dev libx11-xcb-dev       │ the optional-but-standard rendering path (anti-aliased text)                                                                             │

│ libxrender-dev libxft-dev libfreetype-dev      │                                                                                                                                          │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ xvfb openbox x11-utils                         │ the persistent dev display. openbox is the one from issue 0645 whose absence silently made every WM measurement a bare-Xvfb measurement. │

│                                                │  x11-utils gives xdpyinfo/xprop/xwininfo/xlsclients, which devdisplay.sh and the window-mapping suites call directly                     │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ x11vnc                                         │ only for devdisplay.sh view — optional, but devdisplay.sh:341 dies with an install hint without it                                       │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ gdb valgrind                                   │ you asked; xschemtest.tcl -d 3 -l log also does allocation logging natively                                                              │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ ngspice verilator                              │ ~678 test references. Every use is auto_execok-guarded, so the ASE/cosim suites skip rather than fail without them — but skipping is     │

│                                                │ what silently hides a regression                                                                                                         │

└────────────────────────────────────────────────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘


 sudo apt install -y \

  build-essential pkg-config bison flex gawk \

  tcl-dev tk-dev libx11-dev libxpm-dev \

  libcairo2-dev libxcb1-dev libx11-xcb-dev libxrender-dev libxft-dev libfreetype-dev \

  xvfb openbox x11-utils x11vnc \

  gdb valgrind \

  ngspice verilator

Wednesday, July 8, 2026

Beware - Fable 5 the token Hog. And, You Definitely Want the Caveman Mindset

When I did have Fable 5, for a week or so, till Trump killed it, I didn't notice anything special.

What I *have* noticed is that you burn through tokens *fast* if you ultracode with Fable 5. So, don't - unless someone else is paying :)

Sadly, it's taken two months and sheer luck to realize that Claude was hacking a C project using workarounds (bespoke address sanitizers created as needed) because it didn't find gdb or valgrind - when those two would have taken barely a minute to install.

Lesson - think about what you would need if you were hand coding and also ask Claude proactively. I lucked out seeing a message "no gdb/valgrind here".

The other thing that disappointed me - it's using the existing functionality of the tool to try and recreate fails. Once I asked it why it didn't just add hooks to print out trace information, it started flying. If only I'd known :)

So, there you have it - caveman + gdb + valgrind + trace hooks.

Enjoy!




Shipped - Wire Stubbing, Cadence Style Library Manager, Cliosoft SOS Visual Diff, Cadence Style Property Forms, etc..


https://youtu.be/gtipAPsql_M?is=YO0OvlpVY0nlW4VX


https://youtu.be/JOmzWO55FzM?is=qqPYxRrxg0ts58zk


https://youtu.be/NWJ0Bo_14CY?is=6vFUFcrUpdRQJ4jz




Tuesday, March 24, 2026

Who Needs Cadence Anymore (for Schematic Tree Reporting that is :)? Make Your Own Reporter with chatGPT!

You know what I mean, if you've used Cadence - the SHIFT-T thing that gives you the schematic tree can be VERY useful, at times.

No Cadence? No problem! The great thing about our version, it even has a --depth (-d) option. But, you do need a netlist to work with.


Say this is your netlist:
 
.subckt A in out vdd vss
XB1 n1 n2 B
XB2 n3 n4 B
XC1 n5 n6 C
XC2 n7 n8 C
.ends
.subckt B a b
XD1 x y D
XD2 x y D
XD3 x y D
XD4 x y D
XC1 p q C
XE1 p q E
.ends
.subckt C p q
R1 p q 1k
.ends
.subckt D p q
R2 p q 1k
.ends
.subckt E p q
R3 p q 1k
.ends
XTOP in out vdd vss A

This is what you'll get with just python3 report_hierarchy.py netlist.sp:
 
A
|----- B (2)
|      |----- C
|      |----- D (4)
|      \----- E
\----- C (2)

That's right. I wasn't sleeping in the presentation skills class. Don't report (1)!! Maximize info to ink ratio!

Saturday, July 26, 2025

Test Driven Development in Xschem

What tests are currently implemented?

● Current Testing Infrastructure Analysis


  Test Structure:

  - 3 main test suites: create_save, open_close, netlisting

  - Test runner: run_regression.tcl orchestrates all tests

  - Test framework: Tcl-based with standardized test_utility.tcl

  - Not integrated: Tests are NOT part of the main Makefile build process


  Test Coverage:

  1. create_save.tcl: Tests script execution and schematic creation

  2. open_close.tcl: Tests file opening/closing for all .sch/.sym files in xschem_library

  3. netlisting.tcl: Tests netlisting in 4 formats (VHDL, Verilog, TDX, SPICE)


  Test Execution:

  - Tests run XSCHEM in headless mode (-q -x -r)

  - Captures debug output and validates against expected results

  - Tests are comprehensive but do NOT test keyboard/UI interactions


  Critical Gap for Refactoring:

  The existing tests validate file operations and netlisting but cannot test the handle_key_press() function since it requires

  interactive keyboard input. For safe refactoring, we'll need to:


  1. Extract testable helper functions from handle_key_press()

  2. Rely on manual testing for UI validation

  3. Use existing regression tests to ensure no core functionality breaks


  The current test infrastructure is sufficient for validating that our refactoring doesn't break file operations, but manual UI

  testing will be required for keyboard interaction validation.

handle_key_press - the "Monster Function"

> How do you recommend going after the monster function handle_key_press?

● Excellent question! The handle_key_press() function with 1,524 lines is a prime example of what needs systematic refactoring.

  Let me analyze it and provide a concrete attack strategy.

● Update Todos

  ⎿  ☐ Analyze handle_key_press function structure

     ☐ Identify key functional groups and responsibilities

     ☐ Design refactoring strategy with safe incremental steps

     ☐ Test and validate refactored implementation

     ☐ Create helper function extraction plan

     ☐ Implement command dispatch table approach

● Strategic Attack Plan for handle_key_press() Monster Function

  Based on my analysis, here's my recommended safe, incremental refactoring strategy:

  🎯 Phase 1: Extract Helper Functions (Low Risk)

  Start with the most duplicated code to get immediate wins:

  1.1 Extract Layer Selection Logic

  static void handle_layer_selection(int layer_num) {
      char n[30];
      xctx->rectcolor = layer_num;
      my_snprintf(n, S(n), "%d", xctx->rectcolor);
      tclvareval("xschem set rectcolor ", n, NULL);
      /* ... reconfigure_layers_button logic ... */
  }
  Impact: Eliminates ~200 lines of duplication across numeric keys.

  1.2 Extract Common Patterns

  static int should_handle_key(int event, KeySym key, int state, int button) {
      if(xctx->semaphore >= 2) return 0;
      if(waves_selected(event, key, state, button)) {
          waves_callback(event, mx, my, key, button, aux, state);
          return 0;
      }
      return 1;
  }

  static void start_move_operation(int infix_interface) {
      if(infix_interface) {
          xctx->mx_double_save = xctx->mousex_snap;
          xctx->my_double_save = xctx->mousey_snap;
          move_objects(START,0,0,0);
      } else {
          xctx->ui_state |= MENUSTART;
          xctx->ui_state2 = MENUSTARTMOVE;
      }
  }

  🎯 Phase 2: Key Group Extraction (Medium Risk)

  Extract logical groups one at a time, testing thoroughly:

  2.1 Start with Numeric Keys (Safest)

  static void handle_numeric_keys(KeySym key, int state, int rstate) {
      if(rstate == 0) {
          /* Logic level setting */
          if(key >= '0' && key <= '9') {
              handle_layer_selection((int)key - '0');
              return;
          }
      }
      else if(rstate == ControlMask) {
          /* Layer selection with Ctrl */
          // ... existing logic
      }
  }

  2.2 Extract File Operations

  static void handle_file_keys(KeySym key, int state, int rstate,
                              int infix_interface, const char *win_path) {
      switch(key) {
          case 's': handle_save_operation(state); break;
          case 'S': handle_save_as_operation(); break;
          case 'o': handle_open_operation(); break;
          // ... etc
      }
  }

  🎯 Phase 3: Command Dispatch Table (Higher Risk)

  Replace the massive switch with a cleaner dispatch system:

  3.1 Define Key Handler Structure

  typedef struct {
      KeySym key;
      int modifier_mask;
      void (*handler)(KeyHandlerContext *ctx);
      const char *description;
  } KeyHandler;

  typedef struct {
      int event, state, rstate, mx, my, button, aux;
      int infix_interface, enable_stretch, cadence_compat;
      int wire_draw_active, snap_cursor;
      const char *win_path;
      double c_snap;
      KeySym key;
  } KeyHandlerContext;

  3.2 Create Handler Table

  static const KeyHandler key_handlers[] = {
      {'w', 0, handle_place_wire, "Place wire"},
      {'W', 0, handle_place_snapped_wire, "Place snapped wire"},
      {'c', 0, handle_copy, "Copy selection"},
      {'m', 0, handle_move, "Move selection"},
      // ... hundreds of entries
      {0, 0, NULL, NULL} // terminator
  };

  static void handle_key_press_new(/* same params */) {
      KeyHandlerContext ctx = {/* initialize from params */};

      if(!should_handle_key(event, key, state, button)) return;

      for(const KeyHandler *h = key_handlers; h->handler; h++) {
          if(h->key == key && (state & h->modifier_mask) == h->modifier_mask) {
              h->handler(&ctx);
              return;
          }
      }

      // Handle unmapped keys
      handle_unmapped_key(&ctx);
  }

  🎯 Recommended Step-by-Step Attack Plan

  Week 1-2: Quick Wins (Helper Functions)

  1. ✅ Extract handle_layer_selection()
  2. ✅ Extract should_handle_key()
  3. ✅ Extract start_move_operation(), start_copy_operation()
  4. ✅ Extract rotation/flip helpers
  5. ✅ Run full regression tests

  Expected Impact: ~400 lines reduced, 0% risk of breaking functionality

  Week 3-4: First Group Extraction

  1. ✅ Extract handle_numeric_keys() (safest group)
  2. ✅ Extract handle_system_keys() (Delete, Escape, Return, etc.)
  3. ✅ Thorough testing with focus on these key groups
  4. ✅ Update any affected documentation

  Expected Impact: ~300 lines reduced, <5% risk

  Week 5-6: Core Groups

  1. ✅ Extract handle_file_keys() (save, load, etc.)
  2. ✅ Extract handle_navigation_keys() (zoom, pan)
  3. ✅ Extract handle_drawing_keys() (wire, line, arc)
  4. ✅ Intensive testing of drawing operations

  Expected Impact: ~600 lines reduced, 10% risk

  Week 7-8: Complex Groups

  1. ✅ Extract handle_selection_keys() (copy, move, select)
  2. ✅ Extract handle_transformation_keys() (rotate, flip)
  3. ✅ Extract handle_net_keys() (highlighting, tracing)
  4. ✅ Performance testing (these are hot paths)

  Expected Impact: ~400 lines reduced, 15% risk

  Week 9-10: Cleanup and Optimization

  1. ✅ Consider dispatch table approach for remaining keys
  2. ✅ Extract handle_special_keys() for symbols
  3. ✅ Final integration testing
  4. ✅ Performance benchmarks vs. original

  Final Result: 1,524 lines → ~200 lines main function + ~1,300 lines in focused modules

  🛡️ Risk Mitigation Strategies

  Safety Measures

  1. Git branching: Each phase gets its own branch
  2. Regression testing: Full test suite after each extraction
  3. Performance testing: Ensure no keystroke latency increase
  4. User testing: Have power users test drawing operations
  5. Rollback plan: Keep original function as handle_key_press_legacy() initially

  Testing Strategy

  1. Unit tests: Each extracted function gets unit tests
  2. Integration tests: Full drawing workflows
  3. Performance tests: Keystroke latency measurements
  4. Edge case tests: Modifier combinations, rapid key sequences
  5. Memory tests: Check for leaks in new function boundaries

  🎉 Benefits of This Approach

  Immediate Benefits (Phase 1)

  - ✅ Eliminates massive code duplication
  - ✅ Makes individual key handlers readable
  - ✅ Zero functional risk

  Medium-term Benefits (Phase 2)

  - ✅ Function becomes navigable and maintainable
  - ✅ New key handlers become trivial to add
  - ✅ Unit testing becomes possible

  Long-term Benefits (Phase 3)

  - ✅ Self-documenting key binding system
  - ✅ Runtime key remapping becomes possible
  - ✅ Help system can auto-generate from handler table
  - ✅ Plugin system for custom key handlers

  This phased approach gives you immediate wins while building toward a professional-grade architecture with minimal risk to the
  critical user interaction code.

Stefan++ : How? Reduce Cyclomatic Complexity

What does "high cyclomatic complexity" mean?

It means your code has turned into a labyrinth, and anyone trying to maintain it will likely curse your name.

Cyclomatic complexity is a metric that counts the number of independent paths through your code. Think of it as a "how many ways can I break my brain" counter. The higher the number, the more branches, loops, and conditionals are cluttering up your code.

  • Low cyclomatic complexity (1–10): Code is simple, readable, and probably written by someone who still has hope.
  • High cyclomatic complexity (20+): Code is a minefield of if statements, while loops, and spaghetti logic.

In short, “high cyclomatic complexity” means your code is doing too much in one place and needs to be refactored into smaller, cleaner chunks.

Checklist: How to Reduce Cyclomatic Complexity

✅ 1. Split Large Functions

Break big functions into smaller, focused ones.

def process_order(order):
    if order.type == 'online':
        ...
    elif order.type == 'in-store':
        ...

# Better:
def process_order(order):
    if order.type == 'online':
        handle_online(order)
    elif order.type == 'in-store':
        handle_instore(order)

✅ 2. Replace Complex Conditionals with Polymorphism

# Bad:
if shape == 'circle':
    ...
elif shape == 'square':
    ...

# Better:
class Shape:
    def area(self): pass

class Circle(Shape):
    def area(self): return pi * r * r

✅ 3. Use Guard Clauses

# Instead of:
def process(user):
    if user.is_active:
        if user.has_permission:
            ...

# Do:
def process(user):
    if not user.is_active or not user.has_permission:
        return
    ...

✅ 4. Use Lookups Instead of Conditionals

# Instead of:
if key == 'a': do_a()
elif key == 'b': do_b()

# Do:
actions = {'a': do_a, 'b': do_b}
actions.get(key, do_default)()

✅ 5. Extract Logic from Loops

# Instead of:
for item in items:
    if item.is_valid() and not item.is_expired():
        if item.value > threshold:
            ...

# Do:
for item in items:
    handle_item(item)

✅ 6. Minimize Boolean Logic

# Instead of:
if not (x or (y and not z)):

# Do:
should_skip = x or (y and not z)
if not should_skip:
Code copied!